package cn.iocoder.yudao.module.inspection.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.iocoder.yudao.module.inspection.entity.InspectionBatchSettlementOrder;
import cn.iocoder.yudao.module.inspection.entity.InspectionBatchSettlementOrderQuery;
import cn.iocoder.yudao.module.inspection.entity.InspectionBatchSettlementOrderQueryVo;
import cn.iocoder.yudao.module.inspection.mapper.InspectionBatchSettlementOrderMapper;
import cn.iocoder.yudao.module.inspection.service.IInspectionBatchSettlementOrderService;
import cn.iocoder.yudao.module.inspection.service.IInspectionInfoService;
import cn.iocoder.yudao.module.payment.entity.OrderInfo;
import cn.iocoder.yudao.module.payment.service.OrderInfoService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 批量结算订单记录 服务实现类
 * </p>
 *
 * @author author
 * @since 2025-07-09
 */
@Service
@RequiredArgsConstructor
public class InspectionBatchSettlementOrderServiceImpl extends ServiceImpl<InspectionBatchSettlementOrderMapper, InspectionBatchSettlementOrder> implements IInspectionBatchSettlementOrderService {

    private final OrderInfoService orderInfoService;

    /**
     * 分页查询
     *
     * @param page  分页参数
     * @param query 查询参数
     * @return List<InspectionBatchSettlementOrderQueryVo>
     */
    @Override
    public IPage<InspectionBatchSettlementOrderQueryVo> pageVo(Page<InspectionBatchSettlementOrder> page, InspectionBatchSettlementOrderQuery query) {
        IPage<InspectionBatchSettlementOrderQueryVo> pageResp = baseMapper.pageVo(page, query);

        // 收集所有orderIds
        Set<Long> allOrderIds = new HashSet<>();
        for (InspectionBatchSettlementOrderQueryVo record : pageResp.getRecords()) {
            Set<Long> orderIds = ArrayUtil.mapToSet(record.getOrderIds().split(","), Long::parseLong);
            allOrderIds.addAll(orderIds);
        }

        // 一次性批量查询所有订单信息
        if (!allOrderIds.isEmpty()) {
            Map<Long, OrderInfo> orderInfoMap = orderInfoService.queryByIds(allOrderIds)
                    .stream()
                    .collect(Collectors.toMap(OrderInfo::getId, Function.identity()));

            // 填充订单信息
            for (InspectionBatchSettlementOrderQueryVo record : pageResp.getRecords()) {
                Set<Long> orderIds = ArrayUtil.mapToSet(record.getOrderIds().split(","), Long::parseLong);
                List<OrderInfo> orderInfos = orderIds.stream()
                        .map(orderInfoMap::get)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                record.setOrderInfoList(orderInfos);
            }
        }

        return pageResp;
    }
}
