package com.artfess.yhxt.specialcheck.schedule;


import com.artfess.base.util.AppUtil;

import com.artfess.base.util.DateUtils;
import com.artfess.workflow.runtime.manager.IProcessManager;
import com.artfess.workflow.runtime.params.StartFlowParamObject;
import com.artfess.yhxt.specialcheck.dao.InspectionTaskConfigDao;
import com.artfess.yhxt.specialcheck.manager.SiteInspectionManager;
import com.artfess.yhxt.specialcheck.manager.impl.InspectionTaskConfigManagerImpl;
import com.artfess.yhxt.specialcheck.model.InspectionTaskConfig;
import com.artfess.yhxt.specialcheck.model.SiteInspection;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.Period;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author zhx
 * @create 2021/8/27
 */
@Component
@EnableScheduling
public class ScheduledInspectionTask {
    @Resource
    private SiteInspectionManager siteInspectionManager;
    @Resource
    private InspectionTaskConfigDao inspectionTaskConfigDao;

    @Resource
    private IProcessManager iProcessManager;

    @Scheduled(cron = "0 30 1 * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void scheduledInspectionTask() throws Exception {
        System.out.println("定时器开始执行");
        QueryWrapper<InspectionTaskConfig> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("IS_DELE_", 0);
        queryWrapper.eq("STATUS_","0");
        List<InspectionTaskConfig> taskConfigs = this.inspectionTaskConfigDao.selectList(queryWrapper);
        for (InspectionTaskConfig taskConfig : taskConfigs) {
            //每月
            if (taskConfig.getTaskType() == 1) {
                inspectionTaskStartMouth(taskConfig);
            }
            //每天执行
            if (taskConfig.getTaskType() == 2) {
                if (LocalDate.now().isAfter(taskConfig.getPatrolDate()) || LocalDate.now().equals(taskConfig.getPatrolDate())) {
                    this.inspectionTaskStart(taskConfig);
                }
            }
        }
        System.out.println("定时器结束执行");
    }

