package com.storlead.sales.controller.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.common.util.StringUtil;
import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.message.enums.MessageTypeEnum;
import com.storlead.sales.enums.QueryRangeTypeEnum;
import com.storlead.sales.pojo.entity.customer.*;
import com.storlead.sales.enums.ResourceTypeEnum;
import com.storlead.sales.enums.TaskStatusEnum;
import com.storlead.sales.pojo.dto.task.TaskDTO;
import com.storlead.sales.pojo.dto.task.TaskQueryDTO;
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.service.task.TaskService;
import com.storlead.system.pojo.dto.DictExtQueryParam;
import com.storlead.system.pojo.entity.SysDictDetailEntity;
import com.storlead.system.service.SysDictDetailService;
import com.storlead.user.service.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

/**
 * @program: sp-sales-platform
 * @description:
 * @author: chenkq
 * @create: 2024-04-16 16:56
 */

@Api(tags = "任务: 任务模块")
@RestController
@RequestMapping("/sys/task")
@Data
public class TaskApiController {

    @Resource
    private TaskService taskService;

    @Resource
    private SysResourceService resourceService;

    @Resource
    private SysDictDetailService dictDetailService;

    @Resource
    private LiaisonService liaisonService;

    @Resource
    private BusinessService businessService;

    @Resource
    private OrderFormService orderFormService;

    @Resource
    private CustomerFollowUpService customerFollowUpService;

    @Resource
    private WorkOrderService workOrderService;

    @Resource
    private SysResourceService sysResourceService;

    @Resource
    private CustomerService customerService;

    @Resource
    private MessageAssembleService assembleService;

    @Resource
    private IUserService userService;

//    @ApiOperation("测试")
//    @PostMapping("list")
//    public Result list(@RequestBody TaskDTO dto) {
//
//        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.like(TaskEntity::getIsDelete, Integer.valueOf(0));
//        List<TaskVO> vos = taskService.list(queryWrapper);
//        page.setRecords(vos);
//        return Result.result(ss);
//    }

    @ApiOperation("保存任务")
    @PostMapping("save")
    public Result save(@RequestBody TaskDTO dto) {

        if (!TaskStatusEnum.UNSTART.getCode().equals(dto.getTaskStatus()) && Objects.nonNull(dto.getId())) {
            return Result.error("该状态下不能修改任务");
        }
        LocalDateTime startDateTime = dto.getTaskBeginTime();
        if (Objects.isNull(startDateTime)) {
            return Result.error("请选择任务开始时间");
        }
        if (Objects.isNull(dto.getId())) {
            LocalDateTime now = LocalDateTime.now();
            if (startDateTime.isBefore(now) || startDateTime.isEqual(now)) {
                return  Result.error("任务开始时间必须晚于当前时间！");
            }
        }
        if (Objects.nonNull(dto.getRemindType())) {
            dto.setRemindTime(startDateTime.minusMinutes(dto.getRemindType()));
        } else {
            dto.setRemindTime(startDateTime.minusMinutes(dto.getRemindType()));
        }
        if (!CollectionUtils.isEmpty(dto.getRemindModels())) {
            dto.setRemindMode(StringUtils.join(dto.getRemindModels(),","));
        }
        if (!CollectionUtils.isEmpty(dto.getResourceTypeIdls())) {
            List<TaskEntity> taskls = new ArrayList<>();
            TaskEntity task = new TaskEntity();
            dto.getResourceTypeIdls().forEach(dataId -> {
                BeanUtils.copyProperties(dto,task);
                if (CollectionUtils.isEmpty(dto.getRemindModels())) {
                    task.setRemindMode(StringUtils.join(dto.getRemindModels(),","));
                }
                task.setCustomerId(getCustomerId(dto,dataId));
                task.setResourceTypeId(Long.valueOf(dataId));
                taskls.add(task);
            });
            taskService.saveBatch(taskls);
            assembleService.sendCustomerEventMessages(task.getCustomerId(), "NEW_TASK");
            return Result.ok();
        }else {
            TaskEntity task = new TaskEntity();
            BeanUtils.copyProperties(dto,task);
            task.setCustomerId(getCustomerId(dto,dto.getResourceTypeId()));
            taskService.saveOrUpdate(task);
            assembleService.sendCustomerEventMessages(task.getCustomerId(), "NEW_TASK");
            return Result.result(task.getId());
        }
    }

