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.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.util.Date;
import java.util.List;

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

    @Autowired
    private CustomerStatisticsDataMapper customerStatisticsDataMapper;

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

    /**
     * 查询客户统计数据VO列表(用于导出)
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param indicatorName 指标名称
     * @return 客户统计数据VO列表
     */
    @Override
    public List<CustomerStatisticsDataVO> selectCustomerStatisticsDataVOList(Date startDate, Date endDate, String indicatorName) {
        return customerStatisticsDataMapper.selectCustomerStatisticsDataVOList(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(Date curDate, BigDecimal totalCost, 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. 更新总成本
            setFieldValue(totalCostData, titleAttr, totalCost.toString());
            customerStatisticsDataMapper.updateById(totalCostData);

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

            // 5. 计算并更新单条成本
            if (jinFenShuStr != null && !jinFenShuStr.trim().isEmpty()) {
                BigDecimal jinFenShu = new BigDecimal(jinFenShuStr);
                if (jinFenShu.compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal danTiaoCost = totalCost.divide(jinFenShu, 2, RoundingMode.HALF_UP);
                    setFieldValue(danTiaoCostData, titleAttr, danTiaoCost.toString());
                    customerStatisticsDataMapper.updateById(danTiaoCostData);
                } else {
                    setFieldValue(danTiaoCostData, titleAttr, "0");
                    customerStatisticsDataMapper.updateById(danTiaoCostData);
                }
            }

            // 6. 计算并更新成单成本
            if (chengDanShuStr != null && !chengDanShuStr.trim().isEmpty()) {
                BigDecimal chengDanShu = new BigDecimal(chengDanShuStr);
                if (chengDanShu.compareTo(BigDecimal.ZERO) > 0) {
                    BigDecimal chengDanCost = totalCost.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 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);
        }
    }

}
