package com.ruoyi.quartz.task;

import com.alibaba.fastjson2.JSON;
import com.ruoyi.common.constant.DeletedEnum;
import com.ruoyi.common.constant.ScheduleConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.doubledefense.domain.CheckTaskInventory;
import com.ruoyi.doubledefense.domain.CheckTaskInventoryRecord;
import com.ruoyi.doubledefense.dto.CheckTaskDTO;
import com.ruoyi.doubledefense.dto.res.CheckTaskResultDTO;
import com.ruoyi.doubledefense.service.ICheckTaskInventoryRecordService;
import com.ruoyi.doubledefense.service.ICheckTaskInventoryService;
import com.ruoyi.doubledefense.service.ICheckTaskService;
import com.ruoyi.doubledefense.service.impl.CheckTaskInventoryServiceImpl;
import com.ruoyi.system.service.ISysLogininforService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时生成巡检任务清单
 *
 * @author ruoyi
 */
@Slf4j
@Component("checkTaskInventoryTask")
public class CheckTaskInventoryTask {

    @Autowired
    private ICheckTaskService checkTaskService;
    @Autowired
    private ICheckTaskInventoryService checkTaskInventoryService;
    @Autowired
    private ICheckTaskInventoryRecordService checkTaskInventoryRecordService;


    /**
     * 定时任务主方法
     * 定时生成巡检任务清单
     * 1、查询排查要求任务表：需要判断是否已生成（防止重复生成）；是否满足生成时机（小时、天的每天生成；月的只有当月最后一天生成；年的只有当年最后一天生成）
     * 2、生成排查任务清单
     * 3、保存排查任务清单
     */
    public void checkTaskInventory() {
        log.info("定时生成巡检任务清单开始：{}", DateUtils.getTime());

        CheckTaskInventoryTask thisBean = SpringUtils.getBean(CheckTaskInventoryTask.class);


        CheckTaskDTO checkTask = new CheckTaskDTO();
        List<CheckTaskResultDTO> checkTaskList = checkTaskService.selectCheckTaskList(checkTask);
        for (CheckTaskResultDTO task : checkTaskList) {
            log.info("排查要求：{}", JSON.toJSONString(task));
            //巡查方式：1-单位周期N次；2-时间段内1次；
            Long checkTypeCount = task.getCheckTypeCount();
            //1-单位周期N次；
            if (checkTypeCount != null && checkTypeCount == 1) {

                boolean createFlag = thisBean.runCreateTaskNInTime(task);
                log.info("任务创建:{}，时间周期N次，taskId:{}, troubleshootContent:{},  ", createFlag, task.getId(), task.getTroubleshootContent());
            }
            //2-时间段内1次；
            else if (checkTypeCount != null && checkTypeCount == 2) {
                boolean createFlag = thisBean.runCreateTask(task);
                log.info("任务创建:{}，时间段一次，taskId:{}, troubleshootContent:{},  ", createFlag, task.getId(), task.getTroubleshootContent());
            } else {
                log.info("任务创建:异常，巡查方式取值错误，checkTypeCount:{},  ", checkTypeCount);
                continue;
            }
        }

//        CheckTaskInventory checkTaskInventory = new CheckTaskInventory();
//        List<CheckTaskInventory> checkTaskInventoryList = checkTaskInventoryService.selectCheckTaskInventoryList(checkTaskInventory);
//        for (CheckTaskInventory data : checkTaskInventoryList) {
//            System.out.println("任务明细 = " + data);
//        }
        log.info("定时生成巡检任务清单结束：{}", DateUtils.getTime());
    }