    public Long getCustomerId(TaskDTO dto,Long resourceTypeId){
        if (Objects.isNull(dto.getCustomerId())) {
            if (MessageTypeEnum.CUSTOMER.getCode().equals(dto.getResourceType())
                    || MessageTypeEnum.CLUS.getCode().equals(dto.getResourceType())) {
                return  resourceTypeId;
            } else if (MessageTypeEnum.LIAISON.getCode().equals(resourceTypeId)) {
                // 联系人
                LiaisonEntity liaison = liaisonService.getById(resourceTypeId);
                if (Objects.nonNull(liaison)) {
                   return liaison.getCustomerId();
                }

            } else if (MessageTypeEnum.BUSINESS.getCode().equals(dto.getResourceType())) {
                // 商机
                BusinessEntity business = businessService.getById(resourceTypeId);
                if (Objects.nonNull(business)) {
                    return business.getCustomerId();
                }
            } else if (MessageTypeEnum.ORDER_FORM.getCode().equals(dto.getResourceType())) {
                // 订单
                OrderFormEntity orderForm = orderFormService.getById(resourceTypeId);
                if (Objects.nonNull(orderForm)) {
                    return orderForm.getCustomerId();
                }
            } else if (MessageTypeEnum.FOLLOW_UP.getCode().equals(dto.getResourceType())) {
                // 跟进
                CustomerFollowUpEntity followUp = customerFollowUpService.getById(resourceTypeId);
                if (Objects.nonNull(followUp)) {
                    return followUp.getCustomerId();
                }
            } else if (MessageTypeEnum.WORK_ORDER.getCode().equals(dto.getResourceType())) {
                // 工单
                WorkOrderEntity workOrder = workOrderService.getById(resourceTypeId);
                if (Objects.nonNull(workOrder)) {
                    return workOrder.getCustomerId();
                }
            }
            return null;
        } else {
            return dto.getCustomerId();
        }
    }

    @ApiOperation("分页查询")
    @PostMapping("listPage")
    public Result listPage(@RequestBody TaskQueryDTO param) {
        if (Integer.valueOf(1).equals(param.getWaitingTask())) {
            return listWaitingTask(param);
        }

        IPage<TaskEntity> page = new Page<>(param.getPageIndex(),param.getPageSize());
        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(TaskEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(param.getBlurry())) {
            queryWrapper.like(TaskEntity::getTaskContent, param.getBlurry());
        }
        if (StrUtil.isNotBlank(param.getResourceType())) {
            if (param.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code) || param.getResourceType().equals(ResourceTypeEnum.CLUS.code)) {
                queryWrapper.eq(TaskEntity::getCustomerId, param.getResourceTypeId());
            } else {
                queryWrapper.eq(TaskEntity::getResourceType, param.getResourceType());
                queryWrapper.eq(TaskEntity::getResourceTypeId, param.getResourceTypeId());
            }
        }

        if (Objects.nonNull(param.getTaskStatus())) {
            queryWrapper.eq(TaskEntity::getTaskStatus, param.getTaskStatus());
        }
        if (!CollectionUtils.isEmpty(param.getTaskStatusList())){
            queryWrapper.in(TaskEntity::getTaskStatus, param.getTaskStatusList());
        }
        if (Objects.nonNull(param.getNeTaskStatus())) {
            queryWrapper.ne(TaskEntity::getTaskStatus, param.getTaskStatus());
        }
        if (Objects.nonNull(param.getQueryRangeType())) {
            String queryRangeSql = QueryRangeTypeEnum.getQueryRangeSql(param.getQueryRangeType(),LoginUserUtil.getCurrentUserId());
            if (StrUtil.isNotBlank(queryRangeSql)) {
                queryWrapper.apply(queryRangeSql);
            }
        }
        if (Objects.nonNull(param.getCreateBy())) {
            queryWrapper.eq(TaskEntity::getCreateBy, param.getCreateBy());
        }
        if (Objects.nonNull(param.getOwnerBy())) {
            queryWrapper.eq(TaskEntity::getOwnerBy, param.getOwnerBy());
        }

        if (!CollectionUtils.isEmpty(param.getCreateByIdls())) {
            queryWrapper.in(TaskEntity::getCreateBy, param.getCreateByIdls());
        }
        if (!CollectionUtils.isEmpty(param.getOwnerByIdls())) {
            queryWrapper.in(TaskEntity::getOwnerBy, param.getOwnerByIdls());
        }

        if (Objects.nonNull(param.getBeginTime())) {
            queryWrapper.ge(TaskEntity::getTaskBeginTime, param.getBeginTime());
        }
        if (Objects.nonNull(param.getTaskContent())) {
            queryWrapper.like(TaskEntity::getTaskContent, param.getTaskContent());
        }

        if (Objects.nonNull(param.getEndTime())) {
            queryWrapper.le(TaskEntity::getTaskBeginTime, param.getEndTime());
        }
//        queryWrapper.orderByDesc(TaskEntity::getTaskBeginTime);

        Long loginUserId = LoginUserUtil.getCurrentUserId();

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

