package com.zanxiang.game.data.serve.task;

import com.zanxiang.game.data.serve.pojo.properties.SmsProperties;
import com.zanxiang.game.data.serve.service.IGameMonitorAlarmService;
import com.zanxiang.module.sms.service.impl.AliSmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @author tianhua
 * @version 1.0
 * @description: 游戏监控告警定时任务
 * @date 2023/12/13 19:08
 */
@Slf4j
@Component
@RefreshScope
public class GameMonitorAlarmTask {

    @Autowired
    private IGameMonitorAlarmService gameMonitorAlarmService;

    @Resource
    private SmsProperties smsProperties;

    @Resource
    private AliSmsService aliSmsService;


    @Value("${sys-config.task_is_run}")
    private boolean run;

    /**
     * 任务每5分钟运行一次
     */
    @Scheduled(cron = "0 */5 * * * *")
    public void run() {
        log.info("游戏监控告警定时任务开始.");
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
        Runnable task = ()->{
           try {
               log.info("游戏监控在线程里开始执行");
               if (!run) {
                   log.info("游戏监控告警定时任务本地不执行.");
                   return;
               }
               try {
                   log.info("进入告警方法");
                   gameMonitorAlarmService.sendMsgToUser();
                   log.info("游戏监控告警定时任务结束.");
               } catch (Exception e) {
                   log.info("定时任务游戏监控告警出错", e);
               }
           }catch (Exception e){

               log.error("定时任务游戏监控告警出错", e);
           }
        };
        scheduler.submit(task);
        // 使用shutdown()优雅关闭
        scheduler.shutdown();
        try {
            // 等待所有任务完成，最多等待120秒
            if (!scheduler.awaitTermination(120, TimeUnit.SECONDS)) {
                log.info("线程池关闭超时，可能有任务未完成");
            }
        } catch (InterruptedException e) {
            // 当前线程被中断，通常应重新中断自己
            log.info("线程池关闭时当前线程被中断");
            Thread.currentThread().interrupt();

        }

        // 或使用shutdownNow()强制关闭
        List<Runnable> notStartedTasks = scheduler.shutdownNow();
        log.info("已取消 " + notStartedTasks.size() + " 个任务");
    }

    private void sendMsg(String msg) {
        log.info("发送告警消息：{}", msg);
        Date date = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, String> params = new HashMap<>();
        params.put(smsProperties.getMsgParamName(), msg);
        params.put(smsProperties.getTimeParamName(),formatter.format(date));
        String number = "15765577867";
        aliSmsService.send(smsProperties.getDefaultSignName(), smsProperties.getDefaultStstemErrorTemplate(), params, number);
    }

}
