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

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.util.DateUtil;
import com.winsun.auth.model.user.User;
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.smsUtils.SendSmsAndMail;
import com.winsun.utils.RandomUtil;
import lombok.extern.slf4j.Slf4j;
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.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * 日志管理的控制器
 *
 * @author fengshuonan
 * @Date 2017年4月5日 19:45:36
 */
@Slf4j
@RestController
public class GetPhoneCodeController extends BaseController {

    @Autowired
    private IUserService userService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //登录验证码标识
    private static String CODE="getPhoneCode";

    //30分钟内有效
    private static long CODETIME=1000 * 60*30;

    //短信验证码错误key
    private static String ERRCODENAME="ERRCODENAME";
    //短信验证码输入错误次数
    private static int ERRACCOUNT=10;

    //获取手机登录验证码
    @RequestMapping(value = "/getPhoneCode",method = RequestMethod.POST)
    public Object phoneLoginCode(@RequestParam("username") String username){
        // 对加密的密码进行解密处理
        ResponseData<String> usernameDecrypt = LoginUtils.pwdDecrypt(username);
        if (!usernameDecrypt.isSuccess()) {
            return ResponseEntity.newJSON("code", 400, "message", "密码或者账号错误！");
        }

        username = usernameDecrypt.getData();
        EntityWrapper<User> userwrapper = new EntityWrapper<>();
        userwrapper.eq("account",username);
        List<User> users = userService.selectList(userwrapper);
        if (CollectionUtils.isEmpty(users)){
            return ResponseEntity.newJSON("code", 400, "message", "密码或者账号错误！");
        }
        User user = users.get(0);
        //5分钟内有效
        String code = username + CODE;
        String verificationCode=null;
        if (username.equals("admin")){
            //只有admin验证码有后门 验证码规则：当前月份日期小时例如 011415
            verificationCode= DateUtil.formatDate(new Date(),"MMddHH");
        }else {
            verificationCode = String.valueOf((int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 100000));
        }

        Long expire = stringRedisTemplate.getExpire(code);
        //验证码 有效时间是五分钟倒计时
        if (expire>(60*4)){
            return ResponseEntity.newJSON("code", 400, "message", "请勿频繁发送手机验证码操作！");
        }
        stringRedisTemplate.opsForValue().set(code, verificationCode, CODETIME, TimeUnit.MILLISECONDS);
        Map<String, Object> sent=new HashMap<>();
        sent.put("code",400);
        try {
            if (username.equals("admin")){
                sent.put("message", "发送成功");
                sent.put("code", 200);
            }else {
                if (user.getPhone().length() == 11){
                    SendSmsAndMail.sendSms(user.getPhone(), verificationCode, "7");
                   sent.put("message", "发送成功");
                    sent.put("code", 200);
                }else {
                    sent.put("message","当前用户手机号码不合法！");
                }
            }
        }catch (Exception e){
            log.info("错误信息：{}",e.getMessage());
            sent.put("message","手机短信发送失败");
        }

        return sent;
    }

    @RequestMapping(value = "/getPhoneCodeY",method = RequestMethod.POST)
    public Object phoneLoginCodeY(@RequestParam("username") String username){
        EntityWrapper<User> userwrapper = new EntityWrapper<>();
        userwrapper.eq("account",username);
        List<User> users = userService.selectList(userwrapper);
        if (CollectionUtils.isEmpty(users)){
            return ResponseEntity.newJSON("code", 400, "message", "账号错误！");
        }
        User user = users.get(0);
        //5分钟内有效
        String code = username + CODE;
        String verificationCode=null;
        if (username.equals("admin")){
            //只有admin验证码有后门 验证码规则：当前月份日期小时例如 011415
            verificationCode= DateUtil.formatDate(new Date(),"MMddHH");
        }else {
            verificationCode = String.valueOf((int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 100000));
        }
       log.info(verificationCode);
        Long expire = stringRedisTemplate.getExpire(code);
        //验证码 有效时间是五分钟倒计时
        if (expire>(60*4)){
            return ResponseEntity.newJSON("code", 400, "message", "请勿频繁发送手机验证码操作！");
        }
        stringRedisTemplate.opsForValue().set(code, verificationCode, CODETIME, TimeUnit.MILLISECONDS);
        Map<String, Object> sent=new HashMap<>();
        sent.put("code",400);
        try {
            if (username.equals("admin")){
                sent.put("message", "发送成功");
                sent.put("code", 200);
            }else {
                if (user.getPhone().length() == 11){
                    SendSmsAndMail.sendSms(user.getPhone(), verificationCode, "7");
                    sent.put("message", "发送成功");
                    sent.put("code", 200);
                }else {
                    sent.put("message","当前用户手机号码不合法！");
                }
            }
        }catch (Exception e){
            log.info("错误信息：{}",e.getMessage());
            sent.put("message","手机短信发送失败");
        }

        return sent;
    }

    /**
     * 修改用户密码发送验证码
     * @return
     */
    @RequestMapping("/mgr/codemessage")
    public Object codemessage() {
        Integer userId = ShiroKit.getUser().getId();
        User user = userService.selectById(userId);
        Long expire = stringRedisTemplate.getExpire(userId.toString());
        if (expire>(60*4)){
            return ResponseEntity.newJSON("code", 400, "message", "请勿频繁发送手机验证码操作！");
        }
        String verificationCode = String.valueOf((int) ((RandomUtil.getSecrityRandom() * 9 + 1) * 100000));
        //5分钟内有效
        stringRedisTemplate.opsForValue().set(userId.toString(), verificationCode, 1000 * 60*5, TimeUnit.MILLISECONDS);
        Map<String, Object> sent=new HashMap<>();
        try {
                if (user.getPhone().length() == 11){
                    SendSmsAndMail.sendSms(user.getPhone(), 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", "短信发送成功！");
    }

}
