package com.winsun.item.modular.intercept;

import com.alibaba.fastjson.JSON;
import com.winsun.auth.core.common.model.ResponseData;
import com.winsun.item.core.shiro.ShiroKit;
import com.winsun.item.util.LoginUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 *
 * @Date 2020/2/29 18:01
 * @Version 1.0
 */
@Component
public class ChangePwdInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    public StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        String inputCode = request.getParameter("inputCode");
        if (inputCode==null){
            return false;
        }

        Integer userId = ShiroKit.getUser().getId();
        //验证码
        ResponseData<String> codeDecryptre = LoginUtils.pwdDecrypt(inputCode);
        if (!codeDecryptre.isSuccess()) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            Map<String, Object> map = new HashMap<>();
            map.put("code", 500);
            map.put("data", "验证码错误");
            Object toJSON = JSON.toJSON(map);
            writer.write(toJSON.toString());
            return false;
        }
        inputCode = codeDecryptre.getData();
        String rediscode = stringRedisTemplate.opsForValue().get(userId.toString());
        if (StringUtils.isBlank(rediscode)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            Map<String, Object> map = new HashMap<>();
            map.put("code", 500);
            map.put("data", "验证码错误");
            Object toJSON = JSON.toJSON(map);
            writer.write(toJSON.toString());
            return false;
        }
        if (!rediscode.equals(inputCode)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();
            Map<String, Object> map = new HashMap<>();
            map.put("code", 500);
            map.put("data", "验证码错误");
            Object toJSON = JSON.toJSON(map);
            writer.write(toJSON.toString());
            return false;
        }
        return true;
    }
}
