package com.ruoyi.credit.controller;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.credit.domain.UnifiedBankData;
import com.ruoyi.credit.service.IUnifiedBankService;

/**
 * 统一银行数据API网关控制器
 * 提供统一的银行数据访问接口，屏蔽底层数据源的复杂性
 * 以服务周期贷款系统的银行数据为标准数据源
 * 
 * @author ruoyi
 * @date 2025-12-25
 */
@RestController
@RequestMapping("/api/unified/bank")
public class UnifiedBankController extends BaseController
{
    private static final Logger logger = LoggerFactory.getLogger(UnifiedBankController.class);
    
    @Autowired
    private IUnifiedBankService unifiedBankService;

    /**
     * 获取银行列表（统一接口）
     * 路由到服务周期贷款系统API，返回统一格式的银行数据
     */
    @PreAuthorize("@ss.hasPermi('credit:bank:list')")
    @GetMapping("/list")
    public TableDataInfo getBankList(@RequestParam Map<String, Object> params)
    {
        logger.info("统一银行API - 获取银行列表: params={}", params);
        
        try {
            startPage();
            List<UnifiedBankData> unifiedBankList = unifiedBankService.selectUnifiedBankList(params);
            logger.info("统一银行API - 获取银行列表成功: count={}", unifiedBankList.size());
            return getDataTable(unifiedBankList);
            
        } catch (Exception e) {
            logger.error("统一银行API - 获取银行列表失败", e);
            return getDataTable(new java.util.ArrayList<>());
        }
    }

    /**
     * 获取银行详情（统一接口）
     * 优先从服务周期贷款系统获取数据，补充银行管理界面的基础信息
     */
    @PreAuthorize("@ss.hasPermi('credit:bank:query')")
    @GetMapping("/{bankId}")
    public AjaxResult getBankDetail(@PathVariable Long bankId)
    {
        logger.info("统一银行API - 获取银行详情: bankId={}", bankId);
        
        try {
            if (bankId == null) {
                return error("银行ID不能为空");
            }
            
            UnifiedBankData unifiedBank = unifiedBankService.selectUnifiedBankById(bankId);
            if (unifiedBank == null) {
                return error("未找到指定的银行机构");
            }
            
            logger.info("统一银行API - 获取银行详情成功: bankId={}", bankId);
            return success(unifiedBank);
            
        } catch (Exception e) {
            logger.error("统一银行API - 获取银行详情失败: bankId={}", bankId, e);
            return error("查询银行详情失败：" + e.getMessage());
        }
    }

    /**
     * 根据贷款条件匹配银行（统一接口）
     * 直接路由到服务周期贷款系统的银行匹配逻辑
     */
    @PreAuthorize("@ss.hasPermi('credit:bank:list')")
    @GetMapping("/match")
    public AjaxResult matchBanks(@RequestParam BigDecimal loanAmount, 
                                @RequestParam Integer termMonths)
    {
        logger.info("统一银行API - 匹配银行: loanAmount={}, termMonths={}", loanAmount, termMonths);
        
        try {
            if (loanAmount == null || termMonths == null) {
                return error("贷款金额和期限不能为空");
            }
            
            List<UnifiedBankData> matchedBanks = unifiedBankService.matchUnifiedBanks(loanAmount, termMonths);
            logger.info("统一银行API - 匹配银行成功: matchedCount={}", matchedBanks.size());
            return success(matchedBanks);
            
        } catch (Exception e) {
            logger.error("统一银行API - 匹配银行失败: loanAmount={}, termMonths={}", loanAmount, termMonths, e);
            return error("匹配银行失败：" + e.getMessage());
        }
    }

    /**
     * 获取活跃银行列表（统一接口）
     * 从服务周期贷款系统获取活跃银行数据
     */
    @PreAuthorize("@ss.hasPermi('credit:bank:list')")
    @GetMapping("/active")
    public AjaxResult getActiveBanks()
    {
        logger.info("统一银行API - 获取活跃银行列表");
        
        try {
            List<UnifiedBankData> activeBanks = unifiedBankService.selectActiveUnifiedBanks();
            logger.info("统一银行API - 获取活跃银行列表成功: count={}", activeBanks.size());
            return success(activeBanks);
            
        } catch (Exception e) {
            logger.error("统一银行API - 获取活跃银行列表失败", e);
            return error("获取活跃银行列表失败：" + e.getMessage());
        }
    }
}