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

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.financial.controller.request.AdminPayOfflineTransferRecordPageReq;
import com.seer.teach.pay.admin.financial.controller.request.AdminPayOfflineTransferRecordQueryReq;
import com.seer.teach.pay.admin.financial.controller.request.AdminPayOfflineTransferRecordReq;
import com.seer.teach.pay.admin.financial.controller.response.AdminPayOfflineTransferRecordResp;
import com.seer.teach.pay.admin.financial.convert.AdminPayOfflineTransferRecordConvert;
import com.seer.teach.pay.admin.withdrawal.convert.PayWithdrawalApplyConvert;
import com.seer.teach.pay.admin.withdrawal.controller.response.PayWithdrawalApplyResponse;
import com.seer.teach.pay.entity.PayMerchantWithdrawalApplyEntity;
import com.seer.teach.pay.entity.PayOfflineTransferRecordEntity;
import com.seer.teach.pay.service.IPayMerchantWithdrawalApplyService;
import com.seer.teach.pay.service.IPayOfflineTransferRecordService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.collection.CollectionUtil;

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

@Slf4j
@RequiredArgsConstructor
@Service
public class AdminPayOfflineTransferRecordService {

    private final IPayOfflineTransferRecordService payOfflineTransferRecordService;
    private final IPayMerchantWithdrawalApplyService payMerchantWithdrawalApplyService;

    public PageListBean<AdminPayOfflineTransferRecordResp> pageList(AdminPayOfflineTransferRecordPageReq pageRequest) {
        IPage<PayOfflineTransferRecordEntity> page = new Page<>(pageRequest.getPageNo(), pageRequest.getPageSize());

        IPage<PayOfflineTransferRecordEntity> result = payOfflineTransferRecordService.page(page, new LambdaQueryWrapper<PayOfflineTransferRecordEntity>()
                .likeRight(StrUtil.isNotBlank(pageRequest.getWithdrawalNo()), PayOfflineTransferRecordEntity::getWithdrawalNo, pageRequest.getWithdrawalNo())
                .eq(Objects.nonNull(pageRequest.getTransferType()), PayOfflineTransferRecordEntity::getTransferType, pageRequest.getTransferType())
                .likeRight(StrUtil.isNotBlank(pageRequest.getPayerAccount()), PayOfflineTransferRecordEntity::getPayerAccount, pageRequest.getPayerAccount())
                .likeRight(StrUtil.isNotBlank(pageRequest.getPayeeAccountId()), PayOfflineTransferRecordEntity::getPayeeAccountId, pageRequest.getPayeeAccountId())
                .likeRight(StrUtil.isNotBlank(pageRequest.getBankFlowNo()), PayOfflineTransferRecordEntity::getBankFlowNo, pageRequest.getBankFlowNo())
                .ge(Objects.nonNull(pageRequest.getTransferTime()), PayOfflineTransferRecordEntity::getTransferTime, pageRequest.getTransferTime())
                .eq(Objects.nonNull(pageRequest.getOperatorId()), PayOfflineTransferRecordEntity::getOperatorId, pageRequest.getOperatorId())
                .in(CollectionUtil.isNotEmpty(pageRequest.getTransferStatusList()), PayOfflineTransferRecordEntity::getTransferStatus, pageRequest.getTransferStatusList())
                .orderByDesc(PayOfflineTransferRecordEntity::getCreateTime)
        );
        
        // 转换基础响应数据
        PageListBean<AdminPayOfflineTransferRecordResp> response = PageConverterUtils.convertPageListBean(result, AdminPayOfflineTransferRecordConvert.INSTANCE::entityListToResponseList);
        
        // 填充提现申请信息
        fillWithdrawalApplyInfo(response.getList());

        return response;
    }

    public List<AdminPayOfflineTransferRecordResp> list(AdminPayOfflineTransferRecordQueryReq queryParam) {
        List<PayOfflineTransferRecordEntity> result = payOfflineTransferRecordService.list(new LambdaQueryWrapper<PayOfflineTransferRecordEntity>()
                .likeRight(StrUtil.isNotBlank(queryParam.getWithdrawalNo()), PayOfflineTransferRecordEntity::getWithdrawalNo, queryParam.getWithdrawalNo())
                .eq(Objects.nonNull(queryParam.getTransferType()), PayOfflineTransferRecordEntity::getTransferType, queryParam.getTransferType())
                .likeRight(StrUtil.isNotBlank(queryParam.getPayerAccount()), PayOfflineTransferRecordEntity::getPayerAccount, queryParam.getPayerAccount())
                .likeRight(StrUtil.isNotBlank(queryParam.getPayeeAccountId()), PayOfflineTransferRecordEntity::getPayeeAccountId, queryParam.getPayeeAccountId())
                .likeRight(StrUtil.isNotBlank(queryParam.getBankFlowNo()), PayOfflineTransferRecordEntity::getBankFlowNo, queryParam.getBankFlowNo())
                .ge(Objects.nonNull(queryParam.getTransferTime()), PayOfflineTransferRecordEntity::getTransferTime, queryParam.getTransferTime())
                .eq(Objects.nonNull(queryParam.getOperatorId()), PayOfflineTransferRecordEntity::getOperatorId, queryParam.getOperatorId())
                .in(CollectionUtil.isNotEmpty(queryParam.getTransferStatusList()), PayOfflineTransferRecordEntity::getTransferStatus, queryParam.getTransferStatusList())
                .orderByDesc(PayOfflineTransferRecordEntity::getCreateTime)
        );
        
        List<AdminPayOfflineTransferRecordResp> response = AdminPayOfflineTransferRecordConvert.INSTANCE.entityListToResponseList(result);
        
        // 填充提现申请信息
        fillWithdrawalApplyInfo(response);
        
        return response;
    }

