package com.ruoyi.excel.wecom.service.impl;

import com.ruoyi.excel.wecom.domain.CustomerStatisticsDataV2;
import com.ruoyi.excel.wecom.domain.dto.TagTreeDTO;
import com.ruoyi.excel.wecom.mapper.CustomerExportDataMapper;
import com.ruoyi.excel.wecom.mapper.CustomerStatisticsDataV2Mapper;
import com.ruoyi.excel.wecom.service.ICustomerStatisticsDataV2Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 客户统计数据V2 Service业务层处理
 * 支持标签级成本，行列转换存储
 */
@Slf4j
@Service
public class CustomerStatisticsDataV2ServiceImpl implements ICustomerStatisticsDataV2Service {

    @Autowired
    private CustomerStatisticsDataV2Mapper dataV2Mapper;

    @Autowired
    private CustomerExportDataMapper exportDataMapper;
    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 Map<String, String> GROUP_NAME_TO_ATTR_MAP = new LinkedHashMap<>();
    static {
        GROUP_NAME_TO_ATTR_MAP.put("投放", "tag_group1");
        GROUP_NAME_TO_ATTR_MAP.put("公司孵化", "tag_group2");
        GROUP_NAME_TO_ATTR_MAP.put("商务", "tag_group3");
        GROUP_NAME_TO_ATTR_MAP.put("A1组", "tag_group10");
        GROUP_NAME_TO_ATTR_MAP.put("B1组", "tag_group11");
        GROUP_NAME_TO_ATTR_MAP.put("C1组", "tag_group12");
        GROUP_NAME_TO_ATTR_MAP.put("D1组", "tag_group13");
        GROUP_NAME_TO_ATTR_MAP.put("E1组", "tag_group14");
        GROUP_NAME_TO_ATTR_MAP.put("自然流", "tag_group16");
        GROUP_NAME_TO_ATTR_MAP.put("F1组", "tag_group17");
        GROUP_NAME_TO_ATTR_MAP.put("G1组", "tag_group18");
    }

    @Override
    public List<CustomerStatisticsDataV2> selectCustomerStatisticsDataV2List(
            String corpId, Date startDate, Date endDate) {
        return dataV2Mapper.selectGroupLevelList(corpId, startDate, endDate);
    }

    @Override
    public List<CustomerStatisticsDataV2> selectCustomerStatisticsDataV2List(
            String corpId, Date startDate, Date endDate, String groupName, String tagName,
            Boolean onlyGroup, Boolean onlyTag) {
        return dataV2Mapper.selectListByFilter(corpId, startDate, endDate, groupName, tagName, onlyGroup, onlyTag);
    }

    @Override
    public List<TagTreeDTO> selectTagTree(String corpId, Date startDate, Date endDate) {
        log.info("selectTagTree called with corpId={}, startDate={}, endDate={}", corpId, startDate, endDate);
        
        // 查询所有数据，提取组-标签结构
        List<CustomerStatisticsDataV2> allData = dataV2Mapper.selectTreeData(corpId, startDate, endDate);
        log.info("selectTreeData returned {} records", allData.size());
        
        // 按组名分组
        Map<String, List<CustomerStatisticsDataV2>> groupDataMap = allData.stream()
                .filter(d -> d.getGroupName() != null)
                .collect(Collectors.groupingBy(CustomerStatisticsDataV2::getGroupName));
        log.info("groupDataMap has {} groups", groupDataMap.size());

        List<TagTreeDTO> result = new ArrayList<>();

        for (Map.Entry<String, List<CustomerStatisticsDataV2>> entry : groupDataMap.entrySet()) {
            String groupName = entry.getKey();
            List<CustomerStatisticsDataV2> groupDataList = entry.getValue();

            // 创建组节点
            TagTreeDTO groupNode = new TagTreeDTO();
            groupNode.setId("group_" + groupName);
            groupNode.setLabel(groupName);
            groupNode.setType("group");
            groupNode.setGroupName(groupName);
            groupNode.setChildren(new ArrayList<>());

            // 提取该组下的所有标签
            Set<String> tagSet = new LinkedHashSet<>();
            for (CustomerStatisticsDataV2 data : groupDataList) {
                if (data.getTagName() != null && !data.getTagName().isEmpty()) {
                    tagSet.add(data.getTagName());
                }
            }

            // 创建标签节点
            for (String tagName : tagSet) {
                TagTreeDTO tagNode = new TagTreeDTO();
                tagNode.setId("tag_" + groupName + "_" + tagName);
                tagNode.setLabel(tagName);
                tagNode.setType("tag");
                tagNode.setGroupName(groupName);
                tagNode.setTagName(tagName);
                tagNode.setCount(1);
                groupNode.getChildren().add(tagNode);
            }

            groupNode.setCount(groupNode.getChildren().size());
            result.add(groupNode);
        }

        // 按组名排序
        result.sort(Comparator.comparing(TagTreeDTO::getLabel));

        return result;
    }

