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 tankaikai
 * @since 2025-03-07 16:08
 */
@NoArgsConstructor
@Data
public class TotalVo implements Serializable {

    @Serial
    private static final long serialVersionUID = 1L;

    /**
     * 实收金额
     */
    private BigDecimal actualAmount = BigDecimal.ZERO;
    /**
     * 优惠金额
     */
    private BigDecimal discountAmount = BigDecimal.ZERO;
    /**
     * 订单金额
     */
    private BigDecimal orderAmount = BigDecimal.ZERO;
    /**
     * 日期
     */
    @JsonFormat(pattern = "yyyy-MM-dd")
    private LocalDate tradeDay;


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

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

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

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

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