    //每月
    private void inspectionTaskStartMouth(InspectionTaskConfig taskConfig) throws Exception {
        //配置开始时间
        LocalDate patrolDate = taskConfig.getPatrolDate();
        Calendar ca = Calendar.getInstance();
        ca.setTime(new Date());
        //判断是否到达该日期
        if (LocalDate.now().isAfter(patrolDate) && ca.get(Calendar.DAY_OF_MONTH) == 1) {
            Calendar calendar = DateUtils.getCalendar();
            calendar.set(Calendar.DATE, 1);
            calendar.roll(Calendar.DATE, -1);
            //获取本月天数
            int maxDate = calendar.get(Calendar.DATE);
            //根据频率来生成巡检任务
            //相隔多少天巡检一次
            int count = maxDate / taskConfig.getFrequency();
            //获取本月第一天
            Calendar cal = DateUtils.getCalendar();
            cal.add(Calendar.MONTH, 0);
            cal.set(Calendar.DAY_OF_MONTH, 1);
            for (Integer i = 0; i < taskConfig.getFrequency(); i++) {
                if (i > 0) {
                    cal.add(Calendar.DATE, count);
                }
                if (LocalDate.now().equals(cal.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())) {
                    SiteInspection siteInspection = new SiteInspection();
                    //1.保存到巡检表中
                    //路段ID
                    siteInspection.setRouteId(taskConfig.getRouteId());
                    siteInspection.setRouteName(taskConfig.getRouteName());
                    //路段
                    siteInspection.setRoadSegmentId(taskConfig.getRoadSegmentId());
                    siteInspection.setRoadSegmentName(taskConfig.getRoadSegmentName());
                    //公司
                    siteInspection.setCompanyId(taskConfig.getCompanyId());
                    siteInspection.setCompanyName(taskConfig.getCompanyName());
                    //管理中心
                    siteInspection.setManageUnitId(taskConfig.getManageUnitId());
                    siteInspection.setManageUnitName(taskConfig.getManageUnitName());
                    //巡检人
                    siteInspection.setRummagerId(taskConfig.getRummagerId());
                    //巡检人账号
                    siteInspection.setRummagerAccount(taskConfig.getRummagerAccount());
                    siteInspection.setType(taskConfig.getType());
                    //巡检内容
                    siteInspection.setContent(taskConfig.getContent());
                    //巡检日期
                    LocalDate time = cal.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    siteInspection.setPatrolDate(time);
                    siteInspection.setCreateBy(taskConfig.getCreateBy());
                    siteInspection.setCreateCompanyName(taskConfig.getCreateCompanyName());
                    siteInspection.setCreateCompanyId(taskConfig.getCreateCompanyId());
                    siteInspection.setCreateOrgId(taskConfig.getCreateCompanyId());
                   // System.out.println(siteInspection);
                    this.siteInspectionManager.saveSite(siteInspection);

                }
            }
        }

        if (LocalDate.now().equals(patrolDate)) {
            //当前日期
            LocalDate localDate = LocalDate.now();
            LocalDate lastDate = localDate.with(TemporalAdjusters.lastDayOfMonth());
            //本月还有多少天
            int days = Period.between(localDate, lastDate).getDays();
            int count = days / taskConfig.getFrequency();
            Calendar cal = DateUtils.getCalendar();
            for (Integer i = 0; i < taskConfig.getFrequency(); i++) {
                if (i > 0) {
                    cal.add(Calendar.DATE, count);
                }
                if (LocalDate.now().equals(cal.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate())) {
                    SiteInspection siteInspection = new SiteInspection();
                    //1.保存到巡检表中
                    //路段ID
                    siteInspection.setRouteId(taskConfig.getRouteId());
                    siteInspection.setRouteName(taskConfig.getRouteName());
                    //路段
                    siteInspection.setRoadSegmentId(taskConfig.getRoadSegmentId());
                    siteInspection.setRoadSegmentName(taskConfig.getRoadSegmentName());
                    //公司
                    siteInspection.setCompanyId(taskConfig.getCompanyId());
                    siteInspection.setCompanyName(taskConfig.getCompanyName());
                    //管理中心
                    siteInspection.setManageUnitId(taskConfig.getManageUnitId());
                    siteInspection.setManageUnitName(taskConfig.getManageUnitName());
                    //巡检人
                    siteInspection.setRummagerId(taskConfig.getRummagerId());
                    //巡检人账号
                    siteInspection.setRummagerAccount(taskConfig.getRummagerAccount());
                    siteInspection.setType(taskConfig.getType());
                    //巡检内容
                    siteInspection.setContent(taskConfig.getContent());
                    //巡检日期
                    //LocalDate time = cal.getTime().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
                    siteInspection.setPatrolDate(LocalDate.now());
                    //巡检路段
                    siteInspection.setCreateOrgId(taskConfig.getCreateOrgId());
                    siteInspection.setCreateName(taskConfig.getCreateName());
                    System.out.println(siteInspection);
                    this.siteInspectionManager.saveSite(siteInspection);
//                    //2.启动任务
//                    StartFlowParamObject startFlowParam = new StartFlowParamObject();
//                    //2.1流程ID
//                    startFlowParam.setDefId("1427807759855915008");
//                    startFlowParam.setBusinessKey(siteInspection.getId());
//                    startFlowParam.setFormType("frame");
//                    startFlowParam.setSupportMobile(0);
//                    //巡检人账号
//                    startFlowParam.setAccount(taskConfig.getRummagerAccount());
//                    iProcessManager.start(startFlowParam);
                }
            }
        }
    }

    //每天执行
    private void inspectionTaskStart(InspectionTaskConfig taskConfig) throws Exception {
        for (Integer i = 0; i < taskConfig.getFrequency(); i++) {
            SiteInspection siteInspection = new SiteInspection();
            //1.保存到巡检表中
            //路段ID
            siteInspection.setRouteId(taskConfig.getRouteId());
            siteInspection.setRouteName(taskConfig.getRouteName());
            //路段
            siteInspection.setRoadSegmentId(taskConfig.getRoadSegmentId());
            siteInspection.setRoadSegmentName(taskConfig.getRoadSegmentName());
            //公司
            siteInspection.setCompanyId(taskConfig.getCompanyId());
            siteInspection.setCompanyName(taskConfig.getCompanyName());
            //管理中心
            siteInspection.setManageUnitId(taskConfig.getManageUnitId());
            siteInspection.setManageUnitName(taskConfig.getManageUnitName());
            //巡检人
            siteInspection.setRummagerId(taskConfig.getRummagerId());
            //巡检人账号
            siteInspection.setRummagerAccount(taskConfig.getRummagerAccount());
            siteInspection.setType(taskConfig.getType());
            //巡检内容
            siteInspection.setContent(taskConfig.getContent());
            //巡检日期
            siteInspection.setPatrolDate(LocalDate.now());
            siteInspection.setCreateBy(taskConfig.getCreateBy());
            siteInspection.setCreateName(taskConfig.getCreateName());
            siteInspection.setCreateCompanyName(taskConfig.getCreateCompanyName());
            siteInspection.setCreateCompanyId(taskConfig.getCreateCompanyId());
            siteInspection.setCreateOrgId(taskConfig.getCreateCompanyId());

            siteInspection.setCreateOrgId(taskConfig.getCreateOrgId());
            siteInspection.setCreateName(taskConfig.getCreateName());
            this.siteInspectionManager.saveSite(siteInspection);
        }
    }


}