    @Override
    public List<CustomerStatisticsDataV2> selectTreeData(
            String corpId, Date startDate, Date endDate) {
        // 1. 查询所有数据（组级+标签级）
        List<CustomerStatisticsDataV2> allData = dataV2Mapper.selectTreeData(
                corpId, startDate, endDate);

        // 2. 构建树状结构
        Map<Long, CustomerStatisticsDataV2> groupMap = new LinkedHashMap<>();
        List<CustomerStatisticsDataV2> result = new ArrayList<>();

        // 先处理组级数据
        for (CustomerStatisticsDataV2 data : allData) {
            if (data.getDataLevel() != null && data.getDataLevel() == 1) {
                data.setChildren(new ArrayList<>());
                data.setLeaf(false);
                groupMap.put(data.getId(), data);
                result.add(data);
            }
        }

        // 再处理标签级数据，挂载到对应组下
        for (CustomerStatisticsDataV2 data : allData) {
            if (data.getDataLevel() != null && data.getDataLevel() == 2) {
                data.setLeaf(true);
                CustomerStatisticsDataV2 parent = groupMap.get(data.getParentId());
                if (parent != null) {
                    parent.getChildren().add(data);
                }
            }
        }

        return result;
    }

    @Override
    public CustomerStatisticsDataV2 selectCustomerStatisticsDataV2ById(Long id) {
        return dataV2Mapper.selectById(id);
    }

    @Override
    public int insertCustomerStatisticsDataV2(CustomerStatisticsDataV2 data) {
        return dataV2Mapper.insert(data);
    }

    @Override
    public int updateCustomerStatisticsDataV2(CustomerStatisticsDataV2 data) {
        return dataV2Mapper.updateById(data);
    }

    @Override
    public int deleteCustomerStatisticsDataV2ByIds(Long[] ids) {
        int count = 0;
        for (Long id : ids) {
            count += dataV2Mapper.deleteById(id);
        }
        return count;
    }

    @Override
    @Transactional
    public int inputCost(String corpId, Date date, String groupName, String tagName,
                         BigDecimal costValue, String inputType) {
        try {
            // 1. 查询目标记录
            CustomerStatisticsDataV2 data = dataV2Mapper.selectByCorpDateGroupTag(
                    corpId, date, groupName, tagName);

            if (data == null) {
                throw new RuntimeException("未找到对应的统计数据：" + groupName +
                        (tagName != null ? "/" + tagName : ""));
            }

            // 2. 计算实际总成本
            BigDecimal actualTotalCost;
            boolean isSingleInput = "single".equals(inputType);
            if (isSingleInput) {
                // 单条成本 × 进粉数 = 总成本
                actualTotalCost = costValue.multiply(
                        new BigDecimal(data.getCustomerCount()));
                data.setSingleCost(costValue);
                data.setTotalCost(actualTotalCost);  // 更新总成本
            } else {
                actualTotalCost = costValue;
                data.setTotalCost(costValue);
            }
            data.setCostInputType(inputType);

            // 3. 计算派生成本指标（单条成本录入时保留用户输入的单条成本值）
            calculateDerivedCosts(data, actualTotalCost, isSingleInput);

            // 4. 更新记录
            dataV2Mapper.updateById(data);

            // 5. 如果是标签级成本，需要重新计算组级汇总
            if (tagName != null && !tagName.isEmpty()) {
                recalculateGroupCost(corpId, date, groupName);
            }

            log.info("成本录入成功：corpId={}, date={}, group={}, tag={}, cost={}",
                    corpId, date, groupName, tagName, costValue);

            return 1;
        } catch (Exception e) {
            log.error("成本录入失败：" + e.getMessage(), e);
            throw new RuntimeException("成本录入失败: " + e.getMessage(), e);
        }
    }

