package com.sptg.gateway.Interceptor;

import com.codingapi.txlcn.tracing.http.spring.HandlerInterceptor;
import com.sptg.common.core.util.JsonUtils;
import com.sptg.estate.api.entity.Member;
import com.sptg.estate.api.entity.MemberLoginStatus;
import com.sptg.estate.api.feigns.MemberFeign;
import com.sptg.estate.api.feigns.MemberLoginStatusFeign;
import com.sptg.gateway.util.JwtCons;
import com.sptg.gateway.util.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;

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

/**
 * Created with logindemo.
 * Author: dreamer-1
 * Email: zhong--lei@outllok.com
 * Date: 2018/5/13
 * Time: 下午2:58
 * Description:
 */
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private MemberLoginStatusFeign memberLoginStatusFeign;

    @Autowired
    private MemberFeign memberFeign;

    private Boolean isEqualMacUrl(String tel, String macUrl) {
        MemberLoginStatus memberLoginStatus = new MemberLoginStatus();
        memberLoginStatus.setMemberId(tel);
        MemberLoginStatus memberLogin = memberLoginStatusFeign.checkMemberLoginStatus(memberLoginStatus);
        if (memberLogin.getMacUrl().equals(macUrl)) {
            return true;
        } else {
            return false;
        }
    }

    private Boolean isEnable(String tel){
        Member member = new Member();
        member.setTel(tel);
        Member member1 = memberFeign.getMember(member);
        if (member1.getEnable() == 1){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 在请求被处理之前调用
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(@RequestBody HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        String token = request.getHeader(JwtCons.AUTHORIZATION);
        log.warn("token:{}", token);

        OutputStream out = response.getOutputStream();
        Map<String, Object> map = new HashMap<String, Object>();

        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        if (StringUtils.isEmpty(token)) {
            return true;
        }

        if (!StringUtils.isEmpty(token)) {
            if (!jwtUtil.verify(token)) {
                map.put("result_code", "0");
                map.put("result_msg", "token失效");
                map.put("result_success", "false");
                out.write(JsonUtils.objectToJson(map).getBytes("UTF-8"));
                return false;
            }
            String tel = jwtUtil.getUserTel(token);
            String macUrl = jwtUtil.getMacUrl(token);
            if (StringUtils.isEmpty(tel)) {
                map.put("result_code", "0");
                map.put("result_msg", "用户未登录");
                map.put("result_success", "false");
                out.write(JsonUtils.objectToJson(map).getBytes("UTF-8"));
                return false;
            }
            request.setAttribute(JwtCons.USER_TEL, tel);
            if (StringUtils.isEmpty(macUrl)) {
                map.put("result_code", "0");
                map.put("result_msg", "用户未登录");
                map.put("result_success", "false");
                out.write(JsonUtils.objectToJson(map).getBytes("UTF-8"));
                return false;
            }
            request.setAttribute(JwtCons.MAC_URL, macUrl);
            if (!isEqualMacUrl(tel, macUrl)) {
                map.put("result_code", "0");
                map.put("result_msg", "设备不一致");
                map.put("result_success", "false");
                out.write(JsonUtils.objectToJson(map).getBytes("UTF-8"));
                return false;
            }
            if (!isEnable(tel)){
                map.put("result_code", "0");
                map.put("result_msg", "状态不可用");
                map.put("result_success", "false");
                out.write(JsonUtils.objectToJson(map).getBytes("UTF-8"));
                return false;
            }
            return true;
        }
        return false;
    }

    /**
     * 在请求被处理后，视图渲染之前调用
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

    }

    /**
     * 在整个请求结束后调用
     *
     * @param request
     * @param response
     * @param handler
     * @param ex
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

    }
}