package com.czg.order.vo;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serial;
import java.io.Serializable;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.*;


/**
 * 毛利率/净利率 柱状图 左下下
 * 利润率柱状图
 *
 * @author ww
 */
@Data
@NoArgsConstructor
public class ProfitRateVO implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 毛利率
     */
    private BigDecimal profitRate;
    /**
     * 净利润率
     */
    private BigDecimal netProfitRate;
    /**
     * 日期
     */
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate tradeDay;


    public ProfitRateVO(LocalDate tradeDay) {
        this.tradeDay = tradeDay;
    }

    /**
     * 合并实时数据和历史数据，并填充缺失的日期
     */
    public static List<ProfitRateVO> mergeAndFillData(ProfitRateVO onlineData, List<ProfitRateVO> historyData,
                                                      LocalDate startDate, LocalDate endDate) {
        // 创建日期到数据的映射，方便查找
        Map<LocalDate, ProfitRateVO> dataMap = new HashMap<>();

        // 将历史数据放入映射
        for (ProfitRateVO vo : historyData) {
            if (vo.getTradeDay() != null) {
                dataMap.put(vo.getTradeDay(), vo);
            }
        }
        dataMap.put(onlineData.getTradeDay(), onlineData);

        List<ProfitRateVO> result = new ArrayList<>();
        LocalDate currentDay = startDate;

        while (!currentDay.isAfter(endDate)) {
            if (dataMap.containsKey(currentDay)) {
                result.add(dataMap.get(currentDay));
            } else {
                // 创建空的TotalVo填充缺失的日期
                ProfitRateVO emptyVo = new ProfitRateVO(currentDay);
                result.add(emptyVo);
            }
            currentDay = currentDay.plusDays(1);
        }
        // 按日期排序确保顺序正确
        result.sort(Comparator.comparing(ProfitRateVO::getTradeDay));
        return result;
    }
}