    /**
     * 计算派生成本指标
     * @param data 数据对象
     * @param totalCost 总成本
     * @param preserveSingleCost 是否保留原有的单条成本值（单条成本录入模式时为true）
     */
    private void calculateDerivedCosts(CustomerStatisticsDataV2 data, BigDecimal totalCost, boolean preserveSingleCost) {
        // 初始化成本为0
        if (!preserveSingleCost) {
            data.setSingleCost(BigDecimal.ZERO);
        }
        data.setOrderCost(BigDecimal.ZERO);

        // 单条成本 = 总成本 / 进粉数（仅在非单条成本录入模式下计算）
        if (!preserveSingleCost && data.getCustomerCount() != null && data.getCustomerCount() > 0) {
            BigDecimal singleCost = totalCost.divide(
                    new BigDecimal(data.getCustomerCount()), 2, RoundingMode.HALF_UP);
            data.setSingleCost(singleCost);
        }

        // 成单成本 = 总成本 / 成单数
        if (data.getOrderCount() != null && data.getOrderCount() > 0) {
            BigDecimal orderCost = totalCost.divide(
                    new BigDecimal(data.getOrderCount()), 2, RoundingMode.HALF_UP);
            data.setOrderCost(orderCost);
        }
    }

    /**
     * 计算派生成本指标（默认不保留单条成本）
     */
    private void calculateDerivedCosts(CustomerStatisticsDataV2 data, BigDecimal totalCost) {
        calculateDerivedCosts(data, totalCost, false);
    }

    /**
     * 重新计算组级成本汇总
     */
    private void recalculateGroupCost(String corpId, Date date, String groupName) {
        // 1. 查询该组下所有标签级数据
        List<CustomerStatisticsDataV2> tagDataList = dataV2Mapper
                .selectTagLevelByCorpDateGroup(corpId, date, groupName);

        // 2. 汇总标签成本
        BigDecimal totalCostSum = BigDecimal.ZERO;
        int totalCustomerCount = 0;

        for (CustomerStatisticsDataV2 tagData : tagDataList) {
            if (tagData.getTotalCost() != null) {
                totalCostSum = totalCostSum.add(tagData.getTotalCost());
            }
            if (tagData.getCustomerCount() != null) {
                totalCustomerCount += tagData.getCustomerCount();
            }
        }

        // 3. 更新组级记录
        CustomerStatisticsDataV2 groupData = dataV2Mapper
                .selectGroupLevelByCorpDateGroup(corpId, date, groupName);

        if (groupData != null) {
            groupData.setTotalCost(totalCostSum);
            if (totalCustomerCount > 0) {
                BigDecimal avgSingleCost = totalCostSum.divide(
                        new BigDecimal(totalCustomerCount), 2, RoundingMode.HALF_UP);
                groupData.setSingleCost(avgSingleCost);
            }
            calculateDerivedCosts(groupData, totalCostSum);
            dataV2Mapper.updateById(groupData);

            log.info("组级成本重新计算完成：group={}, totalCost={}", groupName, totalCostSum);
        }
    }

    @Override
    public int recalculateStatistics(String corpId, Date date) {
        // 删除旧数据
        dataV2Mapper.deleteByDateRange(corpId, date, date);
        // 重新计算逻辑在 HandleAllDataV2 中实现
        log.info("统计数据已删除，等待重新计算：corpId={}, date={}", corpId, date);
        return 1;
    }

    @Override
    public int recalculateStatisticsRange(String corpId, Date startDate, Date endDate) {
        // 删除旧数据
        dataV2Mapper.deleteByDateRange(corpId, startDate, endDate);
        // 重新计算逻辑在 HandleAllDataV2 中实现
        log.info("统计数据已删除，等待重新计算：corpId={}, startDate={}, endDate={}",
                corpId, startDate, endDate);
        return 1;
    }

