package com.pqs9900.task;

import cn.hutool.core.collection.CollectionUtil;
import com.njcn.utils.PubUtils;
import com.pqs9900.mapper.message.MessageMapper;
import com.pqs9900.mapper.message.MsgCofMapper;
import com.pqs9900.pojo.message.*;
import com.pqs9900.service.message.MessageService;
import jdk.nashorn.internal.runtime.arrays.ArrayLikeIterator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.CronTask;
import org.springframework.scheduling.config.ScheduledTask;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class SendMessage implements SchedulingConfigurer {
    private static final Logger logger = LoggerFactory.getLogger(SendMessage.class);

    private String cron;
    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private MsgCofMapper msgCofMapper;

    @Autowired
    private MessageService messageService;

    private ScheduledTask scheduledTask;
    private ScheduledTaskRegistrar taskRegistrar;


    public ScheduledTaskRegistrar getTaskRegistrar() {
        return taskRegistrar;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        this.taskRegistrar = taskRegistrar;
        start(taskRegistrar);
    }

    private Runnable task(Integer offDay,List<Integer> waveList,Integer intervalTime,List<MsgTypeTemplateDTO> list,Integer[] arr) {
        return new Runnable() {
            @Override
            public void run() {
                //获取当前执行时间
                Calendar calendarEnd = Calendar.getInstance();
                Date endT = calendarEnd.getTime();

                Calendar calendarBeforeInterver = Calendar.getInstance();
                calendarBeforeInterver.add(Calendar.DAY_OF_MONTH,-1);
                Date startT = calendarBeforeInterver.getTime();


                //判断当前时间是否在发送时间内,在则发送短信
               if(list!=null && list.size()!=0){
                   for(int i = 0;i<list.size();i++) {
                       if (list.get(i).getState() == 1) { /*模板启用状态有效*/
                           Integer beg = list.get(i).getValue1().intValue();
                           Integer end = list.get(i).getValue2().intValue();

                           Calendar calendar = Calendar.getInstance();
                           int hour = calendar.get(Calendar.HOUR_OF_DAY);
                           if (hour >= beg && hour < end) {
                               //获取最新发送时间
                               MsgInfoDTO msgInfoDTO = messageMapper.getLastTime();
                               Date start = null;
                               if(msgInfoDTO == null){
                                   //获取上一次执行时间
                                   Calendar calendarBeg = Calendar.getInstance();
                                   calendarBeg.add(Calendar.DATE,-1);
                                   start = calendarBeg.getTime();
                               }else {
                                   start = startT;
                               }



                              /* SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                               Date a =null;
                               Date b =null;
                               try {
                                   a=sdf.parse("2021-03-25 18:00:00");
                                   b =sdf.parse("2021-03-25 18:05:00");
                               } catch (ParseException e) {
                                   e.printStackTrace();
                               }*/

                               System.out.println(start);

                               messageService.sendMsg(null,null,waveList,start,endT,intervalTime,arr);
                           }
                       }
                   }
               }

            }
        };
    }



    public void start(ScheduledTaskRegistrar taskRegistrar) {
        if (taskRegistrar == null) {
            return;
        }

        MsgBaseConfDTO msgBaseConfDTO = msgCofMapper.getMsgConfig();
        if(msgBaseConfDTO == null){
            return;
        }
        if(msgBaseConfDTO.getIsSend()!=1){
            //0.不启用 1.启用
            return;
        }

        //获取类型
        List<Integer> waveList = new ArrayList<>();
        List<MsgTypeTemplateDTO> listType = msgCofMapper.getMsgDicdataList(2,1);
        if(!CollectionUtil.isEmpty(listType)){
            for(MsgTypeTemplateDTO mt:listType){
                String name = mt.getMsgName();
                Integer waveType = getTypeIndex(name);
                waveList.add(waveType);
            }
        }

        Integer intervalTime = msgBaseConfDTO.getTimeInterval();
        Integer offDay = msgBaseConfDTO.getOffDay();
        List<MsgTypeTemplateDTO> list = msgCofMapper.getMsgDicdataList(1,1);
        Integer[] arr = getBrokeTime(list);
        cron = "0 */"+intervalTime+" * * * ?";
        this.scheduledTask = taskRegistrar.scheduleCronTask(new CronTask(task(offDay,waveList,intervalTime,list,arr), cron));
    }

    public void stop() {
        if (this.scheduledTask != null) {
            this.scheduledTask.cancel();
        }
    }

    private Integer getTypeIndex(String name){
        switch (name){
            case "扰动":
                return 0;
            case "暂降":
                return 1;
            case "暂升":
                return 2;
            case "中断":
                return 3;
            case "录波":
                return 5;
            default:
                return 4;
        }

    }

    /**
     * 获取最早执行时间和最晚执行时间
     * @author cdf
     * @date 2021/5/12
     */
    public Integer[] getBrokeTime(List<MsgTypeTemplateDTO> list){
        Integer[] arr = new Integer[2];
        if(CollectionUtil.isNotEmpty(list)){
            List<Integer> begin = new ArrayList<>();
            List<Integer> end = new ArrayList<>();
            for(MsgTypeTemplateDTO m: list){
                begin.add(m.getValue1().intValue());
                end.add(m.getValue2().intValue());
            }

            Integer max = Collections.max(end);
            Integer min = Collections.min(begin);
            arr[0]=min;
            arr[1]=max;

        }
        return arr;
    }
}
