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

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.excel.wecom.domain.CustomerStatisticsData;
import com.ruoyi.excel.wecom.mapper.CustomerStatisticsDataMapper;
import com.ruoyi.excel.wecom.service.ICustomerStatisticsDataService;
import com.ruoyi.excel.wecom.vo.CustomerStatisticsDataVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.WeekFields;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 客户统计数据Service业务层处理
 */
@Service
public class CustomerStatisticsDataServiceImpl implements ICustomerStatisticsDataService {

    private static final Logger log = LoggerFactory.getLogger(CustomerStatisticsDataServiceImpl.class);

    @Autowired
    private CustomerStatisticsDataMapper customerStatisticsDataMapper;

    /**
     * 查询客户统计数据列表
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param indicatorName 指标名称
     * @return 客户统计数据列表
     */
    @Override
    public List<CustomerStatisticsData> selectCustomerStatisticsDataList(String corpId,Date startDate, Date endDate, String indicatorName) {
        return customerStatisticsDataMapper.selectCustomerStatisticsDataList(corpId,startDate, endDate, indicatorName);
    }

    /**
     * 查询客户统计数据VO列表(用于导出)
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param indicatorName 指标名称
     * @return 客户统计数据VO列表
     */
    @Override
    public List<CustomerStatisticsDataVO> selectCustomerStatisticsDataVOList(String corpId,Date startDate, Date endDate, String indicatorName) {
        return customerStatisticsDataMapper.selectCustomerStatisticsDataVOList(corpId,startDate, endDate, indicatorName);
    }

    /**
     * 根据ID查询客户统计数据
     * @param id 主键ID
     * @return 客户统计数据
     */
    @Override
    public CustomerStatisticsData selectCustomerStatisticsDataById(Long id) {
        return customerStatisticsDataMapper.selectById(id);
    }

    /**
     * 新增客户统计数据
     * @param customerStatisticsData 客户统计数据
     * @return 结果
     */
    @Override
    public int insertCustomerStatisticsData(CustomerStatisticsData customerStatisticsData) {
        return customerStatisticsDataMapper.insert(customerStatisticsData);
    }

    /**
     * 修改客户统计数据
     * @param customerStatisticsData 客户统计数据
     * @return 结果
     */
    @Override
    public int updateCustomerStatisticsData(CustomerStatisticsData customerStatisticsData) {
        return customerStatisticsDataMapper.updateById(customerStatisticsData);
    }

    /**
     * 批量删除客户统计数据
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteCustomerStatisticsDataByIds(Long[] ids) {
        int count = 0;
        for (Long id : ids) {
            count += customerStatisticsDataMapper.deleteById(id);
        }
        return count;
    }

    @Override
    @Transactional
    public int updateCost(String corpId,Date curDate, BigDecimal totalCost, String type,String titleAttr) {
        try {
            // 1. 查询该日期的所有记录
            LambdaQueryWrapper<CustomerStatisticsData> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(CustomerStatisticsData::getCurDate, curDate);
            List<CustomerStatisticsData> dataList = customerStatisticsDataMapper.selectList(queryWrapper);

            if (dataList == null || dataList.isEmpty()) {
                throw new RuntimeException("未找到日期为 " + curDate + " 的统计数据");
            }

            // 2. 查找关键指标记录
            CustomerStatisticsData totalCostData = findByIndicatorName(dataList, "总成本（当日）");
            CustomerStatisticsData jinFenShuData = findByIndicatorName(dataList, "进粉数（当日）");
            CustomerStatisticsData chengDanShuData = findByIndicatorName(dataList, "成单数（当日）");
            CustomerStatisticsData danTiaoCostData = findByIndicatorName(dataList, "单条成本（当日）");
            CustomerStatisticsData chengDanCostData = findByIndicatorName(dataList, "成单成本（当日）");

            // 3. 根据type类型处理成本更新
            BigDecimal actualTotalCost;
            if ("single".equals(type)) {
                String jinFenShuStr = getFieldValue(jinFenShuData, titleAttr);
                if (jinFenShuStr != null && !jinFenShuStr.trim().isEmpty()) {
                    BigDecimal jinFenShu = new BigDecimal(jinFenShuStr);
                    actualTotalCost = totalCost.multiply(jinFenShu).setScale(2, RoundingMode.HALF_UP);
                } else {
                    throw new RuntimeException("进粉数为空，无法计算总成本");
                }
                setFieldValue(danTiaoCostData, titleAttr, totalCost.toString());
                customerStatisticsDataMapper.updateById(danTiaoCostData);
            } else {
                actualTotalCost = totalCost;
            }

            // 4. 更新总成本
            setFieldValue(totalCostData, titleAttr, actualTotalCost.toString());
            customerStatisticsDataMapper.updateById(totalCostData);

            // 5. 获取进粉数和成单数
            String jinFenShuStr = getFieldValue(jinFenShuData, titleAttr);
            String chengDanShuStr = getFieldValue(chengDanShuData, titleAttr);

            // 6. 计算并更新单条成本（仅在非single模式下更新）
            if (!"single".equals(type)) {
                if (jinFenShuStr != null && !jinFenShuStr.trim().isEmpty()) {
                    BigDecimal jinFenShu = new BigDecimal(jinFenShuStr);
                    if (jinFenShu.compareTo(BigDecimal.ZERO) > 0) {
                        BigDecimal danTiaoCost = actualTotalCost.divide(jinFenShu, 2, RoundingMode.HALF_UP);
                        setFieldValue(danTiaoCostData, titleAttr, danTiaoCost.toString());
                        customerStatisticsDataMapper.updateById(danTiaoCostData);
                    } else {
                        setFieldValue(danTiaoCostData, titleAttr, "0");
                        customerStatisticsDataMapper.updateById(danTiaoCostData);
                    }
                }
            }

            // 7. 计算并更新成单成本
            if (chengDanShuStr != null && !chengDanShuStr.trim().isEmpty()) {
                BigDecimal chengDanShu = new BigDecimal(chengDanShuStr);
                if (chengDanShu.compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal chengDanCost = actualTotalCost.divide(chengDanShu, 2, RoundingMode.HALF_UP);
                    setFieldValue(chengDanCostData, titleAttr, chengDanCost.toString());
                    customerStatisticsDataMapper.updateById(chengDanCostData);
                } else {
                    setFieldValue(chengDanCostData, titleAttr, "0");
                    customerStatisticsDataMapper.updateById(chengDanCostData);
                }
            }

            return 1;
        } catch (Exception e) {
            throw new RuntimeException("更新成本数据失败: " + e.getMessage(), e);
        }
    }

    /**
     * 根据指标名称查找记录
     */
    private CustomerStatisticsData findByIndicatorName(List<CustomerStatisticsData> dataList, String indicatorName) {
        for (CustomerStatisticsData data : dataList) {
            if (indicatorName.equals(data.getIndicatorName())) {
                return data;
            }
        }
        throw new RuntimeException("未找到指标: " + indicatorName);
    }

