package com.storlead.sales.service.impl.task;

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.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.SpringCompareUtil;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.message.enums.MessageTypeEnum;
import com.storlead.sales.pojo.dto.customer.CustomerSearchSearchDTO;
import com.storlead.sales.pojo.entity.customer.*;
import com.storlead.sales.pojo.vo.customer.BusinessDetailVO;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.enums.TaskStatusEnum;
import com.storlead.sales.pojo.dto.task.UpdateTaskDTO;
import com.storlead.sales.pojo.entity.task.TaskEntity;
import com.storlead.sales.pojo.vo.task.TaskVO;
import com.storlead.sales.service.customer.*;
import com.storlead.sales.mapper.task.TaskMapper;
import com.storlead.sales.service.task.TaskService;
import com.storlead.system.pojo.dto.DictExtQueryParam;
import com.storlead.system.pojo.entity.SysDictDetailEntity;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

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

/**
 * <p>
 * 任务表 服务实现类
 * </p>
 *
 * @author chenkq
 * @since 2024-04-16
 */
@Service
public class TaskServiceImpl extends MyBaseServiceImpl<TaskMapper, TaskEntity> implements TaskService {

    @Resource
    private CustomerService customerService;

    @Resource
    private WorkOrderService workOrderService;

    @Resource
    private BusinessService businessService;

    @Resource
    private LiaisonService liaisonService;

    @Resource
    private OrderFormService orderFormService;

    @Override
    public Boolean addTask(TaskEntity entity) {
        if (!Boolean.TRUE.equals(entity.getIsCreateTask())) {
            return true;
        }
        LocalDateTime startDateTime = entity.getTaskBeginTime();
        if (Objects.nonNull(entity.getRemindType())) {
            entity.setRemindTime(startDateTime.minusMinutes(entity.getRemindType()));
        } else {
            entity.setRemindTime(null);
        }
        if (!CollectionUtils.isEmpty(entity.getRemindModels())) {
            entity.setRemindMode(StringUtils.join(entity.getRemindModels(),","));
        }
        entity.setTaskStatus(0);
        return saveOrUpdate(entity);
    }

