package com.ruoyi.web.controller.common;



import com.ruoyi.common.annotation.RepeatSubmit;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.SendSmsUtils;
import com.ruoyi.system.service.ISysUserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.constant.CommonConstants.ONE;

/**小程序公共接口
 * @Author: tjf
 * @Date: 2023/5/25 11:46
 * @Describe:
 */
@RestController
@RequestMapping("/applet")
public class AppletController extends BaseController {
    @Autowired
    private ISysUserService userService;
    @Resource
    private RedisCache redisCache;


    /**
     *忘记密码发送验证短信
     */
    @RepeatSubmit(interval = 1000,message = "请求过于频繁")
    @GetMapping("/appForgetPW/{phone}")
    public AjaxResult appForgetPW(@PathVariable String phone)
    {
        SysUser sysUser = userService.selectUserByPhonenumber(phone);
        if (sysUser == null || sysUser.getUserId() == null){
            return  AjaxResult.error("当前手机号系统内不存在，无法修改密码");
        }
        String code = SendSmsUtils.getCode(4);
        SendSmsUtils.sendSms(phone,"SMS_219525380","{\"code\":\"" + code + "\"}");
        String key = "SMS_CODE:"+phone;
        redisCache.setCacheObject(key,code, 5,TimeUnit.MINUTES);
        return  AjaxResult.success(code);
    }
    /**
     *忘记密码校验验证码,修改密码
     */

    @GetMapping("/appCheck")
    public AjaxResult appCheck(@RequestParam("code") String code, @RequestParam("phone") String phone, @RequestParam("password") String password)
    {
        String key = "SMS_CODE:"+phone;
        Object cacheObject = redisCache.getCacheObject(key);
        if (ObjectUtils.isNotEmpty(cacheObject)){
            if (code.equals(String.valueOf(cacheObject))){
                redisCache.deleteObject(key);
                SysUser user = new SysUser();
                user.setPassword(password);
               //修改密码
                if (ONE.equals(userService.checkStrongPwd(user))) {
                    return AjaxResult.error("密码必须包含数字、大小写字母、特殊符号且大于8位");
                }
                user.setPhonenumber(phone);
                user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
                return toAjax(userService.resetUserPwdByPhonenumber(user));
            }
        }
        return  AjaxResult.error();
    }

}
