<?php

namespace app\api\controller;

use Firebase\JWT\JWT;
use think\facade\Validate;
use think\facade\Config;
use app\common\library\Ems;
use app\common\library\Sms;
use app\api\BaseController;
use app\api\middleware\Auth;
use think\facade\Db;
use Firebase\JWT\Key;
/**
 * 会员接口.
 */
class User extends BaseController
{
    /**
     * 控制器中间件 [不需要鉴权]
     * @var array
     */
    protected $middleware = [
        Auth::class => ['except' 	=> ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'] ]
    ];


    /**
     * 会员中心.
     */
    public function index()
    {
        $user = Db::table('fa_user')->where('id',JWT_UID)->find();
        $user_msg = Db::table('fa_szxc_information_usermsg')->where('user_id',JWT_UID)->field('id,name,address_name,phone')->find();
        $this->apiSuccess('', [
            'nickname' => $user['nickname'],
            'phone'=>$user_msg['phone'],
            'avatar'=>$user['avatar'],
            'address_name'=>$user_msg['address_name'],
            'name'=>$user_msg['name']
        ]);
    }

    /**
     * 会员登录.
     *
     * @param string $account  账号
     * @param string $password 密码
     */
    public function login()
    {
        $account = $this->request->request('account');
        $password = $this->request->request('password');
        if (! $account || ! $password) {
            $this->apiError('参数不正确');
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->apiSuccess('Logged in successful', $data);
        } else {
            $this->apiError($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录.
     *
     * @param string $mobile  手机号
     * @param string $captcha 验证码
     */
    public function mobilelogin()
    {
        $param = get_params();
        if(empty($param['mobile']) || empty($param['captcha'])){
            $this->apiError('参数错误');
        }
        $mobile = $param['mobile'];
        $captcha = $param['captcha'];
        if (! $mobile ) {
            $this->apiError('参数不正确');
        }
        if (! Validate::regex($mobile, "^1\d{10}$")) {
            $this->apiError('手机格式不正确');
        }
//        if (! Sms::check($mobile, $captcha, 'mobilelogin')) {
//            $this->apiError('验证码错误'));
//        }

        $user = Db::table('fa_user')->where('mobile',$mobile)->find();
        if ($user) {
            if ($user['status'] != 'normal') {
                $this->apiError('账户已经被锁定');
            }
            //如果已经有账号则直接登录
            $token = self::getToken($user['id']);
            $data = [
                'prevtime' => time(),
                'loginip' => request()->ip(),
                'token' => $token
            ];
            $ret = Db::table('fa_user')->where(['id' => $user['id']])->update($data);
            add_user_log('api', '登录');

        } else {
            $ret = $this->reg($mobile,'123456');
        }
        if ($ret) {
//            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => Db::table('fa_user')->where(['id' => $user['id']])->field('id,id as user_id, username, nickname, mobile, avatar,score,group_id,token,createtime')->find()];
            $find=Db::table('fa_szxc_information_usermsg')->where('user_id',$user['id'])->find();
            $group=Db::table('fa_user_group')->where('id',$data['userinfo']['group_id'])->find();
            $data['userinfo']['group_name']=$group['name'];
            if ($find){
                $data['userinfo']['name']=$find['name'];
                $data['userinfo']['no_update']=0;
                $data['userinfo']['address_name']=$find['address_name'];
            }else{
                $data['userinfo']['no_update']=1;
                $data['userinfo']['address_name']='';
            }

            $this->apiSuccess('登录成功', $data);
        } else {
            $this->apiError('登录失败');
        }
    }

    /**
     * @param $user_id
     * @return string
     */
    public function getToken($user_id){
        $time = time(); //当前时间
        $conf = $this->jwt_conf;
        $token = [
            'iss' => $conf['iss'], //签发者 可选
            'aud' => $conf['aud'], //接收该JWT的一方,可选
            'iat' => $time, //签发时间
            'nbf' => $time-1 , //(Not Before):某个时间点后才能访问,比如设置time+30,表示当前时间30秒后才能使用
            'exp' => $time+$conf['exptime'], //过期时间,这里设置2个小时
            'data' => [
                //自定义信息,不要定义敏感信息
                'userid' =>$user_id,
            ]
        ];
        return JWT::encode($token, $conf['secrect'], 'HS256'); //输出Token  默认'HS256'
    }

    /**
     * @api {post} /index/reg 会员注册
     * @apiDescription  系统注册接口,返回是否成功的提示,需再次登录

     * @apiParam (请求参数:) {string}             username 用户名
     * @apiParam (请求参数:) {string}             password 密码

     * @apiSuccessExample {json} 成功示例
     * {"code":0,"msg":"注册成功","time":1627375117,"data":[]}
     * @apiErrorExample {json} 失败示例
     * {"code":1,"msg":"该账户已经存在","time":1627374899,"data":[]}
     */
    public function reg($mobile,$pwd)
    {
        $param = [];
        if($mobile || $pwd){
            $this->apiError('参数错误');
        }
        $user = Db::table('fa_user')->where(['username' => $mobile])->find();
        if (!empty($user)) {
            $this->apiError('该账户已经存在');
        }
        $param['salt'] = set_salt(20);
        $param['password'] = set_password($param['pwd'], $param['salt']);
        $param['register_time'] = time();
        $param['headimgurl'] = '/static/admin/images/icon.png';
        $param['register_ip'] = request()->ip();
        $char = mb_substr($mobile, 0, 1, 'utf-8');
        $uid = Db::table('fa_user')->strict(false)->field(true)->insertGetId($param);
        if($uid){
            add_user_log('api', '注册');
            return true;
        }else{
            return false;
        }
    }

    /**
     * 注册会员.
     *
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $email    邮箱
     * @param string $mobile   手机号
     * @param string $code   验证码
     */
    public function register()
    {
        $username = $this->request->request('username');
        $password = $this->request->request('password');
        $email = $this->request->request('email');
        $mobile = $this->request->request('mobile');
        $code = $this->request->request('code');
        if (! $username || ! $password) {
            $this->apiError('参数不正确');
        }
        if ($email && ! Validate::is($email, 'email')) {
            $this->apiError('Email is incorrect');
        }
        if ($mobile && ! Validate::regex($mobile, "^1\d{10}$")) {
            $this->apiError('手机格式不正确');
        }
        $ret = Sms::check($mobile, $code, 'register');
        if (!$ret) {
            $this->apiError('Captcha is incorrect');
        }
        if (empty($email)) {
            $email = $username;
        }
        if (empty($mobile)) {
            $mobile = $username;
        }
        $ret = $this->auth->register($username, $password, $email, $mobile, []);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->apiSuccess('Sign up successful', $data);
        } else {
            $this->apiError($this->auth->getError());
        }
    }

    /**
     * 注销登录.
     */
    public function logout()
    {
        $this->auth->logout();
        $this->apiSuccess('Logout successful');
    }

    /**
     * 修改会员个人信息.
     *
     * @param string $avatar   头像地址
     * @param string $username 用户名
     * @param string $nickname 昵称
     * @param string $bio      个人简介
     */
    public function profile()
    {
        $user = Db::table('fa_user')->where(['id' => JWT_UID])->find();
//        $username = $this->request->request('username');
        $params = get_params();
        $nickname = $params['nickname'];
//        $bio = $this->request->request('bio');
        $avatar = $params['avatar'];
//        if ($username) {
//            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
//            if ($exists) {
//                $this->apiError('Username already exists'));
//            }
//            $user->username = $username;
//        }
        if($nickname){
            $data['nickname'] = $nickname;
        }
        if($avatar){
            $data['avata'] = $avatar;
        }
//        $user->bio = $bio;
//        $user->save();
        if($data){
            Db::table('fa_user')->where(['id' => JWT_UID])->update($data);
        }
        $user = Db::table('fa_user')->where(['id' => JWT_UID])->find();
        $new_user['nickname'] = $user['nickname'];
        $new_user['avatar'] = $user['avatar'];
        $this->apiSuccess('修改成功',$new_user);
    }

    /**
     * 修改邮箱.
     *
     * @param string $email   邮箱
     * @param string $captcha 验证码
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->request('captcha');
        if (! $email || ! $captcha) {
            $this->apiError('参数不正确');
        }
        if (! Validate::is($email, 'email')) {
            $this->apiError('Email is incorrect');
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->apiError('Email already exists');
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (! $result) {
            $this->apiError('Captcha is incorrect');
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->apiSuccess();
    }

    /**
     * 修改手机号.
     *
     * @param string $mobile   手机号
     * @param string $captcha 验证码
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->request('mobile');
        $captcha = $this->request->request('captcha');
        if (! $mobile || ! $captcha) {
            $this->apiError('参数不正确');
        }
        if (! Validate::regex($mobile, "^1\d{10}$")) {
            $this->apiError('手机格式不正确');
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->apiError('Mobile already exists');
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (! $result) {
            $this->apiError('Captcha is incorrect');
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->apiSuccess();
    }

    /**
     * 第三方登录.
     *
     * @param string $platform 平台名称
     * @param string $code     Code码
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->request('platform');
        $code = $this->request->request('code');
        $config = get_addon_config('third');
        if (! $config || ! isset($config[$platform])) {
            $this->apiError('参数不正确');
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result,
                ];
                $this->apiSuccess('Logged in successful', $data);
            }
        }
        $this->apiError('Operation failed', $url);
    }

    /**
     * 重置密码
     *
     * @param string $mobile      手机号
     * @param string $newpassword 新密码
     * @param string $captcha     验证码
     */
    public function resetpwd()
    {
        $type = $this->request->request('type');
        $mobile = $this->request->request('mobile');
        $email = $this->request->request('email');
        $newpassword = $this->request->request('newpassword');
        $captcha = $this->request->request('captcha');
        if (! $newpassword || ! $captcha) {
            $this->apiError('参数不正确');
        }
        if ($type == 'mobile') {
            if (! Validate::regex($mobile, "^1\d{10}$")) {
                $this->apiError('手机格式不正确');
            }
            $user = \app\common\model\User::where('mobile',$mobile)->find();
            if (! $user) {
                $this->apiError('User not found');
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (! $ret) {
                $this->apiError('Captcha is incorrect');
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (! Validate::is($email, 'email')) {
                $this->apiError('Email is incorrect');
            }
            $user = \app\common\model\User::where('email',$email)->find();
            if (! $user) {
                $this->apiError('User not found');
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (! $ret) {
                $this->apiError('Captcha is incorrect');
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->apiSuccess('Reset password successful');
        } else {
            $this->apiError($this->auth->getError());
        }
    }

//    用户实名认证
    public function realname(){
        $params = get_params();
        $uid = JWT_UID;
        $params['user_id'] = $uid;
        $is_have = Db::table('cms_szxc_user_authentication')->where('user_id',$uid)->find();

        $adds=Db::table('fa_szxc_information_useraddress')->where('user_id',JWT_UID)->find();
        $params['area_id']=$adds['area_id'];
        $params['street_id']=$adds['street_id'];
        $params['village_id']=$adds['village_id'];

        if($is_have){
            if($is_have['status'] == 0){
                $this->apiError('您的实名认证正在审核中','您的实名认证正在审核中');
            }elseif ($is_have['status'] == 1){
                $this->apiError('您的实名认证已通过','您的实名认证已通过');
            }elseif ($is_have['status'] == 2){
                $params['status'] = 0;
                $params['create_time'] = time();
                $res = Db::table('cms_szxc_user_authentication')->where('user_id',$uid)->strict(false)->field(true)->update($params);
                if($res){
                    $this->apiSuccess('提交成功');
                }else {
                    $this->apiError('提交失败');
                }
            }else{
                $this->apiError('数据出错了','数据出错了');
            }
        }else{
            $params['create_time'] = time();
            $res = Db::table('cms_szxc_user_authentication')->strict(false)->field(true)->insert($params);
            if($res){
                $this->apiSuccess('提交成功');
            }else {
                $this->apiError('提交失败');
            }
        }
    }

//    获取实名认证信息
    public function get_shiming(){
        $uid = JWT_UID;
        $is_have = Db::table('cms_szxc_user_authentication')->where('user_id',$uid)->find();
        if($is_have){
            $this->apiSuccess('获取成功',$is_have);
        }else{
            $this->apiError('您还没有提交实名认证','您还没有提交实名认证');
        }
    }

    //    获取后台账号信息
    public function get_backstage(){
        $uid = JWT_UID;
        $admin = Db::table('cms_admin')->where('user_id',$uid)->find();
        if($admin){
            $data['url'] = 'https://nk.lihaink.cn';
            $data['username'] = $admin['username'];
            $pwd = set_password('123456', $admin['salt']);
            if($pwd == $admin['pwd']){
                $data['pwd'] = '123456';
            }else{
                $data['pwd'] = '密码已改';
            }
            $this->apiSuccess('获取成功',$data);
        }else{
            $this->apiError('没有后台权限','没有后台权限');
        }
    }


}