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

import com.storlead.framework.util.LoginUserUtil;
import com.storlead.framework.auth.vo.LoginUser;
import com.storlead.system.enums.OrganizationalTypeEnum;
import com.storlead.system.service.IUserRoleService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.storlead.framework.common.constant.CommonConstant;
import com.storlead.framework.common.util.StringUtil;
import com.storlead.framework.mybatis.entity.SysBaseField;
import com.storlead.sales.pojo.entity.customer.BusinessEntity;
import com.storlead.sales.pojo.entity.customer.CustomerEntity;
import com.storlead.sales.pojo.entity.customer.CustomerFollowUpEntity;
import com.storlead.sales.pojo.entity.customer.OrderFormEntity;
import com.storlead.sales.pojo.dto.target.TargetQuotaSearchDTO;
import com.storlead.sales.pojo.dto.target.TargetRankingDTO;
import com.storlead.sales.pojo.entity.target.TargetPlanEntity;
import com.storlead.sales.pojo.entity.target.TargetQuotaEntity;
import com.storlead.sales.pojo.vo.target.TargetPlanListVO;
import com.storlead.sales.pojo.vo.target.TargetQuotaDetailsListVO;
import com.storlead.sales.pojo.vo.target.TargetQuotaDetailsVO;
import com.storlead.sales.pojo.vo.target.TargetQuotaListVO;
import com.storlead.sales.service.customer.BusinessService;
import com.storlead.sales.service.customer.CustomerFollowUpService;
import com.storlead.sales.service.customer.CustomerService;
import com.storlead.sales.service.customer.OrderFormService;
import com.storlead.sales.mapper.target.TargetQuotaMapper;
import com.storlead.sales.service.target.TargetPlanService;
import com.storlead.sales.service.target.TargetQuotaService;
import com.storlead.framework.common.result.Result;
import com.storlead.framework.mybatis.service.impl.MyBaseServiceImpl;
import com.storlead.user.pojo.entity.DeptEntity;
import com.storlead.user.pojo.entity.SubCompanyEntity;
import com.storlead.user.pojo.entity.UserEntity;
import com.storlead.user.pojo.vo.UserVo;
import com.storlead.user.service.IDepartService;
import com.storlead.user.service.ISubCompanyService;
import com.storlead.user.service.IUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 目标配额表 服务实现类
 * </p>
 *
 * @author YPZ
 * @since 2024-12-11
 */
@Service
public class TargetQuotaServiceImpl extends MyBaseServiceImpl<TargetQuotaMapper, TargetQuotaEntity> implements TargetQuotaService {

    private static final Logger logger = LoggerFactory.getLogger(TargetQuotaServiceImpl.class);

    @Resource
    private IUserService userService;
    @Resource
    private ISubCompanyService subCompanyService;
    @Resource
    private IDepartService departService;

    @Resource
    private IUserRoleService userRoleService;

    @Resource
    private OrderFormService orderFormService;

    @Resource
    private CustomerService customerService;

    @Resource
    private BusinessService businessService;

    @Resource
    private CustomerFollowUpService customerFollowUpService;

    @Resource
    private TargetPlanService targetPlanService;


    private final String[] scopeType = {"全部", "本公司", "自定义","仅自己","本部门"};

    @Override
    public Map<String, Object> getTargetOrder(TargetRankingDTO targetRankingDTO) {
        targetRankingDTO.setType(41);
        return processTargetDatas(targetRankingDTO, "OrdertotalAmount");
    }

    @Override
    public Map<String, Object> getTargetOrderCount(TargetRankingDTO targetRankingDTO) {
        targetRankingDTO.setType(40);
        return processTargetDatas(targetRankingDTO, "OrderCount");
    }

    @Override
    public Map<String, Object> getTargetCustomer(TargetRankingDTO targetRankingDTO) {
        targetRankingDTO.setType(10);
        return processTargetDatas(targetRankingDTO, "CustomerCount");
    }

    @Override
    public Map<String, Object> getBusinessCount(TargetRankingDTO targetRankingDTO) {
        targetRankingDTO.setType(30);
        return processTargetDatas(targetRankingDTO, "BusinessCount");
    }

    @Override
    public Map<String, Object> getFollowUpCount(TargetRankingDTO targetRankingDTO) {
        targetRankingDTO.setType(12);
        return processTargetDatas(targetRankingDTO, "FollowUpCount");
    }

    @Override
    public Map<String, Object> getNewClue(TargetRankingDTO targetRankingDTO) {
        targetRankingDTO.setType(11);
        return processTargetDatas(targetRankingDTO, "NewClueCount");
    }


    private Map<String, Object> processTargetDatas(TargetRankingDTO targetRankingDTO, String methodName) {
        // 获取目标方案
        LambdaQueryWrapper<TargetPlanEntity> targetWrapper = new LambdaQueryWrapper<>();
        targetWrapper.eq(TargetPlanEntity::getType, targetRankingDTO.getType());
        targetWrapper.eq(TargetPlanEntity::getYear, targetRankingDTO.getYear());
        targetWrapper.eq(TargetPlanEntity::getIsDelete,0);
        List<Long> idList;
        try {
            logger.debug("获取目标方案 ID 列表，类型: {}, 年份: {}", targetRankingDTO.getType(), targetRankingDTO.getYear());
            idList = targetPlanService.getTargetPlanId(targetRankingDTO);
        } catch (Exception e) {
            Map<String, Object> result = new HashMap<>();
            return (Map<String, Object>) result;
        }

        Map<String, Object> result = new HashMap<>();

        // 如果无目标方案，则直接返回
        if (idList == null || idList.isEmpty()) {
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return (Map<String, Object>) result;
        }

        try {
            int organizationalType = targetRankingDTO.getOrganizationalType();
            switch (organizationalType) {
                case 2:
                    invokeMethod(2, idList, targetWrapper, targetRankingDTO, result, methodName);
                    break;
                case 3:
                    invokeMethod(3, idList, targetWrapper, targetRankingDTO, result, methodName);
                    break;
                case 4:
                    invokeMethod(4, idList, targetWrapper, targetRankingDTO, result, methodName);
                    break;
                default:
                    result.put("message", "未知的组织类型");
                    List<Map<String, Object>> list = new ArrayList<>();
                    result.put("data", list);
                    return result;
            }
        } catch (Exception e) {
            logger.error("处理数据时发生错误", e);
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return result;
        }
        return (Map<String, Object>) result;
    }

    private void invokeMethod(int organizationalType, List<Long> idList, LambdaQueryWrapper<TargetPlanEntity> targetWrapper, TargetRankingDTO targetRankingDTO, Map<String, Object> result, String methodName) throws Exception {
        switch (methodName) {
            case "OrdertotalAmount":
                OrdertotalAmount(organizationalType, idList, targetWrapper, targetRankingDTO, result);
                break;
            case "OrderCount":
                OrderCount(organizationalType, idList, targetWrapper, targetRankingDTO, result);
                break;
            case "CustomerCount":
                CustomerCount(organizationalType, idList, targetWrapper, targetRankingDTO, result);
                break;
            case "BusinessCount":
                BusinessCount(organizationalType, idList, targetWrapper, targetRankingDTO, result);
                break;
            case "FollowUpCount":
                FollowUpCount(organizationalType, idList, targetWrapper, targetRankingDTO, result);
                break;
            case "NewClueCount":
                NewClueCount(organizationalType, idList, targetWrapper, targetRankingDTO, result);
                break;
            default:
                throw new IllegalArgumentException("未知的方法名");
        }
    }

    public Map<String, Object> getOverallRanking(TargetRankingDTO targetRankingDTO) {
        Map<String, Object> result = new HashMap<>();

        // 定义所有需要统计的type值
        int[] types = {41, 40, 10, 30, 12, 11};

        // 检查是否有任何目标方案
        boolean hasAnyData = false;
        for (int type : types) {
            TargetRankingDTO newTargetRankingDTO = new TargetRankingDTO();
            BeanUtils.copyProperties(targetRankingDTO, newTargetRankingDTO);
            newTargetRankingDTO.setType(type);

            Map<String, Object> rankingData;
            try {
                switch (type) {
                    case 41:
                        rankingData = processTargetDatas(newTargetRankingDTO, "OrdertotalAmount");
                        break;
                    case 40:
                        rankingData = processTargetDatas(newTargetRankingDTO, "OrderCount");
                        break;
                    case 10:
                        rankingData = processTargetDatas(newTargetRankingDTO, "CustomerCount");
                        break;
                    case 30:
                        rankingData = processTargetDatas(newTargetRankingDTO, "BusinessCount");
                        break;
                    case 12:
                        rankingData = processTargetDatas(newTargetRankingDTO, "FollowUpCount");
                        break;
                    case 11:
                        rankingData = processTargetDatas(newTargetRankingDTO, "NewClueCount");
                        break;
                    default:
                        continue;
                }

                if (rankingData != null && rankingData.containsKey("data")) {
                    List<Map<String, Object>> dataList = (List<Map<String, Object>>) rankingData.get("data");
                    if (!dataList.isEmpty()) {
                        hasAnyData = true;
                        break;
                    }
                }
            } catch (Exception e) {
                logger.error("处理类型 " + type + " 的数据时发生错误", e);
            }
        }

        // 如果没有任何目标方案数据，返回空列表
        if (!hasAnyData) {
            List<Map<String, Object>> emptyList = new ArrayList<>();
            result.put("data", emptyList);
            return result;
        }

        // 创建一个新的Map来存放组织ID和对应的达成率
        Map<Long, Double> progressMap = new HashMap<>();
        Map<Long, Integer> validTargetCountMap = new HashMap<>(); // 记录每个组织有效的目标数量

        // 遍历所有type的数据
        for (int type : types) {
            TargetRankingDTO newTargetRankingDTO = new TargetRankingDTO();
            BeanUtils.copyProperties(targetRankingDTO, newTargetRankingDTO);
            newTargetRankingDTO.setType(type);

            Map<String, Object> rankingData;
            try {
                switch (type) {
                    case 41:
                        rankingData = processTargetDatas(newTargetRankingDTO, "OrdertotalAmount");
                        break;
                    case 40:
                        rankingData = processTargetDatas(newTargetRankingDTO, "OrderCount");
                        break;
                    case 10:
                        rankingData = processTargetDatas(newTargetRankingDTO, "CustomerCount");
                        break;
                    case 30:
                        rankingData = processTargetDatas(newTargetRankingDTO, "BusinessCount");
                        break;
                    case 12:
                        rankingData = processTargetDatas(newTargetRankingDTO, "FollowUpCount");
                        break;
                    case 11:
                        rankingData = processTargetDatas(newTargetRankingDTO, "NewClueCount");
                        break;
                    default:
                        continue;
                }

                if (rankingData != null && rankingData.containsKey("data")) {
                    List<Map<String, Object>> dataList = (List<Map<String, Object>>) rankingData.get("data");
                    for (Map<String, Object> data : dataList) {
                        Long organizationalId = Long.parseLong(String.valueOf(data.get("organizationalId")));
                        BigDecimal targetValue = new BigDecimal(String.valueOf(data.get("targetValue")));
                        Object totalNumObj = data.get("totalNum");
                        BigDecimal totalNum;
                        if (totalNumObj instanceof BigDecimal) {
                            totalNum = (BigDecimal) totalNumObj;
                        } else if (totalNumObj instanceof Long) {
                            totalNum = BigDecimal.valueOf((Long) totalNumObj);
                        } else {
                            totalNum = new BigDecimal(String.valueOf(totalNumObj));
                        }

                        // 只有当目标值大于0时才计算进度
                        if (targetValue.compareTo(BigDecimal.ZERO) >= 0) {
                            double progress = BigDecimalProgress(totalNum, targetValue);
                            progressMap.merge(organizationalId, progress, Double::sum);
                            validTargetCountMap.merge(organizationalId, 1, Integer::sum);
                        }
                    }
                }
            } catch (Exception e) {
                logger.error("处理类型 " + type + " 的数据时发生错误", e);
            }
        }

        List<Map<String, Object>> dataList = new ArrayList<>();

        // 遍历progressMap，计算平均达成率
        for (Map.Entry<Long, Double> entry : progressMap.entrySet()) {
            Long organizationalId = entry.getKey();
            Double totalProgress = entry.getValue();
            int validTargetCount = validTargetCountMap.get(organizationalId);

            // 只有当有效目标数量大于0时才计算平均值
            if (validTargetCount > 0) {
                double averageProgress = totalProgress / validTargetCount;

                Map<String, Object> orgData = new HashMap<>();
                orgData.put("organizationalId", organizationalId);
                orgData.put("progress", String.format("%.2f", averageProgress));

                // 根据组织类型添加组织名称
                String organizationalName = getOrganizationalName(organizationalId, targetRankingDTO.getOrganizationalType());
                if (organizationalName != null) {
                    orgData.put("organizationalName", organizationalName);
                }

                dataList.add(orgData);
            }
        }

        // 对dataList按照progress降序排序
        dataList.sort((a, b) -> {
            String progressA = (String) a.get("progress");
            String progressB = (String) b.get("progress");
            return Double.compare(Double.parseDouble(progressB), Double.parseDouble(progressA));
        });

        result.put("data", dataList);
        return result;
    }

    // 获取组织名称的辅助方法
    private String getOrganizationalName(Long organizationalId, Integer organizationalType) {
        if (organizationalId == null || organizationalType == null) {
            return null;
        }

        try {
            switch (organizationalType) {
                case 2:
                    SubCompanyEntity subCompany = subCompanyService.getById(organizationalId);
                    return subCompany != null ? subCompany.getName() : null;
                case 3:
                    DeptEntity dept = departService.getById(organizationalId);
                    return dept != null ? dept.getName() : null;
                case 4:
                    UserEntity user = userService.getById(organizationalId);
                    return user != null ? user.getRealName() : null;
                default:
                    return null;
            }
        } catch (Exception e) {
            logger.error("获取组织名称失败", e);
            return null;
        }
    }