    public AdminPayOfflineTransferRecordResp getDetail(Long id) {
        PayOfflineTransferRecordEntity result = payOfflineTransferRecordService.getById(id);
        log.info("getById:{}", result);
        
        if (result == null) {
            return null;
        }
        
        AdminPayOfflineTransferRecordResp response = AdminPayOfflineTransferRecordConvert.INSTANCE.entityToResponse(result);
        
        // 填充单个记录的提现申请信息
        fillWithdrawalApplyInfoForSingle(response, result.getWithdrawalNo());
        
        return response;
    }

    public boolean save(AdminPayOfflineTransferRecordReq payOfflineTransferRecord) {
        PayOfflineTransferRecordEntity entity = AdminPayOfflineTransferRecordConvert.INSTANCE.reqToEntity(payOfflineTransferRecord);
        boolean saved = payOfflineTransferRecordService.save(entity);
        log.info("save:{}", saved);
        return saved;
    }

    public boolean updateById(AdminPayOfflineTransferRecordReq payOfflineTransferRecord) {
        PayOfflineTransferRecordEntity entity = AdminPayOfflineTransferRecordConvert.INSTANCE.reqToEntity(payOfflineTransferRecord);
        boolean updated = payOfflineTransferRecordService.updateById(entity);
        log.info("updateById:{}", updated);
        return updated;
    }

    public boolean deleteById(Long id) {
        boolean updated = payOfflineTransferRecordService.removeById(id);
        log.info("deleteById:{}", updated);
        return updated;
    }
    
    /**
     * 为转账记录列表填充对应的提现申请信息
     * @param recordRespList 转账记录响应列表
     */
    private void fillWithdrawalApplyInfo(List<AdminPayOfflineTransferRecordResp> recordRespList) {
        if(CollectionUtil.isEmpty(recordRespList)){
            return;
        }
        // 获取相关的提现申请信息
        List<String> withdrawalNos = recordRespList.stream()
                .map(AdminPayOfflineTransferRecordResp::getWithdrawalNo)
                .filter(StrUtil::isNotBlank)
                .distinct()
                .collect(Collectors.toList());
        
        if (CollectionUtil.isNotEmpty(withdrawalNos)) {
            List<PayMerchantWithdrawalApplyEntity> applyEntities = payMerchantWithdrawalApplyService.list(
                    new LambdaQueryWrapper<PayMerchantWithdrawalApplyEntity>()
                            .in(PayMerchantWithdrawalApplyEntity::getWithdrawalNo, withdrawalNos)
            );
            
            // 创建提现申请编号到申请实体的映射
            Map<String, PayMerchantWithdrawalApplyEntity> applyMap = applyEntities.stream()
                    .collect(Collectors.toMap(PayMerchantWithdrawalApplyEntity::getWithdrawalNo, entity -> entity, (existing, replacement) -> existing));
            
            // 为每个转账记录设置对应的提现申请信息
            for (AdminPayOfflineTransferRecordResp recordResp : recordRespList) {
                PayMerchantWithdrawalApplyEntity applyEntity = applyMap.get(recordResp.getWithdrawalNo());
                if (applyEntity != null) {
                    PayWithdrawalApplyResponse applyResp = PayWithdrawalApplyConvert.INSTANCE.entityToResponse(applyEntity);
                    recordResp.setWithdrawalApply(applyResp);
                }
            }
        }
    }
    
    /**
     * 为单个转账记录填充对应的提现申请信息
     * @param recordResp 转账记录响应
     * @param withdrawalNo 提现申请编号
     */
    private void fillWithdrawalApplyInfoForSingle(AdminPayOfflineTransferRecordResp recordResp, String withdrawalNo) {
        // 获取对应的提现申请信息
        if (StrUtil.isNotBlank(withdrawalNo)) {
            PayMerchantWithdrawalApplyEntity applyEntity = payMerchantWithdrawalApplyService.getOne(
                    new LambdaQueryWrapper<PayMerchantWithdrawalApplyEntity>()
                            .eq(PayMerchantWithdrawalApplyEntity::getWithdrawalNo, withdrawalNo)
            );
            
            if (applyEntity != null) {
                PayWithdrawalApplyResponse applyResp = PayWithdrawalApplyConvert.INSTANCE.entityToResponse(applyEntity);
                recordResp.setWithdrawalApply(applyResp);
            }
        }
    }
}