package com.czg.order.vo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ww
 * @description
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class CountPayTypeVo {
    /**
     * 笔数
     */
    private Integer count;
    /**
     * 支付方式
     */
    private String payType;

    private static final Map<String, String> PAY_TYPE_MAPPING = new LinkedHashMap<>();

    static {
        PAY_TYPE_MAPPING.put("cashPay", "现金支付");
        PAY_TYPE_MAPPING.put("wechatPay", "微信支付");
        PAY_TYPE_MAPPING.put("alipayPay", "支付宝支付");
        PAY_TYPE_MAPPING.put("mainScanPay", "被扫支付");
        PAY_TYPE_MAPPING.put("backScanPay", "主扫支付");

        PAY_TYPE_MAPPING.put("memberPay", "余额支付");
        PAY_TYPE_MAPPING.put("creditPay", "挂账支付");
    }

    /**
     * 实时数据
     */
    public static List<CountPayTypeVo> realTimeDataByDay(Map<String, BigDecimal> realTimeData) {
        List<CountPayTypeVo> result = new ArrayList<>();
        for (Map.Entry<String, String> entry : PAY_TYPE_MAPPING.entrySet()) {
            String payCode = entry.getKey();
            String payName = entry.getValue();

            BigDecimal totalCount = getSafeValue(realTimeData, payCode);
            result.add(new CountPayTypeVo(totalCount.intValue(), payName));
        }

        return result;
    }

    /**
     * 合并实时数据和历史统计数据
     */
    public static List<CountPayTypeVo> mergePayTypeData(Map<String, BigDecimal> realTimeData,
                                                 Map<String, BigDecimal> historyData) {

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

        for (Map.Entry<String, String> entry : PAY_TYPE_MAPPING.entrySet()) {
            String payCode = entry.getKey();
            String payName = entry.getValue();

            BigDecimal realTimeCount = getSafeValue(realTimeData, payCode);
            BigDecimal historyCount = getSafeValue(historyData, payCode);

            BigDecimal totalCount = (realTimeCount != null ? realTimeCount : BigDecimal.ZERO)
                    .add(historyCount != null ? historyCount : BigDecimal.ZERO);

            result.add(new CountPayTypeVo(totalCount.intValue(), payName));

        }

        return result;
    }

    /**
     * 安全获取Map中的值，处理null情况
     */
    private static BigDecimal getSafeValue(Map<String, BigDecimal> data, String key) {
        if (data == null || data.isEmpty()) {
            return null;
        }
        return data.get(key);
    }
}