    @Override
    public List<CustomerStatisticsDataV2> selectByWeekAggregation(
            String corpId, Integer year, Integer week, String groupName, String tagName,
            Boolean onlyGroup, Boolean onlyTag) {
        log.info("周聚合查询: corpId={}, year={}, week={}, groupName={}, tagName={}, onlyGroup={}, onlyTag={}", 
                corpId, year, week, groupName, tagName, onlyGroup, onlyTag);
        
        // 计算周的开始和结束日期（使用与V1一致的MySQL WEEK函数逻辑）
        Date[] weekRange = calculateWeekRangeByMySQL(year, week);
        if (weekRange == null) {
            // 如果周范围无效（跨年），返回空列表
            log.info("周范围无效（跨年），返回空列表");
            return new ArrayList<>();
        }
        Date startDate = weekRange[0];
        Date endDate = weekRange[1];
        log.info("周日期范围: {} 至 {}", formatDate(startDate), formatDate(endDate));

        // 查询该周的数据并聚合
        List<CustomerStatisticsDataV2> result = dataV2Mapper.selectAggregatedByDateRange(corpId, startDate, endDate, groupName, tagName, onlyGroup, onlyTag);
        log.info("周聚合查询结果: {}条记录", result.size());
        
        // 从原始数据表按finish_date重新查询成单数（解决跨日成交问题）
        recalculateOrderCountFromOriginalData(corpId, startDate, endDate, result);
        
        // 重新计算比率指标（SQL只聚合数量，比率需要重新计算）
        for (CustomerStatisticsDataV2 data : result) {
            recalculateRates(data);
            log.info("记录: groupName={}, tagName={}, dataLevel={}, customerCount={}, orderCount={}, conversionRate={}",
                    data.getGroupName(), data.getTagName(), data.getDataLevel(), data.getCustomerCount(), 
                    data.getOrderCount(), data.getConversionRate());
        }

        // 设置显示字段
        String yearWeek = year + "年第" + week + "周";
        String dateRange = formatDate(startDate) + " 至 " + formatDate(endDate);
        for (CustomerStatisticsDataV2 data : result) {
            data.setYearWeek(yearWeek);
            data.setDateRange(dateRange);
        }

        return result;
    }

    @Override
    public List<CustomerStatisticsDataV2> selectByMonthAggregation(
            String corpId, String yearMonth, String groupName, String tagName,
            Boolean onlyGroup, Boolean onlyTag) {
        // 解析年月
        String[] parts = yearMonth.split("-");
        int year = Integer.parseInt(parts[0]);
        int month = Integer.parseInt(parts[1]);

        // 计算月的开始和结束日期
        Date[] monthRange = calculateMonthRange(year, month);
        Date startDate = monthRange[0];
        Date endDate = monthRange[1];

        // 查询该月的数据并聚合
        List<CustomerStatisticsDataV2> result = dataV2Mapper.selectAggregatedByDateRange(corpId, startDate, endDate, groupName, tagName, onlyGroup, onlyTag);

        // 从原始数据表按finish_date重新查询成单数（解决跨日成交问题）
        recalculateOrderCountFromOriginalData(corpId, startDate, endDate, result);

        // 重新计算比率指标
        for (CustomerStatisticsDataV2 data : result) {
            recalculateRates(data);
        }

        // 设置显示字段
        String yearMonthDisplay = year + "年" + String.format("%02d", month) + "月";
        String dateRange = formatDate(startDate) + " 至 " + formatDate(endDate);
        for (CustomerStatisticsDataV2 data : result) {
            data.setYearMonth(yearMonthDisplay);
            data.setDateRange(dateRange);
        }

        return result;
    }

    @Override
    public List<CustomerStatisticsDataV2> selectAllAggregation(
            String corpId, String groupName, String tagName,
            Boolean onlyGroup, Boolean onlyTag) {
        // 查询所有数据并聚合
        List<CustomerStatisticsDataV2> result = dataV2Mapper.selectAllAggregated(corpId, groupName, tagName, onlyGroup, onlyTag);

        // 从原始数据表按finish_date重新查询成单数（解决跨日成交问题）
        // 对于全部数据，不限制日期范围
        recalculateOrderCountFromOriginalData(corpId, null, null, result);

        // 重新计算比率指标
        for (CustomerStatisticsDataV2 data : result) {
            recalculateRates(data);
        }

        // 设置显示字段
        for (CustomerStatisticsDataV2 data : result) {
            data.setYearWeek("全部数据");
            data.setYearMonth("全部数据");
            data.setDateRange("全部数据");
        }

        return result;
    }

