<?php

namespace app\api\controller;

use app\api\model\Ticket;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Http;
use fast\Random;
use think\Db;
use think\Validate;
use wxapp\aes\WXBizDataCrypt;

/**
 * 授权接口
 */
class User extends Api
{
    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * @ApiTitle    (获取sessionKey和openid)
     * @ApiSummary  (获取sessionKey和openid)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/getSessionKey)
     * @ApiParams   (name="code", type="string", required=true, description="小程序code")
     * @ApiReturn({
    "code": 1,
    "msg": "获取成功",
    "time": "1553839125",
    "data": {
    "session_key": "session_key",//token
    "openid": "openid",//openid
    },
    })
     */
    public function getSessionKey()
    {
        $validate = new Validate([
            'code' => 'require',
        ]);

        $validate->message([
            'code.require' => '缺少参数code!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error(['code' => '40003', 'msg' => $validate->getError()]);
        }

        $code = $data['code'];
        $appId = config('app_id');
        $appSecret = config('app_secret');

        $response = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code");

        if (!empty($response['errcode'])) {
            $this->error('操作失败',$response['errcode']);
        }
        $this->success('获取成功', json_decode($response['msg'],true));
    }

    /**
     * @ApiTitle    (小程序登录注册)
     * @ApiSummary  (小程序登录注册)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/login)
     * @ApiParams   (name="openid", type="string", required=true, description="openid")
     * @ApiParams   (name="session_key", type="string", required=true, description="session_key")
     * @ApiParams   (name="encrypted_data", type="string", required=true, description="encrypted_data")
     * @ApiParams   (name="iv", type="string", required=true, description="iv")
     * @ApiParams   (name="user_id", type="string", required=false, description="分享人id")
     * @ApiReturn({
    "code": 1,
    "msg": "登陆成功",
    "time": "1553839125",
    "data": {
    "token": "token",//登录唯一标识
    },
    })
     */
    public function login()
    {
        $validate = new Validate([
            'openid' => 'require',
            'session_key' => 'require',
            'encrypted_data' => 'require',
            'iv' => 'require',
        ]);

        $validate->message([
            'openid.require' => '缺少参数openid!',
            'session_key.require' => '缺少参数session_key!',
            'encrypted_data.require' => '缺少参数encrypted_data!',
            'iv.require' => '缺少参数iv!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error(['code' => '40003', 'msg' => $validate->getError()]);
        }

        $appId = config('app_id');

        $openid = $data['openid'];
        $sessionKey = $data['session_key'];

        $pc = new WXBizDataCrypt($appId, $sessionKey);
        $errCode = $pc->decryptData($data['encrypted_data'], $data['iv'], $wxUserData);

        if ($errCode != 0) {
            $this->error('检验数据失败!!', ['errCode' => $errCode, 'param' => $data]);
        }

        $findThirdPartyUser = Db::name("third")
            ->where('openid', $openid)
            ->where('app_id', $appId)
            ->find();

        $currentTime = time();
        $ip = $this->request->ip(0, true);

        $wxUserData['sessionKey'] = $sessionKey;
        unset($wxUserData['watermark']);

        if ($findThirdPartyUser) {
            $token = generate_user_token($findThirdPartyUser['user_id']);
            //判断是否绑定上级
//            $userInfo = Db::name('user')->where('id',$findThirdPartyUser['user_id'])->find();
//            if (!empty($data['user_id']) && !$userInfo['pid']){
//                //绑定上级
//                Db::name('user')->where('id',$findThirdPartyUser['user_id'])->update(['pid'=>$data['user_id']]);
//                $userModel = new \app\api\model\User();
//                $ticketModel = new Ticket();
//                $ticket = $ticketModel->where('setting_share',1)->select();
//                //发放优惠券
//                if ($ticket) $userModel->grantTicket([$data['user_id'],$findThirdPartyUser['user_id']],$ticket);
//            }

            $userData = [
                'loginip' => $ip,
                'logintime' => $currentTime,
                'login_times' => Db::raw('login_times+1'),
                'more' => json_encode($wxUserData)
            ];

            if (isset($wxUserData['unionId'])) {
                $userData['union_id'] = $wxUserData['unionId'];
            }

            Db::name("third")
                ->where('openid', $openid)
                ->where('app_id', $appId)
                ->update($userData);

            $this->success("登录成功!", ['token' => $token]);
        } else {

            Db::startTrans();
            $userId = Db::name("user")->insertGetId([
                'status'     => 'normal',
                'gender'     => $wxUserData['gender'],
                'nickname'   => $wxUserData['nickName'],
                'avatar'     => $wxUserData['avatarUrl'],
                'joinip'     => $ip,
                'jointime'   => $currentTime,
                'createtime' => $currentTime,
                'updatetime' => $currentTime,
                'loginip'    => $ip,
                'logintime'  => $currentTime,
                'pid'  => !empty($data['user_id'])?$data['user_id']:'',
            ]);

            if(empty($userId)){
                Db::rollback();
                $this->error('sql执行失败');
            }

            if (!empty($data['user_id'])){
                $userModel = new \app\api\model\User();
                $ticketModel = new Ticket();
                $ticket = $ticketModel->where('setting_share',1)->select();
                //发放优惠券
                if ($ticket)  $userModel->grantTicket([$data['user_id'],$userId],$ticket);
            }

            $row = Db::name("third")->insert([
                'openid'          => $openid,
                'user_id'         => $userId,
                'nickname'        => $wxUserData['nickName'],
                'app_id'          => $appId,
                'loginip'         => $ip,
                'union_id'        => '',
                'logintime'       => $currentTime,
                'createtime'      => $currentTime,
                'login_times'     => 1,
                'more'            => json_encode($wxUserData)
            ]);

            if ($userId && $row) {
                Db::commit();
                $token = generate_user_token($userId);
                $this->success("登录成功!", ['token' => $token]);
            } else {
                Db::rollback();
                $this->error('登录失败');
            }

        }

    }
    /**
     * @ApiTitle    (通过code获取token)
     * @ApiSummary  (通过code获取token)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/getToken)
     * @ApiParams   (name="code", type="string", required=true, description="code")
     * @ApiReturn({
    "code": 1,
    "msg": "SUCCESS",
    "time": "1553839125",
    "data": {
    "token": "token",//登录唯一标识
    },
    })
     */
    public function getToken(){
        $validate = new Validate([
            'code'           => 'require',
        ]);

        $validate->message([
            'code.require'           => '缺少参数code!',
        ]);

        $data = $this->request->param();
        if (!$validate->check($data)) {
            $this->error(['code'=>'40003','msg'=>$validate->getError()]);
        }

        $code      = $data['code'];
        $appId     = config('app_id');
        $appSecret = config('app_secret');

        $response = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session?appid=$appId&secret=$appSecret&js_code=$code&grant_type=authorization_code");
        $code = json_decode($response['msg'], true);
        print_r($code);
        if (!empty($code['errcode'])) {
            $this->error('操作失败:',$code['errcode']);
        }

        $third = Db::name('third')->where(['openid'=>$code['msg']['openid']])->find();
        if(empty($third)){
            $this->error('查无此人');
        }
        $user_token = Db::name('user_token')->where('user_id',$third['user_id'])->find();
        $data['token'] = $user_token['token'];
        $this->success('SUCCESS',$data);
    }
}