    // 计算成交金额
    private void OrdertotalAmount(int organizationalType, List<Long> idList, LambdaQueryWrapper<TargetPlanEntity> targetWrapper, TargetRankingDTO targetRankingDTO, Map<String, Object> result) {
        LambdaQueryWrapper<TargetQuotaEntity> quotaWrapper = new LambdaQueryWrapper<>();
        quotaWrapper.in(TargetQuotaEntity::getTargetPlanId, idList);
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.eq(TargetQuotaEntity::getIsDelete,0);
        String oIds = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        // 判断DTO里的organizationIds值是否为空
        String organizationIdsStr = oIds;
        if (organizationIdsStr != null && !organizationIdsStr.isEmpty()) {
           List<Long> organizationIds = Arrays.stream(organizationIdsStr.split(","))
                      .map(Long::parseLong)
                      .collect(Collectors.toList());
           quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, organizationIds);
        }

        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));
        if (CollectionUtils.isEmpty(dataScope)){
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return;
        }
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, dataScope);

        List<TargetQuotaEntity> targetQuotaList = this.list(quotaWrapper);

        // 创建一个新的Map来存放组织ID和对应的订单金额总和
        Map<Long, BigDecimal> transactionTotalMap = new HashMap<>();

        List<Long> userIds = getByTargetPlanIdList(idList, organizationalType,oIds);

        // 获取targetRankingDTO中的年份
        int year = targetRankingDTO.getYear();

        // 创建LambdaQueryWrapper来查询TargetPlanEntity表的cycle字段
        LambdaQueryWrapper<TargetPlanEntity> cycleWrapper = new LambdaQueryWrapper<>();
        cycleWrapper.in(TargetPlanEntity::getId, idList);
        cycleWrapper.eq(TargetPlanEntity::getIsDelete,0);
        List<TargetPlanEntity> targetPlanList = targetPlanService.list(cycleWrapper);

        // 遍历targetPlanList，构建一个targetId到cycle的映射
        Map<Long, Integer> targetIdToCycleMap = targetPlanList.stream()
                .collect(Collectors.toMap(TargetPlanEntity::getId, TargetPlanEntity::getCycle));

        // 关联orderFormEntity的ownBy字段，筛选出当前组织的订单
        LambdaQueryWrapper<OrderFormEntity> orderFormWrapper = new LambdaQueryWrapper<>();
        orderFormWrapper.in(!CollectionUtils.isEmpty(userIds),OrderFormEntity::getOwnerBy, userIds);
        orderFormWrapper.eq(OrderFormEntity::getIsDelete, 0);

        // 判断DTO里的quarter和month值是否为空
        Integer quarter = targetRankingDTO.getQuarter();
        Integer month = targetRankingDTO.getMonth();
        if (quarter != null) {
            int startMonth = (quarter - 1) * 3 + 1;
            int endMonth = startMonth + 2;
            orderFormWrapper.apply("MONTH(signing_date) >= {0} AND MONTH(signing_date) <= {1}", startMonth, endMonth);
        } else if (month != null) {
            orderFormWrapper.apply("MONTH(signing_date) = {0}", month);
        } else {
            orderFormWrapper.apply("YEAR(signing_date) = {0}", year);
        }

        List<OrderFormEntity> orderFormList = orderFormService.list(orderFormWrapper);


        // 计算每个组织的订单金额总和
        for (OrderFormEntity orderForm : orderFormList) {
            Long ownerId = orderForm.getOwnerBy();
            BigDecimal totalOrderAmt = orderForm.getTotalOrderAmt();

            // 找到ownerId所属的组织ID
            Long organizationalId =  null;
            if (organizationalType == 4) {
                organizationalId = ownerId;
            } else {
                // 根据用户ID查找其所属的组织
                UserEntity user = userService.getById(ownerId);
                if (user != null) {
                    // 根据organizationalType获取对应的组织ID
                    Long orgId = null;
                    if (organizationalType == 2) {
                        orgId = user.getSubCompanyId();
                    } else if (organizationalType == 3) {
                        orgId = user.getDeptId();
                    }

                    // 在targetQuotaList中查找匹配的组织ID
                    if (orgId != null) {
                        Long finalOrgId = orgId;
                        organizationalId = targetQuotaList.stream()
                                .filter(targetQuota -> targetQuota.getOrganizationalId().equals(finalOrgId))
                                .findFirst()
                                .map(TargetQuotaEntity::getOrganizationalId)
                                .orElse(null);
                    }
                }
            }

            if (organizationalId != null) {
                // 如果map中已经有该组织ID的值，则累加，否则初始化
                transactionTotalMap.put(organizationalId,
                        transactionTotalMap.getOrDefault(organizationalId, BigDecimal.ZERO).add(totalOrderAmt));
            }
        }

        // 存放每个组织的详细数据列表
        List<Map<String, Object>> ResultList = new ArrayList<>();

        // 遍历targetQuotaList，获取每个组织的目标值和成交金额
        for (TargetQuotaEntity targetQuota : targetQuotaList) {
            Long organizationalId = targetQuota.getOrganizationalId();
            BigDecimal targetValue = targetQuota.getTotal(); // 默认目标值

            // 获取组织名称
            String organizationalName = getOrganizationalName(organizationalId, organizationalType);
            // 如果targetValue为null，设置所有相关数据为0
            if (targetValue == null) {
                Map<String, Object> orgData = new HashMap<>();
                orgData.put("organizationalId", organizationalId);
                orgData.put("targetValue", BigDecimal.ZERO);
                orgData.put("totalNum", BigDecimal.ZERO);
                orgData.put("progress", 0.0);

                // 添加组织名称

                if (organizationalName != null) {
                    orgData.put("organizationalName", organizationalName);
                }

                ResultList.add(orgData);
                continue; // 跳到下一个组织
            }

            // 根据cycle字段判断是否替换total字段
            int cycle = targetIdToCycleMap.getOrDefault(targetQuota.getTargetPlanId(), 0);
            if (quarter != null) {
                targetValue = calculateTargetValueByQuarter(targetQuota, cycle, quarter);
            } else if (month != null) {
                targetValue = calculateTargetValueByMonth(targetQuota, cycle, month);
            }

            // 从transactionTotalMap中获取对应的订单金额总和
            BigDecimal transactionTotal = transactionTotalMap.getOrDefault(organizationalId, BigDecimal.ZERO);

            // 计算进度
            double progress = BigDecimalProgress(transactionTotal, targetValue);

            // 创建一个新的Map来存放单个targetQuotaEntity的数据
            Map<String, Object> orgData = new HashMap<>();
            orgData.put("organizationalId", organizationalId);
            orgData.put("targetValue", targetValue);
            orgData.put("totalNum", transactionTotal);
            orgData.put("progress", progress);

            // 如果组织名称不为空，则放入orgData中
            if (organizationalName != null) {
                orgData.put("organizationalName", organizationalName);
            }
            // 将orgData放入列表中
            ResultList.add(orgData);
        }
        if(targetRankingDTO.getTotalOrValue() == 0) {
            ResultList.sort((a, b) -> {
                BigDecimal totalNumA = (BigDecimal)a.get("totalNum");
                BigDecimal totalNumB = (BigDecimal)b.get("totalNum");
                return totalNumB.compareTo(totalNumA);  // 降序排序
            });
        } else if(targetRankingDTO.getTotalOrValue() == 1) {
            ResultList.sort((a, b) -> Double.compare(
                    Double.parseDouble(b.get("progress").toString()),
                    Double.parseDouble(a.get("progress").toString())
            ));
        }

        result.put("data", ResultList);
    }

    // 计算订单数量
    private void OrderCount(int organizationalType, List<Long> idList, LambdaQueryWrapper<TargetPlanEntity> targetWrapper, TargetRankingDTO targetRankingDTO, Map<String, Object> result) {
        LambdaQueryWrapper<TargetQuotaEntity> quotaWrapper = new LambdaQueryWrapper<>();
        quotaWrapper.in(TargetQuotaEntity::getTargetPlanId, idList);
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.eq(TargetQuotaEntity::getIsDelete,0);
        String oIds = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        // 判断DTO里的organizationIds值是否为空
        String organizationIdsStr = oIds;
        if (organizationIdsStr != null && !organizationIdsStr.isEmpty()) {
            List<Long> organizationIds = Arrays.stream(organizationIdsStr.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, organizationIds);
        }

        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));
        if (CollectionUtils.isEmpty(dataScope)){
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return;
        }
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, dataScope);

        List<TargetQuotaEntity> targetQuotaList = this.list(quotaWrapper);

        // 创建一个新的Map来存放组织ID和对应的订单数量
        Map<Long, Long> orderCountMap = new HashMap<>();

        // 获取所有用户的ID
        List<Long> userIds = getByTargetPlanIdList(idList, organizationalType,oIds);

        // 获取targetRankingDTO中的年份
        int year = targetRankingDTO.getYear();

        // 创建LambdaQueryWrapper来查询TargetPlanEntity表的cycle字段
        LambdaQueryWrapper<TargetPlanEntity> cycleWrapper = new LambdaQueryWrapper<>();
        cycleWrapper.in(TargetPlanEntity::getId, idList);
        cycleWrapper.eq(TargetPlanEntity::getIsDelete,0);
        List<TargetPlanEntity> targetPlanList = targetPlanService.list(cycleWrapper);

        // 遍历targetPlanList，构建一个targetId到cycle的映射
        Map<Long, Integer> targetIdToCycleMap = targetPlanList.stream()
                .collect(Collectors.toMap(TargetPlanEntity::getId, TargetPlanEntity::getCycle));

        // 关联orderFormEntity的ownBy字段，筛选出当前组织的订单
        LambdaQueryWrapper<OrderFormEntity> orderFormWrapper = new LambdaQueryWrapper<>();
        orderFormWrapper.in(OrderFormEntity::getOwnerBy, userIds);
        orderFormWrapper.eq(OrderFormEntity::getIsDelete, 0);

        // 判断DTO里的quarter和month值是否为空
        Integer quarter = targetRankingDTO.getQuarter();
        Integer month = targetRankingDTO.getMonth();
        if (quarter != null) {
            int startMonth = (quarter - 1) * 3 + 1;
            int endMonth = startMonth + 2;
            orderFormWrapper.apply("MONTH(signing_date) >= {0} AND MONTH(signing_date) <= {1}", startMonth, endMonth);
        } else if (month != null) {
            orderFormWrapper.apply("MONTH(signing_date) = {0}", month);
        } else {
            orderFormWrapper.apply("YEAR(signing_date) = {0}", year);
        }

        List<OrderFormEntity> orderFormList = orderFormService.list(orderFormWrapper);

        // 计算每个组织的订单数量
        for (OrderFormEntity orderForm : orderFormList) {
            Long ownerId = orderForm.getOwnerBy();

            // 找到ownerId所属的组织ID
            Long organizationalId = null;
            if (organizationalType == 4) {
                organizationalId = ownerId;
            } else {
                // 根据用户ID查找其所属的组织
                UserEntity user = userService.getById(ownerId);
                if (user != null) {
                    // 根据organizationalType获取对应的组织ID
                    Long orgId = null;
                    if (organizationalType == 2) {
                        orgId = user.getSubCompanyId();
                    } else if (organizationalType == 3) {
                        orgId = user.getDeptId();
                    }

                    // 在targetQuotaList中查找匹配的组织ID
                    if (orgId != null) {
                        Long finalOrgId = orgId;
                        organizationalId = targetQuotaList.stream()
                                .filter(targetQuota -> targetQuota.getOrganizationalId().equals(finalOrgId))
                                .findFirst()
                                .map(TargetQuotaEntity::getOrganizationalId)
                                .orElse(null);
                    }
                }
            }

            if (organizationalId != null) {
                // 如果map中已经有该组织ID的值，则累加，否则初始化
                orderCountMap.put(organizationalId,
                        orderCountMap.getOrDefault(organizationalId, 0L) + 1);
            }
        }

        // 存放每个组织的详细数据列表
        List<Map<String, Object>> ResultList = new ArrayList<>();

        // 遍历targetQuotaList，获取每个组织的目标值和订单数量
        for (TargetQuotaEntity targetQuota : targetQuotaList) {
            Long organizationalId = targetQuota.getOrganizationalId();
            BigDecimal targetValue = targetQuota.getTotal(); // 默认目标值

            // 获取组织名称
            String organizationalName = getOrganizationalName(organizationalId, organizationalType);
            // 如果targetValue为null，设置所有相关数据为0
            if (targetValue == null) {
                Map<String, Object> orgData = new HashMap<>();
                orgData.put("organizationalId", organizationalId);
                orgData.put("targetValue", BigDecimal.ZERO);
                orgData.put("totalNum", BigDecimal.ZERO);
                orgData.put("progress", 0.0);

                // 添加组织名称

                if (organizationalName != null) {
                    orgData.put("organizationalName", organizationalName);
                }

                ResultList.add(orgData);
                continue; // 跳到下一个组织
            }

            // 根据cycle字段判断是否替换total字段
            int cycle = targetIdToCycleMap.getOrDefault(targetQuota.getTargetPlanId(), 0);
            if (quarter != null) {
                targetValue = calculateTargetValueByQuarter(targetQuota, cycle, quarter);
            } else if (month != null) {
                targetValue = calculateTargetValueByMonth(targetQuota, cycle, month);
            }

            // 从orderCountMap中获取对应的订单数量
            BigDecimal orderCount = BigDecimal.valueOf(orderCountMap.getOrDefault(organizationalId, 0L));

            // 计算进度
            BigDecimal progress = calculateProgress(orderCount, targetValue);
            // 创建一个新的Map来存放单个targetQuotaEntity数据
            Map<String, Object> orgData = new HashMap<>();
            orgData.put("organizationalId", organizationalId);
            orgData.put("targetValue", targetValue);
            orgData.put("totalNum", orderCount);
            orgData.put("progress", progress);

            // 如果组织名称不为空，则放入orgData中
            if (organizationalName != null) {
                orgData.put("organizationalName", organizationalName);
            }
            // 将orgData放入列表中
            ResultList.add(orgData);
        }
        // 根据totalOrValue排序
        if(targetRankingDTO.getTotalOrValue() == 0) {
            ResultList.sort((a, b) -> {
                BigDecimal totalNumA = (BigDecimal)a.get("totalNum");
                BigDecimal totalNumB = (BigDecimal)b.get("totalNum");
                return totalNumB.compareTo(totalNumA);  // 降序排序
            });
        } else if(targetRankingDTO.getTotalOrValue() == 1) {
            ResultList.sort((a, b) -> {
                // 由于progress是Double类型，需要先转换为Double再比较
                Double progressA = Double.parseDouble(a.get("progress").toString());
                Double progressB = Double.parseDouble(b.get("progress").toString());
                return progressB.compareTo(progressA);  // 降序排序
            });
        }
        result.put("data", ResultList);
    }


    // 计算客户数量
    private void CustomerCount(int organizationalType, List<Long> idList, LambdaQueryWrapper<TargetPlanEntity> targetWrapper, TargetRankingDTO targetRankingDTO, Map<String, Object> result) {
        LambdaQueryWrapper<TargetQuotaEntity> quotaWrapper = new LambdaQueryWrapper<>();
        quotaWrapper.in(TargetQuotaEntity::getTargetPlanId, idList);
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.eq(TargetQuotaEntity::getIsDelete,0);
        String oIds = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        // 判断DTO里的organizationIds值是否为空
        String organizationIdsStr = oIds;
        if (organizationIdsStr != null && !organizationIdsStr.isEmpty()) {
            List<Long> organizationIds = Arrays.stream(organizationIdsStr.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, organizationIds);
        }
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));
        if (CollectionUtils.isEmpty(dataScope)){
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return;
        }
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, dataScope);

        List<TargetQuotaEntity> targetQuotaList = this.list(quotaWrapper);

        // 创建一个新的Map来存放组织ID和对应的客户数量
        Map<Long, Long> customerCountMap = new HashMap<>();

        // 获取所有用户的ID
        List<Long> userIds = getByTargetPlanIdList(idList, organizationalType,oIds);

        // 获取targetRankingDTO中的年份
        int year = targetRankingDTO.getYear();

        // 创建LambdaQueryWrapper来查询TargetPlanEntity表的cycle字段
        LambdaQueryWrapper<TargetPlanEntity> cycleWrapper = new LambdaQueryWrapper<>();
        cycleWrapper.in(TargetPlanEntity::getId, idList);
        cycleWrapper.eq(TargetPlanEntity::getIsDelete,0);
        List<TargetPlanEntity> targetPlanList = targetPlanService.list(cycleWrapper);

        // 遍历targetPlanList，构建一个targetId到cycle的映射
        Map<Long, Integer> targetIdToCycleMap = targetPlanList.stream()
                .collect(Collectors.toMap(TargetPlanEntity::getId, TargetPlanEntity::getCycle));

        // 关联CustomerEntity的ownBy字段，筛选出当前组织的客户
        LambdaQueryWrapper<CustomerEntity> customerWrapper = new LambdaQueryWrapper<>();
        customerWrapper.in(CustomerEntity::getOwnerBy, userIds);
        customerWrapper.eq(CustomerEntity::getCustomerForm, 10);
        customerWrapper.eq(CustomerEntity::getHasGarbageCustomer, 0);
        customerWrapper.eq(CustomerEntity::getIsDelete, 0);

       // 判断DTO里的quarter和month值是否为空
        Integer quarter = targetRankingDTO.getQuarter();
        Integer month = targetRankingDTO.getMonth();
        if (quarter != null) {
            int startMonth = (quarter - 1) * 3 + 1;
            int endMonth = startMonth + 2;
            customerWrapper.apply("MONTH(create_time) >= {0} AND MONTH(create_time) <= {1}", startMonth, endMonth);
        } else if (month != null) {
            customerWrapper.apply("MONTH(create_time) = {0}", month);
        } else {
            customerWrapper.apply("YEAR(create_time) = {0}", year);
        }


        List<CustomerEntity> customerList = customerService.list(customerWrapper);

        // 计算每个组织的客户数量
        for (CustomerEntity customer : customerList) {
            Long ownerId = customer.getOwnerBy();

            // 找到ownerId所属的组织ID
            Long organizationalId = null;
            if (organizationalType == 4) {
                organizationalId = ownerId;
            } else {
                // 根据用户ID查找其所属的组织
                UserEntity user = userService.getById(ownerId);
                if (user != null) {
                    // 根据organizationalType获取对应的组织ID
                    Long orgId = null;
                    if (organizationalType == 2) {
                        orgId = user.getSubCompanyId();
                    } else if (organizationalType == 3) {
                        orgId = user.getDeptId();
                    }

                    // 在targetQuotaList中查找匹配的组织ID
                    if (orgId != null) {
                        Long finalOrgId = orgId;
                        organizationalId = targetQuotaList.stream()
                                .filter(targetQuota -> targetQuota.getOrganizationalId().equals(finalOrgId))
                                .findFirst()
                                .map(TargetQuotaEntity::getOrganizationalId)
                                .orElse(null);
                    }
                }
            }

            if (organizationalId != null) {
                // 如果map中已经有该组织ID的值，则累加，否则初始化
                customerCountMap.put(organizationalId,
                        customerCountMap.getOrDefault(organizationalId, 0L) + 1);
            }
        }
        // 存放每个组织的详细数据列表
        List<Map<String, Object>> ResultList = new ArrayList<>();

        // 遍历targetQuotaList，获取每个组织的目标值和客户数量
        for (TargetQuotaEntity targetQuota : targetQuotaList) {
            Long organizationalId = targetQuota.getOrganizationalId();
            BigDecimal targetValue = targetQuota.getTotal(); // 默认目标值

            // 获取组织名称
            String organizationalName = getOrganizationalName(organizationalId, organizationalType);
            // 如果targetValue为null，设置所有相关数据为0
            if (targetValue == null) {
                Map<String, Object> orgData = new HashMap<>();
                orgData.put("organizationalId", organizationalId);
                orgData.put("targetValue", BigDecimal.ZERO);
                orgData.put("totalNum", BigDecimal.ZERO);
                orgData.put("progress", 0.0);

                // 添加组织名称

                if (organizationalName != null) {
                    orgData.put("organizationalName", organizationalName);
                }

                ResultList.add(orgData);
                continue; // 跳到下一个组织
            }

            // 根据cycle字段判断是否替换total字段
            int cycle = targetIdToCycleMap.getOrDefault(targetQuota.getTargetPlanId(), 0);
            if (quarter != null) {
                targetValue = calculateTargetValueByQuarter(targetQuota, cycle, quarter);
            } else if (month != null) {
                targetValue = calculateTargetValueByMonth(targetQuota, cycle, month);
            }

            // 从customerCountMap中获取对应的客户数量
            BigDecimal customerCount = BigDecimal.valueOf(customerCountMap.getOrDefault(organizationalId, 0L));

            // 计算进度
            BigDecimal progress = calculateProgress(customerCount, targetValue);
            // 创建一个新的Map来存放单个targetQuotaEntity的数据
            Map<String, Object> orgData = new HashMap<>();
            orgData.put("organizationalId", organizationalId);
            orgData.put("targetValue", targetValue);
            orgData.put("totalNum", customerCount);
            orgData.put("progress", progress);

            // 如果组织名称不为空，则放入orgData中
            if (organizationalName != null) {
                orgData.put("organizationalName", organizationalName);
            }

            // 将orgData放入列表中
            ResultList.add(orgData);
        }
        // 根据totalOrValue排序
        if(targetRankingDTO.getTotalOrValue() == 0) {
            ResultList.sort((a, b) -> {
                BigDecimal totalNumA = (BigDecimal)a.get("totalNum");
                BigDecimal totalNumB = (BigDecimal)b.get("totalNum");
                return totalNumB.compareTo(totalNumA);  // 降序排序
            });
        } else if(targetRankingDTO.getTotalOrValue() == 1) {
            ResultList.sort((a, b) -> {
                // 由于progress是Double类型，需要先转换为Double再比较
                Double progressA = Double.parseDouble(a.get("progress").toString());
                Double progressB = Double.parseDouble(b.get("progress").toString());
                return progressB.compareTo(progressA);  // 降序排序
            });
        }

        result.put("data", ResultList);
    }


    // 计算商机数量
    private void BusinessCount(int organizationalType, List<Long> idList, LambdaQueryWrapper<TargetPlanEntity> targetWrapper, TargetRankingDTO targetRankingDTO, Map<String, Object> result) {
        LambdaQueryWrapper<TargetQuotaEntity> quotaWrapper = new LambdaQueryWrapper<>();
        quotaWrapper.in(TargetQuotaEntity::getTargetPlanId, idList);
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.eq(TargetQuotaEntity::getIsDelete,0);
        String oIds = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        // 判断DTO里的organizationIds值是否为空
        String organizationIdsStr = oIds;
        if (organizationIdsStr != null && !organizationIdsStr.isEmpty()) {
            List<Long> organizationIds = Arrays.stream(organizationIdsStr.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, organizationIds);
        }
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));
        if (CollectionUtils.isEmpty(dataScope)){
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return;
        }
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, dataScope);

        List<TargetQuotaEntity> targetQuotaList = this.list(quotaWrapper);

        // 创建一个新的Map来存放组织ID和对应的商机数量
        Map<Long, Long> businessCountMap = new HashMap<>();

        // 获取所有用户的ID
        List<Long> userIds = getByTargetPlanIdList(idList, organizationalType,oIds);

        // 获取targetRankingDTO中的年份
        int year = targetRankingDTO.getYear();

        // 创建LambdaQueryWrapper来查询TargetPlanEntity表的cycle字段
        LambdaQueryWrapper<TargetPlanEntity> cycleWrapper = new LambdaQueryWrapper<>();
        cycleWrapper.in(TargetPlanEntity::getId, idList);
        cycleWrapper.eq(TargetPlanEntity::getIsDelete,0);
        List<TargetPlanEntity> targetPlanList = targetPlanService.list(cycleWrapper);

        // 遍历targetPlanList，构建一个targetId到cycle的映射
        Map<Long, Integer> targetIdToCycleMap = targetPlanList.stream()
                .collect(Collectors.toMap(TargetPlanEntity::getId, TargetPlanEntity::getCycle));

        // 关联BusinessEntity的owner字段，筛选出当前组织的商机
        LambdaQueryWrapper<BusinessEntity> businessWrapper = new LambdaQueryWrapper<>();
        businessWrapper.in(BusinessEntity::getOwnerBy, userIds);
        businessWrapper.eq(BusinessEntity::getHasLoss, 0);
        businessWrapper.eq(BusinessEntity::getIsDelete, 0);

        // 判断DTO里的quarter和month值是否为空
        Integer quarter = targetRankingDTO.getQuarter();
        Integer month = targetRankingDTO.getMonth();
        if (quarter != null) {
            int startMonth = (quarter - 1) * 3 + 1;
            int endMonth = startMonth + 2;
            businessWrapper.apply("MONTH(geted_date) >= {0} AND MONTH(geted_date) <= {1}", startMonth, endMonth);
        } else if (month != null) {
            businessWrapper.apply("MONTH(geted_date) = {0}", month);
        } else {
            businessWrapper.apply("YEAR(geted_date) = {0}", year);
        }

        List<BusinessEntity> businessList = businessService.list(businessWrapper);

        // 计算每个组织的商机数量
        for (BusinessEntity business : businessList) {
            Long ownerId = business.getOwnerBy();

            // 找到ownerId所属的组织ID
            Long organizationalId = null;
            if (organizationalType == 4) {
                organizationalId = ownerId;
            } else {
                // 根据用户ID查找其所属的组织
                UserEntity user = userService.getById(ownerId);
                if (user != null) {
                    // 根据organizationalType获取对应的组织ID
                    Long orgId = null;
                    if (organizationalType == 2) {
                        orgId = user.getSubCompanyId();
                    } else if (organizationalType == 3) {
                        orgId = user.getDeptId();
                    }

                    // 在targetQuotaList中查找匹配的组织ID
                    if (orgId != null) {
                        Long finalOrgId = orgId;
                        organizationalId = targetQuotaList.stream()
                                .filter(targetQuota -> targetQuota.getOrganizationalId().equals(finalOrgId))
                                .findFirst()
                                .map(TargetQuotaEntity::getOrganizationalId)
                                .orElse(null);
                    }
                }
            }

            if (organizationalId != null) {
                // 如果map中已经有该组织ID的值，则累加，否则初始化
                businessCountMap.put(organizationalId,
                        businessCountMap.getOrDefault(organizationalId, 0L) + 1);
            }
        }
        // 存放每个组织的详细数据列表
        List<Map<String, Object>> ResultList = new ArrayList<>();

        // 遍历targetQuotaList，获取每个组织的目标值和商机数量
        for (TargetQuotaEntity targetQuota : targetQuotaList) {
            Long organizationalId = targetQuota.getOrganizationalId();
            BigDecimal targetValue = targetQuota.getTotal(); // 默认目标值

            // 获取组织名称
            String organizationalName = getOrganizationalName(organizationalId, organizationalType);
            // 如果targetValue为null，设置所有相关数据为0
            if (targetValue == null) {
                Map<String, Object> orgData = new HashMap<>();
                orgData.put("organizationalId", organizationalId);
                orgData.put("targetValue", BigDecimal.ZERO);
                orgData.put("totalNum", BigDecimal.ZERO);
                orgData.put("progress", 0.0);

                // 添加组织名称
                if (organizationalName != null) {
                    orgData.put("organizationalName", organizationalName);
                }

                ResultList.add(orgData);
                continue; // 跳到下一个组织
            }

            // 根据cycle字段判断是否替换total字段
            int cycle = targetIdToCycleMap.getOrDefault(targetQuota.getTargetPlanId(), 0);
            if (quarter != null) {
                targetValue = calculateTargetValueByQuarter(targetQuota, cycle, quarter);
            } else if (month != null) {
                targetValue = calculateTargetValueByMonth(targetQuota, cycle, month);
            }

            // 从customerCountMap中获取对应的商机数量
            BigDecimal businessCount = BigDecimal.valueOf(businessCountMap.getOrDefault(organizationalId, 0L));

            // 计算进度
            BigDecimal progress = calculateProgress(businessCount, targetValue);

            // 创建一个新的Map来存放单个targetQuotaEntity的数据
            Map<String, Object> orgData = new HashMap<>();
            orgData.put("organizationalId", organizationalId);
            orgData.put("targetValue", targetValue);
            orgData.put("totalNum", businessCount);
            orgData.put("progress", progress);

            // 如果组织名称不为空，则放入orgData中
            if (organizationalName != null) {
                orgData.put("organizationalName", organizationalName);
            }
            // 将orgData放入列表中
            ResultList.add(orgData);
        }
        // 根据totalOrValue排序
        if(targetRankingDTO.getTotalOrValue() == 0) {
            ResultList.sort((a, b) -> {
                BigDecimal totalNumA = (BigDecimal)a.get("totalNum");
                BigDecimal totalNumB = (BigDecimal)b.get("totalNum");
                return totalNumB.compareTo(totalNumA);  // 降序排序
            });
        } else if(targetRankingDTO.getTotalOrValue() == 1) {
            ResultList.sort((a, b) -> {
                // 由于progress是Double类型，需要先转换为Double再比较
                Double progressA = Double.parseDouble(a.get("progress").toString());
                Double progressB = Double.parseDouble(b.get("progress").toString());
                return progressB.compareTo(progressA);  // 降序排序
            });
        }

        result.put("data", ResultList);
    }

    // 计算跟进数量
    private void FollowUpCount(int organizationalType, List<Long> idList, LambdaQueryWrapper<TargetPlanEntity> targetWrapper, TargetRankingDTO targetRankingDTO, Map<String, Object> result) {
        LambdaQueryWrapper<TargetQuotaEntity> quotaWrapper = new LambdaQueryWrapper<>();
        quotaWrapper.in(TargetQuotaEntity::getTargetPlanId, idList);
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.eq(TargetQuotaEntity::getIsDelete,0);
        String oIds = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        // 判断DTO里的organizationIds值是否为空
        String organizationIdsStr = oIds;
        if (organizationIdsStr != null && !organizationIdsStr.isEmpty()) {
            List<Long> organizationIds = Arrays.stream(organizationIdsStr.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, organizationIds);
        }
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));
        if (CollectionUtils.isEmpty(dataScope)){
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return;
        }
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, dataScope);

        List<TargetQuotaEntity> targetQuotaList = this.list(quotaWrapper);

        // 创建一个新的Map来存放组织ID和对应的跟进数量
        Map<Long, Long> followUpCountMap = new HashMap<>();

        // 获取所有用户的ID
        List<Long> userIds = getByTargetPlanIdList(idList, organizationalType, oIds);

        // 获取targetRankingDTO中的年份
        int year = targetRankingDTO.getYear();

        // 创建LambdaQueryWrapper来查询TargetPlanEntity表的cycle字段
        LambdaQueryWrapper<TargetPlanEntity> cycleWrapper = new LambdaQueryWrapper<>();
        cycleWrapper.in(TargetPlanEntity::getId, idList);
        cycleWrapper.eq(TargetPlanEntity::getIsDelete,0);
        List<TargetPlanEntity> targetPlanList = targetPlanService.list(cycleWrapper);

        // 遍历targetPlanList，构建一个targetId到cycle的映射
        Map<Long, Integer> targetIdToCycleMap = targetPlanList.stream()
                .collect(Collectors.toMap(TargetPlanEntity::getId, TargetPlanEntity::getCycle));

        // 关联CustomerFollowUpEntity的followUpMemberId字段，筛选出当前组织的跟进数据
        LambdaQueryWrapper<CustomerFollowUpEntity> followUpWrapper = new LambdaQueryWrapper<>();
        followUpWrapper.in(CustomerFollowUpEntity::getFollowUpMemberId, userIds);
        followUpWrapper.eq(CustomerFollowUpEntity::getIsDelete, 0);

        // 判断DTO里的quarter和month值是否为空
        Integer quarter = targetRankingDTO.getQuarter();
        Integer month = targetRankingDTO.getMonth();
        if (quarter != null) {
            int startMonth = (quarter - 1) * 3 + 1;
            int endMonth = startMonth + 2;
            followUpWrapper.apply("MONTH(follow_up_time) >= {0} AND MONTH(follow_up_time) <= {1}", startMonth, endMonth);
        } else if (month != null) {
            followUpWrapper.apply("MONTH(follow_up_time) = {0}", month);
        } else {
            followUpWrapper.apply("YEAR(follow_up_time) = {0}", year);
        }

        List<CustomerFollowUpEntity> followUpList = customerFollowUpService.list(followUpWrapper);

        // 计算每个组织的跟进数量
        for (CustomerFollowUpEntity followUp : followUpList) {
            Long followUpMemberId = followUp.getFollowUpMemberId();

            // 找到followUpMemberId所属的组织ID
            Long organizationalId = null;
            if (organizationalType == 4) {
                organizationalId = followUpMemberId;
            } else {
                // 根据用户ID查找其所属的组织
                UserEntity user = userService.getById(followUpMemberId);
                if (user != null) {
                    // 根据organizationalType获取对应的组织ID
                    Long orgId = null;
                    if (organizationalType == 2) {
                        orgId = user.getSubCompanyId();
                    } else if (organizationalType == 3) {
                        orgId = user.getDeptId();
                    }

                    // 在targetQuotaList中查找匹配的组织ID
                    if (orgId != null) {
                        Long finalOrgId = orgId;
                        organizationalId = targetQuotaList.stream()
                                .filter(targetQuota -> targetQuota.getOrganizationalId().equals(finalOrgId))
                                .findFirst()
                                .map(TargetQuotaEntity::getOrganizationalId)
                                .orElse(null);
                    }
                }
            }

            if (organizationalId != null) {
                // 如果map中已经有该组织ID的值，则累加，否则初始化
                followUpCountMap.put(organizationalId,
                        followUpCountMap.getOrDefault(organizationalId, 0L) + 1);
            }
        }

        // 存放每个组织的详细数据列表
        List<Map<String, Object>> ResultList = new ArrayList<>();

        // 遍历targetQuotaList，获取每个组织的目标值和跟进数量
        for (TargetQuotaEntity targetQuota : targetQuotaList) {
            Long organizationalId = targetQuota.getOrganizationalId();
            BigDecimal targetValue = targetQuota.getTotal(); // 默认目标值

            // 获取组织名称
            String organizationalName = getOrganizationalName(organizationalId, organizationalType);
            // 如果targetValue为null，设置所有相关数据为0
            if (targetValue == null) {
                Map<String, Object> orgData = new HashMap<>();
                orgData.put("organizationalId", organizationalId);
                orgData.put("targetValue", BigDecimal.ZERO);
                orgData.put("totalNum", BigDecimal.ZERO);
                orgData.put("progress", 0.0);

                // 添加组织名称
                if (organizationalName != null) {
                    orgData.put("organizationalName", organizationalName);
                }

                ResultList.add(orgData);
                continue; // 跳到下一个组织
            }

            // 根据cycle字段判断是否替换total字段
            int cycle = targetIdToCycleMap.getOrDefault(targetQuota.getTargetPlanId(), 0);
            if (quarter != null) {
                targetValue = calculateTargetValueByQuarter(targetQuota, cycle, quarter);
            } else if (month != null) {
                targetValue = calculateTargetValueByMonth(targetQuota, cycle, month);
            }


            // 从customerCountMap中获取对应的跟进数量
            BigDecimal followUpCount = BigDecimal.valueOf(followUpCountMap.getOrDefault(organizationalId, 0L));

            // 计算进度
            BigDecimal progress = calculateProgress(followUpCount, targetValue);

            // 创建一个新的Map来存放单个targetQuotaEntity的数据
            Map<String, Object> orgData = new HashMap<>();
            orgData.put("organizationalId", organizationalId);
            orgData.put("targetValue", targetValue);
            orgData.put("totalNum", followUpCount);
            orgData.put("progress", progress);

            // 如果组织名称不为空，则放入orgData中
            if (organizationalName != null) {
                orgData.put("organizationalName", organizationalName);
            }
            ResultList.add(orgData);
        }
        // 根据totalOrValue排序
        if(targetRankingDTO.getTotalOrValue() == 0) {
            ResultList.sort((a, b) -> {
                BigDecimal totalNumA = (BigDecimal)a.get("totalNum");
                BigDecimal totalNumB = (BigDecimal)b.get("totalNum");
                return totalNumB.compareTo(totalNumA);  // 降序排序
            });
        } else if(targetRankingDTO.getTotalOrValue() == 1) {
            ResultList.sort((a, b) -> {
                // 由于progress是Double类型，需要先转换为Double再比较
                Double progressA = Double.parseDouble(a.get("progress").toString());
                Double progressB = Double.parseDouble(b.get("progress").toString());
                return progressB.compareTo(progressA);  // 降序排序
            });
        }

        result.put("data", ResultList);
    }


    // 计算线索数量
    private void NewClueCount(int organizationalType, List<Long> idList, LambdaQueryWrapper<TargetPlanEntity> targetWrapper, TargetRankingDTO targetRankingDTO, Map<String, Object> result) {
        LambdaQueryWrapper<TargetQuotaEntity> quotaWrapper = new LambdaQueryWrapper<>();
        quotaWrapper.in(TargetQuotaEntity::getTargetPlanId, idList);
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.eq(TargetQuotaEntity::getIsDelete,0);
        String oIds = StringUtil.longListToString(targetRankingDTO.getOrganizationIds());
        // 判断DTO里的organizationIds值是否为空
        String organizationIdsStr = oIds;
        if (organizationIdsStr != null && !organizationIdsStr.isEmpty() && !"[]".equals(organizationIdsStr)) {
            List<Long> organizationIds = Arrays.stream(organizationIdsStr.split(","))
                    .map(Long::parseLong)
                    .collect(Collectors.toList());
            quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, organizationIds);
        }
        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));
        if (CollectionUtils.isEmpty(dataScope)){
            List<Map<String, Object>> list = new ArrayList<>();
            result.put("data", list);
            return;
        }
        quotaWrapper.eq(TargetQuotaEntity::getOrganizationalType, organizationalType);
        quotaWrapper.in(TargetQuotaEntity::getOrganizationalId, dataScope);

        List<TargetQuotaEntity> targetQuotaList = this.list(quotaWrapper);

        // 创建一个新的Map来存放组织ID和对应的线索数量
        Map<Long, Long> customerCountMap = new HashMap<>();

        // 获取所有用户的ID
        List<Long> userIds = getByTargetPlanIdList(idList, organizationalType,oIds);

        // 获取targetRankingDTO中的年份
        int year = targetRankingDTO.getYear();

        // 创建LambdaQueryWrapper来查询TargetPlanEntity表的cycle字段
        LambdaQueryWrapper<TargetPlanEntity> cycleWrapper = new LambdaQueryWrapper<>();
        cycleWrapper.in(TargetPlanEntity::getId, idList);
        cycleWrapper.eq(TargetPlanEntity::getIsDelete,0);
        List<TargetPlanEntity> targetPlanList = targetPlanService.list(cycleWrapper);

        // 遍历targetPlanList，构建一个targetId到cycle的映射
        Map<Long, Integer> targetIdToCycleMap = targetPlanList.stream()
                .collect(Collectors.toMap(TargetPlanEntity::getId, TargetPlanEntity::getCycle));

        // 关联CustomerEntity的ownBy字段，筛选出当前组织的线索
        LambdaQueryWrapper<CustomerEntity> customerWrapper = new LambdaQueryWrapper<>();
        customerWrapper.in(CustomerEntity::getOwnerBy, userIds);
        customerWrapper.eq(CustomerEntity::getCustomerForm, 11);
        customerWrapper.eq(CustomerEntity::getIsDelete, 0);

        // 判断DTO里的quarter和month值是否为空
        Integer quarter = targetRankingDTO.getQuarter();
        Integer month = targetRankingDTO.getMonth();
        if (quarter != null) {
            int startMonth = (quarter - 1) * 3 + 1;
            int endMonth = startMonth + 2;
            customerWrapper.apply("MONTH(create_time) >= {0} AND MONTH(create_time) <= {1}", startMonth, endMonth);
        } else if (month != null) {
            customerWrapper.apply("MONTH(create_time) = {0}", month);
        } else {
            customerWrapper.apply("YEAR(create_time) = {0}", year);
        }


        List<CustomerEntity> customerList = customerService.list(customerWrapper);

        // 计算每个组织的线索数量
        for (CustomerEntity customer : customerList) {
            Long ownerId = customer.getOwnerBy();

            // 找到ownerId所属的组织ID
            Long organizationalId = null;
            if (organizationalType == 4) {
                organizationalId = ownerId;
            } else {
                // 根据用户ID查找其所属的组织
                UserEntity user = userService.getById(ownerId);
                if (user != null) {
                    // 根据organizationalType获取对应的组织ID
                    Long orgId = null;
                    if (organizationalType == 2) {
                        orgId = user.getSubCompanyId();
                    } else if (organizationalType == 3) {
                        orgId = user.getDeptId();
                    }

                    // 在targetQuotaList中查找匹配的组织ID
                    if (orgId != null) {
                        Long finalOrgId = orgId;
                        organizationalId = targetQuotaList.stream()
                                .filter(targetQuota -> targetQuota.getOrganizationalId().equals(finalOrgId))
                                .findFirst()
                                .map(TargetQuotaEntity::getOrganizationalId)
                                .orElse(null);
                    }
                }
            }

            if (organizationalId != null) {
                // 如果map中已经有该组织ID的值，则累加，否则初始化
                customerCountMap.put(organizationalId,
                        customerCountMap.getOrDefault(organizationalId, 0L) + 1);
            }
        }

        // 存放每个组织的详细数据列表
        List<Map<String, Object>> ResultList = new ArrayList<>();

        // 遍历targetQuotaList，获取每个组织的目标值和线索数量
        for (TargetQuotaEntity targetQuota : targetQuotaList) {
            Long organizationalId = targetQuota.getOrganizationalId();
            BigDecimal targetValue = targetQuota.getTotal(); // 默认目标值

            // 获取组织名称
            String organizationalName = getOrganizationalName(organizationalId, organizationalType);
            // 如果targetValue为null，设置所有相关数据为0
            if (targetValue == null) {
                Map<String, Object> orgData = new HashMap<>();
                orgData.put("organizationalId", organizationalId);
                orgData.put("targetValue", BigDecimal.ZERO);
                orgData.put("totalNum", BigDecimal.ZERO);
                orgData.put("progress", 0.0);

                // 添加组织名称
                if (organizationalName != null) {
                    orgData.put("organizationalName", organizationalName);
                }

                ResultList.add(orgData);
                continue; // 跳到下一个组织
            }

            // 根据cycle字段判断是否替换total字段
            int cycle = targetIdToCycleMap.getOrDefault(targetQuota.getTargetPlanId(), 0);
            if (quarter != null) {
                targetValue = calculateTargetValueByQuarter(targetQuota, cycle, quarter);
            } else if (month != null) {
                targetValue = calculateTargetValueByMonth(targetQuota, cycle, month);
            }

            // 从customerCountMap中获取对应的线索数量
            BigDecimal clubCount = BigDecimal.valueOf(customerCountMap.getOrDefault(organizationalId, 0L));

            // 计算进度
            BigDecimal progress = calculateProgress(clubCount, targetValue);

            // 创建一个新的Map来存放单个targetQuotaEntity的数据
            Map<String, Object> orgData = new HashMap<>();
            orgData.put("organizationalId", organizationalId);
            orgData.put("targetValue", targetValue);
            orgData.put("totalNum", clubCount);
            orgData.put("progress", progress);


            // 如果组织名称不为空，则放入orgData中
            if (organizationalName != null) {
                orgData.put("organizationalName", organizationalName);
            }
            ResultList.add(orgData);
        }
        // 根据totalOrValue排序
        if(targetRankingDTO.getTotalOrValue() == 0) {
            ResultList.sort((a, b) -> {
                BigDecimal totalNumA = (BigDecimal)a.get("totalNum");
                BigDecimal totalNumB = (BigDecimal)b.get("totalNum");
                return totalNumB.compareTo(totalNumA);  // 降序排序
            });
        } else if(targetRankingDTO.getTotalOrValue() == 1) {
            ResultList.sort((a, b) -> {
                // 由于progress是Double类型，需要先转换为Double再比较
                Double progressA = Double.parseDouble(a.get("progress").toString());
                Double progressB = Double.parseDouble(b.get("progress").toString());
                return progressB.compareTo(progressA);  // 降序排序
            });
        }

        result.put("data", ResultList);
    }


    private double BigDecimalProgress(BigDecimal transactionTotal, BigDecimal targetValue) {
        if (transactionTotal.compareTo(BigDecimal.ZERO) == 0 || targetValue.compareTo(BigDecimal.ZERO) == 0) {
            return 0.0;
        }
        // 计算时保留4位小数
        double result = transactionTotal.divide(targetValue, 4, RoundingMode.HALF_UP).doubleValue() * 100;
        // 最终结果保留2位小数
        return new BigDecimal(result).setScale(2, RoundingMode.HALF_UP).doubleValue();
    }

    private BigDecimal calculateProgress(BigDecimal actualValue, BigDecimal targetValue) {
        if ( actualValue.compareTo(BigDecimal.ZERO) == 0 || targetValue.compareTo(BigDecimal.ZERO) == 0) {
            return BigDecimal.ZERO;
        }
        return actualValue
                .divide(targetValue, 4, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100))
                .setScale(2, RoundingMode.HALF_UP);
    }


    private BigDecimal calculateTargetValueByQuarter(TargetQuotaEntity targetQuota, int cycle, int quarter) {
        if (cycle == 1) {
            // 根据quarter值获取对应的季度目标
            switch (quarter) {
                case 1: return targetQuota.getMonthOrQuarter1();
                case 2: return targetQuota.getMonthOrQuarter2();
                case 3: return targetQuota.getMonthOrQuarter3();
                case 4: return targetQuota.getMonthOrQuarter4();
                default: return targetQuota.getTotal(); // 默认值
            }
        } else if (cycle == 2) {
            // 根据quarter值计算对应的月度目标总和
            switch (quarter) {
                case 1: return targetQuota.getMonthOrQuarter1().add(targetQuota.getMonthOrQuarter2()).add(targetQuota.getMonthOrQuarter3());
                case 2: return targetQuota.getMonthOrQuarter4().add(targetQuota.getMonthOrQuarter5()).add(targetQuota.getMonthOrQuarter6());
                case 3: return targetQuota.getMonthOrQuarter7().add(targetQuota.getMonthOrQuarter8()).add(targetQuota.getMonthOrQuarter9());
                case 4: return targetQuota.getMonthOrQuarter10().add(targetQuota.getMonthOrQuarter11()).add(targetQuota.getMonthOrQuarter12());
                default: return targetQuota.getTotal(); // 默认值
            }
        }
        return targetQuota.getTotal(); // 默认值
    }

    private BigDecimal calculateTargetValueByMonth(TargetQuotaEntity targetQuota, int cycle, int month) {
        if (cycle == 2) {
            // 直接取对应的月份目标
            switch (month) {
                case 1: return targetQuota.getMonthOrQuarter1();
                case 2: return targetQuota.getMonthOrQuarter2();
                case 3: return targetQuota.getMonthOrQuarter3();
                case 4: return targetQuota.getMonthOrQuarter4();
                case 5: return targetQuota.getMonthOrQuarter5();
                case 6: return targetQuota.getMonthOrQuarter6();
                case 7: return targetQuota.getMonthOrQuarter7();
                case 8: return targetQuota.getMonthOrQuarter8();
                case 9: return targetQuota.getMonthOrQuarter9();
                case 10: return targetQuota.getMonthOrQuarter10();
                case 11: return targetQuota.getMonthOrQuarter11();
                case 12: return targetQuota.getMonthOrQuarter12();
                default: return targetQuota.getTotal(); // 默认值
            }
        } else if (cycle == 1) {
            // 根据month值计算对应的季度目标
            if (month >= 1 && month <= 3) {
                return targetQuota.getMonthOrQuarter1().divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);
            } else if (month >= 4 && month <= 6) {
                return targetQuota.getMonthOrQuarter2().divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);
            } else if (month >= 7 && month <= 9) {
                return targetQuota.getMonthOrQuarter3().divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);
            } else if (month >= 10 && month <= 12) {
                return targetQuota.getMonthOrQuarter4().divide(BigDecimal.valueOf(3), 2, RoundingMode.HALF_UP);
            }
        }
        return targetQuota.getTotal(); // 默认值
    }

    @Override
    public void updateQuarterById(Long id) {
        baseMapper.updateQuarterById(id);
    }

    @Override
    public List<Long> getByTargetPlanId(Long targetPlanId, Integer organizationalType, String organizationIds) {
        return getByTargetPlanIdList(Arrays.asList(targetPlanId), organizationalType, organizationIds);
    }

    @Override
    public List<Long> getByTargetPlanIdList(List<Long> targetPlanIdList, Integer organizationalType, String organizationIds) {
        if (CollectionUtils.isEmpty(targetPlanIdList) || ObjectUtils.isEmpty(organizationalType)) {
            return new ArrayList<>();
        }
        List<Long> organizationIdList = new ArrayList<>();
        if (!ObjectUtils.isEmpty(organizationIds)){
            organizationIdList = StringUtil.stringToStringList(organizationIds);
        }
//        List<Long> organizationIdList = StringUtil.stringToStringList(organizationIds);
        LambdaQueryWrapper<TargetQuotaEntity> targetQuota = new LambdaQueryWrapper<>();
        targetQuota.in(TargetQuotaEntity::getTargetPlanId, targetPlanIdList);
        targetQuota.eq(TargetQuotaEntity::getIsDelete,CommonConstant.DEL_FLAG_0);

        Set dataScope = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(organizationalType));

        if (organizationalType == 1) {
            targetQuota.eq(TargetQuotaEntity::getOrganizationalType, 4);


            List<TargetQuotaEntity> targetQuotaEntityList = baseMapper.selectList(targetQuota);
            if (CollectionUtils.isEmpty(targetQuotaEntityList)){
                return new ArrayList<>();
            }
            List<Long> userIdList = targetQuotaEntityList.stream().map(TargetQuotaEntity::getOrganizationalId).collect(Collectors.toList());
            return userIdList;
        }
        if (organizationalType == 2){
            LambdaQueryWrapper<TargetQuotaEntity> targetQuotaC = new LambdaQueryWrapper<>();
            targetQuotaC.in(TargetQuotaEntity::getTargetPlanId, targetPlanIdList);
            targetQuotaC.eq(TargetQuotaEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            targetQuotaC.eq(TargetQuotaEntity::getOrganizationalType, 2);
            targetQuotaC.in(!CollectionUtils.isEmpty(organizationIdList),TargetQuotaEntity::getOrganizationalId, organizationIdList);
            targetQuotaC.in(!CollectionUtils.isEmpty(dataScope),TargetQuotaEntity::getOrganizationalId,dataScope);

            List<TargetQuotaEntity> targetQuotaCList = baseMapper.selectList(targetQuotaC);
            if (CollectionUtils.isEmpty(targetQuotaCList)){
                return new ArrayList<>();
            }

            List<Long> cIdList = targetQuotaCList.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
            LambdaQueryWrapper<TargetQuotaEntity> targetQuotaD = new LambdaQueryWrapper<>();
            targetQuotaD.eq(TargetQuotaEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            targetQuotaD.in(TargetQuotaEntity::getParentId, cIdList);
            List<TargetQuotaEntity> targetQuotaDList = baseMapper.selectList(targetQuotaD);
            if (CollectionUtils.isEmpty(targetQuotaDList)){
                return new ArrayList<>();
            }
            List<Long> dIdList = targetQuotaDList.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
            LambdaQueryWrapper<TargetQuotaEntity> targetQuotaU = new LambdaQueryWrapper<>();
            targetQuotaU.eq(TargetQuotaEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            targetQuotaU.in(TargetQuotaEntity::getParentId, dIdList);
            List<TargetQuotaEntity> targetQuotaUList = baseMapper.selectList(targetQuotaU);
            if (CollectionUtils.isEmpty(targetQuotaUList)){
                return new ArrayList<>();
            }
            List<Long> userIdList = targetQuotaUList.stream().map(TargetQuotaEntity::getOrganizationalId).collect(Collectors.toList());
            return userIdList;

        }
        if (organizationalType == 3){
            LambdaQueryWrapper<TargetQuotaEntity> targetQuotaD = new LambdaQueryWrapper<>();
            targetQuotaD.in(TargetQuotaEntity::getTargetPlanId, targetPlanIdList);
            targetQuotaD.eq(TargetQuotaEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            targetQuotaD.eq(TargetQuotaEntity::getOrganizationalType, 3);
            targetQuotaD.in(!CollectionUtils.isEmpty(organizationIdList),TargetQuotaEntity::getOrganizationalId, organizationIdList);
            targetQuotaD.in(!CollectionUtils.isEmpty(dataScope),TargetQuotaEntity::getOrganizationalId,dataScope);
            List<TargetQuotaEntity> targetQuotaDList = baseMapper.selectList(targetQuotaD);
            if (CollectionUtils.isEmpty(targetQuotaDList)){
                return new ArrayList<>();
            }
            List<Long> dIdList = targetQuotaDList.stream().map(TargetQuotaEntity::getId).collect(Collectors.toList());
            LambdaQueryWrapper<TargetQuotaEntity> targetQuotaU = new LambdaQueryWrapper<>();
            targetQuotaU.eq(TargetQuotaEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            targetQuotaU.in(TargetQuotaEntity::getParentId, dIdList);
            List<TargetQuotaEntity> targetQuotaUList = baseMapper.selectList(targetQuotaU);
            if (CollectionUtils.isEmpty(targetQuotaUList)){
                return new ArrayList<>();
            }
            List<Long> userIdList = targetQuotaUList.stream().map(TargetQuotaEntity::getOrganizationalId).collect(Collectors.toList());
            return userIdList;
        }
        if (organizationalType == 4){
            LambdaQueryWrapper<TargetQuotaEntity> targetQuotaU = new LambdaQueryWrapper<>();
            targetQuotaU.in(TargetQuotaEntity::getTargetPlanId, targetPlanIdList);
            targetQuotaU.eq(TargetQuotaEntity::getIsDelete,CommonConstant.DEL_FLAG_0);
            targetQuotaU.eq(TargetQuotaEntity::getOrganizationalType, 4);
            targetQuotaU.in(!CollectionUtils.isEmpty(organizationIdList),TargetQuotaEntity::getOrganizationalId, organizationIdList);
            targetQuotaU.in(!CollectionUtils.isEmpty(dataScope),TargetQuotaEntity::getOrganizationalId,dataScope);
            List<TargetQuotaEntity> targetQuotaUList = baseMapper.selectList(targetQuotaU);
            if (CollectionUtils.isEmpty(targetQuotaUList)){
                return new ArrayList<>();
            }
            List<Long> userIdList = targetQuotaUList.stream().map(TargetQuotaEntity::getOrganizationalId).collect(Collectors.toList());
            return userIdList;
        }
        return new ArrayList<>();
    }


    @Override
    public Result<?> selectListVO(TargetQuotaSearchDTO targetQuotaSearchDTO) {

        IPage<TargetQuotaListVO> pageVO = new Page<>(targetQuotaSearchDTO.getPageIndex(), targetQuotaSearchDTO.getPageSize());
        //查询权限范围
        Set<Long> dataIdSet = userRoleService.dataSelete(OrganizationalTypeEnum.getEnumByCode(targetQuotaSearchDTO.getOrganizationalType()));
//        if (null == dataIdSet){
//            return Result.result(pageVO);
//        }
        if (CollectionUtils.isEmpty(dataIdSet)){
            return Result.result(pageVO);
        }
        List<Long> dataIdList = new ArrayList<>(dataIdSet);
        targetQuotaSearchDTO.setOrganizationalIds(dataIdList);
        IPage<TargetQuotaEntity> page = new Page<>(targetQuotaSearchDTO.getPageIndex(), targetQuotaSearchDTO.getPageSize());
        List<Long> targetPlanIdList = new ArrayList<>();

        if (!ObjectUtils.isEmpty(targetQuotaSearchDTO.getYear()) || !ObjectUtils.isEmpty(targetQuotaSearchDTO.getMethod()) || !ObjectUtils.isEmpty(targetQuotaSearchDTO.getCycle()) || !ObjectUtils.isEmpty(targetQuotaSearchDTO.getType())) {
            LambdaQueryWrapper<TargetPlanEntity> tpWrapper = new LambdaQueryWrapper<>();

            tpWrapper.eq(TargetPlanEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            tpWrapper.eq(!ObjectUtils.isEmpty(targetQuotaSearchDTO.getYear()), TargetPlanEntity::getYear, targetQuotaSearchDTO.getYear());
            tpWrapper.eq(!ObjectUtils.isEmpty(targetQuotaSearchDTO.getMethod()), TargetPlanEntity::getMethod, targetQuotaSearchDTO.getMethod());
            tpWrapper.eq(!ObjectUtils.isEmpty(targetQuotaSearchDTO.getCycle()), TargetPlanEntity::getCycle, targetQuotaSearchDTO.getCycle());
            tpWrapper.eq(!ObjectUtils.isEmpty(targetQuotaSearchDTO.getType()), TargetPlanEntity::getType, targetQuotaSearchDTO.getType());

//            if (!CollectionUtils.isEmpty(targetQuotaSearchDTO.getSubCompanyIdList())){
//                String sql = " CONCAT(',',company_scope_id,',') regexp REPLACE(',',',',',"+ StringUtils.join(targetQuotaSearchDTO.getSubCompanyIdList(),",|,")+",')";
//                tpWrapper.apply(sql);
//            }
//            if (!CollectionUtils.isEmpty(targetQuotaSearchDTO.getDeptIdList())){
//                String sql = " CONCAT(',',dept_scope_id,',') regexp REPLACE(',',',',',"+ StringUtils.join(targetQuotaSearchDTO.getDeptIdList(),",|,")+",')";
//                tpWrapper.apply(sql);
//            }
//            if (!CollectionUtils.isEmpty(targetQuotaSearchDTO.getUserIdList())){
//                String sql = " CONCAT(',',user_scope_id,',') regexp REPLACE(',',',',',"+ StringUtils.join(targetQuotaSearchDTO.getUserIdList(),",|,")+",')";
//                tpWrapper.apply(sql);
//            }
            List<TargetPlanEntity> targetPlanList = targetPlanService.list(tpWrapper);
            if (CollectionUtils.isEmpty(targetPlanList)) {
                return Result.result(pageVO);
            }
            targetPlanIdList = targetPlanList.stream().map(TargetPlanEntity::getId).collect(Collectors.toList());
        }

        LambdaQueryWrapper<TargetQuotaEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
        wrapper.in(!CollectionUtils.isEmpty(targetPlanIdList), TargetQuotaEntity::getTargetPlanId, targetPlanIdList);
        wrapper.eq(!ObjectUtils.isEmpty(targetQuotaSearchDTO.getOrganizationalType()), TargetQuotaEntity::getOrganizationalType, targetQuotaSearchDTO.getOrganizationalType());
        wrapper.in(!CollectionUtils.isEmpty(targetQuotaSearchDTO.getOrganizationalIds()), TargetQuotaEntity::getOrganizationalId, targetQuotaSearchDTO.getOrganizationalIds());
        wrapper.in(!CollectionUtils.isEmpty(targetQuotaSearchDTO.getSubCompanyIdList()), TargetQuotaEntity::getOrganizationalId, targetQuotaSearchDTO.getSubCompanyIdList());
        wrapper.in(!CollectionUtils.isEmpty(targetQuotaSearchDTO.getDeptIdList()), TargetQuotaEntity::getOrganizationalId, targetQuotaSearchDTO.getDeptIdList());
        wrapper.in(!CollectionUtils.isEmpty(targetQuotaSearchDTO.getUserIdList()), TargetQuotaEntity::getOrganizationalId, targetQuotaSearchDTO.getUserIdList());

        wrapper.eq(!ObjectUtils.isEmpty(targetQuotaSearchDTO.getStatus()), TargetQuotaEntity::getStatus, targetQuotaSearchDTO.getStatus());
        wrapper.orderByDesc(TargetQuotaEntity::getId);
        IPage<TargetQuotaEntity> pageList = this.page(page, wrapper);
        if (CollectionUtils.isEmpty(pageList.getRecords())){
            return Result.result(pageList);
        }
        //复制list给VO类
        pageVO = SysBaseField.page(page, TargetQuotaListVO.class);

        List<Long> targetPlanIdListNow = pageVO.getRecords().stream().map(TargetQuotaListVO::getTargetPlanId).collect(Collectors.toList());
        List<TargetPlanEntity> targetPlanListNow = targetPlanService.listByIds(targetPlanIdListNow);
        Map<Long, TargetPlanEntity> targetPlanMap = targetPlanListNow.stream().collect(Collectors.toMap(TargetPlanEntity::getId, targetPlanEntity -> targetPlanEntity));
        for (TargetQuotaListVO targetQuotaVO : pageVO.getRecords()){
            if (targetPlanMap.containsKey(targetQuotaVO.getTargetPlanId())){
                TargetPlanEntity targetPlan = targetPlanMap.get(targetQuotaVO.getTargetPlanId());
                targetQuotaVO.setYear(targetPlan.getYear());
                targetQuotaVO.setMethod(targetPlan.getMethod());
                targetQuotaVO.setCycle(targetPlan.getCycle());
                targetQuotaVO.setType(targetPlan.getType());
            }
        }
        if (!ObjectUtils.isEmpty(targetQuotaSearchDTO.getOrganizationalType())){
            if (targetQuotaSearchDTO.getOrganizationalType().equals(2)){
                List<Long> subCompanyIdList = pageVO.getRecords().stream().map(TargetQuotaListVO::getOrganizationalId).collect(Collectors.toList());
                Map<Long, SubCompanyEntity> subCompanyMap = subCompanyService.getSubCompanyMap(subCompanyIdList);
                pageVO.getRecords().forEach(targetQuotaVO -> {
                    if (subCompanyMap.containsKey(targetQuotaVO.getOrganizationalId())){
                        SubCompanyEntity subCompanyEntity = subCompanyMap.get(targetQuotaVO.getOrganizationalId());
                        targetQuotaVO.setOrganizationalName(subCompanyEntity.getName());
                    }
                });
            }
            if (targetQuotaSearchDTO.getOrganizationalType().equals(3)){
                List<Long> deptIdList = pageVO.getRecords().stream().map(TargetQuotaListVO::getOrganizationalId).collect(Collectors.toList());

                Map<Long, DeptEntity> deptMap = departService.getDeptMap(deptIdList);
                pageVO.getRecords().forEach(targetQuotaVO -> {
                    if (deptMap.containsKey(targetQuotaVO.getOrganizationalId())){
                        DeptEntity deptEntity = deptMap.get(targetQuotaVO.getOrganizationalId());
                        targetQuotaVO.setOrganizationalName(deptEntity.getName());
                    }
                    List<Long> userIdList = StringUtil.stringToLongList(targetQuotaVO.getSubScopeId());
                    if (CollectionUtils.isEmpty(userIdList)){
                        targetQuotaVO.setUserNum(0);
                    }else {
                        targetQuotaVO.setUserNum(userIdList.size());
                    }
                });
            }
            if (targetQuotaSearchDTO.getOrganizationalType().equals(4)){
                List<Long> userIdList = pageVO.getRecords().stream().map(TargetQuotaListVO::getOrganizationalId).collect(Collectors.toList());
                Map<Long, UserEntity> userMap = userService.IdListToUserMap(userIdList);
                pageVO.getRecords().forEach(targetQuotaVO -> {
                    if (userMap.containsKey(targetQuotaVO.getOrganizationalId())){
                        UserEntity userEntity = userMap.get(targetQuotaVO.getOrganizationalId());
                        targetQuotaVO.setOrganizationalName(userEntity.getRealName());
                    }
                });
            }

        }
        SysBaseField.dictFileds(pageVO.getRecords());
        SysBaseField.orgFileds(pageVO.getRecords());

        return Result.result(pageVO);
    }

//    private Set<Long> dataSelete(Integer organizationalType) {
//        StringBuilder whereCondition = new StringBuilder();
//        LoginUser currentUser = LoginUserUtil.getLoginUser();
//        UserEntity user = userService.getById(currentUser.getId());
//
//        Set<Long> roleIds = new HashSet<>();
//        if (Integer.valueOf(1).equals(currentUser.getCommonScope())) {
//            roleIds = userService.selectUserRoleIdsByCommonScopeType(currentUser.getId(),currentUser.getCommonScopeType());
//        } else {
//            roleIds =  userService.selectUserRoleIdsByMenuId(currentUser.getId(),currentUser.getScopeMenuId());
//        }
//        if (CollectionUtil.isNotEmpty(roleIds)) {
//            List<RoleEntity> roles = roleService.listByIds(roleIds).stream().collect(Collectors.toList());
//            boolean allDataScope = this.isAllDataScope(roles);
//            Set<Long> dataIds = new HashSet<>();
//
//                if (organizationalType.equals(1)){
//                    //集团通过菜单权限判定
////                    return dataIds;
//                    List<CompanyEntity> companyList = companyService.list(new LambdaQueryWrapper<CompanyEntity>().eq(CompanyEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
//                    if (CollectionUtil.isNotEmpty(companyList)) {
//                        for (CompanyEntity company : companyList) {
//                            dataIds.add(company.getId());
//                        }
//                    }
//                }
//                if (organizationalType.equals(2)){
//                    if (!allDataScope) {
//                        //分公司权限判定
//                        Long selfSubCompanyId = this.getSubCompanyId(roles, user);
//                        Set<Long> selfSubCompanyIds = this.getSubCompanyIds(roles, user);
////                    dataIds.add(selfSubCompanyId);
//                        dataIds.addAll(selfSubCompanyIds);
////                    return dataIds;
//                    }else {
//                        List<SubCompanyEntity> subCompanyList = subCompanyService.list(new LambdaQueryWrapper<SubCompanyEntity>().eq(SubCompanyEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
//                        if (CollectionUtil.isNotEmpty(subCompanyList)) {
//                            for (SubCompanyEntity subCompany : subCompanyList) {
//                                dataIds.add(subCompany.getId());
//                            }
//                        }
//                    }
//                }
//                if (organizationalType.equals(3)){
//                    if (!allDataScope) {
//                        Long selfSubCompanyId = this.getSubCompanyId(roles, user);
//                        if (Objects.isNull(selfSubCompanyId)) {
//                            List<DeptEntity> deptList = departService.list(new LambdaQueryWrapper<DeptEntity>().eq(DeptEntity::getSubCompanyId, selfSubCompanyId));
//                            List<Long> subDeptIds = deptList.stream().map(DeptEntity::getId).collect(Collectors.toList());
//                            dataIds.addAll(subDeptIds);
//                        }
//                        Set<Long> deptIds = this.getDeptIds(roles, user);
//                        dataIds.addAll(deptIds);
////                    return dataIds;
//                    }else {
//                        List<DeptEntity> deptList = departService.list(new LambdaQueryWrapper<DeptEntity>().eq(DeptEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
//                        if (CollectionUtil.isNotEmpty(deptList)) {
//                            for (DeptEntity dept : deptList) {
//                                dataIds.add(dept.getId());
//                            }
//                        }
//                    }
//                }
//                if (organizationalType.equals(4)){
//                    if (!allDataScope) {
//                        Long selfSubCompanyId = this.getSubCompanyId(roles, user);
//                        if (!Objects.isNull(selfSubCompanyId)) {
//                            List<UserEntity> userList = userService.list(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getSubCompanyId, selfSubCompanyId));
//                            List<Long> userIds = userList.stream().map(UserEntity::getId).collect(Collectors.toList());
//                            dataIds.addAll(userIds);
//                        }
//                        Set<Long> deptIds = this.getDeptIds(roles, user);
//                        if (CollectionUtil.isNotEmpty(deptIds)) {
//                            List<UserEntity> userList = userService.list(new LambdaQueryWrapper<UserEntity>().in(UserEntity::getDeptId, deptIds));
//                            List<Long> userIds = userList.stream().map(UserEntity::getId).collect(Collectors.toList());
//                            dataIds.addAll(userIds);
//                        }
//                        dataIds.add(user.getId());
////                    return dataIds;
//                    }else {
//                        List<UserEntity> userList = userService.list(new LambdaQueryWrapper<UserEntity>().eq(UserEntity::getIsDelete, CommonConstant.DEL_FLAG_0));
//                        if (CollectionUtil.isNotEmpty(userList)) {
//                            for (UserEntity userEntity : userList) {
//                                dataIds.add(userEntity.getId());
//                            }
//                        }
//                    }
//
//                }
//
//
//
//
//
//            return dataIds;
//        }else {
////            whereCondition.append("us.id = 0 ");
//            return null;
//        }
//
//    }
//
//    public boolean isAllDataScope(List<RoleEntity> roleSet) {
//        for (RoleEntity role : roleSet) {
//            if (scopeType[0].equals(role.getDataScope())) {
//                return true;
//            }
//        }
//        return false;
//    }
//
//    public Long getSubCompanyId(List<RoleEntity> roleSet, UserEntity user) {
//        // 存储本公司的数据权限
//        for (RoleEntity role : roleSet) {
//            if (scopeType[1].equals(role.getDataScope())) {
//                return user.getSubCompanyId();
//            }
//        }
//
//        return null;
//    }
//
//    public Set<Long> getSubCompanyIds(List<RoleEntity> roleSet, UserEntity user) {
//        // 存储本公司的数据权限
//        Set<Long> subIds =  new HashSet<>();
//        for (RoleEntity role : roleSet) {
//            if (scopeType[1].equals(role.getDataScope())) {
//                subIds.add(user.getSubCompanyId());
//            }
//
//            if (scopeType[2].equals(role.getDataScope())) {
//                //deptIds.add(user.getDept().getId());
//                List<SubCompanyEntity> subCompanyEntities = subCompanyService.getHasSublist(role.getId());
//                if (!CollectionUtils.isEmpty(subCompanyEntities)){
//                    subIds.addAll(subCompanyEntities.stream().map(SubCompanyEntity::getId).collect(Collectors.toList()));
//                }
//            }
//
//        }
//        return subIds;
//    }
//    public Set<Long> getDeptIds(List<RoleEntity> roleSet, UserEntity user) {
//        // 用于存储部门id
//        Set<Long> deptIds = new HashSet<>();
//
//        for (RoleEntity role : roleSet) {
//            if (scopeType[0].equals(role.getDataScope())) {
//                return new HashSet<>();
//            }
//
//
//            // 存储自定义的数据权限
//            if (scopeType[2].equals(role.getDataScope())) {
//                Set<DeptEntity> depts = deptService.findByRoleId(role.getId());
//                for (DeptEntity dept : depts) {
//                    deptIds.add(dept.getId());
//                    List<DeptEntity> deptChildren = deptService.findByPid(dept.getId());
//                    if (deptChildren != null && deptChildren.size() != 0) {
//                        deptIds.addAll(deptService.getDeptChildren(deptChildren));
//                    }
//                }
//            }
//            // 存储本部的数据权限
//            if (scopeType[4].equals(role.getDataScope())) {
//                //deptIds.add(user.getDept().getId());
//                deptIds.add(user.getDeptId());
//            }
//        }
//        return deptIds;
//    }

    @Override
    public Result<?> getTargetQuotaVOById(Long id) {
        TargetQuotaDetailsVO targetQuotaVO = new TargetQuotaDetailsVO();
        TargetQuotaEntity targetQuotaEntity = this.getById(id);
        if (ObjectUtils.isEmpty(targetQuotaEntity)){
            return Result.error("目标配额不存在");
        }
        BeanUtils.copyProperties(targetQuotaEntity,targetQuotaVO);
        List<Long> subScopeIdList = StringUtil.stringToStringList(targetQuotaEntity.getSubScopeId());
        targetQuotaVO.setSubScopeIdList(subScopeIdList);
        if (targetQuotaEntity.getOrganizationalType().equals(1)){
            targetQuotaVO.setCompanyScopeIdList(subScopeIdList);
        }
        if (targetQuotaEntity.getOrganizationalType().equals(2)){
            targetQuotaVO.setDeptScopeIdList(subScopeIdList);
        }
        if (targetQuotaEntity.getOrganizationalType().equals(3)){
            targetQuotaVO.setUserScopeIdList(subScopeIdList);
        }
        TargetPlanEntity targetPlanEntity = targetPlanService.getById(targetQuotaEntity.getTargetPlanId());
        if (ObjectUtils.isEmpty(targetPlanEntity)){
            return Result.error("目标计划不存在");
        }
        if (targetPlanEntity.getMethod().equals(1)){
            //汇总
            targetQuotaVO.setTargetQuotaList(this.getTargetQuotaVOA(targetQuotaEntity,targetPlanEntity));
        }
        if (targetPlanEntity.getMethod().equals(2)){
            //分配
            targetQuotaVO.setTargetQuotaList(this.getTargetQuotaVOB(targetQuotaEntity,targetPlanEntity));
        }
        if (targetPlanEntity.getMethod().equals(3)){
            //认领
            targetQuotaVO.setTargetQuotaList(this.getTargetQuotaVOC(targetQuotaEntity,targetPlanEntity));

        }
        return Result.result(targetQuotaVO);
    }

    private List<TargetQuotaDetailsListVO> getTargetQuotaVOA(TargetQuotaEntity targetQuotaEntity, TargetPlanEntity targetPlanEntity) {
        //汇总
        List<TargetQuotaDetailsListVO> targetQuotaList = new ArrayList<>();
        if (targetQuotaEntity.getOrganizationalType().equals(1)){
            //集团汇总
            LambdaQueryWrapper<TargetQuotaEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            wrapper.eq(TargetQuotaEntity::getParentId,targetQuotaEntity.getId());
            List<TargetQuotaEntity> targetQuotaListNow = this.list(wrapper);
            targetQuotaList = TargetQuotaEntity.list(targetQuotaListNow,TargetQuotaDetailsListVO.class);
            List<Long> subCompanyIdList = targetQuotaList.stream().map(TargetQuotaDetailsListVO::getOrganizationalId).collect(Collectors.toList());
            Map<Long, SubCompanyEntity> subCompanyMap = subCompanyService.getSubCompanyMap(subCompanyIdList);
            for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaList){
                targetQuotaDetailsListVO.setUserNum(getByTargetPlanId(targetQuotaEntity.getTargetPlanId(),2,targetQuotaDetailsListVO.getOrganizationalId().toString()).size());
                String subCompanyName = subCompanyMap.get(targetQuotaDetailsListVO.getOrganizationalId()).getName();
                targetQuotaDetailsListVO.setSubCompanyId(targetQuotaDetailsListVO.getOrganizationalId());
                targetQuotaDetailsListVO.setOrganizationalName(subCompanyName);
                targetQuotaDetailsListVO.setSubCompanyName(subCompanyName);
            }
        }
        if (targetQuotaEntity.getOrganizationalType().equals(2)){
            //公司汇总
            LambdaQueryWrapper<TargetQuotaEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            wrapper.eq(TargetQuotaEntity::getParentId,targetQuotaEntity.getId());
            List<TargetQuotaEntity> targetQuotaListNow = this.list(wrapper);
            targetQuotaList = TargetQuotaEntity.list(targetQuotaListNow,TargetQuotaDetailsListVO.class);
//            targetQuotaList.forEach(e->e.setSubCompanyId(e.getOrganizationalId()));
            List<Long> deptIdList = targetQuotaList.stream().map(TargetQuotaDetailsListVO::getOrganizationalId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(deptIdList)) {
                Long deptId = deptIdList.get(0);
                //根据部门id查询分公司名称
                DeptEntity deptEntity = departService.getById(deptId);
                SubCompanyEntity subCompanyEntity = subCompanyService.getById(deptEntity.getSubCompanyId());

                Map<Long, DeptEntity> deptMap = departService.getDeptMap(deptIdList);
                for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaList) {
                    String deptName = deptMap.get(targetQuotaDetailsListVO.getOrganizationalId()).getName();
                    targetQuotaDetailsListVO.setDeptId(targetQuotaDetailsListVO.getOrganizationalId());
                    targetQuotaDetailsListVO.setOrganizationalName(deptName);
                    targetQuotaDetailsListVO.setDeptName(deptName);
                    targetQuotaDetailsListVO.setSubCompanyId(subCompanyEntity.getId());
                    targetQuotaDetailsListVO.setSubCompanyName(subCompanyEntity.getName());

                }
            }
        }
        if (targetQuotaEntity.getOrganizationalType().equals(3)){
            //部门汇总
            LambdaQueryWrapper<TargetQuotaEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            wrapper.eq(TargetQuotaEntity::getParentId,targetQuotaEntity.getId());
            List<TargetQuotaEntity> targetQuotaListNow = this.list(wrapper);
            targetQuotaList = TargetQuotaEntity.list(targetQuotaListNow,TargetQuotaDetailsListVO.class);
//            targetQuotaList.forEach(e->e.setUserId(e.getOrganizationalId()));
            if (!CollectionUtils.isEmpty(targetQuotaList)) {
                UserVo userVo = userService.getUserInfoById(targetQuotaList.get(0).getOrganizationalId());
                SubCompanyEntity subCompanyEntity = subCompanyService.getById(userVo.getSubCompanyId());
                for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaList) {

                    targetQuotaDetailsListVO.setUserId(targetQuotaDetailsListVO.getOrganizationalId());
                    targetQuotaDetailsListVO.setDeptName(userVo.getDeptName());
                    targetQuotaDetailsListVO.setSubCompanyName(subCompanyEntity.getName());
                }
            }
        }
        if (targetQuotaEntity.getOrganizationalType().equals(4)){
            //个人汇总
            TargetQuotaDetailsListVO targetQuotaVO = new TargetQuotaDetailsListVO();

            BeanUtils.copyProperties(targetQuotaEntity,targetQuotaVO);
            UserEntity userEntity = userService.getById(targetQuotaEntity.getOrganizationalId());
            DeptEntity deptEntity = departService.getById(userEntity.getDeptId());
            SubCompanyEntity subCompanyEntity = subCompanyService.getById(deptEntity.getSubCompanyId());
            //添加所属公司和所属部门

            targetQuotaVO.setDeptName(deptEntity.getName());
            targetQuotaVO.setSubCompanyName(subCompanyEntity.getName());
            targetQuotaVO.setUserId(targetQuotaEntity.getOrganizationalId());
            targetQuotaVO.setAllocationType(3);
            targetQuotaList.add(targetQuotaVO);
        }

        for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaList) {
            if (!ObjectUtils.isEmpty(targetQuotaDetailsListVO.getOrganizationalType()) ) {
                if (targetQuotaDetailsListVO.getOrganizationalType().equals(2)) {
                    targetQuotaDetailsListVO.setUserNum(getByTargetPlanId(targetQuotaEntity.getTargetPlanId(), 2, targetQuotaDetailsListVO.getOrganizationalId().toString()).size());
                }
                if (targetQuotaDetailsListVO.getOrganizationalType().equals(3)) {
                    targetQuotaDetailsListVO.setUserNum(getByTargetPlanId(targetQuotaEntity.getTargetPlanId(), 3, targetQuotaDetailsListVO.getOrganizationalId().toString()).size());
                }
            }
        }

        SysBaseField.dictFileds(targetQuotaList);
        SysBaseField.orgFileds(targetQuotaList);
        return targetQuotaList;
    }
    private List<TargetQuotaDetailsListVO> getTargetQuotaVOB(TargetQuotaEntity targetQuotaEntity, TargetPlanEntity targetPlanEntity) {
        //分配
        List<TargetQuotaDetailsListVO> targetQuotaList = new ArrayList<>();
        List<TargetQuotaDetailsListVO> targetQuotaNowUseList = new ArrayList<>();

        TargetQuotaDetailsListVO targetQuotaVO = new TargetQuotaDetailsListVO();
        BeanUtils.copyProperties(targetQuotaEntity,targetQuotaVO);

        if (targetQuotaEntity.getOrganizationalType().equals(1)){
            //集团分配
            LambdaQueryWrapper<TargetQuotaEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            wrapper.eq(TargetQuotaEntity::getParentId,targetQuotaEntity.getId());
            List<TargetQuotaEntity> targetQuotaListNow = this.list(wrapper);
            targetQuotaNowUseList = TargetQuotaEntity.list(targetQuotaListNow,TargetQuotaDetailsListVO.class);

            List<Long> subCompanyIdList = targetQuotaNowUseList.stream().map(TargetQuotaDetailsListVO::getOrganizationalId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(subCompanyIdList)) {
                Map<Long, SubCompanyEntity> subCompanyMap = subCompanyService.getSubCompanyMap(subCompanyIdList);
                for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaNowUseList) {
                    targetQuotaDetailsListVO.setUserNum(getByTargetPlanId(targetQuotaEntity.getTargetPlanId(),2,targetQuotaDetailsListVO.getOrganizationalId().toString()).size());
                    String subCompanyName = subCompanyMap.get(targetQuotaDetailsListVO.getOrganizationalId()).getName();
                    targetQuotaDetailsListVO.setSubCompanyId(targetQuotaDetailsListVO.getOrganizationalId());
                    targetQuotaDetailsListVO.setOrganizationalName(subCompanyName);
                    targetQuotaDetailsListVO.setSubCompanyName(subCompanyName);
                }
            }
        }
        if (targetQuotaEntity.getOrganizationalType().equals(2)){
            //公司分配
            LambdaQueryWrapper<TargetQuotaEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            wrapper.eq(TargetQuotaEntity::getParentId,targetQuotaEntity.getId());
            List<TargetQuotaEntity> targetQuotaListNow = this.list(wrapper);
            targetQuotaNowUseList = TargetQuotaEntity.list(targetQuotaListNow,TargetQuotaDetailsListVO.class);
//            targetQuotaNowUseList.forEach(e->e.setDeptId(e.getOrganizationalId()));

            List<Long> deptIdList = targetQuotaNowUseList.stream().map(TargetQuotaDetailsListVO::getOrganizationalId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(deptIdList)){
                Map<Long, DeptEntity> deptMap = departService.getDeptMap(deptIdList);
                for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaNowUseList) {
                    targetQuotaDetailsListVO.setUserNum(getByTargetPlanId(targetQuotaEntity.getTargetPlanId(),3,targetQuotaDetailsListVO.getOrganizationalId().toString()).size());
                    String deptName = deptMap.get(targetQuotaDetailsListVO.getOrganizationalId()).getName();
                    targetQuotaDetailsListVO.setDeptId(targetQuotaDetailsListVO.getOrganizationalId());
                    targetQuotaDetailsListVO.setOrganizationalName(deptName);
                    targetQuotaDetailsListVO.setDeptName(deptName);
                }
            }

        }
        if (targetQuotaEntity.getOrganizationalType().equals(3)){
            //部门分配
            LambdaQueryWrapper<TargetQuotaEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            wrapper.eq(TargetQuotaEntity::getParentId,targetQuotaEntity.getId());
            List<TargetQuotaEntity> targetQuotaListNow = this.list(wrapper);
            targetQuotaNowUseList = TargetQuotaEntity.list(targetQuotaListNow,TargetQuotaDetailsListVO.class);
            //添加所属公司和所属部门
            DeptEntity deptEntity = departService.getById(targetQuotaEntity.getOrganizationalId());
            SubCompanyEntity subCompanyEntity = subCompanyService.getById(deptEntity.getSubCompanyId());

            for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaNowUseList){
                targetQuotaDetailsListVO.setUserId(targetQuotaDetailsListVO.getOrganizationalId());
                targetQuotaDetailsListVO.setDeptName(deptEntity.getName());
                targetQuotaDetailsListVO.setSubCompanyName(subCompanyEntity.getName());
            }
