package com.ruoyi.credit.service.impl;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ruoyi.credit.domain.BankInstitution;
import com.ruoyi.credit.mapper.BankInstitutionMapper;
import com.ruoyi.credit.service.IBankInstitutionService;
import com.ruoyi.framework.security.validator.DepartmentPermissionValidator;

/**
 * 银行机构Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-12-24
 */
@Service
public class BankInstitutionServiceImpl implements IBankInstitutionService 
{
    @Autowired
    private BankInstitutionMapper bankInstitutionMapper;

    @Autowired
    private DepartmentPermissionValidator departmentPermissionValidator;

    /**
     * 查询银行机构
     * 
     * @param bankId 银行机构主键
     * @return 银行机构
     */
    @Override
    public BankInstitution selectBankInstitutionByBankId(Long bankId)
    {
        if (bankId == null) {
            return null;
        }
        return bankInstitutionMapper.selectBankInstitutionByBankId(bankId);
    }

    /**
     * 查询银行机构列表
     * 
     * @param bankInstitution 银行机构
     * @return 银行机构
     */
    @Override
    public List<BankInstitution> selectBankInstitutionList(BankInstitution bankInstitution)
    {
        return bankInstitutionMapper.selectBankInstitutionList(bankInstitution);
    }

    /**
     * 新增银行机构
     * 
     * @param bankInstitution 银行机构
     * @return 结果
     */
    @Override
    public int insertBankInstitution(BankInstitution bankInstitution)
    {
        // 验证数据创建权限并自动设置部门ID
        departmentPermissionValidator.validateDataCreation(bankInstitution);
        
        return bankInstitutionMapper.insertBankInstitution(bankInstitution);
    }

    /**
     * 修改银行机构
     * 
     * @param bankInstitution 银行机构
     * @return 结果
     */
    @Override
    public int updateBankInstitution(BankInstitution bankInstitution)
    {
        return bankInstitutionMapper.updateBankInstitution(bankInstitution);
    }

    /**
     * 批量删除银行机构
     * 
     * @param bankIds 需要删除的银行机构主键
     * @return 结果
     */
    @Override
    public int deleteBankInstitutionByBankIds(Long[] bankIds)
    {
        if (bankIds == null || bankIds.length == 0) {
            return 0;
        }
        return bankInstitutionMapper.deleteBankInstitutionByBankIds(bankIds);
    }

    /**
     * 删除银行机构信息
     * 
     * @param bankId 银行机构主键
     * @return 结果
     */
    @Override
    public int deleteBankInstitutionByBankId(Long bankId)
    {
        if (bankId == null) {
            return 0;
        }
        return bankInstitutionMapper.deleteBankInstitutionByBankId(bankId);
    }

    /**
     * 根据银行编码查询银行机构
     * 
     * @param bankCode 银行编码
     * @return 银行机构
     */
    @Override
    public BankInstitution selectBankInstitutionByBankCode(String bankCode)
    {
        return bankInstitutionMapper.selectBankInstitutionByBankCode(bankCode);
    }

    /**
     * 查询合作状态为活跃的银行机构列表
     * 
     * @return 银行机构集合
     */
    @Override
    public List<BankInstitution> selectActiveBankInstitutions()
    {
        return bankInstitutionMapper.selectActiveBankInstitutions();
    }

    /**
     * 根据贷款条件匹配银行机构
     * 
     * @param loanAmount 贷款金额
     * @param loanTermMonths 贷款期限(月)
     * @return 匹配的银行机构集合
     */
    @Override
    public List<BankInstitution> matchBankInstitutions(java.math.BigDecimal loanAmount, Integer loanTermMonths)
    {
        if (loanAmount == null) {
            return bankInstitutionMapper.selectActiveBankInstitutions();
        }
        
        try {
            // 获取所有活跃的银行机构
            List<BankInstitution> allBanks = bankInstitutionMapper.selectBankInstitutionsByLoanAmount(loanAmount);
            
            if (allBanks == null || allBanks.isEmpty()) {
                return allBanks;
            }
            
            // 在Java代码中进行贷款金额筛选
            List<BankInstitution> amountMatched = allBanks.stream()
                .filter(bank -> {
                    if (bank == null) {
                        return false;
                    }
                    
                    java.math.BigDecimal minAmount = bank.getMinLoanAmountDecimal();
                    java.math.BigDecimal maxAmount = bank.getMaxLoanAmountDecimal();
                    
                    // 如果最小金额为空或贷款金额大于等于最小金额
                    boolean minCheck = (minAmount == null || loanAmount.compareTo(minAmount) >= 0);
                    // 如果最大金额为空或贷款金额小于等于最大金额
                    boolean maxCheck = (maxAmount == null || loanAmount.compareTo(maxAmount) <= 0);
                    
                    return minCheck && maxCheck;
                })
                .collect(Collectors.toList());
            
            // 再根据贷款期限进一步筛选
            if (loanTermMonths != null) {
                List<BankInstitution> termMatched = bankInstitutionMapper.selectBankInstitutionsByLoanTerm(loanTermMonths);
                
                if (termMatched != null && !termMatched.isEmpty()) {
                    // 取交集
                    amountMatched = amountMatched.stream()
                        .filter(bank -> bank != null && termMatched.stream()
                            .anyMatch(termBank -> termBank != null && termBank.getBankId() != null && 
                                     termBank.getBankId().equals(bank.getBankId())))
                        .collect(Collectors.toList());
                }
            }
            
            return amountMatched;
        } catch (Exception e) {
            // 如果出现异常，返回所有活跃银行
            return bankInstitutionMapper.selectActiveBankInstitutions();
        }
    }

    /**
     * 根据当前用户权限查询银行机构列表 (支持账号过滤)
     * 
     * @param bankInstitution 银行机构查询条件
     * @param currentUserType 当前用户类型
     * @param currentUserName 当前用户名
     * @return 银行机构集合
     */
    @Override
    public List<BankInstitution> selectBankInstitutionListWithPermission(BankInstitution bankInstitution, String currentUserType, String currentUserName)
    {
        // 如果是金融公司账号，只显示该账号创建的银行
        if (BankInstitution.CREATOR_FINANCIAL_COMPANY.equals(currentUserType)) {
            if (bankInstitution == null) {
                bankInstitution = new BankInstitution();
            }
            bankInstitution.setCreateBy(currentUserName);
            bankInstitution.setCreatorAccountType(BankInstitution.CREATOR_FINANCIAL_COMPANY);
        }
        
        return bankInstitutionMapper.selectBankInstitutionListWithPermission(bankInstitution, currentUserType, currentUserName);
    }

    /**
     * 根据创建者账号类型查询银行机构列表
     * 
     * @param creatorAccountType 创建者账号类型
     * @return 银行机构集合
     */
    @Override
    public List<BankInstitution> selectBankInstitutionsByCreatorAccountType(String creatorAccountType)
    {
        return bankInstitutionMapper.selectBankInstitutionsByCreatorAccountType(creatorAccountType);
    }
}