package com.ssj.sys.interceptor;

import com.ssj.bean.sys.role.domain.Admin;
import com.ssj.bean.weixin.problem.domain.RequestMethodLog;
import com.ssj.bean.weixin.push.domain.SendTemplateShort;
import com.ssj.framework.basic.utils.DateHelper;
import com.ssj.framework.basic.utils.StringUtils;
import com.ssj.framework.core.util.PropertiesUtil;
import com.ssj.framework.core.util.WebUtil;
import com.ssj.service.weixin.problem.service.RequestMethodLogService;
import com.ssj.service.weixin.push.service.PushTemplateService;
import com.ssj.service.weixin.sales.service.LibStaffingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Component
public class LoginInterceptor extends HandlerInterceptorAdapter{
    @Autowired
    private RequestMethodLogService requestMethodLogService;

    @Autowired
    private LibStaffingService libStaffingService;
    @Autowired
    private PushTemplateService pushTemplateService;

    private static Set<String> sysURLList = new HashSet<String>();
    private static Set<String> notCheckURLList = new HashSet<String>();
    static {
        //notCheckURLList.add("/sys/login/index.html");
        //notCheckURLList.add("/sys/login/index");
        notCheckURLList.add("/sys/login/login");
        notCheckURLList.add("/sys/lib/getAllSchoolMap");
        sysURLList.add("/sys/sales/updatePrice");
        sysURLList.add("/sys/sales/libStaffingDelete");
        sysURLList.add("/sys/sales/libStaffingSave");
        sysURLList.add("/sys/sales/libStaffingZBSave");
    }


    // Controller 前执行
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setCharacterEncoding("UTF8"); // 设置输出编码
        response.setContentType("text/html;charset=UTF-8");