//            targetQuotaNowUseList.forEach(e->e.setUserId(e.getOrganizationalId()));
        }
        if (targetQuotaEntity.getOrganizationalType().equals(4)){
            //个人分配
            UserEntity userEntity = userService.getById(targetQuotaEntity.getOrganizationalId());
            DeptEntity deptEntity = departService.getById(userEntity.getDeptId());
            SubCompanyEntity subCompanyEntity = subCompanyService.getById(deptEntity.getSubCompanyId());
            //添加所属公司和所属部门

            targetQuotaVO.setUserId(targetQuotaEntity.getOrganizationalId());
            targetQuotaVO.setDeptName(deptEntity.getName());
            targetQuotaVO.setSubCompanyName(subCompanyEntity.getName());
            targetQuotaVO.setAllocationType(3);
            targetQuotaVO.setOrganizationalName(userEntity.getRealName());

            targetQuotaNowUseList.add(targetQuotaVO);
        }
        targetQuotaVO.setAllocationType(1);
        if (targetQuotaVO.getOrganizationalType()==2){
            SubCompanyEntity subCompanyEntity = subCompanyService.getById(targetQuotaVO.getOrganizationalId());
            targetQuotaVO.setSubCompanyName(subCompanyEntity.getName());
        }
        if (targetQuotaVO.getOrganizationalType()==3){
            DeptEntity deptEntity = departService.getById(targetQuotaVO.getOrganizationalId());
            targetQuotaVO.setDeptName(deptEntity.getName());
        }
        targetQuotaList.add(targetQuotaVO);

        TargetQuotaDetailsListVO targetQuotaOtherVO = getOtherVO(targetQuotaVO,targetQuotaNowUseList);
        targetQuotaList.add(targetQuotaOtherVO);
        targetQuotaNowUseList.forEach(e->e.setAllocationType(3));
        targetQuotaList.addAll(targetQuotaNowUseList);
        if (targetQuotaEntity.getOrganizationalType().equals(4)) {
            //个人分配不需要返回其他信息
            //清空targetQuotaList
            targetQuotaList.clear();
            targetQuotaList.addAll(targetQuotaNowUseList);
        }
        for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaList) {
            if (!ObjectUtils.isEmpty(targetQuotaDetailsListVO.getOrganizationalType()) ) {
                if (targetQuotaDetailsListVO.getOrganizationalType().equals(2)) {
                    targetQuotaDetailsListVO.setUserNum(getByTargetPlanId(targetQuotaEntity.getTargetPlanId(), 2, targetQuotaDetailsListVO.getOrganizationalId().toString()).size());
                }
                if (targetQuotaDetailsListVO.getOrganizationalType().equals(3)) {
                    targetQuotaDetailsListVO.setUserNum(getByTargetPlanId(targetQuotaEntity.getTargetPlanId(), 3, targetQuotaDetailsListVO.getOrganizationalId().toString()).size());
                }
            }
        }
        SysBaseField.dictFileds(targetQuotaList);
        SysBaseField.orgFileds(targetQuotaList);
        if (targetQuotaEntity.getOrganizationalType().equals(1)){
            targetQuotaList.forEach(e->e.setOrganizationalName(e.getSubCompanyName()));
        }
        if (targetQuotaEntity.getOrganizationalType().equals(2)){
            targetQuotaList.forEach(e->e.setOrganizationalName(e.getDeptName()));
        }
        if (targetQuotaEntity.getOrganizationalType().equals(3)){
            targetQuotaList.forEach(e->e.setOrganizationalName(e.getUserName()));
        }
        return targetQuotaList;
    }
    private List<TargetQuotaDetailsListVO> getTargetQuotaVOC(TargetQuotaEntity targetQuotaEntity, TargetPlanEntity targetPlanEntity) {
        //领取
        List<TargetQuotaDetailsListVO> targetQuotaList = new ArrayList<>();
        List<TargetQuotaDetailsListVO> targetQuotaNowUseList = new ArrayList<>();
        //下级领取
        List<TargetQuotaDetailsListVO> targetQuotaNextList = new ArrayList<>();

        TargetQuotaDetailsListVO targetQuotaVO = new TargetQuotaDetailsListVO();
        BeanUtils.copyProperties(targetQuotaEntity,targetQuotaVO);
        //获取上级目标值
        TargetQuotaDetailsListVO parentTargetQuotaVO = new TargetQuotaDetailsListVO();
//        if (!targetQuotaEntity.getOrganizationalType().equals(1)) {
//
//            TargetQuotaEntity parentTargetQuota = getById(targetQuotaEntity.getParentId());
//            BeanUtils.copyProperties(parentTargetQuota, parentTargetQuotaVO);
//            parentTargetQuotaVO.setAllocationType(1);
//            targetQuotaList.add(parentTargetQuotaVO);
//        }

        if (targetQuotaEntity.getOrganizationalType().equals(1)){
            //集团认领
//            TargetQuotaEntity parentTargetQuota = getById(targetQuotaEntity.getId());
//            BeanUtils.copyProperties(parentTargetQuota, parentTargetQuotaVO);
//            parentTargetQuotaVO.setAllocationType(1);
//            targetQuotaList.add(parentTargetQuotaVO);
            //下级数据
            LambdaQueryWrapper<TargetQuotaEntity> nextWrapper = new LambdaQueryWrapper<>();
            nextWrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            nextWrapper.eq(TargetQuotaEntity::getParentId,targetQuotaEntity.getId());
            List<TargetQuotaEntity> targetQuotaListNext = this.list(nextWrapper);
            targetQuotaNextList = TargetQuotaEntity.list(targetQuotaListNext,TargetQuotaDetailsListVO.class);
            List<Long> subCompanyIdList = targetQuotaNextList.stream().map(TargetQuotaDetailsListVO::getOrganizationalId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(subCompanyIdList)) {
                Map<Long, SubCompanyEntity> subCompanyMap = subCompanyService.getSubCompanyMap(subCompanyIdList);
                for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaNextList) {
                    targetQuotaDetailsListVO.setUserNum(getByTargetPlanId(targetQuotaEntity.getTargetPlanId(),2,targetQuotaDetailsListVO.getOrganizationalId().toString()).size());
                    String subCompanyName = subCompanyMap.get(targetQuotaDetailsListVO.getOrganizationalId()).getName();
                    targetQuotaDetailsListVO.setSubCompanyId(targetQuotaDetailsListVO.getOrganizationalId());
                    targetQuotaDetailsListVO.setOrganizationalName(subCompanyName);
                    targetQuotaDetailsListVO.setSubCompanyName(subCompanyName);
                }
            }

            targetQuotaNextList.forEach(e->e.setAllocationType(5));
//            targetQuotaList.addAll(targetQuotaNowUseList);
        }

        if (targetQuotaEntity.getOrganizationalType().equals(2)){
            //公司领取
            TargetQuotaEntity parentTargetQuota = getById(targetQuotaEntity.getParentId());
            BeanUtils.copyProperties(parentTargetQuota, parentTargetQuotaVO);
            parentTargetQuotaVO.setAllocationType(1);
            targetQuotaList.add(parentTargetQuotaVO);

            LambdaQueryWrapper<TargetQuotaEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            wrapper.eq(TargetQuotaEntity::getParentId,targetQuotaEntity.getParentId());
            wrapper.ne(TargetQuotaEntity::getId,targetQuotaEntity.getId());
            List<TargetQuotaEntity> targetQuotaListNow = this.list(wrapper);
            targetQuotaNowUseList = TargetQuotaEntity.list(targetQuotaListNow,TargetQuotaDetailsListVO.class);
//            targetQuotaNowUseList.forEach(e->e.setSubCompanyId(e.getOrganizationalId()));

            List<Long> subCompanyIdList = targetQuotaNowUseList.stream().map(TargetQuotaDetailsListVO::getOrganizationalId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(subCompanyIdList)) {
                Map<Long, SubCompanyEntity> subCompanyMap = subCompanyService.getSubCompanyMap(subCompanyIdList);
                for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaNowUseList) {
                    String subCompanyName = subCompanyMap.get(targetQuotaDetailsListVO.getOrganizationalId()).getName();
                    targetQuotaDetailsListVO.setSubCompanyId(targetQuotaDetailsListVO.getOrganizationalId());
                    targetQuotaDetailsListVO.setOrganizationalName(subCompanyName);
                    targetQuotaDetailsListVO.setSubCompanyName(subCompanyName);
                }
            }

            //下级数据
            LambdaQueryWrapper<TargetQuotaEntity> nextWrapper = new LambdaQueryWrapper<>();
            nextWrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            nextWrapper.eq(TargetQuotaEntity::getParentId,targetQuotaEntity.getId());
            List<TargetQuotaEntity> targetQuotaListNext = this.list(nextWrapper);
            targetQuotaNextList = TargetQuotaEntity.list(targetQuotaListNext,TargetQuotaDetailsListVO.class);

            List<Long> deptIdList = targetQuotaNextList.stream().map(TargetQuotaDetailsListVO::getOrganizationalId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(deptIdList)) {
                Map<Long, DeptEntity> deptMap = departService.getDeptMap(deptIdList);
                for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaNextList) {
                    String deptName = deptMap.get(targetQuotaDetailsListVO.getOrganizationalId()).getName();
                    targetQuotaDetailsListVO.setDeptId(targetQuotaDetailsListVO.getOrganizationalId());
                    targetQuotaDetailsListVO.setOrganizationalName(deptName);
                    targetQuotaDetailsListVO.setDeptName(deptName);
                }
            }

            targetQuotaNextList.forEach(e->e.setAllocationType(5));

        }
        if (targetQuotaEntity.getOrganizationalType().equals(3)){
            //部门领取
            TargetQuotaEntity parentTargetQuota = getById(targetQuotaEntity.getParentId());
            BeanUtils.copyProperties(parentTargetQuota, parentTargetQuotaVO);
            parentTargetQuotaVO.setAllocationType(1);
            targetQuotaList.add(parentTargetQuotaVO);

            LambdaQueryWrapper<TargetQuotaEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            wrapper.eq(TargetQuotaEntity::getParentId,targetQuotaEntity.getParentId());
            wrapper.ne(TargetQuotaEntity::getId,targetQuotaEntity.getId());
            List<TargetQuotaEntity> targetQuotaListNow = this.list(wrapper);
            targetQuotaNowUseList = TargetQuotaEntity.list(targetQuotaListNow,TargetQuotaDetailsListVO.class);
//            targetQuotaNowUseList.forEach(e->e.setDeptId(e.getOrganizationalId()));

            List<Long> deptIdList = targetQuotaNowUseList.stream().map(TargetQuotaDetailsListVO::getOrganizationalId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(deptIdList)) {
                Map<Long, DeptEntity> deptMap = departService.getDeptMap(deptIdList);
                for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaNowUseList) {
                    String deptName = deptMap.get(targetQuotaDetailsListVO.getOrganizationalId()).getName();
                    targetQuotaDetailsListVO.setDeptId(targetQuotaDetailsListVO.getOrganizationalId());
                    targetQuotaDetailsListVO.setOrganizationalName(deptName);
                    targetQuotaDetailsListVO.setDeptName(deptName);
                }
            }

            //下级数据
            LambdaQueryWrapper<TargetQuotaEntity> nextWrapper = new LambdaQueryWrapper<>();
            nextWrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            nextWrapper.eq(TargetQuotaEntity::getParentId,targetQuotaEntity.getId());
            List<TargetQuotaEntity> targetQuotaListNext = this.list(nextWrapper);
            targetQuotaNextList = TargetQuotaEntity.list(targetQuotaListNext,TargetQuotaDetailsListVO.class);

            List<Long> userIdList = targetQuotaNextList.stream().map(TargetQuotaDetailsListVO::getOrganizationalId).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(userIdList)) {
                Map<Long, UserEntity> userMap = userService.IdListToUserMap(userIdList);
                for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaNextList) {
                    String userName = userMap.get(targetQuotaDetailsListVO.getOrganizationalId()).getRealName();
                    targetQuotaDetailsListVO.setDeptId(targetQuotaDetailsListVO.getOrganizationalId());
                    targetQuotaDetailsListVO.setOrganizationalName(userName);
                    targetQuotaDetailsListVO.setDeptName(userName);
                }
            }

            targetQuotaNextList.forEach(e->e.setAllocationType(5));
        }
        if (targetQuotaEntity.getOrganizationalType().equals(4)){
            //个人分配
            TargetQuotaEntity parentTargetQuota = getById(targetQuotaEntity.getParentId());
            BeanUtils.copyProperties(parentTargetQuota, parentTargetQuotaVO);
            parentTargetQuotaVO.setAllocationType(1);
            targetQuotaList.add(parentTargetQuotaVO);

            LambdaQueryWrapper<TargetQuotaEntity> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TargetQuotaEntity::getIsDelete, CommonConstant.DEL_FLAG_0);
            wrapper.eq(TargetQuotaEntity::getParentId,targetQuotaEntity.getParentId());
            wrapper.ne(TargetQuotaEntity::getId,targetQuotaEntity.getId());
            List<TargetQuotaEntity> targetQuotaListNow = this.list(wrapper);
            targetQuotaNowUseList = TargetQuotaEntity.list(targetQuotaListNow,TargetQuotaDetailsListVO.class);
