package com.cpop.oam.framework.tasks;

import com.cpop.core.utils.SpringUtils;
import com.cpop.oam.business.entity.DataImport;
import com.cpop.oam.business.entity.Task;
import com.cpop.oam.business.entity.table.DataImportTableDef;
import com.cpop.oam.business.service.DataImportService;
import com.cpop.oam.business.service.DutyService;
import com.cpop.oam.business.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDate;
import java.util.List;
import java.util.stream.Collectors;

import static com.cpop.oam.business.entity.table.TaskTableDef.TASK;


/**
 * @author DB
 * @createTime 2023/11/22 18:07
 * @description
 */
@Slf4j
@Configuration
@Profile("prod")
public class OamScheduledTasks {

    @Autowired
    private DutyService dutyService;

    /**
     * @descriptions 每天9点通知值班人员
     * @author DB
     * @date 2023/11/22 18:08
     * @return: void
     */
    @Scheduled(cron = "0 0 9 * * *")
    public void dutyNotice() {
        dutyService.dutyNotice();
    }

    /**
     * 凌晨20分同步导入的数据
     * @author DB
     * @since 2023/12/10
     */
    @Scheduled(cron = "0 20 0 * * *")
    public void syncImportData() throws InterruptedException {
        log.info("==============开始同步校区数据===========");
        long start = System.currentTimeMillis();
        DataImportService dataImportService = SpringUtils.getBean(DataImportService.class);
        List<DataImport> dataList = dataImportService.queryChain()
                .where(DataImportTableDef.DATA_IMPORT.IMPORT_STATUS.eq(false)).list();
        for (DataImport item : dataList) {
            SpringUtils.getBean(DataImportAsyncTask.class).asyncUpdateShoppingCartAmount(item);
            Thread.sleep(600000);
        }
        long end = System.currentTimeMillis();
        log.info("同步校区数据执行时间：{}ms", end - start);
    }

    /**
     * 检查任务是否逾期
     * @author DB
     * @since 2023/12/11
     */
    @Scheduled(cron = "0 10 0 * * *")
    public void checkTaskWhetherFinish() {
        log.info("==============开始检查进行中任务===========");
        TaskService taskService = SpringUtils.getBean(TaskService.class);
        List<Task> taskList = taskService.queryChain().where(TASK.TASK_STATUS.in(2, 3)).and(TASK.TASK_TYPE.in(0, 1)).list();
        List<Task> filterList = taskList.stream().filter(item -> item.getExpectedCompletionDate().plusDays(1).isBefore(LocalDate.now())).collect(Collectors.toList());
        if (!filterList.isEmpty()) {
            //任务项逾期
            taskService.updateChain().set(TASK.TASK_ITEM, -1).where(TASK.ID.in(filterList.stream().map(Task::getId).collect(Collectors.toSet()))).update();
        }
    }
}