        String v2 = "owner_by in (select id from `user` WHERE  FIND_IN_SET("+loginUserId+",managers))";
        mergeSql.append(v2);
        IPage<TaskEntity> pageList = taskService.pageWithScope(page, queryWrapper,param,mergeSql.toString());
        IPage<TaskVO> vos = SysBaseField.page(pageList, TaskVO.class);
        if (!CollectionUtils.isEmpty(vos.getRecords())) {
            SysBaseField.dictFileds(vos.getRecords());
            SysBaseField.orgFileds(vos.getRecords());

            List<CustomerEntity> customerls = customerService.listCustomers(vos.getRecords().stream().map(TaskVO::getCustomerId).collect(Collectors.toList()));
            Map<Long, String> customerMap = CollectionUtils.isEmpty(customerls) ? new HashMap<>() : customerls.stream()
                    .collect(Collectors.toMap(CustomerEntity::getId, CustomerEntity::getCustomerName));

            vos.getRecords().forEach(t -> {
                if (Objects.nonNull(t.getResourceTypeId())) {
                    Map<String,Object> resourceMap = taskService.getResourceTyepMap(t.getResourceType(),t.getResourceTypeId().toString());
//                    String resourceName = taskService.getResourceTyepName(t.getResourceType(),t.getResourceTypeId().toString());
                    if (Objects.nonNull(resourceMap)){
                        t.setResourceName(resourceMap.get("name").toString());
                        t.setResourceObject(resourceMap.get("value"));
                    }
                }
                if (StrUtil.isNotBlank(t.getRemindMode())) {
                    t.setRemindModels(Arrays.asList(t.getRemindMode().split(",")));
                }
                t.setCustomerName(customerMap.getOrDefault(t.getCustomerId(),""));

            });
            List<Long> tIds = vos.getRecords().stream().map(TaskVO::getId).collect(Collectors.toList());
            LambdaQueryWrapper<CustomerFollowUpEntity> wp = new LambdaQueryWrapper<>();
            wp.in(CustomerFollowUpEntity::getTaskId,tIds);
            wp.eq(CustomerFollowUpEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            List<CustomerFollowUpEntity> follows = customerFollowUpService.list(wp);
            if (!CollectionUtils.isEmpty(follows)) {
                Map<Long,CustomerFollowUpEntity> followMap =  follows.stream().collect(Collectors.toMap(CustomerFollowUpEntity::getTaskId, a -> a,(existing, replacement) -> existing));
                // Map<Long,String> taskMap =  follows.stream().collect(Collectors.toMap(CustomerFollowUpEntity::getId,CustomerFollowUpEntity::getSubject, (existing, replacement) -> existing));
                vos.getRecords().forEach(t -> {
                    CustomerFollowUpEntity v = followMap.get(t.getId());
                    if (Objects.nonNull(v)) {
                        t.setFollowId(v.getId());
                        t.setFollowSubject(v.getSubject());
                    }
                });
            }

            Map<String, SysDictDetailEntity> dictMap = dictDetailService.getDictDetailByCode("work_data_group");
            if (!CollectionUtils.isEmpty(dictMap)) {
                Gson gson = new Gson();
                for (TaskVO taskVO : vos.getRecords()) {
                    if (Objects.isNull(taskVO.getResourceType())) {
                        continue;
                    }
                    SysDictDetailEntity dictDetailEntity = dictMap.get(taskVO.getResourceType());
                    if (Objects.nonNull(dictDetailEntity)) {
                        String jsonString = dictDetailEntity.getExtField2();
                        if (StrUtil.isBlank(jsonString)) {
                            continue;
                        }
                        if (Objects.nonNull(taskVO.getResourceTypeId())) {
                            DictExtQueryParam element = gson.fromJson(jsonString, DictExtQueryParam.class);
                            element.setKeyValue(taskVO.getResourceTypeId().toString());
                            String name = dictDetailService.getWorkDataById(element);
                            if (StrUtil.isNotBlank(name)) {
                                taskVO.setLinkWorkGroupName(name);
                            }
                        }
                    }
                }
            }
        }
        return Result.result(vos);
    }


