package com.ruoyi.credit.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.credit.domain.BankInstitution;
import com.ruoyi.credit.domain.UnifiedBankData;
import com.ruoyi.credit.service.IBankInstitutionService;
import com.ruoyi.credit.service.IContractEmployeeService;
import com.ruoyi.credit.service.IUnifiedBankService;

/**
 * 统一银行数据服务实现类
 * 
 * @author ruoyi
 * @date 2025-12-25
 */
@Service
public class UnifiedBankServiceImpl implements IUnifiedBankService 
{
    private static final Logger logger = LoggerFactory.getLogger(UnifiedBankServiceImpl.class);
    
    @Autowired
    private IBankInstitutionService bankInstitutionService;
    
    @Autowired
    private IContractEmployeeService contractEmployeeService;

    @Override
    public List<UnifiedBankData> selectUnifiedBankList(Map<String, Object> params)
    {
        logger.info("获取统一银行列表: params={}", params);
        
        try {
            // 优先从服务周期贷款系统获取数据
            List<UnifiedBankData> unifiedBanks = convertFromServicePeriodLoanData(1L, 12);
            
            if (!unifiedBanks.isEmpty()) {
                // 补充银行管理界面的基础信息
                for (UnifiedBankData unifiedBank : unifiedBanks) {
                    enrichWithBankInstitutionData(unifiedBank);
                }
                
                // 根据参数过滤
                unifiedBanks = filterBanksByParams(unifiedBanks, params);
            } else {
                // 降级使用银行管理界面数据
                logger.warn("服务周期贷款系统无数据，降级使用银行管理界面数据");
                unifiedBanks = convertFromBankInstitutionData(params);
            }
            
            logger.info("获取统一银行列表成功: count={}", unifiedBanks.size());
            return unifiedBanks;
            
        } catch (Exception e) {
            logger.error("获取统一银行列表失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public UnifiedBankData selectUnifiedBankById(Long bankId)
    {
        logger.info("获取统一银行详情: bankId={}", bankId);
        
        try {
            if (bankId == null) {
                return null;
            }
            
            // 从银行管理界面获取基础信息
            BankInstitution bankInstitution = bankInstitutionService.selectBankInstitutionByBankId(bankId);
            if (bankInstitution == null) {
                return null;
            }
            
            UnifiedBankData unifiedBank = UnifiedBankData.fromBankInstitution(bankInstitution);
            
            // 尝试从服务周期贷款系统获取产品信息
            try {
                List<UnifiedBankData> servicePeriodBanks = convertFromServicePeriodLoanData(1L, 12);
                UnifiedBankData servicePeriodBank = servicePeriodBanks.stream()
                    .filter(bank -> bankId.equals(bank.getBankId()))
                    .findFirst()
                    .orElse(null);
                
                if (servicePeriodBank != null) {
                    // 补充服务周期贷款系统的产品信息
                    unifiedBank.setProductName(servicePeriodBank.getProductName());
                    unifiedBank.setInterestRate(servicePeriodBank.getInterestRate());
                    unifiedBank.setTermMonths(servicePeriodBank.getTermMonths());
                    unifiedBank.setMaxAmount(servicePeriodBank.getMaxAmount());
                    unifiedBank.setTermMatch(servicePeriodBank.getTermMatch());
                }
            } catch (Exception e) {
                logger.warn("获取服务周期贷款系统产品信息失败: bankId={}", bankId, e);
            }
            
            logger.info("获取统一银行详情成功: bankId={}", bankId);
            return unifiedBank;
            
        } catch (Exception e) {
            logger.error("获取统一银行详情失败: bankId={}", bankId, e);
            return null;
        }
    }

    @Override
    public List<UnifiedBankData> matchUnifiedBanks(BigDecimal loanAmount, Integer termMonths)
    {
        logger.info("匹配统一银行: loanAmount={}, termMonths={}", loanAmount, termMonths);
        
        try {
            if (loanAmount == null || termMonths == null) {
                return new ArrayList<>();
            }
            
            // 使用服务周期贷款系统的匹配逻辑
            List<UnifiedBankData> servicePeriodBanks = convertFromServicePeriodLoanData(1L, termMonths);
            
            if (!servicePeriodBanks.isEmpty()) {
                // 过滤符合贷款金额条件的银行
                List<UnifiedBankData> matchedBanks = servicePeriodBanks.stream()
                    .filter(bank -> {
                        BigDecimal maxAmount = bank.getMaxAmount();
                        return maxAmount != null && maxAmount.compareTo(loanAmount) >= 0;
                    })
                    .collect(Collectors.toList());
                
                // 补充银行基础信息
                for (UnifiedBankData bank : matchedBanks) {
                    enrichWithBankInstitutionData(bank);
                }
                
                logger.info("匹配统一银行成功: matchedCount={}", matchedBanks.size());
                return matchedBanks;
            } else {
                // 降级使用银行管理界面的匹配逻辑
                logger.warn("服务周期贷款系统匹配失败，降级使用银行管理界面匹配");
                List<BankInstitution> matchedBankInstitutions = bankInstitutionService
                    .matchBankInstitutions(loanAmount, termMonths);
                
                List<UnifiedBankData> matchedBanks = matchedBankInstitutions.stream()
                    .map(UnifiedBankData::fromBankInstitution)
                    .collect(Collectors.toList());
                
                logger.info("匹配统一银行成功（降级）: matchedCount={}", matchedBanks.size());
                return matchedBanks;
            }
            
        } catch (Exception e) {
            logger.error("匹配统一银行失败: loanAmount={}, termMonths={}", loanAmount, termMonths, e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<UnifiedBankData> selectActiveUnifiedBanks()
    {
        logger.info("获取活跃统一银行列表");
        
        try {
            // 从服务周期贷款系统获取银行数据
            List<UnifiedBankData> servicePeriodBanks = convertFromServicePeriodLoanData(1L, 12);
            
            if (!servicePeriodBanks.isEmpty()) {
                // 补充银行基础信息并过滤活跃状态
                List<UnifiedBankData> activeBanks = servicePeriodBanks.stream()
                    .filter(bank -> {
                        enrichWithBankInstitutionData(bank);
                        return BankInstitution.STATUS_ACTIVE.equals(bank.getStatus()) &&
                               BankInstitution.COOPERATION_ACTIVE.equals(bank.getCooperationStatus());
                    })
                    .collect(Collectors.toList());
                
                logger.info("获取活跃统一银行列表成功: count={}", activeBanks.size());
                return activeBanks;
            } else {
                // 降级使用银行管理界面数据
                logger.warn("服务周期贷款系统无活跃银行数据，降级使用银行管理界面数据");
                List<BankInstitution> activeBankInstitutions = bankInstitutionService.selectActiveBankInstitutions();
                List<UnifiedBankData> activeBanks = activeBankInstitutions.stream()
                    .map(UnifiedBankData::fromBankInstitution)
                    .collect(Collectors.toList());
                
                logger.info("获取活跃统一银行列表成功（降级）: count={}", activeBanks.size());
                return activeBanks;
            }
            
        } catch (Exception e) {
            logger.error("获取活跃统一银行列表失败", e);
            return new ArrayList<>();
        }
    }

    @Override
    public List<UnifiedBankData> convertFromServicePeriodLoanData(Long servicePeriodId, Integer contractTermMonths)
    {
        logger.debug("从服务周期贷款系统转换数据: servicePeriodId={}, contractTermMonths={}", 
                    servicePeriodId, contractTermMonths);
        
        try {
            Map<String, Object> servicePeriodResult = contractEmployeeService
                .selectBankFinancingByContractTerm(servicePeriodId, contractTermMonths);
            
            if (servicePeriodResult != null && Boolean.TRUE.equals(servicePeriodResult.get("success"))) {
                @SuppressWarnings("unchecked")
                List<Map<String, Object>> matchedProducts = (List<Map<String, Object>>) servicePeriodResult.get("matchedProducts");
                
                if (matchedProducts != null) {
                    return matchedProducts.stream()
                        .map(UnifiedBankData::fromServicePeriodLoanData)
                        .collect(Collectors.toList());
                }
            }
            
            return new ArrayList<>();
            
        } catch (Exception e) {
            logger.error("从服务周期贷款系统转换数据失败: servicePeriodId={}, contractTermMonths={}", 
                        servicePeriodId, contractTermMonths, e);
            return new ArrayList<>();
        }
    }

    /**
     * 用银行管理界面数据补充统一银行数据
     */
    private void enrichWithBankInstitutionData(UnifiedBankData unifiedBank)
    {
        if (unifiedBank == null || unifiedBank.getBankId() == null) {
            return;
        }
        
        try {
            BankInstitution bankInstitution = bankInstitutionService
                .selectBankInstitutionByBankId(unifiedBank.getBankId());
            
            if (bankInstitution != null) {
                if (unifiedBank.getBankCode() == null) {
                    unifiedBank.setBankCode(bankInstitution.getBankCode());
                }
                if (unifiedBank.getBankType() == null) {
                    unifiedBank.setBankType(bankInstitution.getBankType());
                }
                if (unifiedBank.getCooperationStatus() == null) {
                    unifiedBank.setCooperationStatus(bankInstitution.getCooperationStatus());
                }
                if (unifiedBank.getStatus() == null) {
                    unifiedBank.setStatus(bankInstitution.getStatus());
                }
                if (unifiedBank.getBaseInterestRate() == null) {
                    unifiedBank.setBaseInterestRate(bankInstitution.getBaseInterestRate());
                }
                if (unifiedBank.getMinLoanAmount() == null) {
                    unifiedBank.setMinLoanAmount(bankInstitution.getMinLoanAmountDecimal());
                }
                if (unifiedBank.getMaxLoanAmount() == null) {
                    unifiedBank.setMaxLoanAmount(bankInstitution.getMaxLoanAmountDecimal());
                }
                if (unifiedBank.getMinLoanTermMonths() == null) {
                    unifiedBank.setMinLoanTermMonths(bankInstitution.getMinLoanTermMonths());
                }
                if (unifiedBank.getMaxLoanTermMonths() == null) {
                    unifiedBank.setMaxLoanTermMonths(bankInstitution.getMaxLoanTermMonths());
                }
                if (unifiedBank.getLastUpdateTime() == null) {
                    unifiedBank.setLastUpdateTime(bankInstitution.getUpdateTime());
                }
            }
        } catch (Exception e) {
            logger.warn("补充银行基础信息失败: bankId={}", unifiedBank.getBankId(), e);
        }
    }

    /**
     * 从银行管理界面数据转换为统一格式
     */
    private List<UnifiedBankData> convertFromBankInstitutionData(Map<String, Object> params)
    {
        try {
            BankInstitution queryParam = new BankInstitution();
            
            // 设置查询参数
            if (params.containsKey("bankName")) {
                queryParam.setBankName((String) params.get("bankName"));
            }
            if (params.containsKey("bankType")) {
                queryParam.setBankType((String) params.get("bankType"));
            }
            if (params.containsKey("status")) {
                queryParam.setStatus((String) params.get("status"));
            }
            
            List<BankInstitution> bankInstitutions = bankInstitutionService.selectBankInstitutionList(queryParam);
            return bankInstitutions.stream()
                .map(UnifiedBankData::fromBankInstitution)
                .collect(Collectors.toList());
                
        } catch (Exception e) {
            logger.error("从银行管理界面数据转换失败", e);
            return new ArrayList<>();
        }
    }

    /**
     * 根据参数过滤银行数据
     */
    private List<UnifiedBankData> filterBanksByParams(List<UnifiedBankData> banks, Map<String, Object> params)
    {
        if (params == null || params.isEmpty()) {
            return banks;
        }
        
        return banks.stream()
            .filter(bank -> {
                // 按银行名称过滤
                if (params.containsKey("bankName")) {
                    String bankName = (String) params.get("bankName");
                    if (bankName != null && !bankName.isEmpty()) {
                        return bank.getBankName() != null && 
                               bank.getBankName().contains(bankName);
                    }
                }
                
                // 按银行类型过滤
                if (params.containsKey("bankType")) {
                    String bankType = (String) params.get("bankType");
                    if (bankType != null && !bankType.isEmpty()) {
                        return bankType.equals(bank.getBankType());
                    }
                }
                
                // 按状态过滤
                if (params.containsKey("status")) {
                    String status = (String) params.get("status");
                    if (status != null && !status.isEmpty()) {
                        return status.equals(bank.getStatus());
                    }
                }
                
                return true;
            })
            .collect(Collectors.toList());
    }
}