package com.storlead.sales.task.dispatch;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.storlead.message.service.impl.MessageService;
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.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

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

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-08-13 10:06
 */
@Slf4j
@Component
@NoArgsConstructor
@DisallowConcurrentExecution
public class AutoTakeMailDispatchTaskJob implements Job {

    @Resource
    private TaskService taskService;

    @Resource
    private MessageService messageService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {

        LambdaQueryWrapper<TaskEntity> wrapper = new LambdaQueryWrapper<>();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime triggerTime = now;
        LocalDateTime endTriggerTime = now.plusMinutes(5);
        wrapper.between(TaskEntity::getRemindTime,triggerTime,endTriggerTime);
        List<TaskEntity> list = taskService.list(wrapper);
        list.forEach(
                (t)->{
                    Map<String, Object> beanMap = BeanUtil.beanToMap(t);
                    // messageService.autoMatchEventSendMessage(beanMap,"task",t.getRemindMode().split(","));
                }
        );
        if (CollectionUtils.isNotEmpty(list)) {
            clearRemindTimeByTaskId(list.stream().map(TaskEntity::getId).collect(Collectors.toList()));
        }
    }

    private void clearRemindTimeByTaskId(List<Long> taskIds) {
        LambdaUpdateWrapper<TaskEntity> wrapper = Wrappers.lambdaUpdate();
        wrapper.set(TaskEntity::getRemindTime,null);
        wrapper.eq(TaskEntity::getId,taskIds);
        taskService.update(wrapper);
    }
}
