package com.tax.file.service.async.monitor;

import com.tax.file.constants.FileConstants;
import com.tax.file.service.api.FileTokenService;
import com.tax.file.service.api.TkTaxUserService;
import com.tax.file.utils.DingdingUtil;
import com.yxcheng.token.common.cache.RedisService;
import com.yxcheng.token.utils.DateUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.util.List;
import java.util.Map;

@Component
public class ApplyMonitorService {

    private static final Logger logger = LoggerFactory.getLogger(ApplyMonitorService.class);

    @Autowired
    protected TkTaxUserService tkTaxUserService;
    @Autowired
    protected FileTokenService fileTokenService;
    @Autowired
    private RedisService redisService;

    public static String SERVER_NAME = FileConstants.systemName.toLowerCase();
    public static String MONITOR_COLLECT_001 = SERVER_NAME + ".monitor.collect.001";
    public static String MONITOR_TOKEN_002 = SERVER_NAME + ".monitor.token.002";


    public void applyMonitor(String uuidFlag) {
        logger.info(" run applyMonitor is start ... ");
        //计时器
        Instant start = Instant.now();
        List<Map<String, Object>> userList = tkTaxUserService.queryApplyFileByMonitor();

        String collectMonitor = redisService.get(MONITOR_COLLECT_001);
        if(null != userList && userList.size()>0) {
            if(!"1".equals(collectMonitor)) {

                int totalNum = 0;
                for(Map<String, Object> userMap:userList) {
                    totalNum += (Long)userMap.get("zoneNum");
                }

                String title = SERVER_NAME + "_download超过48小时未获取到数量:"+ totalNum + ",时间：" + DateUtils.getDataString(DateUtils.datetimeFormat);
                StringBuffer context = new StringBuffer();
                context.append(title + "\r\n");

                for(Map<String, Object> userMap:userList) {
                    context.append("地区：" + userMap.get("zoneCode") + "，未按时获取数量：" + userMap.get("zoneNum")  + ";\r\n");
                }
                context.append("------------------------over-------------------------------");
                sendDlMessage(uuidFlag, "1");
                DingdingUtil.send(context.toString(),false,null);
            }
        } else {
            if("1".equals(collectMonitor)) {
                String title = SERVER_NAME + "_download已经恢复正常!" + ",时间：" + DateUtils.getDataString(DateUtils.datetimeFormat);
                sendDlMessage(uuidFlag, "0");
                DingdingUtil.send(title,false,null);
            }
        }
        printEndLog(uuidFlag, start, "applyMonitor");
    }

    public void applyTokenMonitor(String uuidFlag) {
        logger.info(" run applyTokenMonitor is start ... ");
        //计时器
        Instant start = Instant.now();
        List<Map<String, Object>> tokenList = fileTokenService.queryNotifyToken();

        String collectMonitor = redisService.get(MONITOR_TOKEN_002);
        if(null != tokenList && tokenList.size()>0) {
            if(!"1".equals(collectMonitor)) {

                int totalNum = 0;
                for(Map<String, Object> userMap:tokenList) {
                    totalNum += (Long)userMap.get("zoneNum");
                }

                String title = SERVER_NAME + "_token超过30分钟未获取到数量:"+ totalNum + ",时间：" + DateUtils.getDataString(DateUtils.datetimeFormat);
                StringBuffer context = new StringBuffer();
                context.append(title + "\r\n");

                for(Map<String, Object> userMap:tokenList) {
                    context.append("地区：" + userMap.get("zoneCode") + "，未按时获取token数量：" + userMap.get("zoneNum")  + ";\r\n");
                }

                context.append("------------------------over-------------------------------");

                sendDTMessage(uuidFlag, "1");
                DingdingUtil.send(context.toString(),false,null);
            }
        } else {
            if("1".equals(collectMonitor)) {
                String title = SERVER_NAME + "_token已经恢复正常!" + ",时间：" + DateUtils.getDataString(DateUtils.datetimeFormat);
                sendDTMessage(uuidFlag, "0");
                DingdingUtil.send(title,false,null);
            }
        }
        printEndLog(uuidFlag, start, "applyTokenMonitor");
    }


    public void printEndLog(String uuidFlag, Instant start, String vMsg) {
        //统计耗时
        Instant end = Instant.now();
        long duration = end.toEpochMilli() - start.toEpochMilli();
        logger.info(uuidFlag + " " +vMsg+ " is end.cost is {} ms!",duration);
    }

    public void sendDlMessage(String uuidFlag, String monitorFlag) {
        try {
            redisService.set(MONITOR_COLLECT_001, monitorFlag, 3600 * 3);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(uuidFlag + " 发送download异常信息失败" + e.getMessage());
        }
    }

    public void sendDTMessage(String uuidFlag, String monitorFlag) {
        try {
            redisService.set(MONITOR_TOKEN_002, monitorFlag, 3600 * 3);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(uuidFlag + " 发送download token异常信息失败" + e.getMessage());
        }
    }
}