    /**
     * 从原始数据表按finish_date重新查询成单数
     * 解决跨日成交问题：成单数应该按finish_date统计，而不是按add_date
     * 优化：使用批量查询，避免N+1问题
     */
    private void recalculateOrderCountFromOriginalData(String corpId, Date startDate, Date endDate, 
            List<CustomerStatisticsDataV2> dataList) {
        if (dataList == null || dataList.isEmpty()) {
            return;
        }
        
        // 批量查询所有组的成单数（一次SQL查询）
        Map<String, Object> orderCountMap = exportDataMapper.selectOrderCountBatchByFinishDateRange(corpId, startDate, endDate,finishFlag);
        if (orderCountMap == null) {
            orderCountMap = new HashMap<>();
        }
        
        // 批量查询所有组的及时单数量（一次SQL查询）
        Map<String, Object> timelyCountMap = exportDataMapper.selectTimelyOrderCountBatchByDateRange(corpId, startDate, endDate,timelyFinishFlag);
        if (timelyCountMap == null) {
            timelyCountMap = new HashMap<>();
        }
        
        // 批量查询所有组的非及时单数量（一次SQL查询）
        Map<String, Object> nonTimelyCountMap = exportDataMapper.selectNonTimelyOrderCountBatchByDateRange(corpId, startDate, endDate,noTimelyfinishFlag);
        if (nonTimelyCountMap == null) {
            nonTimelyCountMap = new HashMap<>();
        }
        
        // 遍历数据，从批量查询结果中获取对应的值
        for (CustomerStatisticsDataV2 data : dataList) {
            String groupName = data.getGroupName();
            if (groupName == null || groupName.isEmpty()) {
                continue;
            }
            
            String attr = GROUP_NAME_TO_ATTR_MAP.get(groupName);
            if (attr == null) {
                continue;
            }
            
            // 从批量查询结果中获取成单数
            Object orderCountObj = orderCountMap.get(attr);
            int orderCount = 0;
            if (orderCountObj != null) {
                if (orderCountObj instanceof Number) {
                    orderCount = ((Number) orderCountObj).intValue();
                } else {
                    try {
                        orderCount = Integer.parseInt(orderCountObj.toString());
                    } catch (NumberFormatException e) {
                        log.warn("无法解析成单数: {}", orderCountObj);
                    }
                }
            }
            data.setOrderCount(orderCount);
            
            // 从批量查询结果中获取及时单数量
            Object timelyCountObj = timelyCountMap.get(attr);
            int timelyCount = 0;
            if (timelyCountObj != null) {
                if (timelyCountObj instanceof Number) {
                    timelyCount = ((Number) timelyCountObj).intValue();
                } else {
                    try {
                        timelyCount = Integer.parseInt(timelyCountObj.toString());
                    } catch (NumberFormatException e) {
                        log.warn("无法解析及时单数量: {}", timelyCountObj);
                    }
                }
            }
            data.setTimelyOrderCount(timelyCount);
            
            // 从批量查询结果中获取非及时单数量
            Object nonTimelyCountObj = nonTimelyCountMap.get(attr);
            int nonTimelyCount = 0;
            if (nonTimelyCountObj != null) {
                if (nonTimelyCountObj instanceof Number) {
                    nonTimelyCount = ((Number) nonTimelyCountObj).intValue();
                } else {
                    try {
                        nonTimelyCount = Integer.parseInt(nonTimelyCountObj.toString());
                    } catch (NumberFormatException e) {
                        log.warn("无法解析非及时单数量: {}", nonTimelyCountObj);
                    }
                }
            }
            data.setNonTimelyOrderCount(nonTimelyCount);
            
            log.debug("重新计算成单数: groupName={}, orderCount={}, timelyCount={}, nonTimelyCount={}", 
                    groupName, data.getOrderCount(), data.getTimelyOrderCount(), data.getNonTimelyOrderCount());
        }
    }

