<?php

namespace app\api\controller;

use app\common\controller\Api;
use addons\third\library\Wechat;
use think\Db;

define('ak', 'wx76ddffb14a62a7c9');
define('sk', 'fbeab9821d11b6c03402ee419f93618f');
//define('ak', 'wx3b1935a9955e6e56');
//define('sk', '32e1840b3526ff6534bb7f454d7f6fdc');

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

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

    /**
     * 用户接口
     * @ApiTitle    (公众号授权URL)
     * @ApiSummary  (公众号授权URL)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/User/UserInfo)
     * @ApiParams   (name="url", type="string", required=true, description="url")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturn   ({
    'code':'1',
    'msg':'返回成功',
    "data": {
    "url": "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx44ef84b1965a7fd4&redirect_uri=http%3A%2F%2Fshiyong.tvue.brofirst.cn&response_type=code&scope=snsapi_userinfo&state=75cfa074433a6021254eb081f60c4616#wechat_redirect"
    }
    })
     */
    public function UserInfo()
    {
        $callback = input('url');
        $config['app_id'] = ak;
        $config['app_secret'] = sk;
        $config['callback'] = $callback;
        $config['scope'] = 'snsapi_userinfo';
        $Wechat = new Wechat($config);
        $return['url'] = $Wechat->getAuthorizeUrl();
        $this->success('', $return);
    }


    /**
     * 用户接口
     * @ApiTitle    (公众号授权)
     * @ApiSummary  (公众号授权)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/User/UserCode)
     * @ApiParams   (name="code", type="string", 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": {
    }
    })
     */
    public function UserCode()
    {
        $code = input('code');
        $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid=' . ak . '&secret=' . sk . '&code=' . $code . '&grant_type=authorization_code';
        $token = json_decode(file_get_contents($token_url));
        $opendid = $token->openid;
        $access_token = $token->access_token;
        $info_url = 'https://api.weixin.qq.com/sns/userinfo?access_token=' . $access_token . '&openid=' . $opendid . '⟨=zh_CN';
        $info = json_decode(file_get_contents($info_url));
        if (empty($info)) {
            $this->error('登录失败');
        } else {
            $UserInfo['nickname'] = $info->nickname;
            $UserInfo['openid'] = $info->openid;
            $UserInfo['avatar'] = $info->headimgurl;
            $IsHaveUser = Db::name('user')->where(['openid' => $UserInfo['openid']])->find();
            if (empty($IsHaveUser)) {
                $data = [
                    'nickname' => $UserInfo['nickname'],
                    'openid' => $UserInfo['openid'],
                    'avatar' => $UserInfo['avatar'],
                    'money' => 0,
                    'status' => 0,
                    'createtime' => time(),
                    'updatetime' => time(),
                ];
                Db::name('user')->insert($data);
            }
            //是否拉黑
            $Status = Db::name('user')->where(['openid' => $UserInfo['openid']])->value('status');
            if ($Status == 1) {
                $this->error('您已被拉黑', 0, 99998);
            }
            $Token = $this->request->token();
            $res = Db::name('user')->where(['openid' => $UserInfo['openid']])->update(['token' => $Token, 'updatetime' => time(),]);
            if ($res) {
                $data = [
                    'Token' => $Token,
                    'Avatar' => $UserInfo['avatar'],
                    'Nickname' => $UserInfo['nickname']
                ];
                $this->success('成功', $data);
            } else {
                $this->error('失败', 0);
            }
        }
    }


    /**
     * 用户接口
     * @ApiTitle    (商家登陆)
     * @ApiSummary  (商家登陆)
     * @ApiMethod   (POST)
     * @ApiRoute    (/api/User/SellerLogin)
     * @ApiParams   (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams   (name="password", 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": "6eadbd2b95c0a1490efd71ee2f0579be",  //token
    "Title": "鑫茂店", //店铺名称
    "Image": "http://www.obituaries.com/uploads/20201208/eaea75b1acab02914d319e7ba932f5ce.png" //店铺图
    }
    })
     */
    public function SellerLogin()
    {
        $Params = $this->request->param();
        $SellerInfo = Db::name('seller')->where('mobile', $Params['mobile'])->find();
        if (empty($SellerInfo)) {
            $this->error('用户名不存在', 0);
        } else {
            if ($Params['password'] != $SellerInfo['password']) {
                $this->error('密码不正确', 0);
            }
            $Token = $this->request->token();
            $res = Db::name('seller')->where('mobile', $Params['mobile'])->update(
                [
                    'token' => $Token
                ]
            );
            if (!$res) {
                $this->error('登陆失败', 0);
            }
            $data = [
                'Token' => $Token,
                'Title' => $SellerInfo['title'],
                'Image' => $this->ImgUrl($SellerInfo['image'])
            ];
            $this->success('成功', $data);
        }
    }


}