package com.storlead.sales.task.dispatch;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
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.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.StringUtil;
import com.storlead.message.enums.MessageTypeEnum;
import com.storlead.message.service.impl.MessageService;
import com.storlead.sales.pojo.entity.customer.*;
import com.storlead.sales.pojo.entity.task.TaskEntity;
import com.storlead.sales.service.customer.*;
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.*;
import java.util.stream.Collectors;

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2025-04-30 15:04
 */
@Slf4j
@Component
@NoArgsConstructor
@DisallowConcurrentExecution
public class TaskMessageOutTimeRemindAutoTask  implements Job {

    @Resource
    private TaskService taskService;

    @Resource
    private MessageService messageService;

    @Resource
    private CustomerService customerService;

    @Resource
    private LiaisonService liaisonService;

    @Resource
    private BusinessService businessService;

    @Resource
    private WorkOrderService workOrderService;

    @Resource
    private OrderFormService orderFormService;

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

        LambdaQueryWrapper<TaskEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TaskEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.eq(TaskEntity::getTaskStatus, Integer.valueOf(3));
        wrapper.eq(TaskEntity::getOutTimeRemind, CommonConstant.DEL_FLAG_0);
        wrapper.isNull(TaskEntity::getRemindTime);
        LocalDateTime fiveMinutesLater = LocalDateTime.now().minusMinutes(5);
        wrapper.le(TaskEntity::getTaskBeginTime, fiveMinutesLater);
        List<TaskEntity> list = taskService.list(wrapper);
        list.forEach(
                (t)->{
                    Long ownerBy = t.getOwnerBy();
                    Set<Long> toUserIds = new HashSet<>();
                    if (Objects.nonNull(ownerBy)) {
                        toUserIds.add(ownerBy);
                    }
                    if (Objects.nonNull(t.getCreateBy())) {
                        toUserIds.add(t.getCreateBy());
                    }
                    if (StrUtil.isNotBlank(t.getCooperateBy())) {
                        String[] values = StringUtil.trimSpace(t.getCooperateBy(),",").split(",");
                        if (Objects.nonNull(values) && values.length > 0) {
                            Set<Long> cooperateBys  =  Arrays.asList(values).stream().map(Long::valueOf).collect(Collectors.toSet());
                            if (CollectionUtils.isNotEmpty(cooperateBys)) {
                                toUserIds.addAll(cooperateBys);
                            }
                        }
                    }

//                    toUserIds.add(t.getCreateBy());
//                    //根据任务关联业务类型发送给业务对应的负责人
//                    if (!ObjectUtils.isEmpty(t.getCustomerId())){
//                        CustomerEntity customer = customerService.getById(t.getCustomerId());
//                        if (Objects.nonNull(customer)) {
//                            toUserIds.add(customer.getOwnerBy());
//                        }
//                    }

                    Map<String, Object> beanMap = BeanUtil.beanToMap(t);
                    if (Objects.nonNull(t.getResourceTypeId())) {
                        beanMap.put("id",t.getResourceTypeId());
                    }
                    beanMap.put("callbackUrl",getRouteUrl(t.getResourceType()));
                    if (checkResourceIsDelete(t.getResourceType(),t.getResourceTypeId())) {
                        messageService.autoMatchEventSendMessage(beanMap,"80","DISPATCH_TASK_OUT_TIME",toUserIds,t.getRemindMode().split(","));
                    }
                }
        );
        if (CollectionUtils.isNotEmpty(list)) {
            updateOutRemindTimeByTaskId(list.stream().map(TaskEntity::getId).collect(Collectors.toList()));
        }
    }

    public String getRouteUrl(String resourceType) {
        if (MessageTypeEnum.CUSTOMER.getCode().equals(resourceType)) {
            return  "/customer/customerDetail?id=${id}$";
        } else if (MessageTypeEnum.CLUS.getCode().equals(resourceType)) {
            return  "/clue/detail?id=${id}$";
        } else if (MessageTypeEnum.LIAISON.getCode().equals(resourceType)) {
            return  "/liaison/detail?id=${id}$";
        } else if (MessageTypeEnum.BUSINESS.getCode().equals(resourceType)) {
            return  "/business_opportunity/detail?id=${id}$&type=detail&from=allBusiness";
        } else if (MessageTypeEnum.ORDER_FORM.getCode().equals(resourceType)) {
            return  "/order/detail?id=${id}$";
        }
        return "";
    }

    private void updateOutRemindTimeByTaskId(List<Long> taskIds) {
        LambdaUpdateWrapper<TaskEntity> wrapper = Wrappers.lambdaUpdate();
        wrapper.set(TaskEntity::getOutTimeRemind,1);
        wrapper.in(TaskEntity::getId,taskIds);
        taskService.update(wrapper);
    }



    /**
     * 业务没有删除才发提醒
     * @param resourceType
     * @param resourceTypeId
     * @return
     */
    public Boolean checkResourceIsDelete(String resourceType, Long resourceTypeId){
        if (StrUtil.isBlank(resourceType) || Objects.isNull(resourceTypeId)) {
            return false;
        }
        if (MessageTypeEnum.CUSTOMER.getCode().equals(resourceType)
                || MessageTypeEnum.CLUS.getCode().equals(resourceType)) {
            CustomerEntity customer = customerService.getById(resourceTypeId);
            if (Objects.nonNull(customer)) {
                return Integer.valueOf(0).equals(customer.getIsDelete()) ? true : false;
            }
        } else if (MessageTypeEnum.LIAISON.getCode().equals(resourceType)) {
            // 联系人
            LiaisonEntity liaison = liaisonService.getById(resourceTypeId);
            if (Objects.nonNull(liaison)) {
                return Integer.valueOf(0).equals(liaison.getIsDelete()) ? true : false;
            }
        } else if (MessageTypeEnum.BUSINESS.getCode().equals(resourceType)) {
            // 商机
            BusinessEntity business = businessService.getById(resourceTypeId);
            if (Objects.nonNull(business)) {
                return Integer.valueOf(0).equals(business.getIsDelete()) ? true : false;
            }
        } else if (MessageTypeEnum.ORDER_FORM.getCode().equals(resourceType)) {
            // 订单
            OrderFormEntity orderForm = orderFormService.getById(resourceTypeId);
            if (Objects.nonNull(orderForm)) {
                return Integer.valueOf(0).equals(orderForm.getIsDelete()) ? true : false;
            }
        } else if (MessageTypeEnum.WORK_ORDER.getCode().equals(resourceType)) {
            // 工单
            WorkOrderEntity workOrder = workOrderService.getById(resourceTypeId);
            if (Objects.nonNull(workOrder)) {
                return Integer.valueOf(0).equals(workOrder.getIsDelete()) ? true : false;
            }
        }
        return false;
    }
}
