package com.ruoyi.excel.wecom.helper;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.excel.wecom.domain.CorpInfo;
import com.ruoyi.excel.wecom.domain.CustomerExportData;
import com.ruoyi.excel.wecom.domain.CustomerStatisticsDataV2;
import com.ruoyi.excel.wecom.mapper.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 流量看板数据处理V2
 * 支持标签级成本，行列转换存储
 * 与V1的区别：
 * 1. V1：行是指标，列是组
 * 2. V2：行是组/标签，列是指标
 */
@Slf4j
@Component
public class HandleAllDataV2 {

    @Autowired
    private CustomerExportDataMapper customerExportDataMapper;

    @Autowired
    private CustomerStatisticsDataV2Mapper dataV2Mapper;

    @Autowired
    private WecomTagGroupMapper wecomTagGroupMapper;

    @Autowired
    private WecomTagMapper wecomTagMapper;

    @Autowired
    private CorpInfoMapper corpInfoMapper;
    private List<String> finishFlag = Arrays.asList("已成交及时单9元+", "已成交非及时单9元+");
    private List<String> timelyFinishFlag = Arrays.asList("已成交及时单9元+");
    private List<String> noTimelyfinishFlag = Arrays.asList("已成交非及时单9元+");
    private static final String UNGROUPED_NAME = "未分组";

    /**
     * 组名到字段名的映射（使用括号内的名称）
     */
    private static final Map<String, String> GROUP_FIELD_MAP = new LinkedHashMap<>();
    static {
        GROUP_FIELD_MAP.put("投放", "tagGroup1");
        GROUP_FIELD_MAP.put("公司孵化", "tagGroup2");
        GROUP_FIELD_MAP.put("商务", "tagGroup3");
        GROUP_FIELD_MAP.put("A1组", "tagGroup10");
        GROUP_FIELD_MAP.put("B1组", "tagGroup11");
        GROUP_FIELD_MAP.put("C1组", "tagGroup12");
        GROUP_FIELD_MAP.put("D1组", "tagGroup13");
        GROUP_FIELD_MAP.put("E1组", "tagGroup14");
        GROUP_FIELD_MAP.put("自然流", "tagGroup16");
        GROUP_FIELD_MAP.put("F1组", "tagGroup17");
        GROUP_FIELD_MAP.put("G1组", "tagGroup18");
    }

    /**
     * 组名到数据库字段名的映射（用于SQL查询）
     */
    private static final Map<String, String> GROUP_ATTR_MAP = new LinkedHashMap<>();
    static {
        GROUP_ATTR_MAP.put("投放", "tag_group1");
        GROUP_ATTR_MAP.put("公司孵化", "tag_group2");
        GROUP_ATTR_MAP.put("商务", "tag_group3");
        GROUP_ATTR_MAP.put("A1组", "tag_group10");
        GROUP_ATTR_MAP.put("B1组", "tag_group11");
        GROUP_ATTR_MAP.put("C1组", "tag_group12");
        GROUP_ATTR_MAP.put("D1组", "tag_group13");
        GROUP_ATTR_MAP.put("E1组", "tag_group14");
        GROUP_ATTR_MAP.put("自然流", "tag_group16");
        GROUP_ATTR_MAP.put("F1组", "tag_group17");
        GROUP_ATTR_MAP.put("G1组", "tag_group18");
    }

    /**
     * 线程池配置
     */
    private final ExecutorService executorService = Executors.newFixedThreadPool(
            4,
            new ThreadFactory() {
                private final AtomicInteger threadNumber = new AtomicInteger(1);
                @Override
                public Thread newThread(Runnable r) {
                    Thread thread = new Thread(r, "customer-data-v2-handler-" + threadNumber.getAndIncrement());
                    thread.setDaemon(false);
                    return thread;
                }
            }
    );

