<?php

namespace app\api\controller;

use think\Db;
use app\common\controller\Api;

/**
 * 用户接口
 */
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,
    })
     */
    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']
        ];
        $this->success('成功', $return);
    }

}