    @Override
    public LocalDateTime getNextFollowUpTime(Long id, String type) {
        LambdaQueryWrapper<TaskEntity> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.eq(TaskEntity::getResourceType, type);
        taskWrapper.eq(TaskEntity::getResourceTypeId, id);
        taskWrapper.eq(TaskEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        taskWrapper.gt(TaskEntity::getTaskBeginTime, LocalDateTime.now());
        taskWrapper.orderByAsc(TaskEntity::getTaskBeginTime);
        taskWrapper.last("limit 1");
        TaskEntity taskEntity = getOne(taskWrapper);
        if (!ObjectUtils.isEmpty(taskEntity)){
            return taskEntity.getTaskBeginTime();
        }
        return null;
    }

    @Override
    public String getNameById(String tableName, String fieldColumn, Long id) {
        return baseMapper.selectNameById(tableName, fieldColumn, id);
    }

    @Override
    public Result complete(UpdateTaskDTO dto) {

        Long currentUserId  = LoginUserUtil.getCurrentUserId();
        if (Objects.isNull(dto.getTaskId())) {
            return Result.error("参数错误");
        }
        TaskEntity task = this.getById(dto.getTaskId());
        if (Objects.isNull(task)) {
            return Result.error("未找到该任务!");
        }
        if (SpringCompareUtil.includeEqual(task.getTaskStatus(), TaskStatusEnum.COMPLETED.getCode(),TaskStatusEnum.COMPLETED.getCode(), TaskStatusEnum.CANCELED.getCode())) {
            return Result.error("任务状态异常，无法完成任务!");
        }
        LambdaUpdateWrapper<TaskEntity> updateWrapper = new LambdaUpdateWrapper();
        updateWrapper.eq(TaskEntity::getId,dto.getTaskId());
        if (StrUtil.isNotBlank(dto.getRemark())) {
            updateWrapper.set(TaskEntity::getRemark,dto.getRemark());
        }
        updateWrapper.set(TaskEntity::getOperatorBy,currentUserId);
        updateWrapper.set(TaskEntity::getOperatorTime,LocalDateTime.now());
        updateWrapper.set(TaskEntity::getTaskStatus,TaskStatusEnum.COMPLETED.getCode());
        this.update(updateWrapper);
        return Result.ok();
    }

    @Override
    public String getResourceTyepName(String resourceType, String resourceTypeId){
        if (MessageTypeEnum.CUSTOMER.getCode().equals(resourceType)
                || MessageTypeEnum.CLUS.getCode().equals(resourceType)) {
            CustomerEntity customer = customerService.getById(resourceTypeId);
            if (Objects.nonNull(customer)){
                return  customer.getCustomerName();
            }

        } else if (MessageTypeEnum.LIAISON.getCode().equals(resourceType)) {
            // 联系人
            LiaisonEntity liaison = liaisonService.getById(resourceTypeId);
            if (Objects.nonNull(liaison)) {
                return liaison.getName();
            }

        } else if (MessageTypeEnum.BUSINESS.getCode().equals(resourceType)) {
            // 商机
            BusinessEntity business = businessService.getById(resourceTypeId);
            if (Objects.nonNull(business)) {
                return business.getTitle();
            }
        } else if (MessageTypeEnum.ORDER_FORM.getCode().equals(resourceType)) {
            // 订单
            OrderFormEntity orderForm = orderFormService.getById(resourceTypeId);
            if (Objects.nonNull(orderForm)) {
                return orderForm.getTitle();
            }
        } else if (MessageTypeEnum.WORK_ORDER.getCode().equals(resourceType)) {
            // 工单
            WorkOrderEntity workOrder = workOrderService.getById(resourceTypeId);
            if (Objects.nonNull(workOrder)) {
                return workOrder.getTitle();
            }
        }
        return "";
    }

    @Override
    public Map<String,Object> getResourceTyepMap(String resourceType, String resourceTypeId){
        Map<String,Object> map = new HashMap<>();
        String name = "";
        Object value = "";
        if (MessageTypeEnum.CUSTOMER.getCode().equals(resourceType)
                || MessageTypeEnum.CLUS.getCode().equals(resourceType)) {
            CustomerEntity customer = customerService.getById(resourceTypeId);
            if (Objects.nonNull(customer)){
                name = customer.getCustomerName();
                value = customer;
            }

        } else if (MessageTypeEnum.LIAISON.getCode().equals(resourceType)) {
            // 联系人
            LiaisonEntity liaison = liaisonService.getById(resourceTypeId);
            if (Objects.nonNull(liaison)) {
                name = liaison.getName();
                value = liaison;
            }

        } else if (MessageTypeEnum.BUSINESS.getCode().equals(resourceType)) {
            // 商机
            BusinessEntity business = businessService.getById(resourceTypeId);
            if (Objects.nonNull(business)) {
            BusinessDetailVO businessDetailVO = new BusinessDetailVO();
            BeanUtils.copyProperties(business,businessDetailVO);
            SysBaseField.dictFiled(businessDetailVO);

                name = business.getTitle();
                value = businessDetailVO;
            }
        } else if (MessageTypeEnum.ORDER_FORM.getCode().equals(resourceType)) {
            // 订单
            OrderFormEntity orderForm = orderFormService.getById(resourceTypeId);
            if (Objects.nonNull(orderForm)) {
                name = orderForm.getTitle();
                value = orderForm;
            }
        } else if (MessageTypeEnum.WORK_ORDER.getCode().equals(resourceType)) {
            // 工单
            WorkOrderEntity workOrder = workOrderService.getById(resourceTypeId);
            if (Objects.nonNull(workOrder)) {
                name = workOrder.getTitle();
                value = workOrder;
            }
        }
        map.put("name",name);
        map.put("value",value);
        return map;
    }

    @Override
    public IPage<?> selectSimpleListVO(CustomerSearchSearchDTO customerSearchSearchDTO) {

        IPage<TaskEntity> page = new Page<>(customerSearchSearchDTO.getPageIndex(),customerSearchSearchDTO.getPageSize());
        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(TaskEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(customerSearchSearchDTO.getBlurry())) {
            queryWrapper.like(TaskEntity::getTaskContent, customerSearchSearchDTO.getBlurry());
        }

        Long loginUserId = customerSearchSearchDTO.getLoginUser().getId();

        StringBuilder mergeSql = new StringBuilder();
//        List<Long> customerIds = customerService.getCustomerIdList(loginUserId);
//        String customerIdString = customerIds.stream().map(String::valueOf).collect(Collectors.joining(","));
        String v1 = StrUtil.isBlank(customerSearchSearchDTO.getCustomerIdString()) ? "" : " customer_id in ( "+customerSearchSearchDTO.getCustomerIdString() +") ";
        mergeSql.append(v1);

//        String v2 = "owner_by in ("+customerSearchSearchDTO.getUserIdString()+")";
//        mergeSql.append(v2);
        IPage<TaskEntity> pageList = pageWithScope(page, queryWrapper,customerSearchSearchDTO,mergeSql.toString());
        IPage<TaskVO> vos = SysBaseField.page(pageList, TaskVO.class);
        return vos;
    }
}