    /**
     * 动态获取字段值
     */
    private String getFieldValue(CustomerStatisticsData data, String fieldName) {
        try {
            Field field = CustomerStatisticsData.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            Object value = field.get(data);
            return value != null ? value.toString() : null;
        } catch (Exception e) {
            throw new RuntimeException("获取字段值失败: " + fieldName, e);
        }
    }

    /**
     * 动态获取字段值
     */
    private String getFieldValue(CustomerStatisticsDataVO data, String fieldName) {
        try {
            Field field = CustomerStatisticsDataVO.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            Object value = field.get(data);
            return value != null ? value.toString() : null;
        } catch (Exception e) {
            throw new RuntimeException("获取字段值失败: " + fieldName, e);
        }
    }
    /**
     * 动态设置字段值
     */
    private void setFieldValue(CustomerStatisticsDataVO data, String fieldName, String value) {
        try {
            Field field = CustomerStatisticsDataVO.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(data, value);
        } catch (Exception e) {
            throw new RuntimeException("设置字段值失败: " + fieldName, e);
        }
    }

    private void setFieldValue(CustomerStatisticsData data, String fieldName, String value) {
        try {
            Field field = CustomerStatisticsData.class.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(data, value);
        } catch (Exception e) {
            throw new RuntimeException("设置字段值失败: " + fieldName, e);
        }
    }

    @Override
    public List<CustomerStatisticsDataVO> selectByWeekAggregation(String corpId, Integer year, Integer week, String indicatorName) {
        log.info("========== V1周聚合查询开始 ==========");
        log.info("参数: corpId={}, year={}, week={}, indicatorName={}", corpId, year, week, indicatorName);
        
        // 计算周范围（修复跨年问题）
        Date[] weekRange = calculateWeekRangeFixed(year, week);
        if (weekRange == null) {
            // 如果周范围无效（跨年），返回空列表
            log.info("周范围无效（跨年），返回空列表");
            return new ArrayList<>();
        }
        Date startDate = weekRange[0];
        Date endDate = weekRange[1];
        log.info("周日期范围: {} 至 {}", startDate, endDate);
        
        // 使用日期范围查询（修复跨年周问题）
        List<CustomerStatisticsData> dailyDataList = customerStatisticsDataMapper.selectDailyDataByWeekRange(corpId, startDate, endDate, indicatorName);
        log.info("查询到原始数据: {}条", dailyDataList != null ? dailyDataList.size() : 0);
        
        if (dailyDataList != null && !dailyDataList.isEmpty()) {
            // 按指标分组统计
            Map<String, Long> indicatorCount = dailyDataList.stream()
                    .collect(Collectors.groupingBy(CustomerStatisticsData::getIndicatorName, Collectors.counting()));
            log.info("指标分布: {}", indicatorCount);
            
            // 查看第一条数据的详细信息
            CustomerStatisticsData first = dailyDataList.get(0);
            log.info("第一条数据: date={}, indicator={}, ntfGroup={}, ofhGroup={}, wa1Group={}, xb1Group={}",
                    first.getCurDate(), first.getIndicatorName(), 
                    first.getNtfGroup(), first.getOfhGroup(), first.getWa1Group(), first.getXb1Group());
        }
        
        List<CustomerStatisticsDataVO> result = aggregateDataList(dailyDataList, year, week, null);
        log.info("聚合后结果: {}条", result != null ? result.size() : 0);
        log.info("========== V1周聚合查询结束 ==========");
        return result;
    }

