<?php
namespace app\appapi\controller\v1;

use app\appapi\ApiController;
use think\facade\Db;
use think\facade\Session;
use think\facade\Log;

use Lcobucci\JWT\Parser;
use thans\jwt\facade\JWTAuth;

use GuzzleHttp\Client;

use app\common\lib\Vcard;
use app\common\lib\Aes;
use app\common\lib\Sign;

class Auth extends ApiController
{
    /**
     * return 200 成功
     * 201 不是會員
     */
    public function lineLogin(){
        $id_token = input('token');
        $line_id = input('line_id');


        // $profile = (new Parser())->parse($id_token);
        // print_r($token->getClaim('name'));

        //驗證id_token


        $user=Db::name('user')
        ->where('line_id',$line_id)
        ->find();

        if(!$user){
            return $this->success('非會員',201);
        }

        
        $token = JWTAuth::builder(
            [
                'id' => $user['id'],
                'user_id' => $user['user_id'],
                'level' => $user['level']
            ]);
        
        

        if(empty($user['uniqid'])){
                return $this->success(['uid'=>$user['user_id'],'token'=>'Bearer '.$token],202);
        }
    
        return $this->success(['uid'=>$user['user_id'],'token'=>'Bearer '.$token]);
    }

    public function bindCard(){
        $uid = input('uid');
        $verify = input('verify');

        try{
            Db::name('user')
            ->where('user_id',$uid)
            ->update(['uniqid'=>$verify]);
            
            Db::name('precard')
            ->where('verify_code',$verify)
            ->update(['status'=>2]);

            return $this->success('綁定成功');
        }catch(\Exception $e){
            return $this->error('綁定失敗');
        }

    }

    public function checkLineId(){
        $line_id=input('lineid');
        
        $user = Db::name('user')
        ->where('line_id',$line_id)
        ->find();

        if($user){
            return $this->error('會員已存在');
        }

        return $this->success('檢查成功');
    }

    public function register(){
        $data = input();

        unset($data['version']);
        unset($data['controller']);
        unset($data['action']);
        unset($data['uid']);
        unset($data['userid']);
        unset($data['verify']);
        unset($data['token']);

		$data=array_map('asc_trim',$data);

        // //檢查line id是否己經是會員
        // //TODO
        // $user=Db::name('user')
        // ->where('line_id',input('line_id'))
        // ->find();

        // if($user){
        //     return $this->error('已是會員',501);
        // }


        //驗證id_token
        $verify_line = $this->verifyIdToken(input('token'));
        
        if(!$verify_line){
            return $this->error('id token expire',500);
        }

        $data['line_name'] = $verify_line['name'];
        $data['line_picture'] = $verify_line['picture'];
        $data['real_name'] = $verify_line['name'];

        //新增User至Oss Server
        $user_data = [
            'appid' => 'sc',
            'line_id' => $verify_line['sub'],
            'line_name' => $data['line_name'],
            'line_picture' => $data['line_picture'],
            'phone' => $data['phone'],
            'real_name' => $data['line_name'],
            'timestamp' => time()
        ];

        $sign = Sign::genSign($user_data);
        $user_data['sign'] = $sign;
            
        $client = new Client([
            'base_uri' => 'https://sso.h888.fun/api/v1/'
        ]);

        $response = $client->post('user/add',[
            'form_params' => $user_data
        ]);
   

        if($response->getStatusCode()!=200){
            return $this->error('上傳SSO SERVER 失敗');
        }

        $sso_data = json_decode($response->getBody()->getContents(),true)['data'];

        //推薦人
        // if(strlen($data['refer'])>0){
        //     $pid = decodeRefer($data['refer']);
        //     $data['parent_id'] = $pid;
        // }else{
        //     $data['parent_id'] = 0;
        // }
        // unset($data['refer']);

        //預製卡
        if(input('verify')){
            $action = 'openright';

            $user_id=genUniqid();
            $data['user_id'] = $user_id;    

            $data['uniqid'] = input('verify');
            
            $precard = Db::name('precard')
            ->where('verify_code',input('verify'))
            ->find();

            if(!$precard){
                return $this->error('查無預開卡',401);
            }

            $data['agent_id'] = $precard['agent_id']; 
            //TODO 
        }else{
            $action = 'register';
            if(!isset($data['aid'])){
                $data['agent_id'] = 1;
            }else{
                $data['agent_id'] = Db::name('agent')->where('prefix',$data['aid'])->value('id');
                unset($data['aid']);
            }

            $data['user_id'] = $sso_data['uid'];    
        }
    
        $agent = Db::name('agent')->where('id',$data['agent_id'])->find();

        if($agent['try_days']==0){
            $data['status'] = 1;
            $data['level'] = $agent['base_level'];
            $data['overdue_time'] = strtotime(date('Y-m-d',time() + (60 * 60 * 24 * $agent['base_days'])));
        }else{
            $data['status'] = 2;
            $data['level'] = $agent['try_level'];
            $data['overdue_time'] = strtotime(date('Y-m-d',time() + (60 * 60 * 24 * $agent['try_days'])));
        }

        if($agent['parent_id']==0){
            $data['agent_id'] = $agent['id'];
        }else{
            $data['agent_id'] = $agent['parent_id'];
        }

        $level_option = Db::name('user_level')
        ->where('agent_id',$data['agent_id'])
        ->where('level_id',$data['level'])
        ->find();

        $data['nc_type']=$level_option['nc_type'];
        $data['nc_func']=$level_option['nc_func'];

        $data['cus_card'] = '';
        $data['create_time'] = date('Y-m-d H:i:s');


        try{
            $id = Db::name('user')
            ->insertGetId($data);
    
            // $refer_code = encodeRefer($id);

                
            // $result = Db::name('user')
            // ->where('id',$id)
            // ->update(['code'=>$refer_code]);

            
            $qrcodeUrl = genQrCode('https://'.$_SERVER['HTTP_HOST'].'/home/?aid='.$agent['prefix'],$data['user_id'],'refer');

            $aes = new Aes([]);

            $params = urlencode($aes->encrypt('user_id='.$data['user_id'].'&verify_code='.input('verify')));
    
            $nfcUrl = genQrCode('https://'.$_SERVER['HTTP_HOST'].'/card/?params='.$params,$data['user_id'],'nfc');
    
            Vcard::genVcf($data['user_id']);
            
            if($action == 'openright'){
                Db::name('precard')
                ->where('verify_code',input('verify'))
                ->update(['status'=>2]);
            }
            
            return $this->success(['uid'=>$data['user_id'],'token'=>'Bearer'.$sso_data['token']]);
    
        }catch(\Exception $e){
            print_r($e);
            return $this->error('註冊失敗');
        }

    }

