package com.config;


import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.model.Menu;
import com.model.OperationLog;
import com.model.Org;
import com.model.User;
import com.service.OrgService;
import com.utils.CommonUtils;
import org.apache.commons.io.FileUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.*;

public class AuthInterceptor implements Interceptor {
    private static Log log = Log.getLog(AuthInterceptor.class);
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    private OrgService orgService = OrgService.me;
    public static List<String> noauthlist = initpath();
    public static List<String> initpath(){
        List<String> list = new ArrayList<String>();
        try{
            list = FileUtils.readLines(new File(PathKit.getRootClassPath()+ File.separatorChar +"noauth.txt"),"utf-8");
            return list;
        }catch(Exception e){
            e.printStackTrace();
        }
        return list;
    }


    @Override
    public void intercept(Invocation invocation) {
        try{

            String target = invocation.getActionKey();

            if (ignore(target)){
                invocation.invoke();
                return;
            }

            User user = (User)invocation.getController().getSession().getAttribute("userInfo");
            if(user  == null) {
                HttpServletRequest httpServletRequest=invocation.getController().getRequest();
                log.info("非法操作，已被拦截："+target);
                if (httpServletRequest.getHeader("x-requested-with") !=null){
                    Map result = new HashMap();
                    result.put("code","3");
                    result.put("msg","长时间没有使用系统，请先重新登录！");
                    invocation.getController().renderJson(result);
                }else {
                    invocation.getController().redirect(PropKit.get("login_page_url"));
                }
            }else{
                Org org = orgService.findById(user.getOrgid());
                Map map = new HashMap();
                map.put("orgid",user.getOrgid());
                map.put("orgname",org.getOrgname());
                map.put("userid",user.getId());
                map.put("loginname",user.getRealname());
                map.put("url",target.toString());


                

                map.put("time", format.format(new Date()));
                log.info("useraction:" + JSONObject.toJSON(map).toString());
                long time = System.currentTimeMillis();
                invocation.invoke();
                log.info("耗时："+(System.currentTimeMillis()-time)+"ms");
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private boolean ignore(String target){
        for (String url :noauthlist){
            if (url.equals("")){
                continue;
            }
            if (url.endsWith("*") && target.indexOf(url.substring(0,url.length()-2)) !=-1){
                return true;
            }
            if (target.endsWith(url) ){
                return true;
            }
        }
        return false;
    }
}
