<?php

namespace app\api\controller;

use EasyWeChat\Foundation\Application;
use think\Db;
use app\common\controller\Api;
use think\Request;

/**
 * 用户接口
 */
class User extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }


    /**
     * @ApiTitle    (用户登陆)
     * @ApiSummary  (用户登陆)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/User/UserLogin)
     * @ApiParams   (name="code", type="integer", required=true, description="Code")
     * @ApiParams   (name="nickname", type="string", required=true, description="微信名")
     * @ApiParams   (name="avatar", type="string", required=true, description="头像")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    'data':{
    'token' : token,
    'BindMobile':0=未绑定,1=已绑定
    })
     */
    public function UserLogin()
    {
        $param = $this->request->param();
//        授权登录
        $ch = curl_init();
        $appid = "wx6a9080f20326f817";
        $secret = "8fe9780e13dd1fa64b886c4f716cd366";
        $code = $param['code'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $output = curl_exec($ch);
        if ($output === FALSE) {
            echo "CURL Error:" . curl_error($ch);
        }
        curl_close($ch);
        $curl_result = json_decode($output, true);
        $openid = $curl_result['openid'];
        $is_open = Db::name('user')->where(['openid' => $openid])->find();
        if (empty($is_open)) {
            $data = [
                'openid' => $openid,
                'updatetime' => time(),
                'createtime' => time(),
                'avatar' => $param['avatar'],
                'nickname' => $param['nickname'],
            ];
            Db::name('user')->insert($data);
        }
        $token = $this->request->token();
        $arr = [
            'nickname' => $param['nickname'],
            'avatar' => $param['avatar'],
            'token' => $token,
            'updatetime' => time(),
        ];
        $res = Db::name("user")->where(['openid' => $openid])->update($arr);
        if (!$res) {
            $this->error('授权失败', 0);
            die;
        }
        $rult = Db::name("user")->where(['openid' => $openid])->find();
        $return = [
            'token' => $rult['token'],
            'avatar' => $param['avatar'],
            'nickname' => $param['nickname'],
            'BindMobile' => $rult['mobile'] == "" ? 0 : 1
        ];
        $this->success('成功', $return);
    }


    /**
     * @ApiTitle    (Code换token)
     * @ApiSummary  (Code换token)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/User/UserCode)
     * @ApiParams   (name="code", type="integer", required=true, description="Code")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    'data':{
    'token' => token,
    })
     */
    public function UserCode()
    {
        $param = $this->request->param();
//        授权登录
        $ch = curl_init();
        $appid = "wx6a9080f20326f817";
        $secret = "8fe9780e13dd1fa64b886c4f716cd366";
        $code = $param['code'];
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $output = curl_exec($ch);
        if ($output === FALSE) {
            echo "CURL Error:" . curl_error($ch);
        }
        curl_close($ch);
        $curl_result = json_decode($output, true);
        $openid = $curl_result['openid'];
        $is_open = Db::name('user')->where(['openid' => $openid])->find();
        if (empty($is_open)) {
            $this->error('请先注册授权', '', 99991);
        } else {
            $token = $this->request->token();
            $arr = [
                'token' => $token,
                'updatetime' => time(),
            ];
            $res = Db::name("user")->where(['openid' => $openid])->update($arr);
            if (!$res) {
                $this->error('Token更新失败', 0);
                die;
            }
            $rult = Db::name("user")->where(['openid' => $openid])->find();
            $this->success('成功', ['token' => $token, 'BindMobile' => $rult['mobile'] == "" ? 0 : 1]);
        }
    }


    /**
     * 用户接口
     * @ApiTitle    (绑定手机号)
     * @ApiSummary  (绑定手机号)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/User/BindMobile)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams   (name="vi", type="string", required=true, description="vi")
     * @ApiParams   (name="encryptData", type="string", required=true, description="encryptData")
     * @ApiParams   (name="code", type="string", required=true, description="code")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    })
     */
    public function BindMobile()
    {
        $UserId = $this->IsToken($this->request->header());
        $params = Request::instance()->post(false);
        $options = [
            // ...
            'mini_program' => [

                'app_id' => 'wx6a9080f20326f817',
                'secret' => '8fe9780e13dd1fa64b886c4f716cd366',
                'token' => 'component-token',
                'aes_key' => 'component-aes-key'
            ],
            // ...
        ];
        $app = new Application($options);
        $miniProgram = $app->mini_program;
        $sessionKey = $miniProgram->sns->getSessionKey($params['code']);
        $Json = $miniProgram->encryptor->decryptData($sessionKey['session_key'], urldecode($params['iv']), urldecode($params['encryptData']));
       dump($Json);
       die;
        $Mobile = $Json['phoneNumber'];
        $Res = Db::name('user')->where('id', $UserId)->update(['mobile' => $Mobile, 'updatetime' => time()]);
        if ($Res) $this->success('绑定成功', 1);
        else $this->error('绑定失败', 0);
    }

}