    /**
     * 重新计算比率指标
     * 在SQL聚合数量后，需要重新计算各种比率
     */
    private void recalculateRates(CustomerStatisticsDataV2 data) {
        // 转化率 = 成单数 / 进粉数
        data.setConversionRate(calculateRate(data.getOrderCount(), data.getCustomerCount()));
        
        // 及时单占比 = 及时单数 / 成单数
        data.setTimelyRate(calculateRate(data.getTimelyOrderCount(), data.getOrderCount()));
        
        // 非及时单占比 = 非及时单数 / 成单数
        data.setNonTimelyRate(calculateRate(data.getNonTimelyOrderCount(), data.getOrderCount()));
        
        // 客户属性占比
        data.setParentRate(calculateRate(data.getParentCount(), data.getCustomerAttrCount()));
        data.setStudentRate(calculateRate(data.getStudentCount(), data.getCustomerAttrCount()));
        data.setTeacherRate(calculateRate(data.getTeacherCount(), data.getCustomerAttrCount()));
        data.setUnknownRate(calculateRate(data.getUnknownAttrCount(), data.getCustomerAttrCount()));
        
        // 意向度占比
        data.setActiveQuoteRate(calculateRate(data.getActiveQuoteCount(), data.getIntentionCount()));
        data.setPassiveQuoteRate(calculateRate(data.getPassiveQuoteCount(), data.getIntentionCount()));
        data.setNoQuoteRate(calculateRate(data.getNoQuoteCount(), data.getIntentionCount()));
        data.setDeletedQuoteRate(calculateRate(data.getDeletedQuoteCount(), data.getIntentionCount()));
        
        // 年级占比
        data.setPrimaryRate(calculateRate(data.getPrimaryCount(), data.getGradeCount()));
        data.setMiddleRate(calculateRate(data.getMiddleCount(), data.getGradeCount()));
        data.setHighRate(calculateRate(data.getHighCount(), data.getGradeCount()));
        
        // 出单率
        data.setParentOrderRate(calculateRate(data.getParentDailyOrderCount(), data.getParentDailyCount()));
        data.setStudentOrderRate(calculateRate(data.getStudentDailyOrderCount(), data.getStudentDailyCount()));
        data.setTeacherOrderRate(calculateRate(data.getTeacherDailyOrderCount(), data.getTeacherDailyCount()));
        data.setUnknownOrderRate(calculateRate(data.getUnknownDailyOrderCount(), data.getUnknownDailyCount()));
        
        // 成本指标（基于聚合后的总成本重新计算）
        // 初始化成本为0
        data.setSingleCost(BigDecimal.ZERO);
        data.setOrderCost(BigDecimal.ZERO);

        // 确保totalCost不为null
        if (data.getTotalCost() == null) {
            data.setTotalCost(BigDecimal.ZERO);
        }

        if (data.getTotalCost().compareTo(BigDecimal.ZERO) > 0) {
            // 单条成本 = 总成本 / 进粉数
            if (data.getCustomerCount() != null && data.getCustomerCount() > 0) {
                BigDecimal singleCost = data.getTotalCost().divide(
                        new BigDecimal(data.getCustomerCount()), 2, RoundingMode.HALF_UP);
                data.setSingleCost(singleCost);
            }
            // 成单成本 = 总成本 / 成单数
            if (data.getOrderCount() != null && data.getOrderCount() > 0) {
                BigDecimal orderCost = data.getTotalCost().divide(
                        new BigDecimal(data.getOrderCount()), 2, RoundingMode.HALF_UP);
                data.setOrderCost(orderCost);
            }
        }
    }

    /**
     * 计算比率（返回百分比字符串）
     */
    private String calculateRate(Integer count, Integer total) {
        if (total == null || total == 0 || count == null) {
            return "0%";
        }
        BigDecimal rate = new BigDecimal(count)
                .multiply(new BigDecimal(100))
                .divide(new BigDecimal(total), 2, RoundingMode.HALF_UP);
        return rate.toString() + "%";
    }

