<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;

use TencentCloud\Common\Credential;
use TencentCloud\Common\Profile\ClientProfile;
use TencentCloud\Common\Profile\HttpProfile;
use TencentCloud\Common\Exception\TencentCloudSDKException;
use TencentCloud\Faceid\V20180301\FaceidClient;
use TencentCloud\Faceid\V20180301\Models\IdCardVerificationRequest;
use TencentCloud\Iai\V20200303\IaiClient;
use TencentCloud\Iai\V20200303\Models\CompareFaceRequest;


/**
 * 实名认证
 */
class Userauth extends Api
{

    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['test', 'test1'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['test2'];

    //实名认证信息
    public function idcard_confirm_info(){
        $check = Db::name('user_idconfirm')->where('user_id',$this->auth->id)->order('id desc')->find();
        if (!$check) {
            $check = (object)[];
        }

        $this->success('success',$check);
    }


    //实名认证
    public function idcard_auth() {
        $info = Db::name('user_idconfirm')->where(['user_id' => $this->auth->id])->find();

        if ($info['status'] == 1) {
            $this->error('您已通过审核!');
        }

        $nickname = input('nickname', '', 'trim'); // 姓名
        $idcard = input('idcard', '', 'trim'); // 身份证号
        if ($nickname === '') {
            $this->error('请输入姓名');
        }
        if (iconv_strlen($nickname, 'utf-8') > 50) {
            $this->error('请输入正确姓名');
        }
        if ($idcard === '') {
            $this->error('请输入身份证号');
        }
        if (iconv_strlen($idcard, 'utf-8') != 18) {
            $this->error('请输入正确身份证号');
        }
        $count = Db::name('user_idconfirm')->where(['idcard' => $idcard, 'user_id' => ['neq', $this->auth->id]])->count('id');
        if ($count) {
            $this->error('身份证号已存在');
        }

        $data = [];
        $data['truename'] = $nickname;
        $data['idcard'] = $idcard;

        //腾讯云身份证二要素认证
        $auth_restult = $this->userauth_tencent($idcard, $nickname);
        if ($auth_restult) {
            $data['status'] = 1; //通过
            $msg = '认证通过';
        } else {
            $data['status'] = 0; //不通过
            $msg = '自动认证不通过,请等待人工审核';
        }

        //开启事务
        Db::startTrans();
        if (!$info) { //未认证
            $data["user_id"] = $this->auth->id;
            $data["createtime"] = time();
            $res = Db::name('user_idconfirm')->insertGetId($data);
        } else { //认证被拒绝过
            $data['updatetime'] = time();
            $res = Db::name('user_idconfirm')->where(['id' => $info['id'], 'user_id' => $this->auth->id])->setField($data);
        }

        if (!$res) {
            Db::rollback();
            $this->error('认证失败');
        }
        $rt = Db::name('user')->where(['id' => $this->auth->id, 'idcard_status' => $this->auth->idcard_status])->setField('idcard_status', $data['status']);
        if ($rt === false) {
            Db::rollback();
            $this->error('认证失败');
        }

        if ($data['status'] == 1) {
            //完成实名认证  +20金币
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,4);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
            //系统消息
            $msg_id = \app\common\model\Message::addMessage($this->auth->id,'实名认证','实名认证已经审核通过');
        } else {
            //系统消息
            $msg_id = \app\common\model\Message::addMessage($this->auth->id,'实名认证','实名认证审核不通过');
        }

        Db::commit();
        $this->success($msg);
    }

    //腾讯云身份证二要素认证
    public function userauth_tencent($idcard = '', $nickname = '') {
//        require_once 'vendor/autoload.php';
        try {
            // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            $config = config('tencent_im');
            $cred = new Credential($config['SecretId'], $config['SecretKey']);
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("faceid.tencentcloudapi.com");

            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            $client = new FaceidClient($cred, "", $clientProfile);

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req = new IdCardVerificationRequest();

            $params = array(
                "IdCard" => $idcard,
                "Name" => $nickname
            );
            $req->fromJsonString(json_encode($params));

            // 返回的resp是一个IdCardVerificationResponse的实例,与请求对象对应
            $resp = $client->IdCardVerification($req);

            // 输出json格式的字符串回包
//            print_r($resp->toJsonString());
            $result = json_decode($resp->toJsonString(), true);
            if (isset($result['Result']) && $result['Result'] == 0) {
                return 1; //通过
            } else {
                return 0;
            }
        }
        catch(TencentCloudSDKException $e) {
//            echo $e;
            return 0;
        }
    }

/////////////////////////////////////////////////////////////


