<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Lib\XTSign;
use JWT;
use App\Services\Login\LoginService;
class XTSignController extends Controller
{
    //添加签名任务展示二维码
    public function addSignJob(){
        //添加任务签名
        $data=[
            // "userId"=>"b24d281af0b7f2bc3a49c90cf1853cd2e59569c982cb10970aa60a254bcc83f7",
            "title"=>"用户身份确认签名",
            "dataType"=>"DATA",
            "algo"=>"SM3withSM2",
            "description"=>"用户身份确认签名",
            "expiryDate"=>"1440",
            "data"=>"562+5ZCN5rWL6K+V5pWw5o2u",
            "requireQrCode"=>"N",
            "callBackUrl"=>"https://www.yanzai.vip/common/laravel/public/api/XTSignNotify"
        ];
        return XTSign::XTRequest('addSignJob',$data);

    }
    //用户绑定协同签名id
    public function bindUser(Request $request){
        $userid = $request->get('userid');//中间件产生的参数
        $pwd=request('pwd'); //密码
        $signJobId=request('signJobId'); //签名任务 id
        $cha=DB::table('xt_sign_notify')->where(['sign_job_id'=>$signJobId])->get();
        if(count($cha)>0){
            //解析证书信息
            $data=[
                "cert"=>$cha[0]->sign_cert
            ];
            $certInfo= XTSign::XTRequest('getCertInfo',$data);
            if($certInfo['status']){
                $s=app()->make(LoginService::class);
                   $check=$s->CheckPwd(['userid'=>$userid,'password'=>$pwd]);
                   if($check['status']){
                       $u=DB::table('users')->where(['id'=>$userid])->update([
                            'xtsign_userid'=>$certInfo['data']['userId'],
                            'xtsign_username'=>$certInfo['data']['certCN']
                       ]);
                       if($u){
                           return \Yz::Return(true,'绑定成功',[]);
                       }else{
                           return \Yz::echoError1("绑定失败");
                       }
                   }else{
                       return \Yz::echoError1("密码验证失败");
                   }
            }
        }

    }
    //检查协同签名回调状态
    public function CheckNotify(){

        $notifyType=request('notifyType'); //回调类型

        $signJobId=request('signJobId'); //签名任务 id
        $cha=DB::table('xt_sign_notify')->where(['sign_job_id'=>$signJobId])->get();
        if(count($cha)>0){
            //如果查到回调结果，判断回调结果，进行验签和查询证书详情获取用户信息
            if($notifyType=='bind') { //绑定操作
                return \Yz::Return(true,'扫码成功',[]);
            }
            //解析证书信息
            $data=[
                "cert"=>$cha[0]->sign_cert
            ];
           $certInfo= XTSign::XTRequest('getCertInfo',$data);
           if($certInfo['status']){
                   $query= DB::table('users')->where(['xtsign_userid'=>$certInfo['data']['userId'],'status'=>1])->get();
                   if(count($query)>0){

                       $jwt= new JWT();
                       $accessTimeout = $jwt -> GetGetSecretTimeOut();
                       $refreshTimeout = $jwt -> GetRefreshTokenTimeOut();
                       $access_token = $jwt->BuildJWT('yz','access',$query[0]->id,$query[0]->group,$accessTimeout);
                       $refresh_token = $jwt->BuildJWT('yz','refresh',$query[0]->id,'',$refreshTimeout);
                       if(!empty($arr['mian7'])){
                           $mian7_token = $jwt->BuildJWT('yz','mian7',$query[0]->id,'',$jwt -> GetMian7TokenTimeOut());
                           $result['mian7_token']=$mian7_token;
                       }
                       DB::table('users')->where(['id'=>$query[0]->id,'status'=>1])->update(['token'=>md5($refresh_token)]);
                       $result['token']=$access_token;
                       $result['refresh_token']=$refresh_token;
                       $result['status']='ok';

                       return \Yz::Return(true,'用户匹配成功',$result);
                   }else{
                       return \Yz::echoError1("扫码失败，未找到关联此用户的信息");
                   }


           }
           // return \Yz::Return(true,'查到回调信息',$cha);
        }else{
            return \Yz::echoError1("暂未回调");
        }
    }
    //协同签名回调
    public function Notify(){
        $signJobId=request('signJobId'); //签名任务 id
        $status =request('status');  //签名任务状态
        $msspId=request('msspId'); //用户唯一标识
        $signResult =request('signResult'); //签名结果
        $signCert =request('signCert'); //签名证书
        $i=DB::table('xt_sign_notify')->insert([
           'sign_job_id'=>$signJobId,
            'status'=>$status,
            'mssp_id'=>$msspId,
            'sign_result'=>$signResult,
            'sign_cert'=>$signCert
        ]);
        if($i){
            $rd=[
                "status"=>200,
                "message"=>"SUCCESS",
                "data"=>[
                    "signJobId"=>$signJobId,
                    "status"=>$status
                ]
            ];
            return $rd;
        }
    }
}
