package com.ruoyi.credit.controller;

import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.credit.domain.BankInstitution;
import com.ruoyi.credit.service.IBankInstitutionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;

/**
 * 银行机构Controller - 使用数据库直接管理
 *
 * @author ruoyi
 * @date 2025-12-25
 */
@RestController
@RequestMapping("/credit/bank-institution")
public class BankInstitutionController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(BankInstitutionController.class);

    @Autowired
    private IBankInstitutionService bankInstitutionService;

    /**
     * 查询银行机构列表 - 支持账号过滤
     */
    @PreAuthorize("@ss.hasPermi('credit:bank:list')")
    @GetMapping("/list")
    public TableDataInfo list(BankInstitution bankInstitution) {
        try {
            startPage();

            // 获取当前用户信息
            String currentUserName = SecurityUtils.getUsername();
            String currentUserType = getCurrentUserType(); // 需要根据实际业务逻辑判断用户类型

            // 根据用户权限查询银行机构列表
            List<BankInstitution> list = bankInstitutionService.selectBankInstitutionListWithPermission(
                    bankInstitution, currentUserType, currentUserName);

            return getDataTable(list);
        } catch (Exception e) {
            logger.error("查询银行机构列表失败", e);
            return getDataTable(java.util.Collections.emptyList());
        }
    }

    /**
     * 导出银行机构列表
     */
    @PreAuthorize("@ss.hasPermi('credit:bank:export')")
    @Log(title = "银行机构", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, BankInstitution bankInstitution) {
        try {
            // 获取当前用户信息
            String currentUserName = SecurityUtils.getUsername();
            String currentUserType = getCurrentUserType();

            // 根据用户权限查询银行机构列表
            List<BankInstitution> list = bankInstitutionService.selectBankInstitutionListWithPermission(
                    bankInstitution, currentUserType, currentUserName);

            ExcelUtil<BankInstitution> util = new ExcelUtil<>(BankInstitution.class);
            util.exportExcel(response, list, "银行机构数据");
        } catch (Exception e) {
            logger.error("导出银行机构数据失败", e);
        }
    }

    /**
     * 获取银行机构详细信息
     */
    @PreAuthorize("@ss.hasPermi('credit:bank:query')")
    @GetMapping(value = "/{bankId}")
    public AjaxResult getInfo(@PathVariable("bankId") Long bankId) {
        try {
            if (bankId == null) {
                return error("银行ID不能为空");
            }

            BankInstitution bankInstitution = bankInstitutionService.selectBankInstitutionByBankId(bankId);
            if (bankInstitution != null) {
                return success(bankInstitution);
            }

            return error("未找到指定的银行机构");
        } catch (Exception e) {
            logger.error("查询银行机构详情失败", e);
            return error("查询银行机构详情失败：" + e.getMessage());
        }
    }

    /**
     * 新增银行机构 - 只允许金融机构账号操作
     */
    @PreAuthorize("@ss.hasPermi('credit:bank:add')")
    @Log(title = "银行机构", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BankInstitution bankInstitution) {
        try {
            // 获取当前用户信息
            String currentUserName = SecurityUtils.getUsername();
            String currentUserType = getCurrentUserType();

            // 权限检查：只有金融机构账号才能添加银行机构
            if (!BankInstitution.CREATOR_FINANCIAL_COMPANY.equals(currentUserType)) {
                return error("只有金融机构账号才能添加银行机构");
            }

            // 设置创建者信息
            bankInstitution.setCreateBy(currentUserName);
            bankInstitution.setCreatorAccountType(currentUserType);

            // 验证银行编码唯一性
            BankInstitution existingBank = bankInstitutionService.selectBankInstitutionByBankCode(bankInstitution.getBankCode());
            if (existingBank != null) {
                return error("银行编码已存在，请使用其他编码");
            }

            int result = bankInstitutionService.insertBankInstitution(bankInstitution);
            if (result > 0) {
                return success("新增银行机构成功");
            }

            return error("新增银行机构失败");
        } catch (Exception e) {
            logger.error("新增银行机构失败", e);
            return error("新增银行机构失败：" + e.getMessage());
        }
    }

    /**
     * 修改银行机构 - 只允许金融机构账号操作
     */
    @PreAuthorize("@ss.hasPermi('credit:bank:edit')")
    @Log(title = "银行机构", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BankInstitution bankInstitution) {
        try {
            // 获取当前用户信息
            String currentUserName = SecurityUtils.getUsername();
            String currentUserType = getCurrentUserType();

            // 权限检查：只有金融机构账号才能修改银行机构
            if (!BankInstitution.CREATOR_FINANCIAL_COMPANY.equals(currentUserType)) {
                return error("只有金融机构账号才能修改银行机构");
            }

            // 检查权限：金融公司账号只能修改自己创建的银行
            BankInstitution existingBank = bankInstitutionService.selectBankInstitutionByBankId(bankInstitution.getBankId());
            if (existingBank == null || !currentUserName.equals(existingBank.getCreateBy())) {
                return error("您只能修改自己创建的银行机构");
            }

            // 验证银行编码唯一性（排除当前记录）
            BankInstitution existingBankByCode = bankInstitutionService.selectBankInstitutionByBankCode(bankInstitution.getBankCode());
            if (existingBankByCode != null && !existingBankByCode.getBankId().equals(bankInstitution.getBankId())) {
                return error("银行编码已存在，请使用其他编码");
            }

            int result = bankInstitutionService.updateBankInstitution(bankInstitution);
            if (result > 0) {
                return success("修改银行机构成功");
            }

            return error("修改银行机构失败");
        } catch (Exception e) {
            logger.error("修改银行机构失败", e);
            return error("修改银行机构失败：" + e.getMessage());
        }
    }

    /**
     * 删除银行机构 - 只允许金融机构账号操作
     */
    @PreAuthorize("@ss.hasPermi('credit:bank:remove')")
    @Log(title = "银行机构", businessType = BusinessType.DELETE)
    @DeleteMapping("/{bankIds}")
    public AjaxResult remove(@PathVariable Long[] bankIds) {
        try {
            // 获取当前用户信息
            String currentUserName = SecurityUtils.getUsername();
            String currentUserType = getCurrentUserType();

            // 权限检查：只有金融机构账号才能删除银行机构
            if (!BankInstitution.CREATOR_FINANCIAL_COMPANY.equals(currentUserType)) {
                return error("只有金融机构账号才能删除银行机构");
            }

            // 检查权限：金融公司账号只能删除自己创建的银行
            for (Long bankId : bankIds) {
                BankInstitution existingBank = bankInstitutionService.selectBankInstitutionByBankId(bankId);
                if (existingBank == null || !currentUserName.equals(existingBank.getCreateBy())) {
                    return error("您只能删除自己创建的银行机构");
                }
            }

            int result = bankInstitutionService.deleteBankInstitutionByBankIds(bankIds);
            if (result > 0) {
                return success("删除银行机构成功");
            }

            return error("删除银行机构失败");
        } catch (Exception e) {
            logger.error("删除银行机构失败", e);
            return error("删除银行机构失败：" + e.getMessage());
        }
    }

    /**
     * 查询活跃的银行机构列表
     */
    @PreAuthorize("@ss.hasPermi('credit:bank:list')")
    @GetMapping("/active")
    public AjaxResult getActiveBankInstitutions() {
        try {
            List<BankInstitution> activeBanks = bankInstitutionService.selectActiveBankInstitutions();
            return success(activeBanks);
        } catch (Exception e) {
            logger.error("查询活跃银行机构列表失败", e);
            return error("查询活跃银行机构列表失败：" + e.getMessage());
        }
    }

    /**
     * 根据贷款条件匹配银行机构
     */
    @PreAuthorize("@ss.hasPermi('credit:bank:list')")
    @GetMapping("/match")
    public AjaxResult matchBankInstitutions(@RequestParam(required = false) java.math.BigDecimal loanAmount,
            @RequestParam(required = false) Integer loanTermMonths) {
        try {
            List<BankInstitution> matchedBanks = bankInstitutionService.matchBankInstitutions(loanAmount, loanTermMonths);
            return success(matchedBanks);
        } catch (Exception e) {
            logger.error("匹配银行机构失败", e);
            return error("匹配银行机构失败：" + e.getMessage());
        }
    }

    /**
     * 获取当前用户类型 基于系统角色来判断用户是金融机构账号还是系统管理员
     */
    private String getCurrentUserType() {
        try {
            // 获取当前登录用户的角色信息
            com.ruoyi.common.core.domain.model.LoginUser loginUser = SecurityUtils.getLoginUser();
            if (loginUser != null && loginUser.getUser() != null && loginUser.getUser().getRoles() != null) {
                // 检查是否有金融机构相关角色
                boolean isFinancialRole = loginUser.getUser().getRoles().stream()
                        .anyMatch(role -> "financial_institution".equals(role.getRoleKey())
                        || "financial_approver".equals(role.getRoleKey()));

                if (isFinancialRole) {
                    return BankInstitution.CREATOR_FINANCIAL_COMPANY;
                }
            }

            // 默认为系统管理员
            return BankInstitution.CREATOR_SYSTEM;
        } catch (Exception e) {
            logger.warn("获取用户类型失败，默认为系统管理员", e);
            return BankInstitution.CREATOR_SYSTEM;
        }
    }
}
