<?php


namespace App\Services\user;

use App\Models\user\mysql\UserWechatBind;
use Api\PhpUtils\Http\Request;
use App\Services\user\Weixin\WxBizDataCrypt;;
use App\Exception\BaseException;
use App\Exception\custom\UserException;

use Api\PhpUtils\Validate\Validate;
use Api\PhpServices\Idgen\Idgen;
use Api\PhpUtils\Redis\RedisUtil;
use Api\PhpServices\JwUser\JwUser;
use App\Services\common\CommonService;

class UserService
{
    private $code;
    private $grant_type = 'authorization_code';
    private $loginUrl = 'https://api.weixin.qq.com/sns/jscode2session';

    public static function wechatLogin($params)
    {
        $code = !empty($params['code']) ? $params['code'] : '';//小程序授权code
        $openid = !empty($params['openid']) ? $params['openid'] : '';//小程序授权code
        if (empty($code) && empty($openid)) {
            throw new UserException(['cus' => 0]);
        }


        //需要授权微信
        //if (empty($openid)) {
            $appid = \Yaf\Registry::get('config')->wechat->appid;
            $secret = \Yaf\Registry::get('config')->wechat->secret;
            $grant_type = 'authorization_code';
            $loginUrl = 'https://api.weixin.qq.com/sns/jscode2session'; 
            //请求接口，获取用户openid
            $params = [
                'appid' => $appid,
                'secret' => $secret,
                'js_code' => $code,
                'grant_type' => $grant_type,
            ];
            $response = (new Request())->post($loginUrl, $params);

            if ($response['code'] == 0) {
                $response = $response['response'];
            }

            if (empty($response) || array_key_exists('errcode', $response)) {
                //throw new \Exception('获取openid失败:' . $response['errcode']);
                throw new UserException(['cus' => 1]);
            }
            //检查系统是已注册
            $openid = !empty($response['openid']) ? $response['openid'] : ''; 
        //}


        $user = UserWechatBind::getRecord(['openid' => $openid]);
        //如果系统不存在，用户信息，则注册新用户
        if (empty($user) && !empty($response)) {
            $insert = [
                'openid' => !empty($response['openid']) ? $response['openid'] : '',
                'union_id' => !empty($response['unionid']) ? $response['unionid'] : '',
                'session_key' => !empty($response['session_key']) ? $response['session_key'] : '', //默认7200有效期
                'create_time' => date("Y-m-d H:i:s")
            ];

            $newWechatId = UserWechatBind::save($insert);
            if (!$newWechatId) {
                throw new UserException(['cus' => 2]);
            }

            $user['wechat_id'] = $newWechatId;
            $user['openid'] = $response['openid'];
            $user['session_key'] = $response['session_key'];
        }else{
            if (empty($user)) {
                throw new UserException(['cus' => 2]);
            }

            $insert = [
                'session_key' => !empty($response['session_key']) ? $response['session_key'] : '',
            ];
            
            $newWechatId = UserWechatBind::save($insert,['openid' => $openid]);
        }

        $user['third_session'] = self::generate3rdSession($openid);
        return $user;       
    }


    public static function bindPhone($params)
    {

        $openid = !empty($params['openid']) ? $params['openid'] : '';
        $encryptedData = !empty($params['encryptedData']) ? $params['encryptedData'] : '';
        $iv = !empty($params['iv']) ? $params['iv'] : '';        
        $appid = \Yaf\Registry::get('config')->wechat->appid;
 
        if (!$encryptedData) {
            throw new UserException(['cus' => 3]);
        }

        if (!$iv) {
            throw new UserException(['cus' => 4]);
        }

        $userInfo = UserWechatBind::getRecord(['openid' => $openid]);
        $sessionKey = !empty($userInfo['session_key']) ? $userInfo['session_key'] : '';
        $openid = isset($userInfo['openid']) && $userInfo['openid'] ? $userInfo['openid'] : '';
        if (empty($userInfo) || !$sessionKey || !$openid) {
            throw new UserException(['cus' => 5]);
        }

        
       

    
 
        //解密
        $decryptData = [];
        $wXBizDataCrypt = new WxBizDataCrypt($appid, $sessionKey);
        $errCode = $wXBizDataCrypt->decryptData($encryptedData, $iv, $decryptData);




        if ($errCode) {
            throw new UserException(['cus' => 6]);
        }

        // 手机号解密成功
        if (empty($decryptData['phoneNumber'])) {
            throw new UserException(['cus' => 7]);
        }

        $phoneNumber = strval($decryptData['phoneNumber']);

        //判断是否已
        $user = UserWechatBind::getRecord(['phone' => $phoneNumber]);
        if (!empty($user) &&  $openid != $user['openid']) {
            throw new UserException(['cus' => 9]);
        }

        $jwUser = (new JwUser ())->getUserInfo(['mobile' => $phoneNumber]);
        $userId = '';
        if (!empty($jwUser['data'])) {
            $data = $jwUser['data'];
            $userId = !empty($data['userId']) ? $data['userId'] : '';
        }
        //进行绑定
        $update = [
            'phone' => $phoneNumber,
            "update_time" => date("Y-m-d H:i:s"),
            'user_id' => $userId,
        ];
        $bindStatus = UserWechatBind::save($update,['wechat_id' => $userInfo['wechat_id']]);

        if (!$phoneNumber) {
            throw new UserException(['cus' => 8]);
        }

        CommonService::isNewUser($params);
        
        $isNewUser =  CommonService::isNewUser(['openid' => $openid]);
        if (!empty($isNewUser) && $isNewUser['is_new_user'] == 1) {
             $userInfo['is_pop_up'] = 1;
        }else{
            $userInfo['is_pop_up'] = 2;
        }

        $userInfo['user_id'] = $userId;
        $userInfo['phone'] = $phoneNumber;
        $userInfo['pop_up_text'] = "";
        return $userInfo;
    }


    public static function userWechatBind($params)
    {
     
        $data['wechat_id[>]'] = 0;

        if (!empty($params['openid'])) {
            $data['openid'] = $params['openid'];
        }

        if (!empty($params['user_id'])) {
            $data['user_id'] = $params['user_id'];
        }

        if (!empty($params['phone'])) {
            $data['phone'] = $params['phone'];
        }
        
        $userList = UserWechatBind::getRecords($data);
        return $userList;
    }


    public static function bindAvatar($params)
    {
        //进行绑定
        $update = [
            "update_time" => date("Y-m-d H:i:s"),
            'user_nick' => !empty($params['user_nick']) ? $params['user_nick'] : '',
            'user_avatar' =>!empty($params['user_avatar']) ? $params['user_avatar'] : '',
            'gender' => !empty($params['gender']) ? $params['gender'] : '',
            'country' => !empty($params['province']) ? $params['province'] : '',
            'province' => !empty($params['province']) ? $params['province'] : '',
            "city" => !empty($params['city']) ? $params['city'] : '',
            "language" => !empty($params['language']) ? $params['language'] : '',
        ];

        $bindStatus = UserWechatBind::save($update,['openid' => $params['openid']]);
        if (!$bindStatus) {
            throw new UserException(['cus' => 8]);
        }
        return $update;
    }

    private static function generate3rdSession($openid) {
        return md5(mt_rand() . $openid);
    }

}