    //申请真人认证
    public function realauth() {
        if ($this->auth->real_status == 1) {
            $this->error('您已经真人认证过了~');
        }
        if ($this->auth->avatar == config('avatar_boy') || $this->auth->avatar == config('avatar_girl')) {
            $this->error('请先上传真人头像~');
        }

        //获取token
        $token_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token?app_id='.config('tencent_yun')['secret_id'].'&secret='.config('tencent_yun')['secret_key'].'&grant_type=client_credential&version=1.0.0';
        $token_result = file_get_contents($token_url);
        if (!$token_result) {
            $this->error('您的网络开小差啦1~');
        }
        $token_result = json_decode($token_result, true);
        if ($token_result['code'] != 0) {
            $this->error('您的网络开小差啦2~');
        }
        $token = $token_result['access_token'];

        //获取签名鉴权参数ticket
        $ticket_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket?app_id='.config('tencent_yun')['secret_id'].'&access_token='.$token.'&type=SIGN&version=1.0.0';
        $ticket_result = file_get_contents($ticket_url);
        if (!$ticket_result) {
            $this->error('您的网络开小差啦3~');
        }
        $ticket_result = json_decode($ticket_result, true);
        if ($ticket_result['code'] != 0) {
            $this->error('您的网络开小差啦4~');
        }
        $ticket = $ticket_result['tickets'][0]['value'];

        //获取签名
        $sign_data = [
            'wbappid' => config('tencent_yun')['secret_id'],
            'userId'  => (string)$this->auth->id,
            'version' => '1.0.0',
            'ticket'  => $ticket,
            'nonce'   => Random::alnum(32)
        ];//p($sign_data);
        asort($sign_data); //p($sign_data);//排序
        $sign_string = join('', $sign_data);//p($sign_string);
        $sign = sha1($sign_string);//p($sign);

        //上传身份信息
        $orderNo = getMillisecond() . $this->auth->id . mt_rand(1, 1000); //商户请求的唯一标识
        $url = 'https://miniprogram-kyc.tencentcloudapi.com/api/server/getAdvFaceId?orderNo=' . $orderNo;

        $avatar = one_domain_image($this->auth->avatar);
        $avatar = str_replace('https', 'http', $avatar);
        $img = file_get_contents($avatar);
        $img = str_replace('data:image/jpg;base64', '', $img);
        $img = str_replace('\n', '', $img);
        $sourcePhotoStr = base64_encode($img);

        $data = [
            'webankAppId' => config('tencent_yun')['secret_id'],
            'orderNo' => $orderNo,
            'userId' => (string)$this->auth->id,
            'sourcePhotoStr' => $sourcePhotoStr,
            'sourcePhotoType' => 2,
            'version' => '1.0.0',
            'sign' => $sign,
            'nonce' => $sign_data['nonce']
        ];

        $rs = curl_post($url,json_encode($data, 320), ['Content-Type: application/json']);
        if (!$rs) {
            $this->error('您的网络开小差啦5~');
        }
        $rs = json_decode($rs, true);
        if (!$rs || $rs['code'] != 0) {
            $this->error('您的网络开小差啦6~');
        }

        $user_auth = [
            'user_id' => $this->auth->id,
            'certify_id' => $rs['result']['faceId'],
            'out_trade_no' => $data['orderNo'],
            'status' => 0,
            'createtime' => time(),
            'updatetime' => time()
        ];

        //开启事务
        Db::startTrans();
        //查询是否认证过
        $info = Db::name('user_auth')->where(['user_id' => $this->auth->id])->find();
        if ($info) {
            $auth_rs = Db::name('user_auth')->where(['id' => $info['id']])->setField($user_auth);
        } else {
            $auth_rs = Db::name('user_auth')->insertGetId($user_auth);
        }
        if (!$auth_rs) {
            Db::rollback();
            $this->error('您的网络开小差啦7~');
        }
        //修改用户表认证状态
        $user_rs = Db::name('user')->where(['id' => $this->auth->id])->setField('real_status', 0);
        if ($user_rs === false) {
            Db::rollback();
            $this->error('您的网络开小差啦8~');
        }

        Db::commit();

        $return_data = [
            'face_id' => $user_auth['certify_id'],
            'order_no' => $user_auth['out_trade_no'],
            'user_id' => (string)$this->auth->id,
            'nonce' => $sign_data['nonce'],
            'sign' => $sign
        ];
        $this->success('success', $return_data);
    }

