package com.artfess.security.util;

import com.artfess.base.manager.CommonManager;
import com.artfess.base.util.DESUtils;
import com.artfess.base.util.DateUtils;
import com.artfess.security.manager.SysAuthorizationManager;
import com.artfess.security.model.SysAuthorization;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wh
 * @Package com.sysplat.common.util.des
 * @date 2020/11/24 15:06
 * @Description:
 */
@Service
public class AuthorCheck {

//    @Autowired
//    private  JDBCDao jdbcDao;
//    @Autowired
//    private RedisUtil redisUtil;

    /**
     * 项目根目录
     */
    public static final String ROOT_PATH = System.getProperty("user.dir");

    /**
     * 模板下载、文件导入临时文件目录名
     */
    public static final String DATA_TEMP_FILE = "tempFile";

    /**
     * 模板下载、文件导入临时文件目录
     */
    public static final String TEMP_DATA_EXCEL = ROOT_PATH + File.separator + DATA_TEMP_FILE;

    protected JdbcTemplate jdbcTemplate;

    @javax.annotation.Resource
    CommonManager commonManager;

    @Autowired
    private SysAuthorizationManager systemAuthorizationManager;

    public static String FILE_PATH = TEMP_DATA_EXCEL + File.separator + "plat2021.data";
    public static String FILE_PATH_LIC = TEMP_DATA_EXCEL + File.separator + "plat2021.lic";

