<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Random;
use think\Db;
use think\Validate;
use fast\Http;

/**
 * 个人中心
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';

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

    /**
     * @ApiTitle    (小程序登录)
     * @ApiSummary  (小程序登录)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/login)
     * @ApiParams   (name="code", type="string", required=true, description="小程序code")
     * @ApiParams   (name="nickname", type="string", required=true, description="小程序昵称")
     * @ApiParams   (name="avatar", type="string", required=true, description="小程序头像")
     * @ApiReturn({
    "code": 1,
    "msg": "登录成功",
    "time": "1553839125",
    "data": {
    "token": "677afb39-1a4f-4492-84d3-0bcf32016b8a",//token
    "user_id": 27,//用户id
    "createtime": 1553839125,//登录时间
    "expiretime": 1556431125,//token失效时间
    "expires_in": 2592000//token失效剩余时间(单位s)
    "openid": 1485212522522//openid
    })
     */
    public function login(){
        if($this->request->isPost()){
            //小程序配置
            $config =  config('verify.raw');
            //小程序传递数据,包含昵称,头像,code
            $raw_data = $this->request->post();
            //验证表数据
            $rule = config('verify.user');
            $validate = new Validate($rule['rule'],$rule['msg']);//
            if (!$validate->check($raw_data)) {
                $this->error($validate->getError());
            }
            $params = [
                'appid'      => $config['app_id'],
                'secret'     => $config['secret'],
                'js_code'    => $raw_data['code'],
                'grant_type' => 'authorization_code'
            ];
            $result = Http::sendRequest("https://api.weixin.qq.com/sns/jscode2session", $params, 'GET');
            if ($result['ret']) {
                $json = (array)json_decode($result['msg'], true);
                if (isset($json['openid'])) {
                    $result = [
                        'openid' => $json['openid'],
                        'nickname' => $raw_data['nickname'],
                        'avatar' => $raw_data['avatar']
                    ];
                    $ret = $this->auth->login($result);
                    if ($ret) {
                        $data = $this->auth->getUserinfo();
                        $this->success('登录成功', $data);
                    }else {
                        $this->error($this->auth->getError());
                    }
                } else {
                    $this->error("登录失败",$json);
                }
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (首页)
     * @ApiSummary  (首页)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/index)
     * @ApiHeaders  (name=token, type=string, required=true, description="请求的Token")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功'
    })
     */
    public function index()
    {
        $data = Db::name('video')
            ->field('id,thumbnail')
            ->order('id desc')
            ->limit('1')
            ->find();
        $this->success('SUCCESS',$data);
    }

}