//            targetQuotaNowUseList.forEach(e->e.setUserId(e.getOrganizationalId()));

            List<Long> userIdList = targetQuotaNowUseList.stream().map(TargetQuotaDetailsListVO::getOrganizationalId).collect(Collectors.toList());
            Map<Long, UserEntity> userMap = userService.IdListToUserMap(userIdList);
            for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaNowUseList) {
                String userName = userMap.get(targetQuotaDetailsListVO.getOrganizationalId()).getRealName();
                targetQuotaDetailsListVO.setDeptId(targetQuotaDetailsListVO.getOrganizationalId());
                targetQuotaDetailsListVO.setOrganizationalName(userName);
                targetQuotaDetailsListVO.setDeptName(userName);
            }
        }
//        targetQuotaVO.setAllocationType(1);
//        targetQuotaList.add(targetQuotaVO);
        if (!targetQuotaEntity.getOrganizationalType().equals(1)) {
            //同级领取
            targetQuotaNowUseList.forEach(e -> e.setAllocationType(4));
            targetQuotaList.addAll(targetQuotaNowUseList);
            //剩余可领取值
            TargetQuotaDetailsListVO targetQuotaOtherVO = getOtherVO(parentTargetQuotaVO, targetQuotaNowUseList);
            targetQuotaOtherVO.setAllocationType(2);
            targetQuotaOtherVO.setOrganizationalName("可领取");
            targetQuotaList.add(targetQuotaOtherVO);
        }
