<?php

namespace app\controller;

use support\Request;
use Ramsey\Uuid\Uuid;
use support\Redis;
use support\Db;
use tekintian\TekinQR;
use yzh52521\EasyHttp\Http;
use yzh52521\EasyHttp\Response;
use yzh52521\EasyHttp\RequestException;

class QywxOauth
{
    public function index(Request $request)
    {
        $rd=$request->input('rd','null');
        $sum=$request->input('sum','null');
        
        if($rd=='null'||$sum=='null'||$sum!=md5($rd.getenv('aeskey'))){
            return view('404');
        }
        $session = $request->session();
        $session->set('QYWX_OAUTH_rd', $rd);
        $app=$request->header('X-Requested-With','null');
        if($app=='com.tencent.wework'){
            $redirecturl='https://'.getenv('weburl').'/qywxoauth/info';
            $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".getenv('appid')."&redirect_uri=".$redirecturl."&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=".getenv('agentid')."#wechat_redirect";
            return redirect($url);
        }
        $uuid = Uuid::uuid7()->toString();
        Redis::set($uuid, 'null');
        Redis::expire($uuid, 300);

        $redirecturl='https://'.getenv('weburl').'/qywxoauth/answer/'.$uuid;
        $url="https://open.weixin.qq.com/connect/oauth2/authorize?appid=".getenv('appid')."&redirect_uri=".$redirecturl."&response_type=code&scope=snsapi_privateinfo&state=STATE&agentid=".getenv('agentid')."#wechat_redirect";
        $qr = TekinQR::getQRImg($url, 10, base_path().'/public/qywx.png', 1);

        return view('qywx/wait', ['url'=>$url,'uuid'=>$uuid,'qr'=>$qr,'to'=>'https://'.getenv('weburl').'/qywxoauth/info']);
    }

    public function answer(Request $request,$uuid)
    {
        if($uuid=='null'||!Uuid::isValid($uuid)){
            return view('404');
        }
        if(!Redis::exists($uuid)){
            return view('qywx/expire');
        }
        $code=$request->input('code','null');
        if($code=='null'){
            return view('404');
        }
        Redis::set($uuid, $code);
        Redis::expire($uuid, 10);

        return view('qywx/success');
    }

    public function ask(Request $request,$uuid)
    {
        if($uuid=='null'||!Uuid::isValid($uuid)){
            return json(['code' => 501, 'msg' => 'invaild uuid']);
        }
        if(!Redis::exists($uuid)){
            return json(['code' => 500, 'msg' => 'UUID expired']);
        }
        for($i=0;$i<150;$i++){
            if(!Redis::exists($uuid)){
                return json(['code' => 500, 'msg' => 'UUID expired']);
            }
            if(Redis::get($uuid)!='null'){
                return json(['code' => 200, 'msg' => 'ok','rcode'=>Redis::get($uuid)]);
                break;
            }
            sleep(2);
        }
        return json(['code' => 503, 'msg' => 'TimeOut']);
        /**
        $code=Redis::get($uuid);
        if($code=='null'){
            return json(['code' => 201, 'msg' => 'wait for answer']);
        }
        return json(['code' => 200, 'msg' => 'ok','code'=>$code]);
        **/
    }
    public function info(Request $request)
    {
        $code=$request->input('code','null');
        if($code=='null'){
            return view('404');
        }
        $tokenfile=base_path().'/token/qywx/innerQYWX.token';
        if(file_exists($tokenfile)){
            $tokencontent=json_decode(file_get_contents($tokenfile));
            $fulltoken=$tokencontent->token;
            $ddl=$tokencontent->ddl;
            if($ddl-time()<180){
                $reapply=true;
            }else{
                $reapply=false;
            }
        }else{
            $reapply=true;
        }
        if($reapply==true){
            $apply=$response = Http::get('https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.getenv('appid').'&corpsecret='.getenv('token'))->json();
            $fulltoken=$apply->access_token;
                $ddl=time()+$apply->expires_in;
                $file=fopen($tokenfile,"w");
                fwrite($file, json_encode(array('token'=>$fulltoken,'ddl'=>$ddl)));
                fclose($file);
        }
        $lookup= Http::get('https://qyapi.weixin.qq.com/cgi-bin/auth/getuserinfo?access_token='.$fulltoken.'&code='.$code)->json();
        if($lookup->errcode!=0){
            return view('404');
        }
        $userid=$lookup->userid;
        $usertoken=$lookup->user_ticket;
        $userinfo=Http::asJson()->post('https://qyapi.weixin.qq.com/cgi-bin/auth/getuserdetail?access_token='.$fulltoken,['user_ticket' => "$usertoken"])->json();
        $userbasic=Http::get('https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token='.$fulltoken.'&userid='.$userid)->json();
        if($userinfo->errcode!=0 || $userbasic->errcode!=0){
            return view('404');
        }
        $userinfo->name=$userbasic->name;
        $userinfo->postion=$userbasic->position;
        $userinfo->id=$userinfo->userid;
        if($userinfo->email==''||$userinfo->biz_mail==''){
            $mail=$userinfo->email.$userinfo->biz_mail;
            $userinfo->email=$mail;
            $userinfo->biz_mail=$mail;
        }
        Db::table('User')
            ->updateOrInsert(
                ['ID' => $userid.'@laysense'],
                ['public' => 0,'name' => $userinfo->name,'sex'=>$userinfo->gender,'position' => $userinfo->postion,'avatar' => $userinfo->avatar,'email' => $userinfo->email,'phone' => $userinfo->mobile,'biz_mail'=>$userinfo->biz_mail,'address'=>$userinfo->address,'role'=>1]
            );
            $session = $request->session();
            $rd=$session->get('QYWX_OAUTH_rd','null');
            if($rd=='null'){
                return view('404');
            }
            $sum=md5($rd.$userid.'@laysense'.getenv('aeskey'));
            $session->forget(['QYWX_OAUTH_rd']);


        return redirect('/account/loginCallback?rd='.$rd.'&sum='.$sum.'&id='.$userid.'@laysense');
    }

}
