package com.winsun.item.modular.system.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.util.MD5Util;
import com.winsun.auth.model.user.User;
import com.winsun.bean.SysUser;
import com.winsun.item.core.shiro.ShiroKit;
import com.winsun.item.core.util.ResponseEntity;
import com.winsun.item.modular.system.service.IUserService;
import com.winsun.item.util.LoginUtils;
import com.winsun.mapper.SysUserMapper;
import com.winsun.smsUtils.SendSmsAndMail;
import com.winsun.utils.MyBatisPlusUpdateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author: chancy
 * @Date: 2020/3/27 16:14
 */
@Slf4j
@RequestMapping("/forgerpw")
@RestController
public class LoginPwdController  {

    private static SysUserMapper sysUserMapper;

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @Autowired
    public LoginPwdController(SysUserMapper sysUserMapper){
        LoginPwdController.sysUserMapper=sysUserMapper;
    }

    @RequestMapping( "changeOtherPwd")
    public ResponseData<String> passwordEdit(@RequestParam(value = "oldPwd",required = false) String oldPwd,@RequestParam("newPwd") String newPwd,@RequestParam("changeId") String userId){

        Wrapper<SysUser> wrapper = new EntityWrapper<>();
        wrapper.eq("id",userId).eq("status", "1");
        List<SysUser> sysUsers = sysUserMapper.selectList(wrapper);
        if (CollectionUtils.isEmpty(sysUsers)) {
            return ResponseData.error("当前用户不存在！");
        }
        SysUser sysUser = sysUsers.get(0);
        if (!ShiroKit.getUser().getRoleNames().stream().anyMatch(roleName -> StringUtils.equalsAny(roleName, "超级管理员"))) {
            ResponseData<String> old = LoginUtils.pwdDecrypt(oldPwd);
            if (!old.isSuccess()) {
                return ResponseData.error("原密码不合法!");
            }
            oldPwd = ShiroKit.md5(old.getData(), sysUser.getSalt());
            wrapper.eq("password",oldPwd);
            Integer integer = sysUserMapper.selectCount(wrapper);
            if(integer == 0){
                return ResponseData.error("原密码错误或账号非正常状态账号！");
            }
        }
        ResponseData<String> pwdDecrypt = LoginUtils.pwdDecrypt(newPwd);
        if (!pwdDecrypt.isSuccess()) {
            return ResponseData.error("密码不合法！");
        }
        newPwd = pwdDecrypt.getData();
        if(!newPwd.matches("^[a-z0-9A-Z]{8,}$") || newPwd.matches("^[a-zA-Z]{1,}$") || NumberUtils.isDigits(newPwd)) {
            return ResponseData.error("密码强制等级低，必须要数字、英文字母混合，长度至少8位！");
        }
        String newMd5 = ShiroKit.md5(newPwd, sysUser.getSalt());
        Map<String, Object> dataMapping = new HashMap<>();
        dataMapping.put("password", newMd5);
        Integer integer = sysUserMapper.updateForSet(MyBatisPlusUpdateUtils.toUpdateSet(dataMapping), wrapper);
        if(integer == 1){
            return ResponseData.success("密码修改成功！");
        }
        return ResponseData.error("密码修改失败！");
    }

    /**
     * 发送验证码
     *
     * @param account
     * @param
     * @return
     */
    @RequestMapping(value = "verificationCode", method = RequestMethod.POST)
    @ResponseBody
    public Object VerificationCode(@RequestParam(value = "account") String account) {
        EntityWrapper<User> userEntityWrapper = new EntityWrapper<>();
        userEntityWrapper.eq("status", 1).eq("account", account);
        List<User> users = userService.selectList(userEntityWrapper);
        if (CollectionUtils.isEmpty(users)) {
            return ResponseEntity.newJSON("code", 400, "data", "账号不存在！");
        }
        String phone = users.get(0).getPhone();
        String verificationCode = String.valueOf((int) ((Math.random() * 9 + 1) * 100000));
        //5分钟内有效
        stringRedisTemplate.opsForValue().set(account, verificationCode, 1000 * 60*5, TimeUnit.MILLISECONDS);
        Map<String, Object> sent=new HashMap<>();
        try {
            if (phone.length() == 11){
                SendSmsAndMail.sendSms(phone, verificationCode, "7");
            }else {
                sent.put("code",400);
                sent.put("message","当前用户手机号码不合法！");
            }

        }catch (Exception e){
            log.info("错误信息：{}",e.getMessage());
            sent.put("code",400);
            sent.put("message","手机短信发送失败");
        }
        return ResponseEntity.newJSON("code", 200, "data", "短信发送成功！");
    }

    /**
     * 修改密码
     *
     * @param account
     * @param newPwd
     * @param rePwd
     * @param
     * @return
     */
    @RequestMapping(value = "changePwd", method = RequestMethod.POST)
    @ResponseBody
    public Object ChangePassword(@RequestParam(value = "account") String account, @RequestParam(value = "verificationCode") String verificationCode,
                                 @RequestParam(value = "newPwd") String newPwd, @RequestParam(value = "rePwd") String rePwd) {
        // 对加密的密码进行解密处理
        ResponseData<String> pwdDecrypt = LoginUtils.pwdDecrypt(newPwd);
        if (!pwdDecrypt.isSuccess()) {
            return ResponseEntity.newJSON("code", 400, "data", "密码或者账号错误！");
        }
        newPwd = pwdDecrypt.getData();
        if(!newPwd.matches("^[a-z0-9A-Z]{8,}$") || newPwd.matches("^[a-zA-Z]{1,}$") || NumberUtils.isDigits(newPwd)) {
            return ResponseEntity.newJSON("code", 400, "data", "密码强制等级低，必须要数字、英文字母混合，长度至少8位！");
        }

        ResponseData<String> pwdDecryptre = LoginUtils.pwdDecrypt(rePwd);
        if (!pwdDecryptre.isSuccess()) {
            return ResponseEntity.newJSON("code", 400, "data", "密码或者账号错误！");
        }
        rePwd = pwdDecryptre.getData();

        if (!newPwd.equals(rePwd)) {
            return ResponseEntity.newJSON("code", 400, "data", "两次密码不一致！");
        }
        String code = stringRedisTemplate.opsForValue().get(account);
        if (StringUtils.isBlank(code)) {
            return ResponseEntity.newJSON("code", 400, "data", "验证码错误！");
        }
        if (!code.equals(verificationCode)) {
            return ResponseEntity.newJSON("code", 300, "data", "验证码错误！");
        }

        EntityWrapper<User> userwrapper = new EntityWrapper<>();
        userwrapper.eq("account", account).eq("status", "1");
        List<User> users = userService.selectList(userwrapper);
        if (CollectionUtils.isEmpty(users)) {
            return ResponseEntity.newJSON("code", 400, "data", "密码或者账号错误！");
        }
        User user = users.get(0);
        String newMd5 = ShiroKit.md5(newPwd, user.getSalt());
        int updateone = userService.updateone(newMd5, account, user.getPassword());
        if (updateone > 0) {
            return ResponseEntity.newJSON("code", 200, "data", "修改成功！");
        }
        return ResponseEntity.newJSON("code", 300, "data", "修改失败！");
    }
}