        Admin admin= (Admin) request.getSession().getAttribute("admin");
        String url = request.getRequestURI().replaceAll(request.getContextPath(), "");
        if (sysURLList.contains(url)) {
            HandlerMethod method = (HandlerMethod) handler;
            RequestMethodLog methodLog = new RequestMethodLog();
            if(admin !=null){
                methodLog.setAccountName(admin.getNickName());
                methodLog.setMethodUrl(url);
                methodLog.setMethodName(method.getMethod().getName());
                methodLog.setIpAddress(WebUtil.getRemoteAddr(request));
                // methodLog.setOrgCode(admin.getOrgCode());
                methodLog.setCreateTime(new Date());
                if("/sys/sales/updatePrice".equals(request.getRequestURI().replaceAll(request.getContextPath(), "")))
                {
                    String sortName = (String) request.getParameter("sortName");
                    String libId = (String) request.getParameter("libId");
                    String oldPrice = (String) request.getParameter("oldPrice");
                    String aliases = (String) request.getParameter("aliases");
                    String price = (String) request.getParameter("price");
                    methodLog.setSubstance(sortName+"("+oldPrice+"元/张)"+"更改为"+aliases+"("+price+"元/张)");
                    List<String> userList= libStaffingService.findByCDSDAndOpenId(libId, "s_cd","s_sd");
                    String template_id_short="OPENTM407378723";
                    for (String openId : userList) {
                        Map<String,String> data =new HashMap<String, String>();
                        data.put("first", "馆长，你好。你有一则后台管理系统的操作通知，请知晓。\n");
                        data.put("keyword1",sortName+"("+oldPrice+"元/张)"+"更改为"+aliases+"("+price+"元/张)");
                        data.put("keyword2",DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
                        data.put("remark","\n如非您本人操作，请尽快查明原因。");
                        SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, null, data);
                        pushTemplateService.savePushWxTemplate(sendTemplateShort);
                    }
                }else if ("/sys/sales/libStaffingDelete".equals(request.getRequestURI().replaceAll(request.getContextPath(), "")))
                {
                    String name = (String) request.getParameter("name");
                    String libId = (String) request.getParameter("libId");
                    String type = (String) request.getParameter("type");
                    String userName ="其他";
                    if("SSJ-SSJ-SD".equals(type)){
                        userName ="总部SD";
                    }else if("SSJ-SSJ-SR".equals(type)){
                        userName="总部SR";
                    }else if("s_cd".equals(type)){
                        userName="CD";
                    }else if("s_cc".equals(type)){
                        userName="CC";
                    }else if("s_cda".equals(type)){
                        userName="CDA";
                    }else if("s_sd".equals(type)){
                        userName="总部SD人员";
                    }
                    methodLog.setSubstance("删除"+name+"为"+userName+"的销售人员权限");
                    if( type !=null && type.contains("s_")){
                        List<String> userList= libStaffingService.findByCDSDAndOpenId(libId, "s_cd","s_sd");
                        String template_id_short="OPENTM407378723";
                        for (String openId : userList) {
                            Map<String,String> data =new HashMap<String, String>();
                            data.put("first", "馆长，你好。你有一则后台管理系统的操作通知，请知晓。\n");
                            data.put("keyword1","删除"+name+"为"+userName+"的销售人员权限");
                            data.put("keyword2",DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
                            data.put("remark","\n如非您本人操作，请尽快查明原因。");
                            SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, null, data);
                            pushTemplateService.savePushWxTemplate(sendTemplateShort);
                        }
                    }

                }else if ("/sys/sales/libStaffingSave".equals(url)||"/sys/sales/libStaffingZBSave".equals(url)){
                    String[] names = request.getParameterValues("names[]");
                    String name = Arrays.toString(names);

                    String type = (String) request.getParameter("type");
                    String userName ="其他";
                    if("SSJ-SSJ-SD".equals(type)){
                        userName ="总部SD";
                    }else if("SSJ-SSJ-SR".equals(type)){
                        userName="总部SR";
                    }else if("s_cd".equals(type)){
                        userName="CD";
                    }else if("s_cc".equals(type)){
                        userName="CC";
                    }else if("s_cda".equals(type)){
                        userName="CDA";
                    }else if("s_sd".equals(type)){
                        userName="总部SD人员";
                    }

                    if(type !=null && type.contains("s_")){
                        String libId = (String) request.getParameter("libId");
                        List<String> userList= libStaffingService.findByCDSDAndOpenId(libId, "s_cd","s_sd");
                        String template_id_short="OPENTM407378723";
                        for (String openId : userList) {
                            Map<String,String> data =new HashMap<String, String>();
                            data.put("first", "馆长，你好。你有一则后台管理系统的操作通知，请知晓。\n");
                            data.put("keyword1","新增"+name+"为"+userName+"的销售人员权限");
                            data.put("keyword2",DateHelper.format(new Date(),"yyyy年MM月dd日 HH:mm "));
                            data.put("remark","\n如非您本人操作，请尽快查明原因。");
                            SendTemplateShort sendTemplateShort=new SendTemplateShort(openId, template_id_short, null, data);
                            pushTemplateService.savePushWxTemplate(sendTemplateShort);
                        }
                    }

                    methodLog.setSubstance("新增"+name+"为"+userName+"的销售人员权限");
                }
                requestMethodLogService.save(methodLog);

            }
        }
        if (checkRequestURIIntNotFilterList(request)) { return true; }
        if (admin==null) {
            response.sendRedirect(request.getContextPath() + "/login.html");
            return false;
        }
        return true;
       /* //不检查的url
        java.util.Collection<String> collection = commonService.getAttributes(uri);
        if (!StringUtil.isEmpty(collection)) {
            if (!StringUtil.isEmpty(admin) && !StringUtil.isEmpty(admin.getAuthorities())) {
                Collection<String> authorities = admin.getAuthorities();
                for (String coll : collection) {
                    if (authorities.contains(coll)) return true;
                }
            }
        }
        return false;*/
    }

    //运行Controller后运行
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        if (modelAndView != null) {
            request.setCharacterEncoding("UTF-8");
            initModelAndView(request, modelAndView);
        }
    }

    public static void initModelAndView(HttpServletRequest request, ModelAndView modelAndView) throws Exception {
        //modelAndView.addObject("sysUrl", "https://sys.sharingschool.com");
        modelAndView.addObject("sysUrl", PropertiesUtil.getValue("gz_sys_url"));
       // modelAndView.addObject("sysUrl", "http://127.0.0.1:8080");
        modelAndView.addObject("imgUrl", PropertiesUtil.getValue("GZ_STATIC_FILE_URL"));
    }


    /**
     * 检查不过滤的url
     * @param request
     * @return
     */
    private boolean checkRequestURIIntNotFilterList(HttpServletRequest request) {
        String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
        if (uri.startsWith("/resources/") || notCheckURLList.contains(uri) || isAjaxRequest(request)) {
            return true;
        } else {
            return false;
        }
    }
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String ajaxHeader = request.getHeader("x-requested-with");
        if (StringUtils.isEmpty(ajaxHeader) && !"XMLHttpRequest".equalsIgnoreCase(ajaxHeader)) {
            return false;
        } else {
            return true;
        }
    }
}
