package com.lantone.qc.security.util;


import com.lantone.qc.pub.model.vo.TokenVO;
import com.lantone.qc.security.exception.CommonErrorCode;
import com.lantone.qc.security.exception.CommonException;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.util.*;

/**
 * @description: token验证工具类
 * @author: zhoutg
 * @time: 2019/12/24 17:07
 */
@Slf4j
public class TokenUtil {

    // 处理文件路径
    public static final String path = System.getProperty("user.dir") + File.separator + "license.properties";

    // 文件配置信息
    public static Map<String, String> tokenMap = new LinkedHashMap<>();

    /**
     * 读取配置文件内容到map
     *
     * @return
     */
    public static Map<String, String> getFileContent() {
        BufferedReader br = null;
        List<String> list = new ArrayList<>();
        try {
            br = new BufferedReader(
                    new InputStreamReader(
                            new FileInputStream(path), "UTF-8"));

            String lineTxt = br.readLine();
            String lineTxtDe = RSAEncrypt.decrypt(lineTxt);
            String[] item = lineTxtDe.split("\\$\\$"); // $$作为分隔符
            for (String s : item) {
                String[] keyVal = s.split("=");
                tokenMap.put(keyVal[0], keyVal[1]);
            }
            br.close();
        } catch (Exception e) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "文件信息有误");
        } finally {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return tokenMap;
    }


    /**
     * 有效使用天数-1
     *
     * @return
     */
    public static void dealDay() {
        log.info("定时任务执行了！");
        // 处理内存数据
        Integer remainday = Integer.parseInt(tokenMap.get("server.remainday"));
        tokenMap.put("server.remainday", (--remainday).toString());

        // 处理文件内容
        StringBuffer sb = new StringBuffer();
        for (String key : tokenMap.keySet()) {
            sb.append(key);
            sb.append("=");
            sb.append(tokenMap.get(key));
            sb.append("$$");
        }
        // 删除最后2个$$
        String line = sb.toString();
        line = line.substring(0, line.length() - 2);
        try {
            BufferedWriter bw =
                new BufferedWriter(
                    new OutputStreamWriter(
                            new FileOutputStream(path), "UTF-8"));
            String enLine = RSAEncrypt.encrypt(line);
            bw.write(enLine);
            bw.flush();
        } catch (Exception e) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "定时任务执行失败");
        }
    }


    /**
     * 校验token：1、剩余天数是否小于0; 2、有效使用时间是否过期
     *
     * @param tokenVO
     * @return
     */
    public static boolean verifyToken(TokenVO tokenVO) {
        try {
            Map<String, String> map = RSAEncrypt.convertMap(tokenVO.getToken());
            // 剩余使用天数到期
            if (Integer.parseInt(map.get("server.remainday")) <= 0) {
                return false;
            }
            // 有效使用时间超时
            if (Long.parseLong(map.get("server.validtime")) <= new Date().getTime()) {
                return false;
            }
            // 记录日志
            Map<String, String> tokenMap = TokenUtil.tokenMap;
            log.info(tokenMap.get("server.provider") + "——" + tokenMap.get("server.hospital") + "调用接口了");
        } catch (Exception e) {
            throw new CommonException(CommonErrorCode.SERVER_IS_ERROR, "token失效");
        }
        return true;
    }

}
