package com.jeesharp.business.modules.mall.application.support;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.mall.entity.MallOrder;
import com.jeesharp.business.modules.mall.entity.MallPayBatch;
import com.jeesharp.business.modules.mall.service.MallOrderService;
import com.jeesharp.business.modules.mall.service.MallPayBatchService;
import com.jeesharp.business.modules.mall.vo.MallOrderListVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 合并支付批次展示字段补全，供管理端列表/详情与小程序订单详情复用。
 *
 * @author jeesharp
 * @since 2026-06-10
 */
@Component
@AllArgsConstructor
public class MallPayBatchDisplaySupport {

    private final MallPayBatchService mallPayBatchService;
    private final MallOrderService mallOrderService;

    /**
     * 解析合并支付批次编号（小程序列表展示用）。
     */
    public String resolvePayBatchNo(String payBatchId) {
        if (StrUtil.isBlank(payBatchId)) {
            return "";
        }
        MallPayBatch batch = mallPayBatchService.get(payBatchId.trim());
        return batch != null && StrUtil.isNotBlank(batch.getBatchNo()) ? batch.getBatchNo().trim() : "";
    }

    /**
     * 补全订单详情上的批次号与同批子单数。
     */
    public void enrichForDetail(MallOrder order) {
        if (order == null || StrUtil.isBlank(order.getPayBatchId())) {
            return;
        }
        MallPayBatch batch = mallPayBatchService.get(order.getPayBatchId().trim());
        if (batch != null && StrUtil.isNotBlank(batch.getBatchNo())) {
            order.setPayBatchNo(batch.getBatchNo().trim());
        }
        List<MallOrder> siblings = mallOrderService.listByPayBatchId(order.getPayBatchId());
        order.setPayBatchSubOrderCount(siblings == null ? 0 : siblings.size());
    }

    /**
     * 列表行补全合并支付批次编号。
     */
    public void enrichForList(List<MallOrderListVO> rows) {
        if (CollUtil.isEmpty(rows)) {
            return;
        }
        List<String> batchIds = rows.stream()
                .map(MallOrderListVO::getPayBatchId)
                .filter(StrUtil::isNotBlank)
                .distinct()
                .toList();
        if (batchIds.isEmpty()) {
            return;
        }
        Map<String, MallPayBatch> batchMap = new LinkedHashMap<>();
        for (String batchId : batchIds) {
            MallPayBatch batch = mallPayBatchService.get(batchId);
            if (batch != null) {
                batchMap.put(batchId, batch);
            }
        }
        for (MallOrderListVO row : rows) {
            if (StrUtil.isBlank(row.getPayBatchId())) {
                continue;
            }
            MallPayBatch batch = batchMap.get(row.getPayBatchId().trim());
            if (batch != null && StrUtil.isNotBlank(batch.getBatchNo())) {
                row.setPayBatchNo(batch.getBatchNo().trim());
            }
        }
    }
}
