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

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.esotericsoftware.minlog.Log;
import com.winsun.auth.core.base.controller.BaseController;
import com.winsun.auth.core.base.tips.ErrorTip;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.auth.core.support.HttpKit;
import com.winsun.auth.core.util.DateUtil;
import com.winsun.auth.model.user.User;
import com.winsun.bean.AuthCode;
import com.winsun.item.core.shiro.ShiroKit;
import com.winsun.item.core.util.*;
import com.winsun.item.modular.system.service.IUserService;
import com.winsun.item.modular.system.service.impl.AccServiceImpl;
import com.winsun.item.util.LoginUtils;
import com.winsun.mapper.AuthCodeMapper;
import com.winsun.smsUtils.SendSmsAndMail;
import com.winsun.utils.MyBatisPlusUpdateUtils;
import com.winsun.utils.RandomUtil;
import com.winsun.utils.SaveAuthCodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
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 org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.security.interfaces.RSAPrivateKey;

import org.springframework.beans.factory.annotation.Value;

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;

    @Autowired
    private SaveAuthCodeUtil saveAuthCodeUtil;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

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

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

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

    @Value("${spring.redis.ip.exprie}")
    private String exprie;

    public static String msg = "账号或密码或验证码错误，若重复多次错误请联系管理员。";

    //获取手机登录验证码
    @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", "密码或者账号错误！");
            return ResponseEntity.newJSON("code", 200, "message", "操作成功");
        }

        username = usernameDecrypt.getData();
        EntityWrapper<User> userwrapper = new EntityWrapper<>();
        userwrapper.eq("account", username);
        userwrapper.eq("status", "1");
        List<User> users = userService.selectList(userwrapper);
        if (CollectionUtils.isEmpty(users)) {
            //return ResponseEntity.newJSON("code", 400, "message", "密码或者账号错误！");
            return ResponseEntity.newJSON("code", 200, "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 if (username.equals("18027212525")) {
            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", 200);
        try {
            if (username.equals("admin")) {
                sent.put("message", "");
                //sent.put("code", 200);
            } else {
                if (user.getPhone().length() == 11) {
                    saveAuthCodeUtil.saveAuthCode(user.getPhone(), verificationCode); //临时保存数据库
                    SendSmsAndMail.sendSms(user.getPhone(), verificationCode, "", "7");
                    sent.put("message", "");
                    //sent.put("code", 200);
                } else {
                    log.info("当前用户手机号码不合法！");
                    sent.put("message", "");
                }
            }
        } catch (Exception e) {
            log.info("错误信息：{}", e.getMessage());
            sent.put("code", 400);
            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);
        userwrapper.eq("status", "1");
        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) {
                    saveAuthCodeUtil.saveAuthCode(user.getPhone(), verificationCode); // 临时保存数据库
                    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(value = "/mgr/codemessage", method = {RequestMethod.GET, RequestMethod.POST})
    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 = null;
        String username = user.getAccount();
        if (username.equals("admin")) {
            //只有admin验证码有后门 验证码规则：当前月份日期小时例如 011415
            verificationCode = DateUtil.formatDate(new Date(), "MMddHH");
        } else {
            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", "短信发送成功！");
    }

}
