package com.tykj.dev.device.selfcheck.base;

import com.tykj.dev.config.TaskBeanConfig;
import com.tykj.dev.config.repository.SystemVariableDao;
import com.tykj.dev.config.service.SystemVariableService;
import com.tykj.dev.device.selfcheck.service.SelfCheckBillService;
import com.tykj.dev.device.selfcheck.subject.domin.SelfCheckBill;
import com.tykj.dev.device.task.service.TaskService;
import com.tykj.dev.device.task.subject.bto.TaskBto;
import com.tykj.dev.device.user.subject.dao.UnitsDao;
import com.tykj.dev.device.user.subject.entity.Units;
import com.tykj.dev.misc.base.StatusEnum;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.concurrent.ScheduledFuture;

/**
 * @author dengdiyi
 */
@Slf4j
@Component
@EnableAsync
@Data
public class SelfCheckSchedulerTask {

    private String cron = "0 0 0 1 1/3 ? ";

    /**
     * 月度
     */
    private String cron1 = "0 0 0 1 1/1 ? ";
    /**
     * 季度
     */
    private String cron2 = "0 0 0 1 1,4,7,10 ? ";
    /**
     * 年度
     */
    private String cron3 = "0 0 0 1 1 ? ";

    private String cron4 = "0 0/1 * * * ? ";

    final UnitsDao unitsDao;

    final TaskService taskService;

    final SystemVariableService systemVariableService;

    final SystemVariableDao systemVariableDao;

    final SelfCheckBillService selfCheckBillService;

    private ScheduledFuture scheduledFuture;

    public SelfCheckSchedulerTask(UnitsDao unitsDao,TaskService taskService,SystemVariableService systemVariableService,SystemVariableDao systemVariableDao,SelfCheckBillService selfCheckBillService) {
        this.unitsDao = unitsDao;
        this.taskService = taskService;
        this.systemVariableService = systemVariableService;
        this.systemVariableDao = systemVariableDao;
        this.selfCheckBillService = selfCheckBillService;
        String value;
        if (systemVariableDao.findAll().size()==0){
            value = this.cron;
        }
        else {
            value = Objects.requireNonNull(systemVariableService).getVaule("selfCheckCycle");
            if (value.length()!=14){
                value = cron;
            }
        }
//        if ("month".equals(value)){
//            setCron(cron1);
//        }
//        if ("quarter".equals(value)){
//            setCron(cron2);
//        }
//        if ("year".equals(value)){
//            setCron(cron3);
//        }
//        if ("minute".equals(value)){
//            setCron(cron4);
//        }
        setCron(value);
        scheduledFuture = TaskBeanConfig.getThreadPoolTaskScheduler().schedule(new SelfCheckTask(), triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext));
    }

    public class SelfCheckTask implements Runnable{
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void run() {
            if (unitsDao != null && taskService!=null && selfCheckBillService!=null) {
                List<Units> unitsList = unitsDao.findAll();
                unitsList.forEach(units -> {
                    //添加账单
                    SelfCheckBill selfCheckBill = new SelfCheckBill();
                    selfCheckBill.setCheckStatus(3);
                    selfCheckBill.setCheckUnit(units.getName());
                    StringBuffer title = new StringBuffer();
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(new Date());
                    int year = calendar.get(Calendar.YEAR);
                    int month = calendar.get(Calendar.MONTH)+1;
                    title.append(year).append("年");
                    title.append(month).append("月自查任务");
                    int type;
                    if (' '==cron.charAt(11)) {
                        type = Integer.parseInt(cron.substring(10,11));
                    }
                    else {
                        type = Integer.parseInt(cron.substring(10,12));
                    }
                    if (type==1) {
                        selfCheckBill.setCycle(1);
                    }
                    else if (type==3){
                        selfCheckBill.setCycle(2);
                    }
                    else if (type==12){
                        selfCheckBill.setCycle(3);
                    }
                    else {
                        selfCheckBill.setCycle(type+2);
                    }
//                    if (cron.equals(cron1)){
//                        title.append(month).append("月自查任务");
//                        selfCheckBill.setCycle(1);
//                    }
//                    else if (cron.equals(cron2)){
//                        title.append(getQuarter(month)).append("自查任务");
//                        selfCheckBill.setCycle(2);
//                    }
//                    else if (cron.equals(cron3)){
//                        title.append("自查任务");
//                        selfCheckBill.setCycle(3);
//                    }
//                    else {
//                        title.append("自查任务");
//                        selfCheckBill.setCycle(0);
//                    }
                    selfCheckBill.setTitle(title.toString());
                    SelfCheckBill selfCheckBill1 = selfCheckBillService.addEntity(selfCheckBill);
                    //发起待自查任务
                    List<Integer> userIds = new ArrayList<>();
                    userIds.add(0);
                    TaskBto taskBto = new TaskBto(StatusEnum.WAIT_SELF_CHECK.id,"自查业务",null,".",selfCheckBill1.getId(),4,units.getUnitId(),0,null,userIds);
                    taskService.start(taskBto);
                });
            }
            log.info("[自查模块]:自查定时任务执行了");
        }
    }

    public void startTask(){
        scheduledFuture = TaskBeanConfig.getThreadPoolTaskScheduler().schedule(new SelfCheckTask(), triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext));
    }

    /**
     * 当前月份属于本年第几个季度
     */
    public static String getQuarter(int month) {
        if (month <= 3) {
            return "第一季度";
        } else if (month <= 6) {
            return "第二季度";
        } else if (month <= 9) {
            return "第三季度";
        } else {
            return "第四季度";
        }
    }
}
