<?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;

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']])->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']);
        if ($vo !== true) {
            return $vo;
        }
        $data = $request->param();

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

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

        $user['username'] = $data['name'];
        $user['mobile'] = $data['mobile'];
        $user['salt'] = random(4);
        $user['password'] = md5($data['password'].$user['salt']);
        $user['reg_time'] = time();
        $res = userModel::insert($user);
        if (!$res)
        {
            return $this->returnMsg('注册失败',0);
        }


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

    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);
        }

    }



}