<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>银行机构匹配</span>
        </div>
      </template>
      
      <!-- 数据来源说明 -->
      <el-alert
        title="数据来源说明"
        type="info"
        :closable="false"
        show-icon
        class="mb-4">
        <template #default>
          银行匹配数据来源于周期贷款系统，确保与实际业务流程保持一致。
        </template>
      </el-alert>
      
      <el-form :model="matchForm" ref="matchRef" :rules="matchRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="贷款金额" prop="loanAmount">
              <el-input-number
                v-model="matchForm.loanAmount"
                :precision="2"
                :step="10000"
                :min="0"
                placeholder="请输入贷款金额"
                style="width: 100%"
              />
              <span class="input-suffix">元</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="贷款期限" prop="loanTermMonths">
              <el-input-number
                v-model="matchForm.loanTermMonths"
                :min="1"
                :max="360"
                placeholder="请输入贷款期限"
                style="width: 100%"
              />
              <span class="input-suffix">个月</span>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item>
          <el-button type="primary" @click="handleMatch" :loading="matchLoading">
            <el-icon><Search /></el-icon>
            匹配银行
          </el-button>
          <el-button @click="resetMatch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="box-card" v-if="matchResults.length > 0" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>匹配结果 ({{ matchResults.length }}家银行)</span>
        </div>
      </template>
      
      <el-table :data="matchResults" style="width: 100%">
        <el-table-column label="银行名称" prop="bankName" show-overflow-tooltip />
        <el-table-column label="银行类型" align="center" prop="bankType">
          <template #default="scope">
            <dict-tag :options="bank_type" :value="scope.row.bankType"/>
          </template>
        </el-table-column>
        <el-table-column label="基准利率" align="center" prop="baseInterestRate">
          <template #default="scope">
            {{ (scope.row.baseInterestRate * 100).toFixed(2) }}%
          </template>
        </el-table-column>
        <el-table-column label="贷款金额范围" align="center">
          <template #default="scope">
            {{ formatCurrency(scope.row.minLoanAmount) }} - {{ formatCurrency(scope.row.maxLoanAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="贷款期限范围" align="center">
          <template #default="scope">
            {{ scope.row.minLoanTermMonths }} - {{ scope.row.maxLoanTermMonths }}个月
          </template>
        </el-table-column>
        <el-table-column label="风险评级" align="center" prop="riskRating">
          <template #default="scope">
            <el-tag :type="getRiskRatingType(scope.row.riskRating)">
              {{ scope.row.riskRating }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="联系人" align="center" prop="contactPerson" />
        <el-table-column label="操作" align="center" width="120">
          <template #default="scope">
            <el-button link type="primary" @click="handleViewDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-empty v-if="showEmpty" description="暂无匹配的银行机构" />

    <!-- 银行详情对话框 -->
    <el-dialog title="银行机构详情" v-model="detailOpen" width="800px" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="银行编码">{{ detailForm.bankCode }}</el-descriptions-item>
        <el-descriptions-item label="银行名称">{{ detailForm.bankName }}</el-descriptions-item>
        <el-descriptions-item label="银行类型">
          <dict-tag :options="bank_type" :value="detailForm.bankType"/>
        </el-descriptions-item>
        <el-descriptions-item label="联系人">{{ detailForm.contactPerson }}</el-descriptions-item>
        <el-descriptions-item label="联系电话">{{ detailForm.contactPhone }}</el-descriptions-item>
        <el-descriptions-item label="联系邮箱">{{ detailForm.contactEmail }}</el-descriptions-item>
        <el-descriptions-item label="银行地址" :span="2">{{ detailForm.bankAddress }}</el-descriptions-item>
        <el-descriptions-item label="基准利率">{{ (detailForm.baseInterestRate * 100).toFixed(2) }}%</el-descriptions-item>
        <el-descriptions-item label="风险评级">
          <el-tag :type="getRiskRatingType(detailForm.riskRating)">
            {{ detailForm.riskRating }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="最低贷款金额">{{ formatCurrency(detailForm.minLoanAmount) }}</el-descriptions-item>
        <el-descriptions-item label="最高贷款金额">{{ formatCurrency(detailForm.maxLoanAmount) }}</el-descriptions-item>
        <el-descriptions-item label="最短期限">{{ detailForm.minLoanTermMonths }}个月</el-descriptions-item>
        <el-descriptions-item label="最长期限">{{ detailForm.maxLoanTermMonths }}个月</el-descriptions-item>
        <el-descriptions-item label="合作状态">
          <el-tag :type="getCooperationStatusType(detailForm.cooperationStatus)">
            {{ getCooperationStatusLabel(detailForm.cooperationStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="备注信息" :span="2">{{ detailForm.remarks }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailOpen = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="BankMatch">
import { matchBankInstitutions, getBankInstitution } from "@/api/digitalCredit/loan/bankInstitution";
import { Search, Refresh } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();
const { bank_type } = proxy.useDict('bank_type');

const matchLoading = ref(false);
const detailOpen = ref(false);
const showEmpty = ref(false);
const matchResults = ref([]);
const detailForm = ref({});

const matchForm = ref({
  loanAmount: null,
  loanTermMonths: null
});

const matchRules = {
  loanAmount: [
    { required: true, message: "贷款金额不能为空", trigger: "blur" },
    { type: "number", min: 1000, message: "贷款金额不能少于1000元", trigger: "blur" }
  ],
  loanTermMonths: [
    { required: true, message: "贷款期限不能为空", trigger: "blur" },
    { type: "number", min: 1, max: 360, message: "贷款期限必须在1-360个月之间", trigger: "blur" }
  ]
};

/** 匹配银行机构 */
function handleMatch() {
  proxy.$refs["matchRef"].validate(valid => {
    if (valid) {
      matchLoading.value = true;
      showEmpty.value = false;
      
      matchBankInstitutions(matchForm.value.loanAmount, matchForm.value.loanTermMonths)
        .then(response => {
          matchResults.value = response.data || [];
          if (matchResults.value.length === 0) {
            showEmpty.value = true;
          }
          proxy.$modal.msgSuccess(`匹配成功，找到${matchResults.value.length}家符合条件的银行`);
        })
        .catch(() => {
          matchResults.value = [];
          showEmpty.value = true;
        })
        .finally(() => {
          matchLoading.value = false;
        });
    }
  });
}

/** 重置匹配条件 */
function resetMatch() {
  matchForm.value = {
    loanAmount: null,
    loanTermMonths: null
  };
  matchResults.value = [];
  showEmpty.value = false;
  proxy.resetForm("matchRef");
}

/** 查看银行详情 */
function handleViewDetail(row) {
  getBankInstitution(row.bankId).then(response => {
    detailForm.value = response.data;
    detailOpen.value = true;
  });
}

/** 获取风险评级标签类型 */
function getRiskRatingType(rating) {
  const ratingMap = {
    'AAA': 'success',
    'AA': 'success',
    'A': 'primary',
    'BBB': 'warning',
    'BB': 'warning',
    'B': 'danger'
  };
  return ratingMap[rating] || 'info';
}

/** 获取合作状态标签类型 */
function getCooperationStatusType(status) {
  const statusMap = {
    'ACTIVE': 'success',
    'SUSPENDED': 'warning',
    'TERMINATED': 'danger'
  };
  return statusMap[status] || 'info';
}

/** 获取合作状态标签文本 */
function getCooperationStatusLabel(status) {
  const statusMap = {
    'ACTIVE': '合作中',
    'SUSPENDED': '暂停合作',
    'TERMINATED': '终止合作'
  };
  return statusMap[status] || status;
}

/** 格式化货币 */
function formatCurrency(amount) {
  if (!amount) return '0';
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(amount);
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.input-suffix {
  margin-left: 8px;
  color: #909399;
}

.box-card {
  margin-bottom: 20px;
}
</style>