<?php

namespace app\common\service;

use fast\Random;
use think\Exception;

class UserService
{

    /**
     * 获取请求参数
     * @return void
     */
    public function faceAuth($params=[])
    {
        $result = [
            'status' => 1,
            'msg' => '获取成功',
            'data' => [],
        ];
        try {
            $idCard = isset($params['id_card']) ? $params['id_card'] : '';
            $realName = isset($params['real_name']) ? $params['real_name'] : '';
            $userId = isset($params['user_id']) ? $params['user_id'] : 0;
            $tencentConfig = config('tencent_yun');
            $sercrtId = isset($tencentConfig['SecretId']) ? $tencentConfig['SecretId'] : '';
            $sercrtKey = isset($tencentConfig['SecretKey']) ? $tencentConfig['SecretKey'] : '';
            //获取token
            $token_url = 'https://miniprogram-kyc.tencentcloudapi.com/api/oauth2/access_token?app_id='.$sercrtId.'&secret='.$sercrtKey.'&grant_type=client_credential&version=1.0.0';
            $token_result = file_get_contents($token_url);
            if (!$token_result) {
                throw new Exception('您的网络开小差啦1~');
            }
            $token_result = json_decode($token_result, true);
            if ($token_result['code'] != 0) {
                throw new Exception('您的网络开小差啦2~');
            }
            $token = $token_result['access_token'];

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

            //获取签名
            $sign_data = [
                'wbappid' => $sercrtId,
                'userId'  => (string)$userId,
                'version' => '1.0.0',
                'ticket'  => $ticket,
                'nonce'   => Random::alnum(32)
            ];
            asort($sign_data);//排序
            $sign_string = join('', $sign_data);
            $sign = sha1($sign_string);

            //上传身份信息
            $orderNo = getMillisecond() . $userId . mt_rand(1, 1000); //商户请求的唯一标识
            $url = 'https://miniprogram-kyc.tencentcloudapi.com/api/server/getAdvFaceId?orderNo='.$orderNo;
            $data = [
                'webankAppId' => $sercrtId,
                'orderNo' => $orderNo,
                'userId' => (string)$userId,
                'name' => $realName,//姓名
                'idNo' => $idCard,//证件号
                'version' => '1.0.0',
                'sign' => $sign,
                'nonce' => $sign_data['nonce']
            ];
            $res = curl_post($url,json_encode($data, 320), ['Content-Type: application/json']);
            $result['data'] = json_decode($res,true);
            $result['data']['nonce'] = $sign_data['nonce'];
            $result['data']['sign'] = $sign;
        } catch (Exception $e) {
            $result['status'] = 0;
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }

    /**
     * 阿里实名认证二要素
     * https://market.aliyun.com/products/57000002/cmapi026109.html
     * @return void
     */
    public function aliCheck($params=[])
    {
        $result = [
            'status' => 1,
            'msg' => '',
            'data' => [],
        ];
        try {
            $idCard = isset($params['id_card']) ? $params['id_card'] : '';
            $realName = isset($params['real_name']) ? $params['real_name'] : '';
            $aliyunConfig = config('ali_yun');
            $host = "https://eid.shumaidata.com";
            $path = "/eid/check";
            $method = "POST";
            $appcode = isset($aliyunConfig['app_code']) ? $aliyunConfig['app_code'] : '';
            $headers = ['Content-Type: application/json'];
            array_push($headers, "Authorization:APPCODE " . $appcode);
            $querys = "idcard=".$idCard."&name=".urlencode($realName);
            $bodys = "";
            $url = $host . $path . "?" . $querys;

            $curl = curl_init();
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
            curl_setopt($curl, CURLOPT_FAILONERROR, false);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            //设定返回信息中是否包含响应信息头,启用时会将头文件的信息作为数据流输出,true 表示输出信息头, false表示不输出信息头
            //如果需要将字符串转成json,请将 CURLOPT_HEADER 设置成 false
            curl_setopt($curl, CURLOPT_HEADER, false);
            if (1 == strpos("$".$host, "https://"))
            {
                curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            }
            $returnRes = curl_exec($curl);
            curl_close($curl);
            $resultData = json_decode($returnRes,true);
            if (isset($resultData['code']) && !empty($resultData['code'])) {
                throw new Exception($resultData['message']);
            }
            $result['data'] = $resultData;
        } catch (Exception $e) {
            $result['status'] = 0;
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }

    /**
     * 邀请赠送金额
     * @return void
     */
    public function inviteMoney($params=[])
    {
        $result = [
            'status' => 1,
            'msg' => '',
            'data' => [],
        ];
        try {
            $userId = isset($params['user_id']) ? $params['user_id'] : 0;
            if (!empty($userId)) {
                $field = 'id,pre_userid,money';
                $where['id'] = $userId;
                $user = model('User')->field($field)->where($where)->find();
                if (!empty($user)) {
                    if (!empty($user['pre_userid'])) {
                        $preWhere['id'] = $user['pre_userid'];
                        $preUser = model('User')->field($field)->where($preWhere)->find();
                        if (!empty($preUser)) {
                            //查看是否赠送过金额
                            $moneyLogWhere['invite_user_id'] = $userId;
                            $moneyLogWhere['type'] = 15;
                            $moneyLog = model('UserMoneyLog')->where($moneyLogWhere)->find();
                            if (empty($moneyLog)) {
                                $money = config('site.invite_money');
                                $remark = '邀请用户充值赠送金额';
                                $res = model('Wallet')->lockChangeAccountRemain($preUser['id'],$money,'+',$preUser['money'],$remark,15,'money',$userId);
                                if (!$res['status']) {
                                    throw new Exception($res['msg']);
                                }
                            }
                        }
                    }
                }
            }
        } catch (Exception $e) {
            $result['status'] = 0;
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }

    /**
     * 获取用户家族角色
     * @return void
     */
    public function getGuildRole($params=[])
    {
        $result = [
            'status' => 1,
            'msg' => '操作成功',
            'data' => [],
        ];
        try {
            $userId = isset($params['user_id']) ? $params['user_id'] : 0;
            $guildId = isset($params['guild_id']) ? $params['guild_id'] : 0;
            if (empty($userId) || empty($guildId)) {
                throw new Exception('参数错误');
            }
            $guildWhere['id'] = $guildId;
            $guild = model('Guild')->where($guildWhere)->find();
            if (empty($guild)) {
                throw new Exception('未找到家族信息');
            }
            $guildRole = 4;//家族角色:1组长,2副族长,3成员,4非成员
            if ($userId == $guild['user_id']) {
                $guildRole = 1;
            }
            $guildMemberWhere['guild_id'] = $guildId;
            $guildMemberWhere['user_id'] = $userId;
            $guildMember = model('GuildMember')->field('id,role')->where($guildMemberWhere)->find();
            if (!empty($guildMember)) {
                if ($guildMember['role'] == 0) {
                    $guildRole = 3;
                } elseif ($guildMember['role'] == 1) {
                    $guildRole = 2;
                }
            }
            $result['data'] = [
                'guild_role' => $guildRole,
            ];
        } catch (Exception $e) {
            $result['status'] = 0;
            $result['msg'] = $e->getMessage();
        }
        return $result;
    }
}