    @ApiOperation("待办任务")
    @PostMapping("listWaitingTask")
    public Result listWaitingTask(@RequestBody TaskQueryDTO param) {
        IPage<TaskEntity> page = new Page<>(param.getPageIndex(),param.getPageSize());
        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(TaskEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        LocalDateTime localDateTime = LocalDate.now().plusDays(1).atStartOfDay();
        queryWrapper.and(wq -> wq.and(q ->q.eq(TaskEntity::getTaskStatus, TaskStatusEnum.UNSTART.getCode())
                .lt(TaskEntity::getTaskBeginTime,localDateTime)).or(q1 -> q1.eq(TaskEntity::getTaskStatus, TaskStatusEnum.OVERTIME.getCode())
        ));
        Long loginUserId = LoginUserUtil.getCurrentUserId();
        queryWrapper.apply("(FIND_IN_SET("+loginUserId+", cooperate_by) or owner_by in ("+loginUserId+"))");
        IPage<TaskEntity> pageList = taskService.page(page, queryWrapper);
        IPage<TaskVO> vos = SysBaseField.page(pageList, TaskVO.class);
        if (!CollectionUtils.isEmpty(vos.getRecords())) {
            SysBaseField.dictFileds(vos.getRecords());
            SysBaseField.orgFileds(vos.getRecords());

            List<CustomerEntity> customerls = customerService.listCustomers(vos.getRecords().stream().map(TaskVO::getCustomerId).collect(Collectors.toList()));
            Map<Long, String> customerMap = CollectionUtils.isEmpty(customerls) ? new HashMap<>() : customerls.stream()
                    .collect(Collectors.toMap(CustomerEntity::getId, CustomerEntity::getCustomerName));

            vos.getRecords().forEach(t -> {
                if (Objects.nonNull(t.getResourceTypeId())) {
                    Map<String,Object> resourceMap = taskService.getResourceTyepMap(t.getResourceType(),t.getResourceTypeId().toString());
//                    String resourceName = taskService.getResourceTyepName(t.getResourceType(),t.getResourceTypeId().toString());
                    if (Objects.nonNull(resourceMap)){
                        t.setResourceName(resourceMap.get("name").toString());
                        t.setResourceObject(resourceMap.get("value"));
                    }
                }
                if (StrUtil.isNotBlank(t.getRemindMode())) {
                    t.setRemindModels(Arrays.asList(t.getRemindMode().split(",")));
                }
                t.setCustomerName(customerMap.getOrDefault(t.getCustomerId(),""));

            });
            List<Long> tIds = vos.getRecords().stream().map(TaskVO::getId).collect(Collectors.toList());
            LambdaQueryWrapper<CustomerFollowUpEntity> wp = new LambdaQueryWrapper<>();
            wp.in(CustomerFollowUpEntity::getTaskId,tIds);
            wp.eq(CustomerFollowUpEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            List<CustomerFollowUpEntity> follows = customerFollowUpService.list(wp);
            if (!CollectionUtils.isEmpty(follows)) {
                Map<Long,CustomerFollowUpEntity> followMap =  follows.stream().collect(Collectors.toMap(CustomerFollowUpEntity::getTaskId, a -> a,(existing, replacement) -> existing));
                // Map<Long,String> taskMap =  follows.stream().collect(Collectors.toMap(CustomerFollowUpEntity::getId,CustomerFollowUpEntity::getSubject, (existing, replacement) -> existing));
                vos.getRecords().forEach(t -> {
                    CustomerFollowUpEntity v = followMap.get(t.getId());
                    if (Objects.nonNull(v)) {
                        t.setFollowId(v.getId());
                        t.setFollowSubject(v.getSubject());
                    }
                });
            }

            Map<String, SysDictDetailEntity> dictMap = dictDetailService.getDictDetailByCode("work_data_group");
            if (!CollectionUtils.isEmpty(dictMap)) {
                Gson gson = new Gson();
                for (TaskVO taskVO : vos.getRecords()) {
                    if (Objects.isNull(taskVO.getResourceType())) {
                        continue;
                    }
                    SysDictDetailEntity dictDetailEntity = dictMap.get(taskVO.getResourceType());
                    if (Objects.nonNull(dictDetailEntity)) {
                        String jsonString = dictDetailEntity.getExtField2();
                        if (StrUtil.isBlank(jsonString)) {
                            continue;
                        }
                        if (Objects.nonNull(taskVO.getResourceTypeId())) {
                            DictExtQueryParam element = gson.fromJson(jsonString, DictExtQueryParam.class);
                            element.setKeyValue(taskVO.getResourceTypeId().toString());
                            String name = dictDetailService.getWorkDataById(element);
                            if (StrUtil.isNotBlank(name)) {
                                taskVO.setLinkWorkGroupName(name);
                            }
                        }
                    }
                }
            }
        }
        return Result.result(vos);
    }


    @ApiOperation("获取代办任务")
    @PostMapping("get_waiting_task")
    public Result getWaitingTask() {
        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(TaskEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        LocalDateTime localDateTime = LocalDate.now().plusDays(1).atStartOfDay();
        queryWrapper.and(wq -> wq.and(q ->q.eq(TaskEntity::getTaskStatus, TaskStatusEnum.UNSTART.getCode())
                .lt(TaskEntity::getTaskBeginTime,localDateTime)).or(q1 -> q1.eq(TaskEntity::getTaskStatus, TaskStatusEnum.OVERTIME.getCode())
        ));
        Long loginUserId = LoginUserUtil.getCurrentUserId();
        queryWrapper.apply("(FIND_IN_SET("+loginUserId+", cooperate_by) or owner_by in ("+loginUserId+"))");

        Integer taskCount = taskService.count(queryWrapper);

        Map<String,Integer> map = new TreeMap<>();
        map.put("taskCount",taskCount);
        return Result.result(map);

    }


    @ApiOperation("保存任务")
    @PostMapping("getTaskDetail")
    public Result getTaskDetail(@RequestBody TaskDTO dto) {

        TaskEntity  task = taskService.getById(dto.getId());
        TaskVO taskVo = new TaskVO();
        BeanUtils.copyProperties(task,taskVo);
        if (Objects.isNull(taskVo)) {
            return Result.error("未找到");
        }
        taskVo.dictFiled();
        taskVo.orgFiled();
        if (Objects.nonNull(taskVo.getResourceTypeId())) {
            Map<String, Object> resourceMap = taskService.getResourceTyepMap(taskVo.getResourceType(), taskVo.getResourceTypeId().toString());
            if (Objects.nonNull(resourceMap)) {
                taskVo.setResourceName(resourceMap.get("name").toString());
                taskVo.setResourceObject(resourceMap.get("value"));
            }
            taskVo.setResourceStatus(customerFollowUpService.getResourceStatusTyepId(taskVo.getResourceType(),taskVo.getResourceTypeId()));
        }
        if (StrUtil.isNotBlank(taskVo.getRemindMode())) {
            taskVo.setRemindModels(Arrays.asList(taskVo.getRemindMode().split(",")));
        }
        if (Objects.nonNull(taskVo.getCustomerId())) {
            CustomerEntity customer = customerService.getById(taskVo.getCustomerId());
            if (Objects.nonNull(customer)) {
                taskVo.setCustomerName(customer.getCustomerName());
            }
        }

        LambdaQueryWrapper<CustomerFollowUpEntity> wp = new LambdaQueryWrapper<>();
        wp.eq(CustomerFollowUpEntity::getTaskId,taskVo.getId());
        wp.eq(CustomerFollowUpEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
        wp.last("limit 1");
        CustomerFollowUpEntity follow = customerFollowUpService.getOne(wp);
        if (Objects.nonNull(follow)) {
            taskVo.setFollowId(follow.getId());
            taskVo.setFollowSubject(follow.getSubject());
        }

        Map<String, SysDictDetailEntity> dictMap = dictDetailService.getDictDetailByCode("work_data_group");
        if (!CollectionUtils.isEmpty(dictMap)) {
            Gson gson = new Gson();
            if (Objects.nonNull(taskVo.getResourceType())) {
                SysDictDetailEntity dictDetailEntity = dictMap.get(taskVo.getResourceType());
                if (Objects.nonNull(dictDetailEntity)) {
                    String jsonString = dictDetailEntity.getExtField2();
                    if (StrUtil.isNotBlank(jsonString)) {
                        if (Objects.nonNull(taskVo.getResourceTypeId())) {
                            DictExtQueryParam element = gson.fromJson(jsonString, DictExtQueryParam.class);
                            element.setKeyValue(taskVo.getResourceTypeId().toString());
                            String name = dictDetailService.getWorkDataById(element);
                            if (StrUtil.isNotBlank(name)) {
                                taskVo.setLinkWorkGroupName(name);
                            }
                        }
                    }
                }
            }
        }
        return Result.result(taskVo);
    }

    @ApiOperation("取消任务")
    @PostMapping("canceled")
    public Result canceled(@RequestBody UpdateTaskDTO dto) {
        Long currentUserId  = LoginUserUtil.getCurrentUserId();
        TaskEntity task = new TaskEntity();
        task.setId(dto.getTaskId());
        if (StrUtil.isNotBlank(dto.getRemark())) {
            task.setRemark(dto.getRemark());
        }
        task.setOperatorBy(currentUserId);
        task.setOperatorTime(LocalDateTime.now());
        task.setTaskStatus(TaskStatusEnum.CANCELED.getCode());
        taskService.updateById(task);
//        sysResourceService.updateResourceById(ResourceTypeEnum.TASK_CANCELED.code,task.getId(),dto.getResourceList());
        return Result.ok();
    }


    @ApiOperation("完成任务")
    @PostMapping("complete")
    public Result complete(@RequestBody UpdateTaskDTO dto) {
        return taskService.complete(dto);

    }

    @ApiOperation("未能完成")
    @PostMapping("unfinished")
    public Result unfinished(@RequestBody UpdateTaskDTO dto) {
        Long currentUserId  = LoginUserUtil.getCurrentUserId();
        if (Objects.isNull(dto.getTaskId())) {
            return Result.error("参数错误");
        }
        TaskEntity task = taskService.getById(dto.getTaskId());
        if (Objects.isNull(task)) {
            return Result.error("未找到该任务!");
        }
        if (SpringCompareUtil.includeEqual(task.getTaskStatus(), TaskStatusEnum.COMPLETED.getCode(),TaskStatusEnum.UNFINISHED.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.UNFINISHED.getCode());
        taskService.update(updateWrapper);
        return Result.ok();
    }

    @ApiOperation("删除任务数据")
    @PostMapping("delete")
    public Result delete(Long id) {
        if(Objects.isNull(id)) {
            return Result.error("参数错误");
        }
        taskService.lgDelete(id);
        return Result.ok();
    }

    @ApiOperation("任务日程统计")
    @PostMapping("total_task")
    public Result totalTask(TaskQueryDTO param) {

        Long ownerBy = param.getOwnerBy();
        Long  currentUserId  = LoginUserUtil.getCurrentUserId();
        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(TaskEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(param.getBlurry())) {
            queryWrapper.like(TaskEntity::getTaskContent, param.getBlurry());
        }
        if (StrUtil.isNotBlank(param.getResourceType())) {
            if (param.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code) || param.getResourceType().equals(ResourceTypeEnum.CLUS.code)) {
                queryWrapper.eq(TaskEntity::getCustomerId, param.getResourceTypeId());
            } else {
                queryWrapper.eq(TaskEntity::getResourceType, param.getResourceType());
                queryWrapper.eq(TaskEntity::getResourceTypeId, param.getResourceTypeId());
            }
        }
        if (StrUtil.isNotBlank(param.getResourceType())) {
            if (param.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code) || param.getResourceType().equals(ResourceTypeEnum.CLUS.code)) {
                queryWrapper.eq(TaskEntity::getCustomerId, param.getResourceTypeId());
            } else {
                queryWrapper.eq(TaskEntity::getResourceType, param.getResourceType());
                queryWrapper.eq(TaskEntity::getResourceTypeId, param.getResourceTypeId());
            }
        }
        if (Objects.nonNull(param.getQueryRangeType())) {
            String queryRangeSql = QueryRangeTypeEnum.getQueryRangeSql(param.getQueryRangeType(),LoginUserUtil.getCurrentUserId());
            if (StrUtil.isNotBlank(queryRangeSql)) {
                queryWrapper.apply(queryRangeSql);
            }
        }
        if (Objects.nonNull(param.getTaskStatus())) {
            queryWrapper.eq(TaskEntity::getTaskStatus, param.getTaskStatus());
        }
        if (!CollectionUtils.isEmpty(param.getTaskStatusList())){
            queryWrapper.in(TaskEntity::getTaskStatus, param.getTaskStatusList());
        }
        if (Objects.nonNull(param.getNeTaskStatus())) {
            queryWrapper.ne(TaskEntity::getTaskStatus, param.getTaskStatus());
        }

        if (Objects.nonNull(param.getCreateBy())) {
            queryWrapper.eq(TaskEntity::getCreateBy, param.getCreateBy());
        }
        if (Objects.nonNull(ownerBy)) {
            queryWrapper.eq(TaskEntity::getOwnerBy, ownerBy);
        }
        if (Objects.nonNull(param.getPriorityGrade())) {
            queryWrapper.eq(TaskEntity::getPriorityGrade, param.getPriorityGrade());
        }
        if (!CollectionUtils.isEmpty(param.getCooperateByList())) {
            String sql = " CONCAT(',',cooperate_by,',') regexp REPLACE(',',',',',"+ StringUtils.join(param.getCooperateByList(),",|,")+",')";
            queryWrapper.apply(sql);
        }
        if (StrUtil.isNotBlank(param.getBeginCycleTime())) {
            String beginCycleTime = param.getBeginCycleTime()+" 00:00:00";
            queryWrapper.ge(TaskEntity::getTaskBeginTime, beginCycleTime);
        }

        if (StrUtil.isNotBlank(param.getEndCycleTime())) {
            String endCycleTime = param.getEndCycleTime()+" 23:59:59";
            queryWrapper.le(TaskEntity::getTaskBeginTime,endCycleTime);
        }
        if (Integer.valueOf(1).equals(param.getIsMySelf())) {
            if (Objects.isNull(param.getOwnerBy())) {
                queryWrapper.eq(TaskEntity::getCreateBy, currentUserId);
            }
        } else {
            StringBuilder mergeSql = new StringBuilder();
            List<Long> customerIds = customerService.getCustomerIdList(currentUserId);
            String customerIdString = customerIds.stream().map(String::valueOf).collect(Collectors.joining(","));
            String v1 = StrUtil.isBlank(customerIdString) ? "" : " customer_id in ( "+customerIdString +") or ";
            mergeSql.append(v1);
            String v2 = "owner_by in (select id from `user` WHERE  FIND_IN_SET("+currentUserId+",managers))";
            mergeSql.append(v2);
        }
//      queryWrapper.ge(TaskEntity::getOwnerBy, currentUserId);
        queryWrapper.orderByDesc(TaskEntity::getTaskBeginTime);
        List<TaskEntity> pageList = taskService.listWithScope(queryWrapper);
        //IPage<TaskEntity> pageList = taskService.pageWithScope(page, queryWrapper,param,mergeSql.toString());

        if (CollectionUtils.isEmpty(pageList)) {
            return Result.result(Collections.EMPTY_MAP);
        }
        List<TaskVO> vos = SysBaseField.list(pageList, TaskVO.class);

        if (!CollectionUtils.isEmpty(vos)) {
            SysBaseField.dictFileds(vos);
            SysBaseField.orgFileds(vos);

            List<CustomerEntity> customerls = customerService.listCustomers(vos.stream().map(TaskVO::getCustomerId).collect(Collectors.toList()));
            Map<Long, String> customerMap = CollectionUtils.isEmpty(customerls) ? new HashMap<>() : customerls.stream()
                    .collect(Collectors.toMap(CustomerEntity::getId, CustomerEntity::getCustomerName));

            vos.forEach(t -> {
                if (Objects.nonNull(t.getResourceTypeId())) {
                    String resourceName = taskService.getResourceTyepName(t.getResourceType(),t.getResourceTypeId().toString());
                    t.setResourceName(resourceName);
                }
                if (StrUtil.isNotBlank(t.getRemindMode())) {
                    t.setRemindModels(Arrays.asList(t.getRemindMode().split(",")));
                }
                t.setCustomerName(customerMap.getOrDefault(t.getCustomerId(),""));
            });

            Map<String, SysDictDetailEntity> dictMap = dictDetailService.getDictDetailByCode("work_data_group");
            if (!CollectionUtils.isEmpty(dictMap)) {
                Gson gson = new Gson();
                for (TaskVO taskVO : vos) {
                    if (Objects.isNull(taskVO.getResourceType())) {
                        continue;
                    }
                    SysDictDetailEntity dictDetailEntity = dictMap.get(taskVO.getResourceType());
                    if (Objects.nonNull(dictDetailEntity)) {
                        String jsonString = dictDetailEntity.getExtField2();
                        if (StrUtil.isBlank(jsonString)) {
                            continue;
                        }
                        if (Objects.nonNull(taskVO.getResourceTypeId())) {
                            DictExtQueryParam element = gson.fromJson(jsonString, DictExtQueryParam.class);
                            element.setKeyValue(taskVO.getResourceTypeId().toString());
                            String name = dictDetailService.getWorkDataById(element);
                            if (StrUtil.isNotBlank(name)) {
                                taskVO.setLinkWorkGroupName(name);
                            }
                        }
                    }
                }
            }
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        Map<String, List<TaskVO>> groupedByDate = vos.stream()
                .collect(Collectors.groupingBy(task -> task.getTaskBeginTime().format(formatter)));
        return Result.result(groupedByDate);
    }


    @ApiOperation("我的任务日程汇总")
    @PostMapping("total_my_task")
    public Result listMyTask(TaskQueryDTO param) {

        Long ownerBy = param.getOwnerBy();
        Long  currentUserId  = LoginUserUtil.getCurrentUserId();
        LambdaQueryWrapper<TaskEntity> queryWrapper = new LambdaQueryWrapper();
        queryWrapper.eq(TaskEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        if (StrUtil.isNotBlank(param.getBlurry())) {
            queryWrapper.like(TaskEntity::getTaskContent, param.getBlurry());
        }
        if (StrUtil.isNotBlank(param.getResourceType())) {
            if (param.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code) || param.getResourceType().equals(ResourceTypeEnum.CLUS.code)) {
                queryWrapper.eq(TaskEntity::getCustomerId, param.getResourceTypeId());
            } else {
                queryWrapper.eq(TaskEntity::getResourceType, param.getResourceType());
                queryWrapper.eq(TaskEntity::getResourceTypeId, param.getResourceTypeId());
            }
        }
        if (StrUtil.isNotBlank(param.getResourceType())) {
            if (param.getResourceType().equals(ResourceTypeEnum.CUSTOMER.code) || param.getResourceType().equals(ResourceTypeEnum.CLUS.code)) {
                queryWrapper.eq(TaskEntity::getCustomerId, param.getResourceTypeId());
            } else {
                queryWrapper.eq(TaskEntity::getResourceType, param.getResourceType());
                queryWrapper.eq(TaskEntity::getResourceTypeId, param.getResourceTypeId());
            }
        }
        if (Objects.nonNull(param.getQueryRangeType())) {
            String queryRangeSql = QueryRangeTypeEnum.getQueryRangeSql(param.getQueryRangeType(),LoginUserUtil.getCurrentUserId());
            if (StrUtil.isNotBlank(queryRangeSql)) {
                queryWrapper.apply(queryRangeSql);
            }
            if (QueryRangeTypeEnum.QUERY_SUBORDINATE_SQL.getCode().equals(param.getQueryRangeType())) {
                List<Long> subUserIds = userService.getAllSubordinate(currentUserId);
                if (!CollectionUtils.isEmpty(subUserIds)){
                    queryWrapper.apply(("(("+queryRangeSql+") or (CONCAT(',',cooperate_by,',') REGEXP ',"+ StringUtil.concatRegexp(subUserIds)+",'")+"))");
                }
            }
        } else {
            queryWrapper.apply("(FIND_IN_SET("+currentUserId+", cooperate_by) or owner_by in ("+currentUserId+"))");
        }

        if (Objects.nonNull(param.getTaskStatus())) {
            queryWrapper.eq(TaskEntity::getTaskStatus, param.getTaskStatus());
        }
        if (!CollectionUtils.isEmpty(param.getTaskStatusList())){
            queryWrapper.in(TaskEntity::getTaskStatus, param.getTaskStatusList());
        }
        if (Objects.nonNull(param.getNeTaskStatus())) {
            queryWrapper.ne(TaskEntity::getTaskStatus, param.getTaskStatus());
        }

        if (Objects.nonNull(param.getCreateBy())) {
            queryWrapper.eq(TaskEntity::getCreateBy, param.getCreateBy());
        }
        if (Objects.nonNull(ownerBy)) {
            queryWrapper.eq(TaskEntity::getOwnerBy, ownerBy);
        }
        if (Objects.nonNull(param.getPriorityGrade())) {
            queryWrapper.eq(TaskEntity::getPriorityGrade, param.getPriorityGrade());
        }

        if (StrUtil.isNotBlank(param.getBeginCycleTime())) {
            String beginCycleTime = param.getBeginCycleTime()+" 00:00:00";
            queryWrapper.ge(TaskEntity::getTaskBeginTime, beginCycleTime);
        }

        if (StrUtil.isNotBlank(param.getEndCycleTime())) {
            String endCycleTime = param.getEndCycleTime()+" 23:59:59";
            queryWrapper.le(TaskEntity::getTaskBeginTime,endCycleTime);
        }


        queryWrapper.orderByDesc(TaskEntity::getTaskBeginTime);
        List<TaskEntity> pageList = taskService.list(queryWrapper);

        if (CollectionUtils.isEmpty(pageList)) {
            return Result.result(Collections.EMPTY_MAP);
        }
        List<TaskVO> vos = SysBaseField.list(pageList, TaskVO.class);

        if (!CollectionUtils.isEmpty(vos)) {
            SysBaseField.dictFileds(vos);
            SysBaseField.orgFileds(vos);

            List<CustomerEntity> customerls = customerService.listCustomers(vos.stream().map(TaskVO::getCustomerId).collect(Collectors.toList()));
            Map<Long, String> customerMap = CollectionUtils.isEmpty(customerls) ? new HashMap<>() : customerls.stream()
                    .collect(Collectors.toMap(CustomerEntity::getId, CustomerEntity::getCustomerName));

            vos.forEach(t -> {
                if (Objects.nonNull(t.getResourceTypeId())) {
                    String resourceName = taskService.getResourceTyepName(t.getResourceType(),t.getResourceTypeId().toString());
                    t.setResourceName(resourceName);
                }
                if (StrUtil.isNotBlank(t.getRemindMode())) {
                    t.setRemindModels(Arrays.asList(t.getRemindMode().split(",")));
                }
                t.setCustomerName(customerMap.getOrDefault(t.getCustomerId(),""));
            });

            Map<String, SysDictDetailEntity> dictMap = dictDetailService.getDictDetailByCode("work_data_group");
            if (!CollectionUtils.isEmpty(dictMap)) {
                Gson gson = new Gson();
                for (TaskVO taskVO : vos) {
                    if (Objects.isNull(taskVO.getResourceType())) {
                        continue;
                    }
                    SysDictDetailEntity dictDetailEntity = dictMap.get(taskVO.getResourceType());
                    if (Objects.nonNull(dictDetailEntity)) {
                        String jsonString = dictDetailEntity.getExtField2();
                        if (StrUtil.isBlank(jsonString)) {
                            continue;
                        }
                        if (Objects.nonNull(taskVO.getResourceTypeId())) {
                            DictExtQueryParam element = gson.fromJson(jsonString, DictExtQueryParam.class);
                            element.setKeyValue(taskVO.getResourceTypeId().toString());
                            String name = dictDetailService.getWorkDataById(element);
                            if (StrUtil.isNotBlank(name)) {
                                taskVO.setLinkWorkGroupName(name);
                            }
                        }
                    }
                }
            }
        }

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        Map<String, List<TaskVO>> groupedByDate = vos.stream()
                .collect(Collectors.groupingBy(task -> task.getTaskBeginTime().format(formatter)));
        return Result.result(groupedByDate);
    }


}