    /**
     * 生成排查任务清单：单位时间内生成N个任务
     *
     * @param task
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean runCreateTaskNInTime(CheckTaskResultDTO task) {
        try {
            String checkTaskId = task.getId();
//            Date startDate = task.getStartDate();
//            Date endDate = task.getEndDate();
            String companyCode = task.getCompanyCode();
            //巡查周期单位：小时，天，月，年
            String checkCycleUnit = task.getCheckCycleUnit();
            //频次
            int count = Math.toIntExact(task.getCheckCycle());
            List<CheckTaskInventory> list = checkTaskInventoryService.createCheckTaskInventoryTime(checkTaskId, checkCycleUnit, count);
            if (list == null || list.isEmpty()) {
                return true;
            }

            for (CheckTaskInventory checkTaskInventory : list) {
                checkTaskInventory.setId(UUID.randomUUID().toString()); // NOT NULL主键UUID
                checkTaskInventory.setCheckTaskId(checkTaskId);// NOT NULL隐患排查任务UUID
//                checkTaskInventory.setStartDate(startDate);//         NULL开始时间
//                checkTaskInventory.setEndDate(endDate);//         NULL结束时间
                checkTaskInventory.setStatus(0l);//排查状态：0未排查，1已排查
                checkTaskInventory.setIsDel(DeletedEnum.VALID.getValue());//         NOT NULL删除标识：0正常，1已删除
                checkTaskInventory.setCreateDate(new Date());//         NOT NULL创建时间
                checkTaskInventory.setCreateUserId(1l);//创建人ID
                checkTaskInventory.setUpdateDate(new Date());//NOT NULL更新时间
                checkTaskInventory.setUpdateUserId(1l);// NOT NULL更新人
                checkTaskInventory.setCompanyCode(companyCode);//企业编码
            }
            int insertCount = checkTaskInventoryService.batchInsertCheckTaskInventory(list);

            //保存到任务清单表记录表
            List<CheckTaskInventoryRecord> recordList = new ArrayList<>();
            for (CheckTaskInventory data : list) {
                CheckTaskInventoryRecord checkTaskInventoryRecord = new CheckTaskInventoryRecord();
                BeanUtils.copyProperties(data, checkTaskInventoryRecord);
                recordList.add(checkTaskInventoryRecord);
            }

            int insertRecordCount = checkTaskInventoryRecordService.batchInsertCheckTaskInventoryRecord(recordList);
            boolean addStatus = (insertCount == 0 || insertRecordCount == 0 || insertCount != insertRecordCount) ? false : true;
            if (!addStatus) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }

//            int a = 1 / 0;
            return true;
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            e.printStackTrace();
        }
        return false;
    }


    /**
     * 生成排查任务清单：指定时间内生成一个任务
     *
     * @param task
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean runCreateTask(CheckTaskResultDTO task) {
        String checkTaskId = task.getId();
        Date startDate = task.getStartDate();
        Date endDate = task.getEndDate();
        String companyCode = task.getCompanyCode();

        CheckTaskInventory param = new CheckTaskInventory();
        param.setCheckTaskId(checkTaskId);
        param.setIsDel(DeletedEnum.VALID.getValue());
        List<CheckTaskInventory> checkTaskInventoryList = checkTaskInventoryService.selectCheckTaskInventoryList(param);
        if (!checkTaskInventoryList.isEmpty()) {
            log.info("巡检任务明细已生成，无需重复生成");
            return true;
        }

        CheckTaskInventory checkTaskInventory = new CheckTaskInventory();
        checkTaskInventory.setId(UUID.randomUUID().toString()); // NOT NULL主键UUID
        checkTaskInventory.setCheckTaskId(checkTaskId);// NOT NULL隐患排查任务UUID
        checkTaskInventory.setStartDate(startDate);//         NULL开始时间
        checkTaskInventory.setEndDate(endDate);//         NULL结束时间
        checkTaskInventory.setStatus(Long.parseLong(ScheduleConstants.Status.NORMAL.getValue()));//         NOT NULL排查状态：0未排查，1已排查
//        checkTaskInventory.setremark_info        (500) NULL备注
//        checkTaskInventory.setIsDel(DeletedEnum.VALID.getValue());//         NOT NULL删除标识：0正常，1已删除
//        checkTaskInventory.setCreateDate(new Date());//         NOT NULL创建时间
        checkTaskInventory.setCreateUserId(1l);//创建人ID
//        checkTaskInventory.setUpdateDate(new Date());//NOT NULL更新时间
        checkTaskInventory.setUpdateUserId(1l);// NOT NULL更新人
        checkTaskInventory.setCompanyCode(companyCode);//企业编码
        //保存到任务清单表
        int insertCount = checkTaskInventoryService.insertCheckTaskInventory(checkTaskInventory);

        //保存到任务清单表记录表
        CheckTaskInventoryRecord checkTaskInventoryRecord = new CheckTaskInventoryRecord();
        BeanUtils.copyProperties(checkTaskInventory, checkTaskInventoryRecord);
        int insertRecordCount = checkTaskInventoryRecordService.insertCheckTaskInventoryRecord(checkTaskInventoryRecord);
        boolean addStatus = (insertCount == 0 || insertRecordCount == 0 || insertCount != insertRecordCount) ? false : true;
        if (!addStatus) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return addStatus;
    }

}