//        else {
//            targetQuotaList.addAll(targetQuotaNowUseList);
//        }
        //当前用户领取值
        targetQuotaVO.setAllocationType(3);
        if (targetQuotaVO.getOrganizationalType()==2){
            SubCompanyEntity subCompanyEntity = subCompanyService.getById(targetQuotaVO.getOrganizationalId());
            targetQuotaVO.setSubCompanyName(subCompanyEntity.getName());
        }
        if (targetQuotaVO.getOrganizationalType()==3){
            DeptEntity deptEntity = departService.getById(targetQuotaVO.getOrganizationalId());
            targetQuotaVO.setDeptName(deptEntity.getName());
        }
        if (targetQuotaVO.getOrganizationalType()==4){
            UserEntity userEntity = userService.getById(targetQuotaVO.getOrganizationalId());
            targetQuotaVO.setUserId(userEntity.getId());
            targetQuotaVO.setUserName(userEntity.getRealName());
            targetQuotaVO.setSubScopeName(userEntity.getRealName());
        }
        targetQuotaList.add(targetQuotaVO);

        if (!targetQuotaEntity.getOrganizationalType().equals(4) && !CollectionUtils.isEmpty(targetQuotaNextList)) {
            //下级领取
            targetQuotaNextList.forEach(e -> e.setAllocationType(5));
            targetQuotaList.addAll(targetQuotaNextList);
            //下级剩余可领取值
            TargetQuotaDetailsListVO targetQuotaNextOtherVO = getOtherVO(targetQuotaVO, targetQuotaNextList);
            targetQuotaNextOtherVO.setAllocationType(6);
            targetQuotaNextOtherVO.setOrganizationalName("剩余可领取");
            targetQuotaList.add(targetQuotaNextOtherVO);
        }

        for (TargetQuotaDetailsListVO targetQuotaDetailsListVO : targetQuotaList) {
            if (!ObjectUtils.isEmpty(targetQuotaDetailsListVO.getOrganizationalType()) ) {
                if (targetQuotaDetailsListVO.getOrganizationalType().equals(2)) {
                    targetQuotaDetailsListVO.setUserNum(getByTargetPlanId(targetQuotaEntity.getTargetPlanId(), 2, targetQuotaDetailsListVO.getOrganizationalId().toString()).size());
                }
                if (targetQuotaDetailsListVO.getOrganizationalType().equals(3)) {
                    targetQuotaDetailsListVO.setUserNum(getByTargetPlanId(targetQuotaEntity.getTargetPlanId(), 3, targetQuotaDetailsListVO.getOrganizationalId().toString()).size());
                }
            }
        }

            SysBaseField.dictFileds(targetQuotaList);
        SysBaseField.orgFileds(targetQuotaList);
        return targetQuotaList;
    }

    //获取剩余分配值
    private TargetQuotaDetailsListVO getOtherVO(TargetQuotaDetailsListVO targetQuotaVO, List<TargetQuotaDetailsListVO> targetQuotaNowUseList) {
        TargetQuotaDetailsListVO targetQuotaOtherVO = new TargetQuotaDetailsListVO();
        targetQuotaOtherVO.setAllocationType(2);
        if (ObjectUtils.isEmpty(targetQuotaVO.getMonthOrQuarter1())){
            targetQuotaVO.setMonthOrQuarter1(BigDecimal.ZERO);
        }
        if (ObjectUtils.isEmpty(targetQuotaVO.getMonthOrQuarter2())){
            targetQuotaVO.setMonthOrQuarter2(BigDecimal.ZERO);
        }
        if (ObjectUtils.isEmpty(targetQuotaVO.getMonthOrQuarter3())){
            targetQuotaVO.setMonthOrQuarter3(BigDecimal.ZERO);
        }
        if (ObjectUtils.isEmpty(targetQuotaVO.getMonthOrQuarter4())){
            targetQuotaVO.setMonthOrQuarter4(BigDecimal.ZERO);
        }
        if (ObjectUtils.isEmpty(targetQuotaVO.getMonthOrQuarter5())){
            targetQuotaVO.setMonthOrQuarter5(BigDecimal.ZERO);
        }
        if (ObjectUtils.isEmpty(targetQuotaVO.getMonthOrQuarter6())){
            targetQuotaVO.setMonthOrQuarter6(BigDecimal.ZERO);
        }
        if (ObjectUtils.isEmpty(targetQuotaVO.getMonthOrQuarter7())){
            targetQuotaVO.setMonthOrQuarter7(BigDecimal.ZERO);
        }
        if (ObjectUtils.isEmpty(targetQuotaVO.getMonthOrQuarter8())){
            targetQuotaVO.setMonthOrQuarter8(BigDecimal.ZERO);
        }
        if (ObjectUtils.isEmpty(targetQuotaVO.getMonthOrQuarter9())){
            targetQuotaVO.setMonthOrQuarter9(BigDecimal.ZERO);
        }
        if (ObjectUtils.isEmpty(targetQuotaVO.getMonthOrQuarter10())){
            targetQuotaVO.setMonthOrQuarter10(BigDecimal.ZERO);
        }
        if (ObjectUtils.isEmpty(targetQuotaVO.getMonthOrQuarter11())){
            targetQuotaVO.setMonthOrQuarter11(BigDecimal.ZERO);
        }
        if (ObjectUtils.isEmpty(targetQuotaVO.getMonthOrQuarter12())){
            targetQuotaVO.setMonthOrQuarter12(BigDecimal.ZERO);
        }
        if (ObjectUtils.isEmpty(targetQuotaVO.getTotal())){
            targetQuotaVO.setTotal(BigDecimal.ZERO);
        }
        TargetQuotaDetailsListVO targetQuotaAllVO = new TargetQuotaDetailsListVO();

        targetQuotaAllVO.setMonthOrQuarter1(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getMonthOrQuarter1)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaAllVO.setMonthOrQuarter2(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getMonthOrQuarter2)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaAllVO.setMonthOrQuarter3(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getMonthOrQuarter3)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaAllVO.setMonthOrQuarter4(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getMonthOrQuarter4)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaAllVO.setMonthOrQuarter5(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getMonthOrQuarter5)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaAllVO.setMonthOrQuarter6(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getMonthOrQuarter6)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaAllVO.setMonthOrQuarter7(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getMonthOrQuarter7)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaAllVO.setMonthOrQuarter8(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getMonthOrQuarter8)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaAllVO.setMonthOrQuarter9(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getMonthOrQuarter9)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaAllVO.setMonthOrQuarter10(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getMonthOrQuarter10)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaAllVO.setMonthOrQuarter11(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getMonthOrQuarter11)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaAllVO.setMonthOrQuarter12(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getMonthOrQuarter12)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaAllVO.setTotal(targetQuotaNowUseList.stream()
                .map(TargetQuotaDetailsListVO::getTotal)
                .filter(Objects::nonNull)
                .reduce(BigDecimal.ZERO, BigDecimal::add));
        targetQuotaOtherVO.setMonthOrQuarter1(targetQuotaVO.getMonthOrQuarter1().subtract(targetQuotaAllVO.getMonthOrQuarter1()));
        targetQuotaOtherVO.setMonthOrQuarter2(targetQuotaVO.getMonthOrQuarter2().subtract(targetQuotaAllVO.getMonthOrQuarter2()));
        targetQuotaOtherVO.setMonthOrQuarter3(targetQuotaVO.getMonthOrQuarter3().subtract(targetQuotaAllVO.getMonthOrQuarter3()));
        targetQuotaOtherVO.setMonthOrQuarter4(targetQuotaVO.getMonthOrQuarter4().subtract(targetQuotaAllVO.getMonthOrQuarter4()));
        targetQuotaOtherVO.setMonthOrQuarter5(targetQuotaVO.getMonthOrQuarter5().subtract(targetQuotaAllVO.getMonthOrQuarter5()));
        targetQuotaOtherVO.setMonthOrQuarter6(targetQuotaVO.getMonthOrQuarter6().subtract(targetQuotaAllVO.getMonthOrQuarter6()));
        targetQuotaOtherVO.setMonthOrQuarter7(targetQuotaVO.getMonthOrQuarter7().subtract(targetQuotaAllVO.getMonthOrQuarter7()));
        targetQuotaOtherVO.setMonthOrQuarter8(targetQuotaVO.getMonthOrQuarter8().subtract(targetQuotaAllVO.getMonthOrQuarter8()));
        targetQuotaOtherVO.setMonthOrQuarter9(targetQuotaVO.getMonthOrQuarter9().subtract(targetQuotaAllVO.getMonthOrQuarter9()));
        targetQuotaOtherVO.setMonthOrQuarter10(targetQuotaVO.getMonthOrQuarter10().subtract(targetQuotaAllVO.getMonthOrQuarter10()));
        targetQuotaOtherVO.setMonthOrQuarter11(targetQuotaVO.getMonthOrQuarter11().subtract(targetQuotaAllVO.getMonthOrQuarter11()));
        targetQuotaOtherVO.setMonthOrQuarter12(targetQuotaVO.getMonthOrQuarter12().subtract(targetQuotaAllVO.getMonthOrQuarter12()));
        targetQuotaOtherVO.setTotal(targetQuotaVO.getTotal().subtract(targetQuotaAllVO.getTotal()));
        return targetQuotaOtherVO;
    }
}
