package com.storlead.sales.task.dispatch;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.sales.enums.TaskStatusEnum;
import com.storlead.sales.pojo.entity.task.TaskEntity;
import com.storlead.sales.service.task.TaskService;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.quartz.DisallowConcurrentExecution;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-09-21 15:03
 */
@Slf4j
@Component
@NoArgsConstructor
@DisallowConcurrentExecution
public class AutoTaskStatuChangeJob implements Job {

    @Resource
    private TaskService taskService;
    @Override
    public void execute(JobExecutionContext jobExecutionContext) {
        LambdaQueryWrapper<TaskEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskEntity::getTaskStatus, TaskStatusEnum.UNSTART.getCode());
        wrapper.le(TaskEntity::getTaskBeginTime, LocalDateTime.now());
        wrapper.eq(TaskEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        List<TaskEntity> ts = taskService.list(wrapper);
        if (!CollectionUtils.isEmpty(ts)) {
           List<Long> tIds = ts.stream().map(TaskEntity::getId).collect(Collectors.toList());
           LambdaUpdateWrapper<TaskEntity> updateWrapper = new LambdaUpdateWrapper<>();
           updateWrapper.set(TaskEntity::getTaskStatus, TaskStatusEnum.OVERTIME.getCode());
           updateWrapper.in(TaskEntity::getId, tIds);
           taskService.update(updateWrapper);
        }
    }
}