    /**
     * 计算周范围（修复跨年问题）
     * 规则：
     * 1. 周的第一天是周一（不是周日）
     * 2. 第一周：从1月1日开始，到1月1日所在周的周日结束
     *    - 如果1月1日是周日，第一周只有1天（1月1日当天）
     * 3. 最后一周：从最后一周的周一（12月31日往前推）开始，到12月31日结束
     *    - 如果12月31日是周一，最后一周只有1天（12月31日当天）
     * 4. 其他周：按正常的周一到周日计算
     */
    private Date[] calculateWeekRangeFixed(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};
    }

    @Override
    public List<CustomerStatisticsDataVO> selectByMonthAggregation(String corpId, String yearMonth, String indicatorName) {
        log.info("按月聚合查询 - corpId: {}, yearMonth: {}, indicatorName: {}", corpId, yearMonth, indicatorName);
        List<CustomerStatisticsData> dailyDataList = customerStatisticsDataMapper.selectDailyDataByMonth(corpId, yearMonth, indicatorName);
        log.info("查询到 {} 条原始数据", dailyDataList != null ? dailyDataList.size() : 0);
        if (dailyDataList != null && !dailyDataList.isEmpty()) {
            log.info("第一条数据: indicatorName={}, ntfGroup={}, ofhGroup={}", 
                    dailyDataList.get(0).getIndicatorName(), 
                    dailyDataList.get(0).getNtfGroup(), 
                    dailyDataList.get(0).getOfhGroup());
        }
        return aggregateDataList(dailyDataList, null, null, yearMonth);
    }

    @Override
    public List<CustomerStatisticsDataVO> selectAllAggregation(String corpId, String indicatorName) {
        List<CustomerStatisticsData> dailyDataList = customerStatisticsDataMapper.selectAllDailyData(corpId, indicatorName);
        return aggregateAllData(dailyDataList);
    }

    private List<CustomerStatisticsDataVO> aggregateAllData(List<CustomerStatisticsData> dailyDataList) {
        if (dailyDataList == null || dailyDataList.isEmpty()) {
            return new ArrayList<>();
        }

        Map<String, List<CustomerStatisticsData>> groupByIndicator = dailyDataList.stream()
                .collect(Collectors.groupingBy(CustomerStatisticsData::getIndicatorName));

        List<CustomerStatisticsDataVO> allAggregatedList = new ArrayList<>();
        Map<String, CustomerStatisticsDataVO> indicatorMap = new java.util.HashMap<>();
        Map<String, Boolean> hiddenFlagMap = new java.util.HashMap<>();

        for (List<CustomerStatisticsData> indicatorDataList : groupByIndicator.values()) {
            CustomerStatisticsData firstData = indicatorDataList.get(0);
            String indicatorName = firstData.getIndicatorName();
            
            CustomerStatisticsDataVO aggregated = new CustomerStatisticsDataVO();
            aggregated.setIndicatorName(indicatorName);
            aggregated.setSortNo(firstData.getSortNo());

            hiddenFlagMap.put(indicatorName, firstData.getHiddenFlag());

            String[] groupFields = {"ntfGroup", "ofhGroup", "pswGroup", "wa1Group", "xb1Group", 
                    "yc1Group", "zd1Group", "aaGroup", "acGroup", "adGroup", "aeGroup"};

            boolean isPercentIndicator = indicatorName.contains("占比") || indicatorName.contains("转化率");
            boolean isDerivedCostIndicator = indicatorName.equals("单条成本（当日）") || indicatorName.equals("成单成本（当日）");

            if (!isPercentIndicator && !isDerivedCostIndicator) {
                for (String field : groupFields) {
                    BigDecimal sum = BigDecimal.ZERO;
                    boolean hasValue = false;
                    for (CustomerStatisticsData data : indicatorDataList) {
                        String value = getFieldValue(data, field);
                        if (value != null && !value.trim().isEmpty()) {
                            String cleanValue = value.replace("%", "").trim();
                            if (cleanValue.equals("需手工填写")) {
                                continue;
                            }
                            if (cleanValue.matches("-?\\d+(\\.\\d+)?")) {
                                try {
                                    sum = sum.add(new BigDecimal(cleanValue));
                                    hasValue = true;
                                } catch (NumberFormatException e) {
                                }
                            }
                        }
                    }
                    if (hasValue) {
                        setFieldValue(aggregated, field, sum.setScale(2, RoundingMode.HALF_UP).toString());
                    } else if (indicatorName.equals("总成本（当日）")) {
                        setFieldValue(aggregated, field, "0");
                    }
                }
            }

            allAggregatedList.add(aggregated);
            indicatorMap.put(indicatorName, aggregated);
        }

        recalculateCostIndicators(indicatorMap);

        List<CustomerStatisticsDataVO> result = new ArrayList<>();
        for (CustomerStatisticsDataVO vo : allAggregatedList) {
            Boolean hidden = hiddenFlagMap.get(vo.getIndicatorName());
            if (!Boolean.TRUE.equals(hidden)) {
                result.add(vo);
            }
        }

        result.sort((a, b) -> Integer.compare(a.getSortNo(), b.getSortNo()));

        return result;
    }

    private List<CustomerStatisticsDataVO> aggregateDataList(List<CustomerStatisticsData> dailyDataList, Integer year, Integer week, String yearMonth) {
        if (dailyDataList == null || dailyDataList.isEmpty()) {
            return new ArrayList<>();
        }

        Map<String, List<CustomerStatisticsData>> groupByIndicator = dailyDataList.stream()
                .collect(Collectors.groupingBy(CustomerStatisticsData::getIndicatorName));

        List<CustomerStatisticsDataVO> allAggregatedList = new ArrayList<>();
        Map<String, CustomerStatisticsDataVO> indicatorMap = new java.util.HashMap<>();
        Map<String, Boolean> hiddenFlagMap = new java.util.HashMap<>();

        for (List<CustomerStatisticsData> indicatorDataList : groupByIndicator.values()) {
            CustomerStatisticsData firstData = indicatorDataList.get(0);
            String indicatorName = firstData.getIndicatorName();
            
            CustomerStatisticsDataVO aggregated = aggregateIndicatorData(indicatorDataList, year, week, yearMonth);
            allAggregatedList.add(aggregated);
            indicatorMap.put(indicatorName, aggregated);
            hiddenFlagMap.put(indicatorName, firstData.getHiddenFlag());
        }

        recalculateCostIndicators(indicatorMap);

        List<CustomerStatisticsDataVO> result = new ArrayList<>();
        for (CustomerStatisticsDataVO vo : allAggregatedList) {
            Boolean hidden = hiddenFlagMap.get(vo.getIndicatorName());
            if (!Boolean.TRUE.equals(hidden)) {
                result.add(vo);
            }
        }

        result.sort((a, b) -> Integer.compare(a.getSortNo(), b.getSortNo()));

        return result;
    }

    private CustomerStatisticsDataVO aggregateIndicatorData(List<CustomerStatisticsData> dailyList, Integer year, Integer week, String yearMonth) {
        CustomerStatisticsDataVO result = new CustomerStatisticsDataVO();
        String indicatorName = dailyList.get(0).getIndicatorName();
        result.setIndicatorName(indicatorName);
        result.setSortNo(dailyList.get(0).getSortNo());

        log.info("聚合指标: {}, 数据条数: {}", indicatorName, dailyList.size());

        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        
        if (year != null && week != null) {
            result.setYearWeek(year + "年第" + week + "周");
            WeekFields weekFields = WeekFields.of(DayOfWeek.MONDAY, 4);
            LocalDate startDate = LocalDate.of(year, 1, 1)
                    .with(weekFields.weekOfYear(), week)
                    .with(DayOfWeek.MONDAY);
            LocalDate endDate = startDate.plusDays(6);
            result.setDateRange(startDate.format(formatter) + " 至 " + endDate.format(formatter));
        } else if (yearMonth != null) {
            result.setYearMonth(yearMonth.substring(0, 4) + "年" + yearMonth.substring(5) + "月");
            LocalDate startDate = LocalDate.parse(yearMonth + "-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
            LocalDate endDate = startDate.withDayOfMonth(startDate.lengthOfMonth());
            result.setDateRange(startDate.format(formatter) + " 至 " + endDate.format(formatter));
        }

        String[] groupFields = {"ntfGroup", "ofhGroup", "pswGroup", "wa1Group", "xb1Group", 
                "yc1Group", "zd1Group", "aaGroup", "acGroup", "adGroup", "aeGroup"};

        boolean isPercentIndicator = indicatorName.contains("占比") || indicatorName.contains("转化率");
        boolean isDerivedCostIndicator = indicatorName.equals("单条成本（当日）") || indicatorName.equals("成单成本（当日）");

        if (isPercentIndicator) {
            log.info("指标 {} 是占比指标，跳过聚合", indicatorName);
            return result;
        }

        if (isDerivedCostIndicator) {
            log.info("指标 {} 是派生成本指标，跳过聚合", indicatorName);
            return result;
        }

        // 针对成单数和进粉数添加详细日志
        boolean isTargetIndicator = indicatorName.equals("成单数（当日）") || indicatorName.equals("进粉数（当日）");
        if (isTargetIndicator) {
            log.info("========== 开始聚合指标: {} ==========", indicatorName);
        }
        
        for (String field : groupFields) {
            BigDecimal sum = BigDecimal.ZERO;
            boolean hasValue = false;

            for (CustomerStatisticsData data : dailyList) {
                String value = getFieldValue(data, field);
                
                if (value != null && !value.trim().isEmpty()) {
                    String cleanValue = value.replace("%", "").trim();
                    if (indicatorName.equals("总成本（当日）") && !cleanValue.equals("需手工填写")) {
                        log.info("总成本数据 - curDate: {}, 字段: {}, 原始值: {}, 清理后: {}", 
                                data.getCurDate(), field, value, cleanValue);
                    }
                    if (cleanValue.equals("需手工填写")) {
                        continue;
                    }
                    if (cleanValue.matches("-?\\d+(\\.\\d+)?")) {
                        try {
                            BigDecimal decimalValue = new BigDecimal(cleanValue);
                            sum = sum.add(decimalValue);
                            hasValue = true;

                        } catch (NumberFormatException e) {
                            if (isTargetIndicator) {
                                log.info("  解析失败: {}", cleanValue);
                            }
                        }
                    }
                }
            }
            if (hasValue) {
                setFieldValue(result, field, sum.setScale(2, RoundingMode.HALF_UP).toString());
                if (isTargetIndicator) {
                    log.info("指标 {} 字段 {} 最终聚合值: {}", indicatorName, field, sum.setScale(2, RoundingMode.HALF_UP));
                }
            } else if (indicatorName.equals("总成本（当日）")) {
                setFieldValue(result, field, "0");
            }
        }
        
        if (isTargetIndicator) {
            log.info("========== 结束聚合指标: {} ==========", indicatorName);
        }

        return result;
    }

    private void recalculateCostIndicators(Map<String, CustomerStatisticsDataVO> indicatorMap) {
        CustomerStatisticsDataVO totalCostData = indicatorMap.get("总成本（当日）");
        CustomerStatisticsDataVO jinFenShuData = indicatorMap.get("进粉数（当日）");
        CustomerStatisticsDataVO chengDanShuData = indicatorMap.get("成单数（当日）");
        CustomerStatisticsDataVO danTiaoCostData = indicatorMap.get("单条成本（当日）");
        CustomerStatisticsDataVO chengDanCostData = indicatorMap.get("成单成本（当日）");
        CustomerStatisticsDataVO zhuanHuaLvData = indicatorMap.get("转化率(当日)");
        CustomerStatisticsDataVO jiShiDanZhanBiData = indicatorMap.get("及时单占比(当日)");
        CustomerStatisticsDataVO feiJiShiDanZhanBiData = indicatorMap.get("非及时单占比(当日)");
        CustomerStatisticsDataVO jiaZhangZhanBiData = indicatorMap.get("家长占比（当日）");
        CustomerStatisticsDataVO keHuShuXingData = indicatorMap.get("客户属性数量（当日）");
        CustomerStatisticsDataVO xueShengZhanBiData = indicatorMap.get("学生占比（当日）");
        CustomerStatisticsDataVO weiZhiZhanBiData = indicatorMap.get("未知占比（当日）");
        CustomerStatisticsDataVO laoshiZhanBiData = indicatorMap.get("老师占比（当日）");

        CustomerStatisticsDataVO zhuDongBaoJiaZhanBiData = indicatorMap.get("主动报价占比（当日）");
        CustomerStatisticsDataVO beiDongBaoJiaZhanBiData = indicatorMap.get("被动报价占比（当日）");
        CustomerStatisticsDataVO weiKaiKouBaoJiaZhanBiData = indicatorMap.get("未开口报价占比（当日）");
        CustomerStatisticsDataVO yiShanChuBaoJiaZhanBiData = indicatorMap.get("已删除报价占比（当日）");
        CustomerStatisticsDataVO xiaoXueZhanBiData = indicatorMap.get("小学占比（当日）");
        CustomerStatisticsDataVO chuZhongZhanBiData = indicatorMap.get("初中占比（当日）");
        CustomerStatisticsDataVO gaoZhongZhanBiData = indicatorMap.get("高中占比（当日）");
        CustomerStatisticsDataVO jiaZhangChuDanZhanBiData = indicatorMap.get("家长出单占比（当日）");
        CustomerStatisticsDataVO xueShengChuDanZhanBiData = indicatorMap.get("学生出单占比（当日）");

        CustomerStatisticsDataVO yiXiangDuShuLiangData = indicatorMap.get("意向度数量（当日）");
        CustomerStatisticsDataVO nianJiShuLiangData = indicatorMap.get("年级数量（当日）");

        CustomerStatisticsDataVO jiShiDanShuLiangData = indicatorMap.get("及时单数量(当日)");
        CustomerStatisticsDataVO feiJiShiDanShuLiangData = indicatorMap.get("非及时单数量(当日)");
        CustomerStatisticsDataVO jiaZhangShuLiangData = indicatorMap.get("家长数量（当日）");
        CustomerStatisticsDataVO xueShengShuLiangData = indicatorMap.get("学生数量（当日）");
        CustomerStatisticsDataVO laoshiShuLiangData = indicatorMap.get("老师数量（当日）");
        CustomerStatisticsDataVO weiZhiShuLiangData = indicatorMap.get("未知数量（当日）");
        CustomerStatisticsDataVO zhuDongBaoJiaShuLiangData = indicatorMap.get("主动报价数量（当日）");
        CustomerStatisticsDataVO beiDongBaoJiaShuLiangData = indicatorMap.get("被动报价数量（当日）");
        CustomerStatisticsDataVO weiKaiKouBaoJiaShuLiangData = indicatorMap.get("未开口报价数量（当日）");
        CustomerStatisticsDataVO yiShanChuShuLiangData = indicatorMap.get("已删除数量（当日）");
        CustomerStatisticsDataVO xiaoXueShuLiangData = indicatorMap.get("小学数量（当日）");
        CustomerStatisticsDataVO chuZhongShuLiangData = indicatorMap.get("初中数量（当日）");
        CustomerStatisticsDataVO gaoZhongShuLiangData = indicatorMap.get("高中数量（当日）");
        CustomerStatisticsDataVO jiaZhangChuDanShuLiangData = indicatorMap.get("家长出单数量（当日）");
        CustomerStatisticsDataVO xueShengChuDanShuLiangData = indicatorMap.get("学生出单数量（当日）");

        CustomerStatisticsDataVO jiazhangChuDanLvData = indicatorMap.get("家长出单率（当日）");
        CustomerStatisticsDataVO jiazhangJishiDanShuLiangData = indicatorMap.get("家长即时单数量（当日）");
        CustomerStatisticsDataVO xueshengChuDanLvData = indicatorMap.get("学生出单率（当日）");
        CustomerStatisticsDataVO xueshengJishiDanShuLiangData = indicatorMap.get("学生即时单数量（当日）");

        String[] groupFields = {"ntfGroup", "ofhGroup", "pswGroup", "wa1Group", "xb1Group", 
                "yc1Group", "zd1Group", "aaGroup", "acGroup", "adGroup", "aeGroup"};

        log.info("开始计算派生指标 - totalCostData: {}, jinFenShuData: {}, chengDanShuData: {}, danTiaoCostData: {}, chengDanCostData: {}",
                totalCostData != null, jinFenShuData != null, chengDanShuData != null, danTiaoCostData != null, chengDanCostData != null);

        if (totalCostData != null) {
            log.info("总成本数据: ntfGroup={}, ofhGroup={}", totalCostData.getNtfGroup(), totalCostData.getOfhGroup());
        }
        if (jinFenShuData != null) {
            log.info("进粉数数据: ntfGroup={}, ofhGroup={}", jinFenShuData.getNtfGroup(), jinFenShuData.getOfhGroup());
        }
        if (chengDanShuData != null) {
            log.info("成单数数据: ntfGroup={}, ofhGroup={}", chengDanShuData.getNtfGroup(), chengDanShuData.getOfhGroup());
        }

        if (danTiaoCostData != null && totalCostData != null && jinFenShuData != null) {
            for (String field : groupFields) {
                String totalCostStr = getFieldValue(totalCostData, field);
                String jinFenShuStr = getFieldValue(jinFenShuData, field);
                log.debug("计算单条成本 - 字段: {}, 总成本: {}, 进粉数: {}", field, totalCostStr, jinFenShuStr);
                if (totalCostStr != null && jinFenShuStr != null) {
                    try {
                        BigDecimal totalCost = parseCostValue(totalCostStr);
                        BigDecimal jinFenShu = new BigDecimal(jinFenShuStr);
                        log.info("计算单条成本 - 字段: {}, 总成本: {}, 进粉数: {}", field, totalCost, jinFenShu);
                        if (jinFenShu.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal danTiaoCost = totalCost.divide(jinFenShu, 2, RoundingMode.HALF_UP);
                            setFieldValue(danTiaoCostData, field, danTiaoCost.toString());
                            log.info("单条成本计算结果 - 字段: {}, 值: {}", field, danTiaoCost);
                        } else {
                            setFieldValue(danTiaoCostData, field, "0");
                        }
                    } catch (NumberFormatException e) {
                        log.warn("计算单条成本失败 - 字段: {}, 错误: {}", field, e.getMessage());
                    }
                }
            }
        }

        if (chengDanCostData != null && totalCostData != null && chengDanShuData != null) {
            for (String field : groupFields) {
                String totalCostStr = getFieldValue(totalCostData, field);
                String chengDanShuStr = getFieldValue(chengDanShuData, field);
                log.debug("计算成单成本 - 字段: {}, 总成本: {}, 成单数: {}", field, totalCostStr, chengDanShuStr);
                if (totalCostStr != null && chengDanShuStr != null) {
                    try {
                        BigDecimal totalCost = parseCostValue(totalCostStr);
                        BigDecimal chengDanShu = new BigDecimal(chengDanShuStr);
                        log.info("计算成单成本 - 字段: {}, 总成本: {}, 成单数: {}", field, totalCost, chengDanShu);
                        if (chengDanShu.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal chengDanCost = totalCost.divide(chengDanShu, 2, RoundingMode.HALF_UP);
                            setFieldValue(chengDanCostData, field, chengDanCost.toString());
                            log.info("成单成本计算结果 - 字段: {}, 值: {}", field, chengDanCost);
                        } else {
                            setFieldValue(chengDanCostData, field, "0");
                        }
                    } catch (NumberFormatException e) {
                        log.warn("计算成单成本失败 - 字段: {}, 错误: {}", field, e.getMessage());
                    }
                }
            }
        }

        if (zhuanHuaLvData != null && chengDanShuData != null && jinFenShuData != null) {
            for (String field : groupFields) {
                String chengDanShuStr = getFieldValue(chengDanShuData, field);
                String jinFenShuStr = getFieldValue(jinFenShuData, field);
                if (chengDanShuStr != null && jinFenShuStr != null) {
                    try {
                        BigDecimal chengDanShu = new BigDecimal(chengDanShuStr);
                        BigDecimal jinFenShu = new BigDecimal(jinFenShuStr);
                        if (jinFenShu.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhuanHuaLv = chengDanShu.divide(jinFenShu, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(zhuanHuaLvData, field, zhuanHuaLv + "%");
                        } else {
                            setFieldValue(zhuanHuaLvData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (jiShiDanZhanBiData != null && jiShiDanShuLiangData != null && chengDanShuData != null) {
            for (String field : groupFields) {
                String jiShiDanStr = getFieldValue(jiShiDanShuLiangData, field);
                String chengDanShuStr = getFieldValue(chengDanShuData, field);
                if (jiShiDanStr != null && chengDanShuStr != null) {
                    try {
                        BigDecimal jiShiDan = new BigDecimal(jiShiDanStr);
                        BigDecimal chengDanShu = new BigDecimal(chengDanShuStr);
                        if (chengDanShu.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = jiShiDan.divide(chengDanShu, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(jiShiDanZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(jiShiDanZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (feiJiShiDanZhanBiData != null && feiJiShiDanShuLiangData != null && chengDanShuData != null) {
            for (String field : groupFields) {
                String feiJiShiDanStr = getFieldValue(feiJiShiDanShuLiangData, field);
                String chengDanShuStr = getFieldValue(chengDanShuData, field);
                if (feiJiShiDanStr != null && chengDanShuStr != null) {
                    try {
                        BigDecimal feiJiShiDan = new BigDecimal(feiJiShiDanStr);
                        BigDecimal chengDanShu = new BigDecimal(chengDanShuStr);
                        if (chengDanShu.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = feiJiShiDan.divide(chengDanShu, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(feiJiShiDanZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(feiJiShiDanZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (keHuShuXingData != null && jiaZhangShuLiangData != null && laoshiShuLiangData != null  && xueShengShuLiangData != null && weiZhiShuLiangData != null) {
            for (String field : groupFields) {
                String jiaZhangStr = getFieldValue(jiaZhangShuLiangData, field);
                String xueShengStr = getFieldValue(xueShengShuLiangData, field);
                String laoShiStr = getFieldValue(laoshiShuLiangData, field);
                String weiZhiStr = getFieldValue(weiZhiShuLiangData, field);
                try {
                    BigDecimal jiaZhang = jiaZhangStr != null ? new BigDecimal(jiaZhangStr) : BigDecimal.ZERO;
                    BigDecimal xueSheng = xueShengStr != null ? new BigDecimal(xueShengStr) : BigDecimal.ZERO;
                    BigDecimal laoshi = laoShiStr != null ? new BigDecimal(laoShiStr) : BigDecimal.ZERO;
                    BigDecimal weiZhi = weiZhiStr != null ? new BigDecimal(weiZhiStr) : BigDecimal.ZERO;
                    BigDecimal total = jiaZhang.add(xueSheng).add(weiZhi).add(laoshi);
                    setFieldValue(keHuShuXingData, field, total.setScale(0, RoundingMode.HALF_UP).toString());
                } catch (NumberFormatException e) {
                }
            }
        }

        if (jiaZhangZhanBiData != null && jiaZhangShuLiangData != null && keHuShuXingData != null ) {
            for (String field : groupFields) {
                String jiaZhangStr = getFieldValue(jiaZhangShuLiangData, field);
                String keHuShuXingStr = getFieldValue(keHuShuXingData, field);
                if (jiaZhangStr != null && keHuShuXingStr != null) {
                    try {
                        BigDecimal jiaZhang = new BigDecimal(jiaZhangStr);
                        BigDecimal keHuShuXing = new BigDecimal(keHuShuXingStr);
                        if (keHuShuXing.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = jiaZhang.divide(keHuShuXing, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(jiaZhangZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(jiaZhangZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (xueShengZhanBiData != null && xueShengShuLiangData != null && keHuShuXingData != null) {
            for (String field : groupFields) {
                String xueShengStr = getFieldValue(xueShengShuLiangData, field);
                String keHuShuXingStr = getFieldValue(keHuShuXingData, field);
                if (xueShengStr != null && keHuShuXingStr != null) {
                    try {
                        BigDecimal xueSheng = new BigDecimal(xueShengStr);
                        BigDecimal keHuShuXing = new BigDecimal(keHuShuXingStr);
                        if (keHuShuXing.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = xueSheng.divide(keHuShuXing, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(xueShengZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(xueShengZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (weiZhiZhanBiData != null && weiZhiShuLiangData != null && keHuShuXingData != null) {
            for (String field : groupFields) {
                String weiZhiStr = getFieldValue(weiZhiShuLiangData, field);
                String keHuShuXingStr = getFieldValue(keHuShuXingData, field);
                if (weiZhiStr != null && keHuShuXingStr != null) {
                    try {
                        BigDecimal weiZhi = new BigDecimal(weiZhiStr);
                        BigDecimal keHuShuXing = new BigDecimal(keHuShuXingStr);
                        if (keHuShuXing.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = weiZhi.divide(keHuShuXing, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(weiZhiZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(weiZhiZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }


        if (laoshiZhanBiData != null && laoshiShuLiangData != null && keHuShuXingData != null) {
            for (String field : groupFields) {
                String laoshiStr = getFieldValue(laoshiShuLiangData, field);
                String keHuShuXingStr = getFieldValue(keHuShuXingData, field);
                if (laoshiStr != null && keHuShuXingStr != null) {
                    try {
                        BigDecimal laoshi = new BigDecimal(laoshiStr);
                        BigDecimal keHuShuXing = new BigDecimal(keHuShuXingStr);
                        if (keHuShuXing.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = laoshi.divide(keHuShuXing, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(laoshiZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(laoshiZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (zhuDongBaoJiaZhanBiData != null && zhuDongBaoJiaShuLiangData != null && yiXiangDuShuLiangData != null) {
            for (String field : groupFields) {
                String zhuDongStr = getFieldValue(zhuDongBaoJiaShuLiangData, field);
                String yiXiangDuStr = getFieldValue(yiXiangDuShuLiangData, field);
                if (zhuDongStr != null && yiXiangDuStr != null) {
                    try {
                        BigDecimal zhuDong = new BigDecimal(zhuDongStr);
                        BigDecimal yiXiangDu = new BigDecimal(yiXiangDuStr);
                        if (yiXiangDu.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = zhuDong.divide(yiXiangDu, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(zhuDongBaoJiaZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(zhuDongBaoJiaZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (beiDongBaoJiaZhanBiData != null && beiDongBaoJiaShuLiangData != null && yiXiangDuShuLiangData != null) {
            for (String field : groupFields) {
                String beiDongStr = getFieldValue(beiDongBaoJiaShuLiangData, field);
                String yiXiangDuStr = getFieldValue(yiXiangDuShuLiangData, field);
                if (beiDongStr != null && yiXiangDuStr != null) {
                    try {
                        BigDecimal beiDong = new BigDecimal(beiDongStr);
                        BigDecimal yiXiangDu = new BigDecimal(yiXiangDuStr);
                        if (yiXiangDu.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = beiDong.divide(yiXiangDu, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(beiDongBaoJiaZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(beiDongBaoJiaZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (weiKaiKouBaoJiaZhanBiData != null && weiKaiKouBaoJiaShuLiangData != null && yiXiangDuShuLiangData != null) {
            for (String field : groupFields) {
                String weiKaiKouStr = getFieldValue(weiKaiKouBaoJiaShuLiangData, field);
                String yiXiangDuStr = getFieldValue(yiXiangDuShuLiangData, field);
                if (weiKaiKouStr != null && yiXiangDuStr != null) {
                    try {
                        BigDecimal weiKaiKou = new BigDecimal(weiKaiKouStr);
                        BigDecimal yiXiangDu = new BigDecimal(yiXiangDuStr);
                        if (yiXiangDu.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = weiKaiKou.divide(yiXiangDu, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(weiKaiKouBaoJiaZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(weiKaiKouBaoJiaZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (yiShanChuBaoJiaZhanBiData != null && yiShanChuShuLiangData != null && yiXiangDuShuLiangData != null) {
            for (String field : groupFields) {
                String yiShanChuStr = getFieldValue(yiShanChuShuLiangData, field);
                String yiXiangDuStr = getFieldValue(yiXiangDuShuLiangData, field);
                if (yiShanChuStr != null && yiXiangDuStr != null) {
                    try {
                        BigDecimal yiShanChu = new BigDecimal(yiShanChuStr);
                        BigDecimal yiXiangDu = new BigDecimal(yiXiangDuStr);
                        if (yiXiangDu.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = yiShanChu.divide(yiXiangDu, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(yiShanChuBaoJiaZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(yiShanChuBaoJiaZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (xiaoXueZhanBiData != null && xiaoXueShuLiangData != null && nianJiShuLiangData != null) {
            for (String field : groupFields) {
                String xiaoXueStr = getFieldValue(xiaoXueShuLiangData, field);
                String nianJiStr = getFieldValue(nianJiShuLiangData, field);
                if (xiaoXueStr != null && nianJiStr != null) {
                    try {
                        BigDecimal xiaoXue = new BigDecimal(xiaoXueStr);
                        BigDecimal nianJi = new BigDecimal(nianJiStr);
                        if (nianJi.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = xiaoXue.divide(nianJi, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(xiaoXueZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(xiaoXueZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (chuZhongZhanBiData != null && chuZhongShuLiangData != null && nianJiShuLiangData != null) {
            for (String field : groupFields) {
                String chuZhongStr = getFieldValue(chuZhongShuLiangData, field);
                String nianJiStr = getFieldValue(nianJiShuLiangData, field);
                if (chuZhongStr != null && nianJiStr != null) {
                    try {
                        BigDecimal chuZhong = new BigDecimal(chuZhongStr);
                        BigDecimal nianJi = new BigDecimal(nianJiStr);
                        if (nianJi.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = chuZhong.divide(nianJi, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(chuZhongZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(chuZhongZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (gaoZhongZhanBiData != null && gaoZhongShuLiangData != null && nianJiShuLiangData != null) {
            for (String field : groupFields) {
                String gaoZhongStr = getFieldValue(gaoZhongShuLiangData, field);
                String nianJiStr = getFieldValue(nianJiShuLiangData, field);
                if (gaoZhongStr != null && nianJiStr != null) {
                    try {
                        BigDecimal gaoZhong = new BigDecimal(gaoZhongStr);
                        BigDecimal nianJi = new BigDecimal(nianJiStr);
                        if (nianJi.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = gaoZhong.divide(nianJi, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(gaoZhongZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(gaoZhongZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (jiazhangChuDanLvData != null && jiaZhangShuLiangData != null && jiazhangJishiDanShuLiangData != null) {
            for (String field : groupFields) {
                String jiazhangJishidanStr = getFieldValue(jiazhangJishiDanShuLiangData, field);
                String jiazhangShuLiangStr = getFieldValue(jiaZhangShuLiangData, field);
                if (jiazhangJishidanStr != null && jiazhangShuLiangStr != null) {
                    try {
                        BigDecimal jiasZhangJishidan = new BigDecimal(jiazhangJishidanStr);
                        BigDecimal jiazhangshuliang = new BigDecimal(jiazhangShuLiangStr);
                        if (jiazhangshuliang.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = jiasZhangJishidan.divide(jiazhangshuliang, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(jiazhangChuDanLvData, field, zhanBi + "%");
                        } else {
                            setFieldValue(jiazhangChuDanLvData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }


        if (xueshengChuDanLvData != null && xueShengShuLiangData != null && xueshengJishiDanShuLiangData != null) {
            for (String field : groupFields) {
                String xueshengJishidanStr = getFieldValue(xueshengJishiDanShuLiangData, field);
                String xueshengShuLiangStr = getFieldValue(xueShengShuLiangData, field);
                if (xueshengJishidanStr != null && xueshengShuLiangStr != null) {
                    try {
                        BigDecimal xueshengJishidan = new BigDecimal(xueshengJishidanStr);
                        BigDecimal xueshengshuliang = new BigDecimal(xueshengShuLiangStr);
                        if (xueshengshuliang.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = xueshengJishidan.divide(xueshengshuliang, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(xueshengChuDanLvData, field, zhanBi + "%");
                        } else {
                            setFieldValue(xueshengChuDanLvData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

 /*       if (jiaZhangChuDanZhanBiData != null && jiaZhangChuDanShuLiangData != null && jiaZhangShuLiangData != null) {
            for (String field : groupFields) {
                String jiaZhangChuDanStr = getFieldValue(jiaZhangChuDanShuLiangData, field);
                String jiaZhangStr = getFieldValue(jiaZhangShuLiangData, field);
                if (jiaZhangChuDanStr != null && jiaZhangStr != null) {
                    try {
                        BigDecimal jiaZhangChuDan = new BigDecimal(jiaZhangChuDanStr);
                        BigDecimal jiaZhang = new BigDecimal(jiaZhangStr);
                        if (jiaZhang.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = jiaZhangChuDan.divide(jiaZhang, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(jiaZhangChuDanZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(jiaZhangChuDanZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }

        if (xueShengChuDanZhanBiData != null && xueShengChuDanShuLiangData != null && xueShengShuLiangData != null) {
            for (String field : groupFields) {
                String xueShengChuDanStr = getFieldValue(xueShengChuDanShuLiangData, field);
                String xueShengStr = getFieldValue(xueShengShuLiangData, field);
                if (xueShengChuDanStr != null && xueShengStr != null) {
                    try {
                        BigDecimal xueShengChuDan = new BigDecimal(xueShengChuDanStr);
                        BigDecimal xueSheng = new BigDecimal(xueShengStr);
                        if (xueSheng.compareTo(BigDecimal.ZERO) > 0) {
                            BigDecimal zhanBi = xueShengChuDan.divide(xueSheng, 4, RoundingMode.HALF_UP)
                                    .multiply(new BigDecimal("100"))
                                    .setScale(2, RoundingMode.HALF_UP);
                            setFieldValue(xueShengChuDanZhanBiData, field, zhanBi + "%");
                        } else {
                            setFieldValue(xueShengChuDanZhanBiData, field, "0%");
                        }
                    } catch (NumberFormatException e) {
                    }
                }
            }
        }*/
    }

    private BigDecimal parseCostValue(String value) {
        if (value == null || value.trim().isEmpty()) {
            return BigDecimal.ZERO;
        }
        String cleanValue = value.trim();
        if (cleanValue.equals("需手工填写") || !cleanValue.matches("-?\\d+(\\.\\d+)?")) {
            return BigDecimal.ZERO;
        }
        try {
            return new BigDecimal(cleanValue);
        } catch (NumberFormatException e) {
            return BigDecimal.ZERO;
        }
    }

}