    /**
     * 计算周范围（修复跨年问题）
     * 规则：
     * 1. 周的第一天是周一（不是周日）
     * 2. 第一周：从1月1日开始，到1月1日所在周的周日结束
     *    - 如果1月1日是周日，第一周只有1天（1月1日当天）
     * 3. 最后一周：从最后一周的周一（12月31日往前推）开始，到12月31日结束
     *    - 如果12月31日是周一，最后一周只有1天（12月31日当天）
     * 4. 其他周：按正常的周一到周日计算
     */
    private Date[] calculateWeekRangeByMySQL(int year, int week) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, Calendar.JANUARY);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        // 获取1月1日是星期几（1=周日，2=周一，...，7=周六）
        int jan1DayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
        // 转换为：0=周日，1=周一，...，6=周六
        int jan1Weekday = (jan1DayOfWeek == Calendar.SUNDAY) ? 0 : (jan1DayOfWeek - 1);

        // 计算12月31日
        Calendar dec31Cal = Calendar.getInstance();
        dec31Cal.set(Calendar.YEAR, year);
        dec31Cal.set(Calendar.MONTH, Calendar.DECEMBER);
        dec31Cal.set(Calendar.DAY_OF_MONTH, 31);
        dec31Cal.set(Calendar.HOUR_OF_DAY, 0);
        dec31Cal.set(Calendar.MINUTE, 0);
        dec31Cal.set(Calendar.SECOND, 0);
        dec31Cal.set(Calendar.MILLISECOND, 0);

        // 第一周：从1月1日开始
        if (week == 1) {
            Date startDate = calendar.getTime();
            // 计算第一周的结束日期（周日）
            // 如果1月1日是周日(0)，则第一周只有1天（当天）
            // 否则，计算到本周日
            int daysToSunday;
            if (jan1Weekday == 0) {
                daysToSunday = 0; // 1月1日是周日，第一周只有1天
            } else {
                daysToSunday = 7 - jan1Weekday; // 到本周日
            }
            calendar.add(Calendar.DAY_OF_MONTH, daysToSunday);
            Date endDate = calendar.getTime();
            return new Date[]{startDate, endDate};
        }

        // 计算第一周结束日期（1月1日所在周的周日）
        Calendar firstWeekEndCal = (Calendar) calendar.clone();
        int firstWeekDays;
        if (jan1Weekday == 0) {
            firstWeekDays = 0; // 1月1日是周日，第一周只有1天
        } else {
            firstWeekDays = 7 - jan1Weekday; // 到本周日
        }
        firstWeekEndCal.add(Calendar.DAY_OF_MONTH, firstWeekDays);

        // 计算第二周开始日期（第一周结束后的周一）
        Calendar secondWeekStartCal = (Calendar) firstWeekEndCal.clone();
        secondWeekStartCal.add(Calendar.DAY_OF_MONTH, 1);

        // 计算目标周的开始和结束
        // 从第二周开始，每周都是周一到周日
        Calendar targetWeekStartCal = (Calendar) secondWeekStartCal.clone();
        targetWeekStartCal.add(Calendar.WEEK_OF_YEAR, week - 2);

        // 如果开始日期已经跨年了（大于12月31日），则返回null
        if (targetWeekStartCal.after(dec31Cal)) {
            return null;
        }

        Date startDate = targetWeekStartCal.getTime();

        Calendar targetWeekEndCal = (Calendar) targetWeekStartCal.clone();
        targetWeekEndCal.add(Calendar.DAY_OF_MONTH, 6);
        Date endDate = targetWeekEndCal.getTime();

        // 如果目标周的结束超过了12月31日，则调整到12月31日
        if (targetWeekEndCal.after(dec31Cal)) {
            endDate = dec31Cal.getTime();
        }

        return new Date[]{startDate, endDate};
    }

    /**
     * 计算月的开始和结束日期
     */
    private Date[] calculateMonthRange(int year, int month) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.YEAR, year);
        calendar.set(Calendar.MONTH, month - 1);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        Date startDate = calendar.getTime();

        calendar.add(Calendar.MONTH, 1);
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date endDate = calendar.getTime();

        return new Date[]{startDate, endDate};
    }

    /**
     * 格式化日期为 yyyy-MM-dd 字符串
     */
    private String formatDate(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        return String.format("%d-%02d-%02d", year, month, day);
    }
}
