package cn.wisenergy.web.config.auto;

import cn.wisenergy.common.utils.exception.BASE_RESP_CODE_ENUM;
import cn.wisenergy.common.utils.exception.BaseCustomException;
import cn.wisenergy.mapper.WorkTimeOrderMapper;
import cn.wisenergy.model.app.WorkSubmitAdopt;
import cn.wisenergy.model.app.WorkTimeOrder;
import cn.wisenergy.service.WorkCollectService;
import cn.wisenergy.service.WorkSubmitAdoptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

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


@Component
@Configuration
@EnableScheduling
public class Trigger implements SchedulingConfigurer {

    @Autowired
    private WorkTimeOrderMapper workTimeOrderMapper;

    @Autowired
    private WorkCollectService workCollectService;

    @Autowired
    private WorkSubmitAdoptService workSubmitAdoptService;


    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        TriggerTask trigerTask = new TriggerTask(
                () -> {
                    //这里写业务方法
                    WorkSubmitAdopt workSubmitAdopt = workSubmitAdoptService.getById(1);
                    Integer autoExamine = workSubmitAdopt.getAutoExamine();
                    if (null == autoExamine && 0 == autoExamine) {
                        throw new BaseCustomException(BASE_RESP_CODE_ENUM.INPUT_PARAM_IS_NULL);
                    }
                    //  更新work_time_order表
                    List<WorkTimeOrder> workTimeOrders = workTimeOrderMapper.getAutoOrder(autoExamine*24);
                    if (!CollectionUtils.isEmpty(workTimeOrders)) {
                        List<Integer> projectIds = new ArrayList<>();
                        workTimeOrders.forEach(wto -> projectIds.add(wto.getWorkId()));
                        workTimeOrderMapper.updateAutoExamine(projectIds);
                        // 更新work_collect表
                        workCollectService.updateByWorkTimeOrder(workTimeOrders);
                    }

                }
                , triggerContext -> {

            Integer autoAdopt = workSubmitAdoptService.getById(1).getAutoAdopt();
            String time = "0 0 0 */" + autoAdopt + " * ?";
            //返回执行的周期
            return new CronTrigger(time).nextExecutionTime(triggerContext);
        });
        scheduledTaskRegistrar.addTriggerTask(trigerTask);
    }
}