    //读取授权文件
    public static String redFileStr() {
        String registerContent = "";
        StringBuffer sb = new StringBuffer();

        Resource resource = new ClassPathResource(FILE_PATH);
        File file = null;
        try {
            file = resource.getFile();
        } catch (IOException e) {
            return registerContent;
        }

        if (!file.exists()) {
            registerContent = "";
        } else try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), "UTF-8"));
            try {
                registerContent = br.readLine();
                if ((registerContent == null) || (registerContent.trim().length() == 0))
                    registerContent = "";
            } catch (Throwable localThrowable1) {
            } finally {
                if (br != null)
                    br.close();
            }
        } catch (IOException e) {
            registerContent = "";
        }
        return registerContent;
    }

    //得到解密内容
    public static String getDesStr(String registerContent) {
        return DESUtils.myDecrypt(registerContent.split("/")[1]);
    }

    //解密授权码，返回授权信息 成都振讯科技,1.01,1,2020-11-30,2020-12-30,C03FD50F1872,199.199.199.203,QWERTYUIOPL0123456789KJHGFDSAZXCVBNM,20
    public static Map<String, String> getInfo(String desStr) {
        Map<String, String> map = new HashMap<>();
        try {
            String[] infoArr = getDesStr(desStr).split(",");
            String deptName = infoArr[0];
            String version = infoArr[1];
            String type = infoArr[2];//1临时 2永久
            String install = infoArr[3];
            String endDay = infoArr[4];
            String mac = infoArr[5];
            String ip = infoArr[6];
            String user = infoArr[8];//用户数限制 -1不限制
            map.put("deptName", deptName);
            map.put("version", version);
            map.put("install", install);
            map.put("type", type);
            map.put("endDay", endDay);
            map.put("mac", mac);
            map.put("ip", ip);
            map.put("user", user);
        } catch (RuntimeException e) {
            System.out.println("解析出错。");
        }
        return map;
    }

    //登录或者启动验证
    public static Map<String, String> getMapInfo() {
        String registerContent = redFileStr();
        return getInfo(registerContent);
    }

    //验证运行时间限制
    public static int checkDate(String day) {
        try {
            Date newDate = new Date();
            Date checkDate = DateUtils.str2Date(day);
            if (checkDate.before(newDate)) {
                return 0;
            }
            return getGapCount(newDate, checkDate);
        } catch (Exception e) {
            return 0;
        }
    }

    //如果系统的当前时间小于登录日志的最大时间，则说明修改了系统时间，直接验证不通过
    public boolean checkSystemUpdate() {
        try {
            Date newDate = new Date();
            String sql = "select max(EXECUTION_TIME_) maxdate from portal_sys_login_logs";
            List<Map<String, Object>> list = commonManager.query(sql);
            if (list.size() == 0) {
                return false;
            }
            String maxdate = list.get(0).get("maxdate").toString();
            Date checkDate = DateUtils.str2Date(maxdate);
            //Date checkDate = jdbcDao.queryToObject("select max(LOGIN_DATE) maxdate from sys_person_login_log", Date.class,new Object[]{});
            if (newDate.before(checkDate)) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     *     * 获取两个日期之间的间隔天数     * @return     
     */
    public static int getGapCount(Date startDate, Date endDate) {
        long da = endDate.getTime() - startDate.getTime();
        return (int) (da / (1000 * 60 * 60 * 24));
    }

    //20201126新的验证逻辑
    //反序列化得到授权对象
    public SysAuthorization redFileToObject() {
        //反序列化
        try {
            SysAuthorization entity = new SysAuthorization();
            File file = new File(FILE_PATH);
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            entity = (SysAuthorization) ois.readObject();
            entity.setDeptName(DESUtils.myDecrypt(entity.getDeptName()));
            entity.setVersionCode(DESUtils.myDecrypt(entity.getVersionCode()));
            entity.setType(DESUtils.myDecrypt(entity.getType()));//1临时 2永久
            entity.setInstallDate(DESUtils.myDecrypt(entity.getInstallDate()));
            entity.setEndDate(DESUtils.myDecrypt(entity.getEndDate()));
            //entity.setDeptId(DESUtils.myDecrypt(entity.getDeptId()));
            if(StringUtils.isNotBlank(entity.getTel())) {
                entity.setTel(DESUtils.myDecrypt(entity.getTel()));
            }
            entity.setUser(DESUtils.myDecrypt(entity.getUser()));
            entity.setSystemType(DESUtils.myDecrypt(entity.getSystemType()));
            entity.setUserNum(DESUtils.myDecrypt(entity.getUserNum()));//用户数限制 0不限制
            entity.setOgnNum(DESUtils.myDecrypt(entity.getOgnNum()));//机构数限制 0不限制
            entity.setTenantNum(DESUtils.myDecrypt(entity.getTenantNum()));//租户数限制 0不限制
            ois.close();
            return entity;
        } catch (FileNotFoundException e) {
            //throw new ApplicationException("系统没有授权。");
        } catch (Exception e) {
            //throw new ApplicationException("读取文件出错。"+e.getMessage());
        }
        return null;
    }

    //反序列化得到授权对象
    public SysAuthorization redFileToObject(File file) {
        try {
            SysAuthorization entity = new SysAuthorization();
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
            entity = (SysAuthorization) ois.readObject();
            entity.setDeptName(DESUtils.myDecrypt(entity.getDeptName()));
            entity.setVersionCode(DESUtils.myDecrypt(entity.getVersionCode()));
            entity.setType(DESUtils.myDecrypt(entity.getType()));//1临时 2永久
            entity.setInstallDate(DESUtils.myDecrypt(entity.getInstallDate()));
            entity.setEndDate(DESUtils.myDecrypt(entity.getEndDate()));
            // entity.setDeptId(DESUtils.myDecrypt(entity.getDeptId()));
            entity.setSystemType(DESUtils.myDecrypt(entity.getSystemType()));
            entity.setTel(DESUtils.myDecrypt(entity.getTel()));
            entity.setUser(DESUtils.myDecrypt(entity.getUser()));
            entity.setUserNum(DESUtils.myDecrypt(entity.getUserNum()));//用户数限制 0不限制
            entity.setOgnNum(DESUtils.myDecrypt(entity.getOgnNum()));
            entity.setTenantNum(DESUtils.myDecrypt(entity.getTenantNum()));
            ois.close();
            return entity;
        } catch (FileNotFoundException e) {
            //throw new ApplicationException("系统没有授权。");
        } catch (Exception e) {
            //throw new ApplicationException("读取文件出错。"+e.getMessage());
        }
        return null;
    }

    //启动或登录验证
    public String newCheck() {
        SysAuthorization registerEntity = redFileToObject();
        if (null == registerEntity) {
            return ResultCode.NO_DECRYPT_ERROR + ":" + ResultCode.NO_DECRYPT_ERROR.getMessage();
        }
        //不限制
        if ("2".equals(registerEntity.getType())) {
            return ResultCode.SUCCESS + ":" + ResultCode.SUCCESS.getMessage();
        }
        boolean systemDate = checkSystemUpdate();
        if (!systemDate) {
            return ResultCode.NO_DECRYPT_ERROR + ":" + ResultCode.NO_DECRYPT_ERROR.getMessage();
        }

        int dayCount = checkDate(registerEntity.getEndDate());
        if (dayCount == 0) {
            //授权已到期
            return ResultCode.NO_DECRYPT_DATE_LONG + ":" + ResultCode.NO_DECRYPT_DATE_LONG.getMessage();
        } else if (dayCount <= 7) {
            return ResultCode.NO_DECRYPT_WILL_DATE_LONG + ":" + ResultCode.NO_DECRYPT_WILL_DATE_LONG.getMessage().replace("{day}", String.valueOf(dayCount));
        }
        //验证授权文件里面的id和系统里面ID匹配不,如果是试用版就不匹配
        if (!"试用单位".equals(registerEntity.getDeptName())) {
            SysAuthorization commonBasicEntity = this.systemAuthorizationManager.getByName(registerEntity.getDeptName());
            if (null == commonBasicEntity) {
                return ResultCode.NO_DECRYPT_SYSTEM + ":" + ResultCode.NO_DECRYPT_SYSTEM.getMessage();
            } else {
                //如果单位名称不一致
                if (!commonBasicEntity.getDeptName().equals(registerEntity.getDeptName())) {
                    return ResultCode.NO_DECRYPT_SYSTEM + ":" + ResultCode.NO_DECRYPT_SYSTEM.getMessage();
                }
            }
        }

        return ResultCode.SUCCESS + ":" + ResultCode.SUCCESS.getMessage();
    }

    public static void main(String[] args) {
        AuthorCheck authorCheck = new AuthorCheck();
        System.out.println(authorCheck.newCheck());
    }
}