<?php

namespace app\api\controller;

use app\admin\model\Collection;
use app\admin\model\Free;
use app\admin\model\Rcoupon;
use app\admin\model\Registers;
use app\common\controller\Api;
use fast\Http;
use think\db\Query;
use think\Validate;
use think\Db;
use think\db\Expression;

/**
 * 个人中心接口
 */
class User extends Api
{
    //无需登录,*表都不需要
//    protected $noNeedLogin = ['login', 'mobilelogin'];
    protected  $noNeedLogin = ['login'];
    protected $noNeedRight = '*';
    protected $uid = '';
    public function _initialize()
    {
        parent::_initialize();
        $this->uid = $this->auth->getUserId();
    }

    /**
     * @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();
                        $data['nickname'] = $this->auth->emoji_decode($data['nickname']);
                        $this->success('登录成功', $data);
                    }else {
                        $this->error($this->auth->getError());
                    }
                } else {
                    $this->error("登录失败",$json);
                }
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (免费预约)
     * @ApiSummary  (免费预约)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/freeBook)
     * @ApiParams   (name="user_name", type="string", required=true, description="姓名")
     * @ApiParams   (name="mobile", type="number", required=true, description="手机号")
     * @ApiParams   (name="province", type="string", required=true, description="省")
     * @ApiParams   (name="city", type="string", required=true, description="市")
     * @ApiParams   (name="district", type="string", required=true, description="区")
     * @ApiParams   (name="address", type="string", required=true, description="详细地址")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1578555060",
        "data": null
    })
     */
    public function freeBook(){
        if($this->request->isPost()){
            $data = $this->request->post();
            //验证表数据
            $rule = config('verify.free_book');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            $freeModel = new Free();
            $data['uid'] = $this->uid;
            $res = $freeModel->create($data);
            if($res){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }else{
            $this->error('请求方式错误');
        }
    }

    /**
     * @ApiTitle    (会员注册)
     * @ApiSummary  (会员注册)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/user/userRegister)
     * @ApiParams   (name="user_name", type="string", required=true, description="姓名")
     * @ApiParams   (name="mobile", type="number", required=true, description="手机号")
     * @ApiParams   (name="province", type="string", required=true, description="省")
     * @ApiParams   (name="city", type="string", required=true, description="市")
     * @ApiParams   (name="district", type="string", required=true, description="区")
     * @ApiReturn({
        "code": 1,
        "msg": "成功",
        "time": "1578555060",
        "data": null
    })
     */
    public function userRegister(){
        if($this->request->isPost()){
            $data = $this->request->post();
            //验证表数据
            $rule = config('verify.user_register');
            $validate = new Validate($rule['rule'],$rule['msg']);
            if (!$validate->check($data)) {
                $this->error($validate->getError());
            }

            $registersModel = new Registers();
            $data['uid'] = $this->uid;
            //查询是否注册
            $res1 = Common::findWhereData('registers',['uid'=>$this->uid],'id');
            if($res1){
                $this->error('你已经注册过');
            }
            $res = $registersModel->create($data);
            if($res){
                $this->success('成功');
            }else{
                $this->error('失败');
            }
        }else{
            $this->error('请求方式错误');
        }
    }
}