package com.seer.teach.pay.admin.withdrawal.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.seer.teach.common.PageListBean;
import com.seer.teach.common.utils.PageConverterUtils;
import com.seer.teach.pay.admin.withdrawal.controller.request.AdminPayMerchantRevenueUsagePageReq;
import com.seer.teach.pay.admin.withdrawal.controller.request.AdminPayMerchantRevenueUsageQueryReq;
import com.seer.teach.pay.admin.withdrawal.controller.response.AdminPayMerchantRevenueDetailResp;
import com.seer.teach.pay.admin.withdrawal.controller.response.AdminPayMerchantRevenueUsageResp;
import com.seer.teach.pay.admin.withdrawal.convert.AdminPayMerchantRevenueDetailConvert;
import com.seer.teach.pay.admin.withdrawal.convert.AdminPayMerchantRevenueUsageConvert;
import com.seer.teach.pay.entity.PayMerchantRevenueDetailEntity;
import com.seer.teach.pay.entity.PayMerchantRevenueUsageEntity;
import com.seer.teach.pay.service.IPayMerchantRevenueDetailService;
import com.seer.teach.pay.service.IPayMerchantRevenueUsageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.StrUtil;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@RequiredArgsConstructor
@Service
public class AdminPayMerchantRevenueUsageService {

    private final IPayMerchantRevenueUsageService payMerchantRevenueUsageService;
    private final IPayMerchantRevenueDetailService payMerchantRevenueDetailService;

    public PageListBean<AdminPayMerchantRevenueUsageResp> pageList(AdminPayMerchantRevenueUsagePageReq pageRequest) {
        IPage<PayMerchantRevenueUsageEntity> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());
        IPage<PayMerchantRevenueUsageEntity> result = payMerchantRevenueUsageService.page(page, new LambdaQueryWrapper<PayMerchantRevenueUsageEntity>()
                .eq(Objects.nonNull(pageRequest.getRevenueDetailId()), PayMerchantRevenueUsageEntity::getRevenueDetailId, pageRequest.getRevenueDetailId())
                .eq(StrUtil.isNotBlank(pageRequest.getWithdrawalApplySn()), PayMerchantRevenueUsageEntity::getWithdrawalApplyId, pageRequest.getWithdrawalApplySn())
                .eq(StrUtil.isNotBlank(pageRequest.getStatus()), PayMerchantRevenueUsageEntity::getStatus, pageRequest.getStatus())
                .orderByAsc(PayMerchantRevenueUsageEntity::getId)
        );

        PageListBean<AdminPayMerchantRevenueUsageResp> response = PageConverterUtils.convertPageListBean(result, AdminPayMerchantRevenueUsageConvert.INSTANCE::entityListToResponseList);

        // 为每个响应对象设置收益明细列表
        setItemsForResponses(response.getList());

        return response;
    }

    public List<AdminPayMerchantRevenueUsageResp> list(AdminPayMerchantRevenueUsageQueryReq queryRequest) {
        List<PayMerchantRevenueUsageEntity> result = payMerchantRevenueUsageService.list(new LambdaQueryWrapper<PayMerchantRevenueUsageEntity>()
                .eq(Objects.nonNull(queryRequest.getId()), PayMerchantRevenueUsageEntity::getId, queryRequest.getId())
                .eq(Objects.nonNull(queryRequest.getRevenueDetailId()), PayMerchantRevenueUsageEntity::getRevenueDetailId, queryRequest.getRevenueDetailId())
                .eq(StrUtil.isNotBlank(queryRequest.getWithdrawalApplySn()), PayMerchantRevenueUsageEntity::getWithdrawalApplyId, queryRequest.getWithdrawalApplySn())
                .eq(StrUtil.isNotBlank(queryRequest.getStatus()), PayMerchantRevenueUsageEntity::getStatus, queryRequest.getStatus())
                .eq(StrUtil.isNotBlank(queryRequest.getTenantId()), PayMerchantRevenueUsageEntity::getTenantId, queryRequest.getTenantId())
        );
        List<AdminPayMerchantRevenueUsageResp> response = AdminPayMerchantRevenueUsageConvert.INSTANCE.entityListToResponseList(result);

        // 为每个响应对象设置收益明细列表
        setItemsForResponses(response);

        return response;
    }

    public AdminPayMerchantRevenueUsageResp getDetail(Long id) {
        PayMerchantRevenueUsageEntity entity = payMerchantRevenueUsageService.getById(id);
        AdminPayMerchantRevenueUsageResp response = AdminPayMerchantRevenueUsageConvert.INSTANCE.entityToResponse(entity);

        // 为响应对象设置收益明细列表
        if (response != null && entity != null) {
            AdminPayMerchantRevenueDetailResp item = AdminPayMerchantRevenueDetailConvert.INSTANCE
                    .entityToResponse(payMerchantRevenueDetailService.getOne(new LambdaQueryWrapper<PayMerchantRevenueDetailEntity>()
                            .eq(PayMerchantRevenueDetailEntity::getId, entity.getRevenueDetailId())));
            response.setItem(item);
        }
        return response;
    }

    /**
     * 为响应列表中的每个对象设置收益明细列表
     *
     * @param responses 响应列表
     */
    private void setItemsForResponses(List<AdminPayMerchantRevenueUsageResp> responses) {
        if (responses == null || responses.isEmpty()) {
            return;
        }

        // 收集所有需要查询的收益流水ID
        List<Long> revenueDetailIds = responses.stream()
                .filter(resp -> resp != null && resp.getRevenueDetailId() != null)
                .map(AdminPayMerchantRevenueUsageResp::getRevenueDetailId)
                .distinct()
                .collect(Collectors.toList());

        if (revenueDetailIds.isEmpty()) {
            return;
        }

        // 批量查询收益明细
        List<PayMerchantRevenueDetailEntity> detailEntities = payMerchantRevenueDetailService.list(
                new LambdaQueryWrapper<PayMerchantRevenueDetailEntity>()
                        .in(PayMerchantRevenueDetailEntity::getId, revenueDetailIds));
        if (CollUtil.isEmpty(detailEntities)) {
            return;
        }
        // 转换为Map，key为revenueDetailId，value为对应的明细列表
        Map<Long, AdminPayMerchantRevenueDetailResp> itemsMap = AdminPayMerchantRevenueDetailConvert.INSTANCE.entityListToResponseList(detailEntities).stream()
                .collect(Collectors.toMap(AdminPayMerchantRevenueDetailResp::getId, Function.identity(), (old, newItem) -> newItem));

        // 为每个响应对象设置items
        responses.forEach(resp -> {
            if (resp != null && resp.getRevenueDetailId() != null) {
                resp.setItem(itemsMap.get(resp.getRevenueDetailId()));
            }
        });
    }

}