    //查询真人认证结果
    public function getrealauthresult() {
        $user_auth = Db::name('user_auth')->where(['user_id' => $this->auth->id])->find();
        if (!$user_auth) {
            $this->success('尚未认证');
        }
        if ($user_auth['status'] == 1) {
            $this->success('真人认证通过');
        }
        if (!$user_auth['certify_id']) {
            $this->success('请先进行真人认证');
        }

        //获取token
        $token_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token?app_id='.config('tencent_yun')['secret_id'].'&secret='.config('tencent_yun')['secret_key'].'&grant_type=client_credential&version=1.0.0';
        $token_result = file_get_contents($token_url);
        if (!$token_result) {
            $this->error('您的网络开小差啦1~');
        }
        $token_result = json_decode($token_result, true);
        if ($token_result['code'] != 0) {
            $this->error('您的网络开小差啦2~');
        }
        $token = $token_result['access_token'];

        //获取签名鉴权参数ticket
        $ticket_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/api_ticket?app_id='.config('tencent_yun')['secret_id'].'&access_token='.$token.'&type=SIGN&version=1.0.0';
        $ticket_result = file_get_contents($ticket_url);
        if (!$ticket_result) {
            $this->error('您的网络开小差啦3~');
        }
        $ticket_result = json_decode($ticket_result, true);
        if ($ticket_result['code'] != 0) {
            $this->error('您的网络开小差啦4~');
        }
        $ticket = $ticket_result['tickets'][0]['value'];

        //获取签名
        $sign_data = [
            'wbappid' => config('tencent_yun')['secret_id'],
            'orderNo'  => $user_auth['out_trade_no'],
            'version' => '1.0.0',
            'ticket'  => $ticket,
            'nonce'   => Random::alnum(32)
        ];//p($sign_data);
        asort($sign_data); //p($sign_data);//排序
        $sign_string = join('', $sign_data);//p($sign_string);
        $sign = sha1($sign_string);//p($sign);

        //人脸核身结果查询
        $url = 'https://miniprogram-kyc.tencentcloudapi.com/api/v2/base/queryfacerecord?orderNo=' . $user_auth['out_trade_no'];
        $data = [
            'appId' => config('tencent_yun')['secret_id'],
            'version' => '1.0.0',
            'nonce' => $sign_data['nonce'],
            'orderNo' => $user_auth['out_trade_no'],
            'sign' => $sign
        ];

        $rs = curl_post($url,json_encode($data, 320), ['Content-Type: application/json']);
        if (!$rs) {
            $this->error('您的网络开小差啦5~');
        }
        $rs = json_decode($rs, true);
        if (!$rs || $rs['code'] != 0) {
            $this->error($rs['msg']);
        }
        if ($rs['result']['liveRate'] >= 90 && $rs['result']['similarity'] >= 90) {
            $edit_data['status'] = 1;
            $msg = '真人认证成功';
        } else {
            $edit_data['status'] = 2;
            $edit_data['certify_id'] = '';
            $edit_data['out_trade_no'] = '';
            $msg = '真人认证失败';
        }

        $edit_data['updatetime'] = time();
        //开启事务
        Db::startTrans();
        //修改认证信息
        $result = Db::name('user_auth')->where(['user_id' => $this->auth->id, 'status' => $user_auth['status']])->setField($edit_data);
        if (!$result) {
            Db::rollback();
            $this->error('查询认证结果失败2');
        }
        //修改用户信息
        $rs = Db::name('user')->where(['id' => $this->auth->id])->setField('real_status', $edit_data['status']);
        if (!$rs) {
            Db::rollback();
            $this->error('查询认证结果失败3');
        }
        if ($edit_data['status'] == 1) { //通过
            //tag任务赠送金币
            //真人认证奖励
            $task_rs = \app\common\model\TaskLog::tofinish($this->auth->id,20);
            if($task_rs === false){
                Db::rollback();
                $this->error('完成任务赠送奖励失败');
            }
            //系统消息
            $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证已经审核通过');
        } else {
            //系统消息
            $msg_id = \app\common\model\Message::addMessage($this->auth->id,'真人认证','真人认证审核不通过');
        }

        Db::commit();
        $this->success($msg);
    }



