<?php

namespace app\api\controller;

use app\api\service\TokenService;
use app\api\service\UserService;
use app\api\service\UtilService;
use app\api\validate\UserValidate;
use app\BaseController;
use app\Request;
use app\model\project\User as userModel;
use think\exception\ValidateException;
use think\facade\Cache;

class User extends BaseController
{

    public function login(Request $request)
    {

        $vo = (new UserValidate())->goCheck(['mobile', 'password']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();
        $user = userModel::where(['mobile' => $data['mobile']])->where('is_del', 0)->find();
        if (!$user) {
            return $this->returnMsg('用户不存在', 0);
        }

        $data['password'] = md5($data['password'] . $user['salt']);
        if ($data['password'] != $user['password']) {
            return $this->returnMsg('密码不正确', 0);
        }
        if ($user['status'] != 1) {
            return $this->returnMsg('账号禁止登录', 0);
        }

        $token = TokenService::generateToken($user['id'], $user->toArray());

        $update['token'] = $token;
        $update['last_login_time'] = time();
        userModel::where(['id' => $user['id']])->update($update);

        return $this->returnMsg('操作成功', 1, ['token' => $token, 'expires_in' => TokenService::EXPIRE]);


    }


    public function register(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['name', 'mobile', 'password', 'code', 'role', 'password2']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();

        $is_exit = userModel::where(['mobile' => $data['mobile']])->where('is_del', 0)->count();
        if ($is_exit) {
            return $this->returnMsg('用户已存在', 0);
        }

        //只有普通用户验证验证码
        if ($data['role'] == 1) {
            $checkSmsCode = UtilService::checkSmsCode($data['mobile'], $data['code']);
            if (!$checkSmsCode) {
                return $this->returnMsg('验证码错误');
            }
        }
        if(isset($data['cachekey']) && !empty($data['cachekey'])) {
            $cachekey = $data['cachekey'];
            $openid = Cache::get($cachekey . '_wxopenid');
            if($openid){
                $user['wx_openid'] = $openid;
            }
        }

        $user['username'] = $data['name'];
        $user['mobile'] = $data['mobile'];
        $user['salt'] = random(4);
        $user['password'] = md5($data['password'] . $user['salt']);
        $user['reg_time'] = time();
        $user['create_time'] = time();
        $user['role'] = $data['role'] ?? 1;
        $user['headico'] = vconfig('default_user') ?? null;

        $res = userModel::insert($user);
        if (!$res) {
            return $this->returnMsg('注册失败', 0);
        }


        return $this->returnMsg('注册成功', 1);
    }

    //微信登录成功绑定已有手机号
    public function bindmobile(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['cachekey', 'mobile', 'code']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();
        $user = userModel::where(['mobile' => $data['mobile']])->where('is_del', 0)->find();
        if (empty($user)) {
            return $this->returnMsg('手机号未注册');
        }
        $checkSmsCode = UtilService::checkSmsCode($data['mobile'], $data['code']);
        if (!$checkSmsCode) {
//            return $this->returnMsg('验证码错误');
        }
        $cachekey = $data['cachekey'];
        $openid = Cache::get($cachekey . '_wxopenid');
        if (empty($openid)) {
            return $this->returnMsg('微信登录生效请重新扫码登录');
        }
        //绑定微信openid
        userModel::where('id', $user['id'])->save(['wx_openid' => $openid]);
        $user['wx_openid'] = $openid;
        //登录
        $token = TokenService::generateToken($user['id'], $user->toArray());

        $update['token'] = $token;
        $update['last_login_time'] = time();
        userModel::where(['id' => $user['id']])->update($update);

        return $this->returnMsg('操作成功', 1, ['token' => $token, 'expires_in' => TokenService::EXPIRE]);
    }


    //微信登录后新建账号 不用了
    public function bindregister(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['cachekey', 'name', 'mobile', 'password', 'code', 'password2', 'role']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();
        $is_exit = userModel::where(['mobile' => $data['mobile']])->where('is_del', 0)->count();
        if ($is_exit) {
            return $this->returnMsg('手机号已存在');
        }
        $checkSmsCode = UtilService::checkSmsCode($data['mobile'], $data['code']);
        if (!$checkSmsCode) {
            return $this->returnMsg('验证码错误');
        }

        $cachekey = $data['cachekey'];
        $openid = Cache::get($cachekey. '_wxopenid');
        if (empty($openid)) {
            return $this->returnMsg('微信登录生效请重新扫码登录');
        }

        $is_exit = userModel::where(['wx_openid' => $openid])->where('is_del', 0)->count();
        if ($is_exit) {
            return $this->returnMsg('此微信已绑定其它账号');
        }
        //绑定用户信息
        $user['wx_openid'] = $openid;
        $user['username'] = $data['name'];
        $user['mobile'] = $data['mobile'];
        $user['salt'] = random(4);
        $user['reg_time'] = time();
        $user['create_time'] = time();
        $user['password'] = md5($data['password'] . $user['salt']);
        $user['role'] = $data['role'] ?? 1;
        $user['headico'] = vconfig('default_user') ?? null;

        $user = userModel::create($user);
        if (!$user) {
            return $this->returnMsg('注册失败', 0);
        }
        //登录
        $token = TokenService::generateToken($user->id, $user->toArray());
        $update['token'] = $token;
        $update['last_login_time'] = time();
        userModel::where(['id' => $user->id])->update($update);

        return $this->returnMsg('操作成功', 1, ['token' => $token, 'expires_in' => TokenService::EXPIRE]);
    }

    public function restUserPasswordStep1(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['str', 'code']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();

        $checkSmsCode = UtilService::checkSmsCode($data['str'], $data['code']);
        if (!$checkSmsCode) {
            return $this->returnMsg('验证码错误');
        }

        $user = userModel::where(['mobile' => $data['str']])->whereOr(['username' => $data['str']])->find();


        if (!$user) {
            return $this->returnMsg('用户不存在', 0);
        }

        // 生成重置令牌并设置过期时间(如10分钟)
        $resetToken = md5(uniqid() . $user['id'] . time());
        cache('reset_token_' . $user['id'], $resetToken, 600); // 10分钟有效期

        //sms
        return $this->returnMsg('success', 1, ['reset_token' => $resetToken]);

    }

    public function restUserPasswordStep2(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['str', 'confirm_password', 'password', 'reset_token']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();

        $user = userModel::where(['mobile' => $data['str']])->whereOr(['username' => $data['str']])->find();

        if (!$user) {
            return $this->returnMsg('用户不存在', 0);
        }
        // 验证重置令牌
        $storedToken = cache('reset_token_' . $user['id']);
        if (!$storedToken || $storedToken !== $data['reset_token']) {
            return $this->returnMsg('无效的重置令牌或已过期', 0);
        }


        $update['password'] = md5($data['password'] . $user['salt']);
        userModel::where(['id' => $user['id']])->update($update);

        // 清除重置令牌
        cache('reset_token_' . $user['id'], null);
        //销毁token
        TokenService::deleteToken($user['token']);

        return $this->returnMsg('success', 1);

    }

    public function test()
    {
        try {
            // 验证参数
            (new UserValidate())->goCheck(['str', 'code']);
        } catch (ValidateException $e) {
            return $this->returnMsg($e->getError(), 0);
        } catch (\Exception $e) {
            return json([
                'code' => 500,
                'msg' => '系统错误',
                'data' => null
            ], 500);
        }

    }

    /**验证验证码
     * @param Request $request
     * @return \app\html|\think\response\Json|true
     */
    public function checkSmsCode(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['mobile', 'code']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();

        $checkSmsCode = UtilService::checkSmsCode($data['mobile'], $data['code']);
        if (!$checkSmsCode) {
            return $this->returnMsg('验证码错误');
        }

        return $this->returnMsg('success', 1);

    }

    public function checkMobile(Request $request)
    {
        $vo = (new UserValidate())->goCheck(['mobile']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();

        $count = userModel::where(['mobile' => $data['mobile']])->count();
        if ($count > 0) {
            return $this->returnMsg('手机号已存在');
        }

        return $this->returnMsg('success', 1);

    }

    public function rankUserExperience(Request $request)
    {
        $limit = $request->param('limit/d', 5);
        $type = $request->param('type', 'all');


        $list = UserService::rankUserExperience($limit, $type);

        return $this->returnMsg('success', 1, $list);
    }


}