package com.cirle.scientific.config;

import com.cirle.scientific.constants.LoginConsts;
import com.cirle.scientific.dao.QkjMemberAppDao;
import com.cirle.scientific.po.QkjMemberApp;
import com.cirle.scientific.utils.CookieUtil;
import com.cirle.scientific.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
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.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@Component
@Slf4j
public class CirleInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    StringRedisTemplate stringRedisTemplate;
    @Autowired
    QkjMemberAppDao qkjMemberAppDao;

    /*
     * 视图渲染之后的操作
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3) throws Exception {

        System.out.println("执行到了afterCompletion方法");
    }

    /*
     * 处理请求完成后视图渲染之前的处理操作
     * 通过ModelAndView参数改变显示的视图，或发往视图的方法
     */
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception {
        arg0.setAttribute("memToken",arg0.getParameter("memToken"));
    }

    /*
     * 进入controller层之前拦截请求
     * 返回值：表示是否将当前的请求拦截下来  false：拦截请求，请求别终止。true：请求不被拦截，继续执行
     * Object obj:表示被拦的请求的目标对象（controller中方法）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object obj) throws Exception {
        //从header取出token换取memCard
        String memToken = request.getHeader("memToken");
        //String memToken = "miniapp_OzrZumLHyOq9zjyGNs1qny02AAw8Kf95tRgOIod5UdqDTSadJvAtNiuiW1_tltVJgJ8GkPqrqbSXR8HQn3v1VA";
        log.info("preHandle memToken:{}",memToken);
        //2.先从Redis取
        String memCard = "";
        if(StringUtils.isNotBlank(memToken)){
            String key = String.format("miniapp-token:%s", memToken);
            String memCardRedis = stringRedisTemplate.opsForValue().get(key);
            if(StringUtils.isNotBlank(memCard)){
                memCard = memCardRedis;
            }
            if(StringUtils.isBlank(memCard)){
                QkjMemberApp memberApp = qkjMemberAppDao.findByMemToken(memToken);
                if(Objects.nonNull(memberApp)){
                    memCard = memberApp.getMemCard();
                    if(StringUtils.isNotBlank(memCard)){
                        stringRedisTemplate.opsForValue().set(key, memCard, 2, TimeUnit.DAYS);
                    }
                }
            }
        }
        log.info("preHandle memCard:{}",memCard);
        if(StringUtils.isNotBlank(memCard)){
            request.setAttribute(LoginConsts.MIMI_APP_LOGIN_KEY,memCard);
        }
        return true;
    }

    /**
     * 获取cookie里的值
     *
     * @param request
     * @param key
     * @return 不存在 返回null
     */
    public String getValueByCookie(HttpServletRequest request, String key) {
        String cookievalue = null;
        Cookie[] cookies = request.getCookies();
        if (null != cookies && cookies.length != 0) {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                if (cookie.getName().equals(key)) {
                    // String value = cookie.getValue();
                    try {
                        cookievalue = URLDecoder.decode(cookie.getValue(), "UTF-8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    // cookievalue = value;
                    break;
                }
            }
        }
        return cookievalue;
    }
    /**
     * 将值存入cookie
     *
     * @param response
     * @param key
     * @param val
     */
    public void addValue2Cookie(HttpServletResponse response, String domain, String path, String key, String val,
                                int time) {
        if(val == null || "".equals(val)){
            return;
        }
        try {
            val = URLEncoder.encode(val, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.addHeader("P3P", "CP=CAO PSA OUR");
        Cookie c = new Cookie(key, val);
        c.setDomain(domain);
        c.setMaxAge(time);
        c.setPath(path);
        response.addCookie(c);
    }


    /**
     * 清除cookie
     * @param response
     */
    public void clearCookies(HttpServletResponse response, String domain, String path, String key) {
        Cookie c = new Cookie(key, null);
        c.setDomain(domain);
        c.setMaxAge(0);
        c.setPath(path);
        response.addCookie(c);
    }

    public static void main(String[] args) {
        String tmp = "http://www.qkyxzx.com/";
        String domain = "";
        if(tmp.split(":").length>2){
            domain = tmp.substring(0,tmp.lastIndexOf(":"));
        }else{
            if(tmp.endsWith("/")){
                tmp = tmp.substring(0,tmp.length()-1);
            }
            domain = tmp;
        }
        if(domain.contains("http:")){
            domain = domain.replaceAll("http://","");
        }
        if(domain.contains("https:")){
            domain = domain.replaceAll("https://","");
        }
        if(domain.contains("www")){
            domain = domain.replaceAll("www\\.","");
        }
        System.out.println(domain);
    }
}