    private function verifyIdToken($token){
        try{
            $client = new Client();
            $response = $client->request('POST', 'https://api.line.me/oauth2/v2.1/verify', [
                'form_params' => [
                    'id_token' => $token,
                    'client_id'=> env('utel.line_channel_id')    
                ]
            ]);    

            $body = $response->getBody()->getContents();
            return json_decode($body, true);

	} catch (\Exception $e) {
            return false;   
        }    

        // print_r($response);
        // $body = $response->getBody()->getContents();

        // print_r($body);

    }

    private function saveLineImage($pictureUrl,$uid)
    {
			if($pictureUrl){
		    	$curl = curl_init($pictureUrl);
		    	curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
		    	$imageData=curl_exec($curl);
		    	curl_close($curl);

		    	$filename=$uid."_line.jpg";
		    	$filedir=$_SERVER['DOCUMENT_ROOT'].'/storage/'.$uid;
			    if (!file_exists($filedir)) {
			        mkdir($filedir , 0777 , true);
			    }
		    	$fp=fopen($filedir.'/'.$filename,'a');
		    	fwrite($fp,$imageData);
		    	fclose($fp);

				return $filename;
			}else{
				return false;
			}
    }

    public function getSiteConfig(){
        $result = Db::name('site_config')
        ->where('parent_id','<>',0)
        ->select();

        foreach($result as $key => $val){
            $rtn[$val['code']]=$val['value'];
        }

        return $this->success($rtn);        
    }

    public function uploadAvatar(){

		$files = request()->file('file');
		$savename =  \think\facade\Filesystem::disk('public')->putFile( 'temp' , $files);

		$avatar = getUrl().'/storage/'.$savename;

        
        // Db::name('user')
        // ->where('user_id',input('user_id'))
        // ->update(['avatar'=>$avatar]);

        return $this->Success($avatar);
    }

    public function test(){
        Vcard::genVcf('mc63de2a162b218');
    }            
}