    //真人认证后修改头像前比对
    public function realavatar_auit() {
        if ($this->auth->real_status != 1) {
            $this->error('尚未通过真人认证');
        }
        $avatar = input('avatar', '', 'trim'); //头像地址
        if ($avatar === '') {
            $this->error('参数缺失');
        }
        $avatar = one_domain_image($avatar);
        $now_avatar = one_domain_image($this->auth->avatar);
        if ($avatar == $now_avatar) {
            $this->error('头像未改变');
        }
        //腾讯云人脸识别
        $result = $this->face_tencent($now_avatar, $avatar); //1通过 0拒绝

        $this->success('结果', $result);
    }

    //真人认证后修改头像
    public function editrealavatar() {
        if ($this->auth->real_status != 1) {
            $this->error('尚未通过真人认证');
        }
        $avatar = input('avatar', '', 'trim'); //头像地址
        if ($avatar === '') {
            $this->error('参数缺失');
        }
        $avatar = one_domain_image($avatar);
        $now_avatar = one_domain_image($this->auth->avatar);
        if ($avatar == $now_avatar) {
            $this->error('头像未改变');
        }
        //腾讯云人脸识别
        $auit_result = $this->face_tencent($now_avatar, $avatar); //1通过 0拒绝
        if ($auit_result != 1) {
            $this->success('提示', ['code' => 2]);
        }

        $data['avatar'] = $avatar;

        $user_result = Db::name('user')->where(['id' => $this->auth->id])->setField($data);
        if (!$user_result) {
            $this->error('修改失败');
        }

        $this->success('修改成功');
    }

    //真人认证后修改头像并取消真人认证
    public function editrealavatarcancelauit() {
        if ($this->auth->real_status != 1) {
            $this->error('尚未通过真人认证');
        }
        $avatar = input('avatar', '', 'trim'); //头像地址
        if ($avatar === '') {
            $this->error('参数缺失');
        }
        $avatar = one_domain_image($avatar);
        $now_avatar = one_domain_image($this->auth->avatar);
        if ($avatar == $now_avatar) {
            $this->error('头像未改变');
        }

        $data['avatar'] = $avatar;
        $data['real_status'] = -1;

        //开启事务
        Db::startTrans();
        $user_result = Db::name('user')->where(['id' => $this->auth->id])->setField($data);
        if (!$user_result) {
            Db::rollback();
            $this->error('修改失败');
        }
        $user_auth_result = Db::name('user_auth')->where(['user_id' => $this->auth->id])->delete();
        if (!$user_auth_result) {
            Db::rollback();
            $this->error('修改失败');
        }

        Db::commit();
        $this->success('修改成功');
    }

    //腾讯云人脸识别
    public function face_tencent($urla = '', $urlb = '') {
//        require_once 'vendor/autoload.php';
        try {
            // 实例化一个认证对象,入参需要传入腾讯云账户secretId,secretKey,此处还需注意密钥对的保密
            // 密钥可前往https://console.cloud.tencent.com/cam/capi网站进行获取
            $config = config('tencent_im');
            $cred = new Credential($config['SecretId'], $config['SecretKey']);
            // 实例化一个http选项,可选的,没有特殊需求可以跳过
            $httpProfile = new HttpProfile();
            $httpProfile->setEndpoint("iai.tencentcloudapi.com");

            // 实例化一个client选项,可选的,没有特殊需求可以跳过
            $clientProfile = new ClientProfile();
            $clientProfile->setHttpProfile($httpProfile);
            // 实例化要请求产品的client对象,clientProfile是可选的
            $client = new IaiClient($cred, "ap-beijing", $clientProfile);

            // 实例化一个请求对象,每个接口都会对应一个request对象
            $req = new CompareFaceRequest();

            $params = array(
                "UrlA" => $urla,
                "UrlB" => $urlb,
                "FaceModelVersion" => "3.0"
            );
            $req->fromJsonString(json_encode($params));

            // 返回的resp是一个CompareFaceResponse的实例,与请求对象对应
            $resp = $client->CompareFace($req);

            // 输出json格式的字符串回包
//            print_r($resp->toJsonString());
            $result = json_decode($resp->toJsonString(), true);
            //3.0版本误识率千分之一对应分数为40分,误识率万分之一对应分数为50分,误识率十万分之一对应分数为60分。 一般超过50分则可认定为同一人。
            if (isset($result['Score']) && $result['Score'] >= 60) {
                return 1; //通过
            } else {
                return 0;
            }
        }
        catch(TencentCloudSDKException $e) {
//            echo $e;
            return 0;
        }
    }

}