<?php

namespace app\api\controller;

use app\api\model\StudyScore;
use app\common\controller\Api;
use app\common\library\Auth;
use EasyWeChat\Factory;
use fast\Http;
use think\Config;
use think\Db;

/**
 * 个人中心
 * @ApiWeigh    (99)
 */
class User extends Api
{
    protected $noNeedLogin = ['login'];
    protected $noNeedRight = ['*'];

    /**
     *手机号授权登录
     *
     * @ApiTitle    (手机号授权登录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/myinfo/login)
     * @ApiParams   (name="code", type="string", required=true, description="code-wx.login的code")
     * @ApiParams   (name="encryptedData", type="string", required=true, description="encryptedData")
     * @ApiParams   (name="iv", type="string", required=true, description="iv")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    'data':[
    'id':'用户id'
    'nickname':'用户昵称'
    'mobile':'手机号'
    'avatar':'头像'
    'token':'token']
    })
     */
    public function login(){
        //接收传递信息
        $config = Config::get('wechat');
        $encryptedData = $this->request->post('encryptedData');
        $iv = $this->request->post('iv');
        $code = $this->request->post('code');
        if(empty($code)){
            $this->error('参数错误');
        }
        $params = [
            'appid'=>$config['app_id'],         //小程序appid
            'secret'=>$config['secret'],        //小程序appid的秘钥
            'js_code'=>$code,                   //前端传来的code
            'grant_type' => 'authorization_code'    //authorization_code — 授权码模式(即先登录获取code,再获取token)
        ];
        $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');//接口
        if($result['ret']){
            $json = json_decode($result['msg'],true);  //json_decode()接收一个json格式数据将他变为php变量
            if(isset($json['openid'])){
                $options = [
                    'debug'=>true,
                    'app_id'=>$config['app_id'],
                    'secret'=>$config['secret'],
                    'token'=>$this->auth->getToken(), //获取token
                    'log' => [
                        'level' => 'debug',
                        'file' =>'/tmp/easywechat.log',
                    ],
                ];
                $sessionKey = $json['session_key'];
                $app = Factory::miniProgram($options);
                try {
                    $phone = $app->encryptor->decryptData($sessionKey,$iv,$encryptedData);
                }catch (\Exception $e){
                    $this->error('网络不好,重新操作');
                }
                if (isset($phone['phoneNumber'])){
                    $userId = Db::name('third')->where(['apptype'=>'wxapp','openid'=>$json['openid']])->value('user_id');
                    $auth = Auth::instance();
                    $ret = $auth->direct($userId);
                    if ($ret){  //假如登录上后获取信息
                        $data = $auth->getUserinfo();
                        $aut = \db('user')->where('id',$userId)->find();
                        $data['avatar'] = cdnurl($data['avatar']);  //cdnurl第三方存储
                        $data['mobile'] = $aut['mobile'];
                        $this->success('登录成功',$data);
                    }elseif(empty($ret)){
                        /*注册一个用户*/
                        $data = [
                            'nickname' => '微信用户',
                            'username' => '微信用户',
                            'avatar' => '/assets/img/avatar.png',
                            'status' => 'normal',
                            'mobile' => $phone['phoneNumber'],
                            'jointime'=>time()
                        ];
                        //插入user
                        $id = \db('user')->insertGetId($data);
                        //插入third
                        \db('third')->insert(['user_id' => $id, 'apptype' => 'wxapp', 'openname' => '微信用户',
                            'access_token' => $json['session_key'], 'openid' => $json['openid']]);
                        $userId = Db::name('third')->where(['apptype'=> 'wxapp', 'openid'=>$json['openid']])->value('user_id');
                        $auth = Auth::instance();
                        $ret = $auth->direct($userId);
                        if ($ret){
                            $data = $auth->getUserinfo();
                            $aut = \db('user')->where('id',$userId)->find();
                            $data['avatar'] = cdnurl($data['avatar']);
                            $data['mobile'] = $aut['mobile'];
                            $this->success('登录成功',$data);
                        }else{
                            $this->error('连接失败');
                        }
                    }
                }else{
                    $this->error('手机号未找到,请重新输入');
                }
            }else{
                $this->error('获取openid失败');
            }
        }else{
            $this->error('请求失败');
        }

    }

    /**
     * @ApiTitle (我的首页)
     * @ApiMethod (POST)
     * @ApiReturn   ({"code":状态码,
    "msg":"提示信息"
    "time": "时间戳",
    "data": "返回数据",
    })
     */
    public function index()
    {
        $user = $this->auth->getUserinfo();
        $phone = \db('user')->where('id', $user['id'])->value('teach_phone');
        $data = [];
        if ($user['mobile'] == $phone) {
            //老师
            $data['hd'] = '活动现场';
        }
        $data['xh'] = "输入学号绑定信息";
        $data['sm'] = "扫码绑定信息";
        $this->success('',$data);
    }


    /**
     * @ApiTitle    (积分明细)
     * @ApiSummary  (积分明细)
     * @ApiMethod (POST)
     * @ApiParams   (name="row", type="string", required=false, description="显示多少行[非必填]")
     * @ApiParams   (name="page", type="string", required=false, description="当前页[非必填]")
     * @ApiReturn   ({
    "code":"状态码",
    "msg": "提示消息",
    "data": {
    "study_info": 学生信息{
    "earn_score": "总得分",
    "id": "学生id"
    },
    "score": 积分明细{
    "total": 23,
    "per_page": 10,
    "current_page": 1,
    "last_page": 3,
    "data": [
    {
    "score": "所获积分",
    "memo": "加分备注",
    "createtime": null
    "date": "得分时间"
    },}
    })
     */
    public function getScoreDetail()
    {
        $row = $this->request->param('row');
        $page = $this->request->param('page');
        $row = $row ? $row : 10;
        $page = $page ? $page : 1;
        $user = $this->auth->getUserinfo();
        $data['study_info'] = \db('study')->where('user_id', $user['id'])->field('earn_score,id')->find();
        if (empty($data['study_info']['id'])) {
            $this->error('您当前还未绑定学生', ['status' => 2]);
        }
        $where = ['study_id' => $data['study_info']['id']];
        $data['score'] = \db('study_score_log')
            ->where($where)
            ->field('score,memo,createtime')
            ->paginate($row, false, ['pages' => $page])
            ->each(function ($item, $key) {
                $item['date'] = date('Y-m-d H:i:s', $item['createtime']);
                return $item;
            });
        $this->success('获取成功', $data);
    }

    /**
     * @ApiTitle (用户协议)
     * @ApiMethod (POST)
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn   ({"code":状态码,
    "msg":"提示信息"
    "time": "时间戳",
    "data": "返回数据",
    })
     */
    public function getPolicy()
    {
        $data = Config::get('site.privacy_policy');
        if (!$data) {
            $this->error('暂无内容', ['status' => 2]);
        }
        $this->success('获取成功',$data);
    }


    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }
}