    /**
     * 创建所有日期的流量看板数据V2
     */
    public void createAllReportDataV2() {
        List<CorpInfo> corpInfos = corpInfoMapper.selectCorpInfoList(new CorpInfo());
        int batchSize = 10;

        for (CorpInfo item : corpInfos) {
            try {
                String corpId = item.getCorpId();
                List<Date> allDate = getAllDate(corpId);

                for (int i = 0; i < allDate.size(); i += batchSize) {
                    int end = Math.min(i + batchSize, allDate.size());
                    List<Date> batchDates = allDate.subList(i, end);

                    List<CompletableFuture<Void>> futures = new ArrayList<>();
                    for (Date date : batchDates) {
                        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                            createReportDataV2(corpId, date);
                        }, executorService);
                        futures.add(future);
                    }

                    CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
                }
            } catch (Exception e) {
                throw new RuntimeException("多线程处理流量看板V2数据时发生错误: " + e.getMessage(), e);
            }
        }
    }

    /**
     * 创建指定日期的流量看板数据V2
     * @param corpId 企业ID
     * @param date 统计日期
     */
    @Transactional
    public void createReportDataV2(String corpId, Date date) {
        log.info("开始创建V2流量看板数据：corpId={}, date={}", corpId, date);

        // 1. 先删除当天已存在的数据
        LambdaQueryWrapper<CustomerStatisticsDataV2> deleteWrapper = new LambdaQueryWrapper<>();
        deleteWrapper.eq(CustomerStatisticsDataV2::getCorpId, corpId)
                     .eq(CustomerStatisticsDataV2::getCurDate, date);
        dataV2Mapper.delete(deleteWrapper);

        // 2. 重新计算并插入当天数据
        List<CustomerStatisticsDataV2> dataList = calculateStatisticsV2(corpId, date);

        // 3. 批量插入
        if (!dataList.isEmpty()) {
            // 分批插入，每批500条
            int batchSize = 500;
            for (int i = 0; i < dataList.size(); i += batchSize) {
                int end = Math.min(i + batchSize, dataList.size());
                List<CustomerStatisticsDataV2> batch = dataList.subList(i, end);
                dataV2Mapper.batchInsert(batch);
            }
        }

        log.info("V2流量看板数据创建完成：corpId={}, date={}, 共{}条记录", 
                corpId, date, dataList.size());
    }

    /**
     * 计算统计数据V2
     * @param corpId 企业ID
     * @param date 目标日期
     * @return 统计结果列表
     */
    private List<CustomerStatisticsDataV2> calculateStatisticsV2(String corpId, Date date) {
        // 1. 初始化累加器（按组和标签）
        GroupTagAccumulator accumulator = new GroupTagAccumulator();

        // 2. 分页查询并累加统计
        int pageSize = 1000;
        int pageNum = 1;
        LambdaQueryWrapper<CustomerExportData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerExportData::getCorpId, corpId)
               .eq(CustomerExportData::getAddDate, date);

        while (true) {
            Page<CustomerExportData> page = new Page<>(pageNum, pageSize);
            Page<CustomerExportData> pageData = customerExportDataMapper.selectPage(page, wrapper);

            for (CustomerExportData data : pageData.getRecords()) {
                processDataRecordV2(data, date, accumulator);
            }

            if (!pageData.hasNext()) {
                break;
            }
            pageNum++;
        }

        // 3. 从累加器生成最终结果
        return generateStatisticsResultsV2(corpId, date, accumulator);
    }

    /**
     * 处理单条数据记录，累加到组级和标签级统计
     */
    private void processDataRecordV2(CustomerExportData data, Date date, GroupTagAccumulator accumulator) {
        boolean hasGroup = false;
        
        // 遍历所有组
        for (Map.Entry<String, String> entry : GROUP_FIELD_MAP.entrySet()) {
            String groupName = entry.getKey();
            String fieldName = entry.getValue();

            // 获取该组的标签值
            String tagValue = getFieldValue(data, fieldName);

            // 如果该组标签为空，跳过
            if (tagValue == null || tagValue.trim().isEmpty()) {
                continue;
            }
            
            hasGroup = true;

            // 获取该组的统计器
            GroupStatistics groupStats = accumulator.getGroupStats(groupName);

            // 累加组级统计
            accumulateGroupStatistics(data, date, groupStats);

            // 解析标签值（可能是逗号分隔的多个标签）
            String[] tags = tagValue.split(",");
            for (String tag : tags) {
                tag = tag.trim();
                if (tag.isEmpty()) continue;

                // 累加到标签级统计
                TagStatistics tagStats = accumulator.getTagStats(groupName, tag);
                accumulateGroupStatistics(data, date, tagStats);
            }
        }
        
        // 如果不属于任何组，统计到"未分组"
        if (!hasGroup) {
            GroupStatistics ungroupedStats = accumulator.getGroupStats(UNGROUPED_NAME);
            accumulateGroupStatistics(data, date, ungroupedStats);
        }
    }

    /**
     * 使用反射获取字段值（带缓存）
     */
    private String getFieldValue(CustomerExportData data, String fieldName) {
        try {
            java.lang.reflect.Field field = CustomerExportData.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            Object value = field.get(data);
            return value == null ? "" : value.toString();
        } catch (Exception e) {
            return "";
        }
    }

    /**
     * 累加单条数据的统计指标
     */
    private void accumulateGroupStatistics(CustomerExportData data, Date date, BaseStatistics stats) {
        // 1. 成单数统计
        if (matchesQValue(data, date)) {
            stats.setOrderCount(stats.getOrderCount() + 1);
            String orderStatus = data.getTagGroup7();
            if (orderStatus != null) {
                if (orderStatus.equals("已成交及时单9元+")) {
                    stats.setTimelyOrderCount(stats.getTimelyOrderCount() + 1);
                } else if (orderStatus.equals("已成交非及时单9元+")) {
                    stats.setNonTimelyOrderCount(stats.getNonTimelyOrderCount() + 1);
                }
            }
        }

        // 来源筛选
        if (!matchesSource(data) || !matchesDate(data, date)) {
            return;
        }

        // 2. 进粉数
        stats.setCustomerCount(stats.getCustomerCount() + 1);

        // 3. 客户属性统计
        String customerAttr = data.getTagGroup6();
        if (customerAttr != null && !customerAttr.trim().isEmpty()) {
            stats.setCustomerAttrCount(stats.getCustomerAttrCount() + 1);
            if (customerAttr.contains("家长")) {
                stats.setParentCount(stats.getParentCount() + 1);
                stats.setParentOrderCount(stats.getParentOrderCount() + 1);
                stats.setParentDailyCount(stats.getParentDailyCount() + 1);
                if (matchesQValue(data, date) && isTimelyOrder(data)) {
                    stats.setParentDailyOrderCount(stats.getParentDailyOrderCount() + 1);
                }
            } else if (customerAttr.contains("学生")) {
                stats.setStudentCount(stats.getStudentCount() + 1);
                stats.setStudentOrderCount(stats.getStudentOrderCount() + 1);
                stats.setStudentDailyCount(stats.getStudentDailyCount() + 1);
                if (matchesQValue(data, date) && isTimelyOrder(data)) {
                    stats.setStudentDailyOrderCount(stats.getStudentDailyOrderCount() + 1);
                }
            } else if (customerAttr.contains("老师")) {
                stats.setTeacherCount(stats.getTeacherCount() + 1);
                stats.setTeacherOrderCount(stats.getTeacherOrderCount() + 1);
                stats.setTeacherDailyCount(stats.getTeacherDailyCount() + 1);
                if (matchesQValue(data, date) && isTimelyOrder(data)) {
                    stats.setTeacherDailyOrderCount(stats.getTeacherDailyOrderCount() + 1);
                }
            } else {
                // 属性不为空但无法识别（未知）
                stats.setUnknownAttrCount(stats.getUnknownAttrCount() + 1);
                stats.setUnknownOrderCount(stats.getUnknownOrderCount() + 1);
                stats.setUnknownDailyCount(stats.getUnknownDailyCount() + 1);
                if (matchesQValue(data, date) && isTimelyOrder(data)) {
                    stats.setUnknownDailyOrderCount(stats.getUnknownDailyOrderCount() + 1);
                }
            }
        }
        // 注意：属性为空的客户不统计在 customerAttrCount 和 unknownAttrCount 中

        // 4. 意向度统计
        String intention = data.getTagGroup15();
        if (intention != null && !intention.trim().isEmpty() && !"空白".equals(intention)) {
            stats.setIntentionCount(stats.getIntentionCount() + 1);
            if (intention.contains("主动报价")) {
                stats.setActiveQuoteCount(stats.getActiveQuoteCount() + 1);
            } else if (intention.contains("被动报价")) {
                stats.setPassiveQuoteCount(stats.getPassiveQuoteCount() + 1);
            } else if (intention.contains("未开口")) {
                stats.setNoQuoteCount(stats.getNoQuoteCount() + 1);
            } else if (intention.contains("已删除")) {
                stats.setDeletedQuoteCount(stats.getDeletedQuoteCount() + 1);
            }
        }

        // 5. 年级统计
        String grade = data.getTagGroup5();
        if (grade != null && !grade.trim().isEmpty() && !"空白".equals(grade)) {
            stats.setGradeCount(stats.getGradeCount() + 1);
            if (isPrimarySchool(grade)) {
                stats.setPrimaryCount(stats.getPrimaryCount() + 1);
            } else if (isMiddleSchool(grade)) {
                stats.setMiddleCount(stats.getMiddleCount() + 1);
            } else if (isHighSchool(grade)) {
                stats.setHighCount(stats.getHighCount() + 1);
            }
        }
    }

    /**
     * 从累加器生成最终统计结果V2
     * 修复：遍历所有预定义的组，确保"有成单但无进粉"的组也被统计
     */
    private List<CustomerStatisticsDataV2> generateStatisticsResultsV2(
            String corpId, Date date, GroupTagAccumulator accumulator) {
        List<CustomerStatisticsDataV2> result = new ArrayList<>();
        int sortNo = 0;
        long tempId = 1;

        // 1. 生成组级数据 - 遍历所有预定义的组，确保有成单但无进粉的组也被统计
        Map<String, Long> groupIdMap = new HashMap<>();
        for (Map.Entry<String, String> groupEntry : GROUP_FIELD_MAP.entrySet()) {
            String groupName = groupEntry.getKey();
            String attr = GROUP_ATTR_MAP.get(groupName);
            
            // 获取或创建该组的统计器
            GroupStatistics stats = accumulator.getGroupStats(groupName);
            
            // 使用SQL查询获取成单数（与V1保持一致）
            Long finishCount = customerExportDataMapper.selectByFinishDate(
                    corpId, date, attr, finishFlag);
            stats.setOrderCount(finishCount.intValue());

            // 使用SQL查询获取及时单数量（根据成交日期和订单状态）
            Long timelyCount = customerExportDataMapper.selectTimelyOrderCount(
                    corpId, date, attr, timelyFinishFlag);
            stats.setTimelyOrderCount(timelyCount.intValue());

            // 使用SQL查询获取非及时单数量（根据成交日期和订单状态）
            Long nonTimelyCount = customerExportDataMapper.selectNonTimelyOrderCount(
                    corpId, date, attr, noTimelyfinishFlag);
            stats.setNonTimelyOrderCount(nonTimelyCount.intValue());
            
            // 只有当有成单数或进粉数时才生成记录
            if (stats.getOrderCount() > 0 || stats.getCustomerCount() > 0) {
                CustomerStatisticsDataV2 groupData = createStatisticsDataV2(
                        corpId, date, groupName, null, stats, sortNo++);
                groupData.setDataLevel(1);
                groupData.setId(tempId);
                result.add(groupData);

                groupIdMap.put(groupName, tempId);
                tempId++;
            }
        }

        // 2. 处理"未分组"数据
        GroupStatistics ungroupedStats = accumulator.getGroupStats(UNGROUPED_NAME);
        // 查询未分组记录的成单数
        Long ungroupedFinishCount = customerExportDataMapper.selectUngroupedFinishCount(
                corpId, date, finishFlag);
        ungroupedStats.setOrderCount(ungroupedFinishCount.intValue());
        
        // 查询未分组记录的及时单数量
        Long ungroupedTimelyCount = customerExportDataMapper.selectUngroupedTimelyOrderCount(
                corpId, date, timelyFinishFlag);
        ungroupedStats.setTimelyOrderCount(ungroupedTimelyCount.intValue());
        
        // 查询未分组记录的非及时单数量
        Long ungroupedNonTimelyCount = customerExportDataMapper.selectUngroupedNonTimelyOrderCount(
                corpId, date, noTimelyfinishFlag);
        ungroupedStats.setNonTimelyOrderCount(ungroupedNonTimelyCount.intValue());
        
        // 只有当有成单数或进粉数时才生成记录
        if (ungroupedStats.getOrderCount() > 0 || ungroupedStats.getCustomerCount() > 0) {
            CustomerStatisticsDataV2 ungroupedData = createStatisticsDataV2(
                    corpId, date, UNGROUPED_NAME, null, ungroupedStats, sortNo++);
            ungroupedData.setDataLevel(1);
            ungroupedData.setId(tempId);
            result.add(ungroupedData);
            tempId++;
        }

        // 3. 生成标签级数据
        for (Map.Entry<String, Map<String, TagStatistics>> groupEntry : 
                accumulator.getTagStatsMap().entrySet()) {
            String groupName = groupEntry.getKey();
            Long parentId = groupIdMap.get(groupName);

            for (Map.Entry<String, TagStatistics> tagEntry : groupEntry.getValue().entrySet()) {
                String tagName = tagEntry.getKey();
                TagStatistics stats = tagEntry.getValue();

                // 使用SQL查询获取该标签的成单数（根据标签值筛选）
                Long finishCount = customerExportDataMapper.selectByFinishDateAndTag(
                        corpId, date, GROUP_ATTR_MAP.get(groupName), tagName, finishFlag);
                stats.setOrderCount(finishCount.intValue());

                // 使用SQL查询获取该标签的及时单数量
                Long timelyCount = customerExportDataMapper.selectTimelyOrderCountByTag(
                        corpId, date, GROUP_ATTR_MAP.get(groupName), tagName, timelyFinishFlag);
                stats.setTimelyOrderCount(timelyCount.intValue());

                // 使用SQL查询获取该标签的非及时单数量
                Long nonTimelyCount = customerExportDataMapper.selectNonTimelyOrderCountByTag(
                        corpId, date, GROUP_ATTR_MAP.get(groupName), tagName, noTimelyfinishFlag);
                stats.setNonTimelyOrderCount(nonTimelyCount.intValue());

                CustomerStatisticsDataV2 tagData = createStatisticsDataV2(
                        corpId, date, groupName, tagName, stats, sortNo++);
                tagData.setDataLevel(2);
                tagData.setId(tempId);
                tagData.setParentId(parentId);
                result.add(tagData);
                tempId++;
            }
        }

        return result;
    }

    /**
     * 创建统计数据V2对象
     */
    private CustomerStatisticsDataV2 createStatisticsDataV2(
            String corpId, Date date, String groupName, String tagName,
            BaseStatistics stats, int sortNo) {
        CustomerStatisticsDataV2 data = new CustomerStatisticsDataV2();
        data.setCorpId(corpId);
        data.setCurDate(date);
        data.setGroupName(groupName);
        data.setTagName(tagName);
        data.setSortNo(sortNo);

        // 数量指标
        data.setOrderCount(stats.getOrderCount());
        data.setCustomerCount(stats.getCustomerCount());
        data.setTimelyOrderCount(stats.getTimelyOrderCount());
        data.setNonTimelyOrderCount(stats.getNonTimelyOrderCount());

        // 比率指标
        // 转化率 = 成单数 / 进粉数
        data.setConversionRate(calculateRate(stats.getOrderCount(), stats.getCustomerCount()));
        // 及时单占比 = 及时单数 / 成单数（当日）
        data.setTimelyRate(calculateRate(stats.getTimelyOrderCount(), stats.getOrderCount()));
        // 非及时单占比 = 非及时单数 / 成单数（当日）
        data.setNonTimelyRate(calculateRate(stats.getNonTimelyOrderCount(), stats.getOrderCount()));

        // 客户属性指标
        data.setCustomerAttrCount(stats.getCustomerAttrCount());
        data.setParentCount(stats.getParentCount());
        data.setStudentCount(stats.getStudentCount());
        data.setTeacherCount(stats.getTeacherCount());
        data.setUnknownAttrCount(stats.getUnknownAttrCount());
        data.setParentRate(calculateRate(stats.getParentCount(), stats.getCustomerAttrCount()));
        data.setStudentRate(calculateRate(stats.getStudentCount(), stats.getCustomerAttrCount()));
        data.setTeacherRate(calculateRate(stats.getTeacherCount(), stats.getCustomerAttrCount()));
        data.setUnknownRate(calculateRate(stats.getUnknownAttrCount(), stats.getCustomerAttrCount()));

        // 出单率指标
        data.setParentOrderCount(stats.getParentOrderCount());
        data.setStudentOrderCount(stats.getStudentOrderCount());
        data.setTeacherOrderCount(stats.getTeacherOrderCount());
        data.setUnknownOrderCount(stats.getUnknownOrderCount());
        data.setParentDailyCount(stats.getParentDailyCount());
        data.setStudentDailyCount(stats.getStudentDailyCount());
        data.setTeacherDailyCount(stats.getTeacherDailyCount());
        data.setUnknownDailyCount(stats.getUnknownDailyCount());
        data.setParentDailyOrderCount(stats.getParentDailyOrderCount());
        data.setStudentDailyOrderCount(stats.getStudentDailyOrderCount());
        data.setTeacherDailyOrderCount(stats.getTeacherDailyOrderCount());
        data.setUnknownDailyOrderCount(stats.getUnknownDailyOrderCount());
        data.setParentOrderRate(calculateRate(stats.getParentDailyOrderCount(), stats.getParentDailyCount()));
        data.setStudentOrderRate(calculateRate(stats.getStudentDailyOrderCount(), stats.getStudentDailyCount()));
        data.setTeacherOrderRate(calculateRate(stats.getTeacherDailyOrderCount(), stats.getTeacherDailyCount()));
        data.setUnknownOrderRate(calculateRate(stats.getUnknownDailyOrderCount(), stats.getUnknownDailyCount()));

        // 意向度指标
        data.setIntentionCount(stats.getIntentionCount());
        data.setActiveQuoteCount(stats.getActiveQuoteCount());
        data.setPassiveQuoteCount(stats.getPassiveQuoteCount());
        data.setNoQuoteCount(stats.getNoQuoteCount());
        data.setDeletedQuoteCount(stats.getDeletedQuoteCount());
        data.setActiveQuoteRate(calculateRate(stats.getActiveQuoteCount(), stats.getIntentionCount()));
        data.setPassiveQuoteRate(calculateRate(stats.getPassiveQuoteCount(), stats.getIntentionCount()));
        data.setNoQuoteRate(calculateRate(stats.getNoQuoteCount(), stats.getIntentionCount()));
        data.setDeletedQuoteRate(calculateRate(stats.getDeletedQuoteCount(), stats.getIntentionCount()));

        // 年级指标
        data.setGradeCount(stats.getGradeCount());
        data.setPrimaryCount(stats.getPrimaryCount());
        data.setMiddleCount(stats.getMiddleCount());
        data.setHighCount(stats.getHighCount());
        data.setPrimaryRate(calculateRate(stats.getPrimaryCount(), stats.getGradeCount()));
        data.setMiddleRate(calculateRate(stats.getMiddleCount(), stats.getGradeCount()));
        data.setHighRate(calculateRate(stats.getHighCount(), stats.getGradeCount()));

        return data;
    }

    /**
     * 计算百分比
     */
    private String calculateRate(int count, int total) {
        if (total == 0) {
            return "0%";
        }
        BigDecimal rate = new BigDecimal(count)
                .multiply(new BigDecimal(100))
                .divide(new BigDecimal(total), 2, RoundingMode.HALF_UP);
        return rate.toString() + "%";
    }

    /**
     * 检查数据是否匹配日期
     */
    private boolean matchesDate(CustomerExportData data, Date date) {
        if (data.getAddDate() != null && date != null) {
            return date.compareTo(data.getAddDate()) == 0;
        }
        return false;
    }

    /**
     * 检查数据来源是否匹配
     * 排除"由管理员XXX分配"的记录
     */
    private boolean matchesSource(CustomerExportData data) {
        if(data == null || data.getSource() == null) {
            return true;
        }
        if (data.getSource().contains("管理员") &&
                data.getSource().contains("分配")) {
            return false;
        }
        return true;
    }

    /**
     * 检查成交日期是否匹配（使用finishDate字段）
     */
    private boolean matchesQValue(CustomerExportData data, Date curDate) {
        Date finishDate = data.getFinishDate();
        if (finishDate == null) {
            return false;
        }

        try {
            Calendar orderCal = Calendar.getInstance();
            orderCal.setTime(finishDate);
            orderCal.set(Calendar.HOUR_OF_DAY, 0);
            orderCal.set(Calendar.MINUTE, 0);
            orderCal.set(Calendar.SECOND, 0);
            orderCal.set(Calendar.MILLISECOND, 0);

            Calendar targetCal = Calendar.getInstance();
            targetCal.setTime(curDate);
            targetCal.set(Calendar.HOUR_OF_DAY, 0);
            targetCal.set(Calendar.MINUTE, 0);
            targetCal.set(Calendar.SECOND, 0);
            targetCal.set(Calendar.MILLISECOND, 0);

            return orderCal.getTimeInMillis() == targetCal.getTimeInMillis();

        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 判断是否为及时单
     */
    private boolean isTimelyOrder(CustomerExportData data) {
        String orderStatus = data.getTagGroup7();
        if (orderStatus == null || orderStatus.trim().isEmpty()) {
            return false;
        }
        return orderStatus.equals("已成交及时单9元+");
    }

    /**
     * 判断是否为小学
     */
    private boolean isPrimarySchool(String grade) {
        return grade.contains("小学") || grade.contains("一年级") || grade.contains("二年级") ||
               grade.contains("三年级") || grade.contains("四年级") || grade.contains("五年级") ||
               grade.contains("六年级");
    }

    /**
     * 判断是否为初中
     */
    private boolean isMiddleSchool(String grade) {
        return grade.contains("初中") || grade.contains("初一") ||
               grade.contains("初二") || grade.contains("初三");
    }

    /**
     * 判断是否为高中
     */
    private boolean isHighSchool(String grade) {
        return grade.contains("高中") || grade.contains("高一") ||
               grade.contains("高二") || grade.contains("高三");
    }

    /**
     * 获取所有日期
     */
    private List<Date> getAllDate(String corpId) {
        return customerExportDataMapper.getDistinctDate(corpId);
    }

    /**
     * 关闭线程池
     */
    public void shutdown() {
        executorService.shutdown();
        try {
            if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                executorService.shutdownNow();
            }
        } catch (InterruptedException e) {
            executorService.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }

    // ==================== 内部类定义 ====================

    /**
     * 基础统计类
     */
    public static class BaseStatistics {
        // 数量指标
        private int orderCount;
        private int customerCount;
        private int timelyOrderCount;
        private int nonTimelyOrderCount;

        // 客户属性指标
        private int customerAttrCount;
        private int parentCount;
        private int studentCount;
        private int teacherCount;
        private int unknownAttrCount;

        // 出单率指标
        private int parentOrderCount;
        private int studentOrderCount;
        private int teacherOrderCount;
        private int unknownOrderCount;
        private int parentDailyCount;
        private int studentDailyCount;
        private int teacherDailyCount;
        private int unknownDailyCount;
        private int parentDailyOrderCount;
        private int studentDailyOrderCount;
        private int teacherDailyOrderCount;
        private int unknownDailyOrderCount;

        // 意向度指标
        private int intentionCount;
        private int activeQuoteCount;
        private int passiveQuoteCount;
        private int noQuoteCount;
        private int deletedQuoteCount;

        // 年级指标
        private int gradeCount;
        private int primaryCount;
        private int middleCount;
        private int highCount;

        // Getters and Setters
        public int getOrderCount() { return orderCount; }
        public void setOrderCount(int orderCount) { this.orderCount = orderCount; }
        public int getCustomerCount() { return customerCount; }
        public void setCustomerCount(int customerCount) { this.customerCount = customerCount; }
        public int getTimelyOrderCount() { return timelyOrderCount; }
        public void setTimelyOrderCount(int timelyOrderCount) { this.timelyOrderCount = timelyOrderCount; }
        public int getNonTimelyOrderCount() { return nonTimelyOrderCount; }
        public void setNonTimelyOrderCount(int nonTimelyOrderCount) { this.nonTimelyOrderCount = nonTimelyOrderCount; }
        public int getCustomerAttrCount() { return customerAttrCount; }
        public void setCustomerAttrCount(int customerAttrCount) { this.customerAttrCount = customerAttrCount; }
        public int getParentCount() { return parentCount; }
        public void setParentCount(int parentCount) { this.parentCount = parentCount; }
        public int getStudentCount() { return studentCount; }
        public void setStudentCount(int studentCount) { this.studentCount = studentCount; }
        public int getTeacherCount() { return teacherCount; }
        public void setTeacherCount(int teacherCount) { this.teacherCount = teacherCount; }
        public int getUnknownAttrCount() { return unknownAttrCount; }
        public void setUnknownAttrCount(int unknownAttrCount) { this.unknownAttrCount = unknownAttrCount; }
        public int getParentOrderCount() { return parentOrderCount; }
        public void setParentOrderCount(int parentOrderCount) { this.parentOrderCount = parentOrderCount; }
        public int getStudentOrderCount() { return studentOrderCount; }
        public void setStudentOrderCount(int studentOrderCount) { this.studentOrderCount = studentOrderCount; }
        public int getTeacherOrderCount() { return teacherOrderCount; }
        public void setTeacherOrderCount(int teacherOrderCount) { this.teacherOrderCount = teacherOrderCount; }
        public int getUnknownOrderCount() { return unknownOrderCount; }
        public void setUnknownOrderCount(int unknownOrderCount) { this.unknownOrderCount = unknownOrderCount; }
        public int getParentDailyCount() { return parentDailyCount; }
        public void setParentDailyCount(int parentDailyCount) { this.parentDailyCount = parentDailyCount; }
        public int getStudentDailyCount() { return studentDailyCount; }
        public void setStudentDailyCount(int studentDailyCount) { this.studentDailyCount = studentDailyCount; }
        public int getTeacherDailyCount() { return teacherDailyCount; }
        public void setTeacherDailyCount(int teacherDailyCount) { this.teacherDailyCount = teacherDailyCount; }
        public int getUnknownDailyCount() { return unknownDailyCount; }
        public void setUnknownDailyCount(int unknownDailyCount) { this.unknownDailyCount = unknownDailyCount; }
        public int getParentDailyOrderCount() { return parentDailyOrderCount; }
        public void setParentDailyOrderCount(int parentDailyOrderCount) { this.parentDailyOrderCount = parentDailyOrderCount; }
        public int getStudentDailyOrderCount() { return studentDailyOrderCount; }
        public void setStudentDailyOrderCount(int studentDailyOrderCount) { this.studentDailyOrderCount = studentDailyOrderCount; }
        public int getTeacherDailyOrderCount() { return teacherDailyOrderCount; }
        public void setTeacherDailyOrderCount(int teacherDailyOrderCount) { this.teacherDailyOrderCount = teacherDailyOrderCount; }
        public int getUnknownDailyOrderCount() { return unknownDailyOrderCount; }
        public void setUnknownDailyOrderCount(int unknownDailyOrderCount) { this.unknownDailyOrderCount = unknownDailyOrderCount; }
        public int getIntentionCount() { return intentionCount; }
        public void setIntentionCount(int intentionCount) { this.intentionCount = intentionCount; }
        public int getActiveQuoteCount() { return activeQuoteCount; }
        public void setActiveQuoteCount(int activeQuoteCount) { this.activeQuoteCount = activeQuoteCount; }
        public int getPassiveQuoteCount() { return passiveQuoteCount; }
        public void setPassiveQuoteCount(int passiveQuoteCount) { this.passiveQuoteCount = passiveQuoteCount; }
        public int getNoQuoteCount() { return noQuoteCount; }
        public void setNoQuoteCount(int noQuoteCount) { this.noQuoteCount = noQuoteCount; }
        public int getDeletedQuoteCount() { return deletedQuoteCount; }
        public void setDeletedQuoteCount(int deletedQuoteCount) { this.deletedQuoteCount = deletedQuoteCount; }
        public int getGradeCount() { return gradeCount; }
        public void setGradeCount(int gradeCount) { this.gradeCount = gradeCount; }
        public int getPrimaryCount() { return primaryCount; }
        public void setPrimaryCount(int primaryCount) { this.primaryCount = primaryCount; }
        public int getMiddleCount() { return middleCount; }
        public void setMiddleCount(int middleCount) { this.middleCount = middleCount; }
        public int getHighCount() { return highCount; }
        public void setHighCount(int highCount) { this.highCount = highCount; }
    }

    /**
     * 组级统计
     */
    public static class GroupStatistics extends BaseStatistics {}

    /**
     * 标签级统计
     */
    public static class TagStatistics extends BaseStatistics {}

    /**
     * 组和标签累加器
     */
    public static class GroupTagAccumulator {
        private final Map<String, GroupStatistics> groupStatsMap = new LinkedHashMap<>();
        private final Map<String, Map<String, TagStatistics>> tagStatsMap = new LinkedHashMap<>();

        public GroupStatistics getGroupStats(String groupName) {
            return groupStatsMap.computeIfAbsent(groupName, k -> new GroupStatistics());
        }

        public TagStatistics getTagStats(String groupName, String tagName) {
            Map<String, TagStatistics> tagMap = tagStatsMap.computeIfAbsent(groupName, k -> new LinkedHashMap<>());
            return tagMap.computeIfAbsent(tagName, k -> new TagStatistics());
        }

        public Map<String, GroupStatistics> getGroupStatsMap() {
            return groupStatsMap;
        }

        public Map<String, Map<String, TagStatistics>> getTagStatsMap() {
            return tagStatsMap;
        }
    }
}
