<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>融资申请管理</span>
          <div>
            <el-button type="success" @click="handleValidateAll" :loading="validationLoading">
              <el-icon><Check /></el-icon>
              批量验证
            </el-button>
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 查询条件 -->
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="申请编号" prop="applicationNumber">
          <el-input
            v-model="queryParams.applicationNumber"
            placeholder="请输入申请编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="债权编号" prop="creditNumber">
          <el-input
            v-model="queryParams.creditNumber"
            placeholder="请输入债权编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="申请人名称" prop="applicantName" label-width="90px">
          <el-input
            v-model="queryParams.applicantName"
            placeholder="请输入申请人名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="金融机构" prop="financialInstitutionName">
          <el-input
            v-model="queryParams.financialInstitutionName"
            placeholder="请输入金融机构名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="融资状态" prop="financingStatus">
          <el-select v-model="queryParams.financingStatus" placeholder="请选择融资状态" clearable>
            <el-option label="待审批" value="PENDING" />
            <el-option label="审批通过" value="APPROVED" />
            <el-option label="审批拒绝" value="REJECTED" />
            <el-option label="已放款" value="DISBURSED" />
            <el-option label="已结清" value="SETTLED" />
          </el-select>
        </el-form-item>
        <el-form-item label="风险等级" prop="riskLevel">
          <el-select v-model="queryParams.riskLevel" placeholder="请选择风险等级" clearable>
            <el-option label="低风险" value="LOW" />
            <el-option label="中风险" value="MEDIUM" />
            <el-option label="高风险" value="HIGH" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 操作工具栏 -->
      <el-row :gutter="10" class="mb8">
        <!--<el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['credit:financing:add']"
          >新增申请</el-button>
        </el-col> -->
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['credit:financing:export']"
          >导出</el-button>
        </el-col>
      </el-row>

      <!-- 统计信息 -->
      <el-row :gutter="20" class="stats-row">
        <el-col :span="4">
          <el-card class="stats-card">
            <el-statistic title="通过验证融资" :value="stats.eligibleCount" />
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stats-card">
            <el-statistic title="待审批金额" :value="stats.pendingAmount" :precision="2" suffix="万元" />
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stats-card">
            <el-statistic title="已放款金额" :value="stats.disbursedAmount" :precision="2" suffix="万元" />
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stats-card">
            <el-statistic title="验证通过率" :value="stats.passRate" :precision="1" suffix="%" />
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stats-card">
            <el-statistic title="总验证次数" :value="stats.totalValidations" />
          </el-card>
        </el-col>
        <el-col :span="4">
          <el-card class="stats-card">
            <el-statistic title="风险评级" :value="stats.riskLevel" />
          </el-card>
        </el-col>
      </el-row>

      <!-- 融资申请列表 -->
      <el-table v-loading="loading" :data="loanList" border>
        <el-table-column label="融资ID" prop="financingId" min-width="120" />
        <el-table-column label="申请编号" prop="applicationNumber" min-width="160" show-overflow-tooltip />
        <el-table-column label="债权编号" prop="creditNumber" min-width="160" show-overflow-tooltip />
        <el-table-column label="申请人名称" prop="applicantName" min-width="120" />
        <el-table-column label="金融机构名称" prop="financialInstitutionName" min-width="140" show-overflow-tooltip />
        <el-table-column label="申请金额" prop="requestedAmount" min-width="120" align="right">
          <template #default="scope">
            {{ formatMoney(scope.row.requestedAmount) }}
          </template>
        </el-table-column>
        <el-table-column label="批准金额" prop="approvedAmount" min-width="120" align="right">
          <template #default="scope">
            {{ scope.row.approvedAmount ? formatMoney(scope.row.approvedAmount) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="利率" prop="interestRate" min-width="80" align="center">
          <template #default="scope">
            {{ scope.row.interestRate ? (parseFloat(scope.row.interestRate) * 100).toFixed(2) + '%' : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="融资期限" prop="financingTerm" min-width="100" align="center">
          <template #default="scope">
            {{ scope.row.financingTerm ? scope.row.financingTerm + '天' : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="融资状态" prop="financingStatus" min-width="100" align="center">
          <template #default="scope">
            <el-tag :type="getFinancingStatusType(scope.row.financingStatus)">
              {{ getFinancingStatusText(scope.row.financingStatus) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="风险等级" prop="riskLevel" min-width="100" align="center">
          <template #default="scope">
            <el-tag :type="getRiskLevelType(scope.row.riskLevel)" v-if="scope.row.riskLevel">
              {{ getRiskLevelText(scope.row.riskLevel) }}
            </el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="风险评分" prop="riskScore" min-width="100" align="center">
          <template #default="scope">
            <span v-if="scope.row.riskScore" :style="{ color: getRiskScoreColor(scope.row.riskScore) }">
              {{ scope.row.riskScore }}
            </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="审批人" prop="createBy" min-width="100" />
        <el-table-column label="审批时间" prop="approvedTime" min-width="160">
          <template #default="scope">
            {{ scope.row.approvedTime ? parseTime(scope.row.approvedTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="放款时间" prop="disbursementTime" min-width="160">
          <template #default="scope">
            {{ scope.row.disbursementTime ? parseTime(scope.row.disbursementTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="createTime" min-width="160">
          <template #default="scope">
            {{ parseTime(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="280" align="center" fixed="right">
          <template #default="scope">
            <!-- 已放款状态：显示详细按钮和状态 -->
            <div v-if="scope.row.financingStatus === 'DISBURSED'" class="disbursed-container">
              <el-button 
                link 
                type="primary" 
                size="small" 
                @click="handleViewDetails(scope.row)"
                class="details-btn">
                <el-icon><View /></el-icon>
                详细
              </el-button>
              <el-tag type="success" size="small" class="disbursed-tag">
                已放款
              </el-tag>
            </div>
            <!-- 其他状态的按钮 -->
            <template v-else>
              <!-- 待审批状态 -->
              <div v-if="scope.row.financingStatus === 'PENDING'" class="status-container pending">
                <el-button 
                  link 
                  type="primary" 
                  size="small" 
                  @click="handleApprove(scope.row)"
                  v-hasPermi="['credit:financing:approve']"
                  class="action-btn">
                  <el-icon><Edit /></el-icon>
                  审批
                </el-button>
                <el-button 
                  link 
                  type="danger" 
                  size="small" 
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['credit:financing:remove']"
                  class="action-btn">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
                <el-tag type="warning" size="small" class="status-tag">
                  <el-icon><Clock /></el-icon>
                  待审批
                </el-tag>
              </div>
              
              <!-- 已审批状态 -->
              <div v-if="scope.row.financingStatus === 'APPROVED'" class="status-container approved">
                <el-button 
                  link 
                  type="success" 
                  size="small" 
                  @click="handleDisburse(scope.row)"
                  v-hasPermi="['credit:financing:disburse']"
                  class="action-btn">
                  <el-icon><Money /></el-icon>
                  放款
                </el-button>
                <el-tag type="primary" size="small" class="status-tag">
                  <el-icon><CircleCheck /></el-icon>
                  已审批
                </el-tag>
              </div>
              
              <!-- 其他状态 -->
              <div v-if="scope.row.financingStatus !== 'PENDING' && scope.row.financingStatus !== 'APPROVED'" class="status-container other">
                <el-tag :type="getFinancingStatusType(scope.row.financingStatus)" size="small" class="status-tag">
                  {{ getFinancingStatusText(scope.row.financingStatus) }}
                </el-tag>
              </div>
            </template>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 融资审批对话框 -->
    <el-dialog v-model="approvalDialogVisible" title="融资审批" width="60%" append-to-body>
      <el-form :model="approvalForm" :rules="approvalRules" ref="approvalFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请编号">
              <el-input v-model="approvalForm.applicationNumber" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请金额">
              <el-input v-model="approvalForm.requestedAmount" readonly>
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审批结果" prop="approvalResult">
              <el-radio-group v-model="approvalForm.approvalResult">
                <el-radio label="APPROVED">批准</el-radio>
                <el-radio label="REJECTED">拒绝</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="批准金额" prop="approvedAmount" v-if="approvalForm.approvalResult === 'APPROVED'">
              <el-input-number 
                v-model="approvalForm.approvedAmount" 
                :min="0" 
                :max="approvalForm.requestedAmount"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="利率(%)" prop="interestRate" v-if="approvalForm.approvalResult === 'APPROVED'">
              <el-input-number 
                v-model="approvalForm.interestRate" 
                :min="0" 
                :max="20"
                :precision="2"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="融资期限(天)" prop="financingTerm" v-if="approvalForm.approvalResult === 'APPROVED'">
              <el-input-number 
                v-model="approvalForm.financingTerm" 
                :min="1" 
                :max="365"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="审批意见" prop="approvalOpinion">
          <el-input 
            v-model="approvalForm.approvalOpinion" 
            type="textarea" 
            :rows="4"
            placeholder="请输入审批意见"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="approvalDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitApproval" :loading="approvalLoading">
            提交审批
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 验证详情对话框 -->
    <el-dialog v-model="validationDetailsVisible" title="验证详情" width="70%" append-to-body>
      <div class="validation-details-container">
        <!-- 基本信息 -->
        <el-card class="validation-basic-info" shadow="never">
          <template #header>
            <span>基本信息</span>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="申请编号">
              {{ validationDetails.applicationNumber }}
            </el-descriptions-item>
            <el-descriptions-item label="融资ID">
              {{ validationDetails.financingId }}
            </el-descriptions-item>
            <el-descriptions-item label="验证状态">
              <el-tag 
                :type="getValidationStatusType(validationDetails.validationStatus)"
                :icon="getValidationStatusIcon(validationDetails.validationStatus)"
              >
                {{ getValidationStatusText(validationDetails.validationStatus) }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="验证时间">
              {{ parseTime(validationDetails.validationTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="验证得分" v-if="validationDetails.validationScore !== undefined">
              <el-progress 
                :percentage="validationDetails.validationScore" 
                :color="getScoreColor(validationDetails.validationScore)"
                :show-text="true"
                :format="(percentage) => `${percentage}分`"
              />
            </el-descriptions-item>
            <el-descriptions-item label="规则版本" v-if="validationDetails.ruleVersion">
              {{ validationDetails.ruleVersion }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 验证结果详情 -->
        <el-card class="validation-result-details" shadow="never" v-if="validationDetails.validationResult">
          <template #header>
            <span>验证结果详情</span>
          </template>
          <div class="validation-result-content">
            <pre>{{ formatValidationResult(validationDetails.validationResult) }}</pre>
          </div>
        </el-card>

        <!-- 失败原因详情 -->
        <el-card 
          class="validation-failure-details" 
          shadow="never" 
          v-if="validationDetails.failureReason && (validationDetails.validationStatus === 'FAIL' || validationDetails.validationStatus === 'FAILED')"
        >
          <template #header>
            <span>失败原因详情</span>
          </template>
          <el-alert
            :title="validationDetails.failureReason"
            type="error"
            :closable="false"
            show-icon
          >
            <template #default>
              <div class="failure-reason-content">
                <p><strong>问题描述:</strong></p>
                <p>{{ getFailureDescription(validationDetails.failureReason) }}</p>
                
                <p><strong>建议解决方案:</strong></p>
                <ul>
                  <li v-for="solution in getFailureSolutions(validationDetails.failureReason)" :key="solution">
                    {{ solution }}
                  </li>
                </ul>
                
                <p><strong>相关数据:</strong></p>
                <p v-if="validationDetails.creditId">债权凭证ID: {{ validationDetails.creditId }}</p>
                <p v-if="validationDetails.servicePeriodId">服务周期ID: {{ validationDetails.servicePeriodId }}</p>
              </div>
            </template>
          </el-alert>
        </el-card>

        <!-- 验证历史记录 -->
        <el-card class="validation-history" shadow="never" v-if="validationHistory.length > 0">
          <template #header>
            <span>验证历史记录</span>
          </template>
          <el-timeline>
            <el-timeline-item
              v-for="(record, index) in validationHistory"
              :key="index"
              :timestamp="parseTime(record.validationTime)"
              :type="getTimelineType(record.validationStatus)"
              :icon="getValidationStatusIcon(record.validationStatus)"
            >
              <el-card shadow="hover">
                <div class="history-record">
                  <div class="record-header">
                    <el-tag 
                      :type="getValidationStatusType(record.validationStatus)"
                      size="small"
                    >
                      {{ getValidationStatusText(record.validationStatus) }}
                    </el-tag>
                    <span class="record-score" v-if="record.validationScore !== undefined">
                      得分: {{ record.validationScore }}
                    </span>
                  </div>
                  <div class="record-content" v-if="record.validationResult">
                    {{ record.validationResult }}
                  </div>
                  <div class="record-failure" v-if="record.failureReason">
                    <el-text type="danger">{{ record.failureReason }}</el-text>
                  </div>
                </div>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-card>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="validationDetailsVisible = false">关闭</el-button>
          <el-button 
            type="warning" 
            @click="handleRevalidateFromDetails"
            :loading="revalidatingFromDetails"
            v-if="validationDetails.validationStatus === 'FAIL' || validationDetails.validationStatus === 'FAILED'"
          >
            重新验证
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增融资申请对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增融资申请" width="60%" append-to-body>
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请编号" prop="applicationNumber">
              <el-input v-model="addForm.applicationNumber" placeholder="请输入申请编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="债权ID" prop="creditId">
              <el-input v-model="addForm.creditId" placeholder="请输入债权ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="债权编号" prop="creditNumber">
              <el-input v-model="addForm.creditNumber" placeholder="请输入债权编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请人ID" prop="applicantId">
              <el-input v-model="addForm.applicantId" placeholder="请输入申请人ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="申请人名称" prop="applicantName">
              <el-input v-model="addForm.applicantName" placeholder="请输入申请人名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金融机构ID" prop="financialInstitutionId">
              <el-input v-model="addForm.financialInstitutionId" placeholder="请输入金融机构ID" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="金融机构名称" prop="financialInstitutionName">
              <el-input v-model="addForm.financialInstitutionName" placeholder="请输入金融机构名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="申请金额" prop="requestedAmount">
              <el-input-number 
                v-model="addForm.requestedAmount" 
                :min="0" 
                :precision="2"
                style="width: 100%"
                placeholder="请输入申请金额"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="融资期限" prop="financingTerm">
              <el-input-number 
                v-model="addForm.financingTerm" 
                :min="1" 
                :max="365"
                style="width: 100%"
              />
              <span style="margin-left: 8px; color: #909399;">天</span>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="申请材料" prop="applicationMaterials">
          <el-input 
            v-model="addForm.applicationMaterials" 
            type="textarea" 
            :rows="3"
            placeholder="请输入申请材料说明"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input 
            v-model="addForm.remark" 
            type="textarea" 
            :rows="2"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAdd" :loading="addLoading">
            提交申请
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 放款对话框 -->
    <el-dialog v-model="disburseDialogVisible" title="融资放款" width="50%" append-to-body>
      <el-form :model="disburseForm" :rules="disburseRules" ref="disburseFormRef" label-width="120px">
        <el-form-item label="申请编号">
          <el-input v-model="disburseForm.applicationNumber" readonly />
        </el-form-item>
        <el-form-item label="批准金额">
          <el-input v-model="disburseForm.approvedAmount" readonly>
            <template #append>元</template>
          </el-input>
        </el-form-item>
        <el-form-item label="放款账户" prop="disbursementAccount">
          <el-input v-model="disburseForm.disbursementAccount" placeholder="请输入放款账户" />
        </el-form-item>
        <el-form-item label="放款备注" prop="disbursementNote">
          <el-input 
            v-model="disburseForm.disbursementNote" 
            type="textarea" 
            :rows="3"
            placeholder="请输入放款备注"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="disburseDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitDisburse" :loading="disburseLoading">
            确认放款
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 贷款详细信息对话框 -->
    <el-dialog v-model="detailsDialogVisible" title="贷款详细信息" width="60%" append-to-body>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="申请编号">
          {{ loanDetails.applicationNumber }}
        </el-descriptions-item>
        <el-descriptions-item label="放款状态">
          <el-tag type="success" size="large">
            <el-icon><Check /></el-icon>
            已放款
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="贷款金额">
          <span style="color: #409EFF; font-weight: bold;">
            {{ formatMoney(loanDetails.requestedAmount) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="批准金额">
          <span style="color: #67C23A; font-weight: bold;">
            {{ formatMoney(loanDetails.approvedAmount) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="合同编号">
          {{ loanDetails.contractNumber || '暂无' }}
        </el-descriptions-item>
        <el-descriptions-item label="放款时间">
          {{ loanDetails.disbursementTime ? parseTime(loanDetails.disbursementTime) : '暂无' }}
        </el-descriptions-item>
        <el-descriptions-item label="利润">
          <span style="color: #E6A23C; font-weight: bold;">
            {{ calculateProfit(loanDetails) }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="利率">
          {{ loanDetails.interestRate ? (parseFloat(loanDetails.interestRate) * 100).toFixed(2) + '%' : '暂无' }}
        </el-descriptions-item>
        <el-descriptions-item label="融资期限">
          {{ loanDetails.financingTerm ? loanDetails.financingTerm + '天' : '暂无' }}
        </el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailsDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="LoanManagement">
import { ref, getCurrentInstance, onMounted, onUnmounted } from 'vue';
import { listFinancing, getFinancing, applyFinancing, updateFinancing, delFinancing, approveFinancing, riskAssessment, getInterestRate, getFinancingStats, getRiskAssessmentHistory, disburseFinancing, exportFinancing } from "@/api/credit/financing";
import { revalidateLoan, validateAllLoans, getLoanValidationStatus } from "@/api/credit/loanConsistency";

const { proxy } = getCurrentInstance();

// 响应式数据
const loading = ref(true);
const showSearch = ref(true);
const loanList = ref([]);
const total = ref(0);
const validationLoading = ref(false);
const stats = ref({
  eligibleCount: 0,
  pendingAmount: 0,
  disbursedAmount: 0,
  riskLevel: 'A',
  totalValidations: 0,
  passedValidations: 0,
  failedValidations: 0,
  passRate: 0
});

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  applicationNumber: null,
  creditNumber: null,
  applicantName: null,
  financialInstitutionName: null,
  financingStatus: null,
  riskLevel: null
});

// 审批对话框
const approvalDialogVisible = ref(false);
const approvalLoading = ref(false);
const approvalForm = ref({
  creditId: null,
  financingId: null,
  applicationNumber: '',
  requestedAmount: 0,
  approvalResult: 'APPROVED',
  approvedAmount: 0,
  interestRate: 0.05,
  financingTerm: 30,
  approvalOpinion: ''
});

const approvalRules = {
  approvalResult: [
    { required: true, message: "请选择审批结果", trigger: "change" }
  ],
  approvedAmount: [
    { required: true, message: "请输入批准金额", trigger: "blur" }
  ],
  interestRate: [
    { required: true, message: "请输入利率", trigger: "blur" }
  ],
  financingTerm: [
    { required: true, message: "请输入融资期限", trigger: "blur" }
  ],
  approvalOpinion: [
    { required: true, message: "请输入审批意见", trigger: "blur" }
  ]
};

// 放款对话框
const disburseDialogVisible = ref(false);
const disburseLoading = ref(false);
const disburseForm = ref({
  creditId: null,
  financingId: null,
  applicationNumber: '',
  approvedAmount: 0,
  disbursementAccount: '',
  disbursementNote: ''
});

// 新增申请对话框
const addDialogVisible = ref(false);
const addLoading = ref(false);
const addForm = ref({
  applicationNumber: '',
  creditId: '',
  creditNumber: '',
  applicantId: '',
  applicantName: '',
  financialInstitutionId: '',
  financialInstitutionName: '',
  requestedAmount: null,
  financingTerm: 30,
  applicationMaterials: '',
  remark: ''
});

const addRules = {
  applicationNumber: [
    { required: true, message: "请输入申请编号", trigger: "blur" }
  ],
  creditId: [
    { required: true, message: "请输入债权ID", trigger: "blur" }
  ],
  creditNumber: [
    { required: true, message: "请输入债权编号", trigger: "blur" }
  ],
  applicantName: [
    { required: true, message: "请输入申请人名称", trigger: "blur" }
  ],
  financialInstitutionName: [
    { required: true, message: "请输入金融机构名称", trigger: "blur" }
  ],
  requestedAmount: [
    { required: true, message: "请输入申请金额", trigger: "blur" }
  ],
  financingTerm: [
    { required: true, message: "请输入融资期限", trigger: "blur" }
  ]
};

// 验证详情对话框
const validationDetailsVisible = ref(false);
const validationDetails = ref({
  creditId: null,
  loanId: null,
  financingId: null,
  applicationNumber: '',
  contractId: null,
  validationStatus: '',
  validationTime: null,
  validationResult: '',
  failureReason: '',
  validationScore: null,
  ruleVersion: '',
  servicePeriodId: null
});
const validationHistory = ref([]);
const revalidatingFromDetails = ref(false);

// 贷款详细信息对话框
const detailsDialogVisible = ref(false);
const loanDetails = ref({
  applicationNumber: '',
  requestedAmount: 0,
  approvedAmount: 0,
  contractNumber: '',
  disbursementTime: null,
  interestRate: 0,
  financingTerm: 0
});

// 实时更新相关
const statusUpdateInterval = ref(null);
const VALIDATION_STATUS_UPDATE_INTERVAL = 5000; // 5秒更新一次

const disburseRules = {
  disbursementAccount: [
    { required: true, message: "请输入放款账户", trigger: "blur" }
  ],
  disbursementNote: [
    { required: true, message: "请输入放款备注", trigger: "blur" }
  ]
};

/** 查询贷款列表 */
function getList() {
  loading.value = true;
  
  // 构建查询参数，映射到financing API的参数结构
  const params = {
    pageNum: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    applicationNumber: queryParams.value.applicationNumber,
    creditNumber: queryParams.value.creditNumber,
    applicantName: queryParams.value.applicantName,
    financialInstitutionName: queryParams.value.financialInstitutionName,
    financingStatus: queryParams.value.financingStatus,
    riskLevel: queryParams.value.riskLevel
  };

  // 过滤空值参数
  Object.keys(params).forEach(key => {
    if (params[key] === null || params[key] === undefined || params[key] === '') {
      delete params[key];
    }
  });
  
  // 调用融资API获取融资申请列表
  listFinancing(params).then(response => {
    const data = response.data || response;
    loanList.value = data.rows || data.list || data || [];
    total.value = data.total || 0;
    
    // 更新统计信息
    updateStats();
    loading.value = false;
  }).catch(error => {
    console.error('获取融资申请列表失败:', error);
    proxy.$modal.msgError("获取融资申请列表失败");
    loading.value = false;
    
    // 如果API调用失败，显示空列表
    loanList.value = [];
    total.value = 0;
    updateStats();
  });
}

/** 更新统计信息 */
function updateStats() {
  // 从融资统计API获取统计信息
  getFinancingStats().then(response => {
    const statsData = response.data || {};
    
    stats.value = {
      eligibleCount: statsData.eligibleCount || loanList.value.length,
      pendingAmount: (statsData.pendingAmount || loanList.value.filter(item => item.financingStatus === 'PENDING' || item.financingStatus === 'APPROVED')
        .reduce((sum, item) => sum + (parseFloat(item.requestedAmount) || 0), 0)) / 10000,
      disbursedAmount: (statsData.disbursedAmount || loanList.value.filter(item => item.financingStatus === 'DISBURSED')
        .reduce((sum, item) => sum + (parseFloat(item.approvedAmount) || 0), 0)) / 10000,
      riskLevel: statsData.riskLevel || 'A',
      totalValidations: statsData.totalValidations || loanList.value.length,
      passedValidations: statsData.passedValidations || loanList.value.filter(item => item.financingStatus === 'APPROVED').length,
      failedValidations: statsData.failedValidations || loanList.value.filter(item => item.financingStatus === 'REJECTED').length,
      passRate: statsData.passRate || (loanList.value.length > 0 ? 
        (loanList.value.filter(item => item.financingStatus === 'APPROVED').length / loanList.value.length * 100) : 0)
    };
  }).catch(error => {
    console.error('获取统计信息失败:', error);
    // 使用本地计算的基础统计信息
    stats.value = {
      eligibleCount: loanList.value.length,
      pendingAmount: loanList.value.filter(item => item.financingStatus === 'PENDING' || item.financingStatus === 'APPROVED')
        .reduce((sum, item) => sum + (parseFloat(item.requestedAmount) || 0), 0) / 10000,
      disbursedAmount: loanList.value.filter(item => item.financingStatus === 'DISBURSED')
        .reduce((sum, item) => sum + (parseFloat(item.approvedAmount) || 0), 0) / 10000,
      riskLevel: 'A',
      totalValidations: loanList.value.length,
      passedValidations: loanList.value.filter(item => item.financingStatus === 'APPROVED').length,
      failedValidations: loanList.value.filter(item => item.financingStatus === 'REJECTED').length,
      passRate: loanList.value.length > 0 ? 
        (loanList.value.filter(item => item.financingStatus === 'APPROVED').length / loanList.value.length * 100) : 0
    };
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 刷新数据 */
function refreshData() {
  getList();
  proxy.$modal.msgSuccess("数据已刷新");
}

/** 批量验证所有贷款 */
function handleValidateAll() {
  validationLoading.value = true;
  
  validateAllLoans().then(response => {
    validationLoading.value = false;
    proxy.$modal.msgSuccess("批量验证已启动，请稍后刷新查看结果");
    
    // 延迟刷新数据以获取验证结果
    setTimeout(() => {
      getList();
    }, 800);
  }).catch(error => {
    console.error('批量验证失败:', error);
    validationLoading.value = false;
    proxy.$modal.msgError("批量验证失败，请稍后重试");
  });
}

/** 重新验证单个贷款 */
function handleRevalidate(row) {
  // 设置该行的重新验证状态
  row.revalidating = true;
  
  revalidateLoan(row.loanId).then(response => {
    row.revalidating = false;
    proxy.$modal.msgSuccess("重新验证已启动");
    
    // 延迟刷新数据以获取验证结果
    setTimeout(() => {
      getList();
    }, 1500);
  }).catch(error => {
    console.error('重新验证失败:', error);
    row.revalidating = false;
    proxy.$modal.msgError("重新验证失败，请稍后重试");
  });
}

/** 审批融资申请 */
function handleApprove(row) {
  approvalForm.value = {
    creditId: row.creditId,
    financingId: row.financingId,
    applicationNumber: row.applicationNumber,
    requestedAmount: parseFloat(row.requestedAmount),
    approvalResult: 'APPROVED',
    approvedAmount: parseFloat(row.requestedAmount),
    interestRate: 5.0, // 默认5%
    financingTerm: row.financingTerm || 30, // 默认30天
    approvalOpinion: ''
  };
  approvalDialogVisible.value = true;
}

/** 提交审批 */
function submitApproval() {
  proxy.$refs["approvalFormRef"].validate(valid => {
    if (valid) {
      approvalLoading.value = true;
      
      // 准备审批数据
      const approvalData = {
        status: approvalForm.value.approvalResult === 'APPROVED' ? 'APPROVED' : 'REJECTED',
        approvedAmount: approvalForm.value.approvedAmount,
        interestRate: approvalForm.value.interestRate / 100, // 转换为小数
        approvalNote: approvalForm.value.approvalOpinion
      };
      
      // 调用真实的审批API
      approveFinancing(approvalForm.value.financingId, approvalData).then(response => {
        approvalLoading.value = false;
        approvalDialogVisible.value = false;
        
        if (approvalForm.value.approvalResult === 'APPROVED') {
          proxy.$modal.msgSuccess("融资申请审批通过");
        } else {
          proxy.$modal.msgSuccess("融资申请审批已拒绝");
        }
        
        getList(); // 刷新列表
      }).catch(error => {
        console.error('审批失败:', error);
        approvalLoading.value = false;
        proxy.$modal.msgError(error.msg || "审批失败，请稍后重试");
      });
    }
  });
}

/** 放款操作 */
function handleDisburse(row) {
  disburseForm.value = {
    creditId: row.creditId,
    financingId: row.financingId,
    applicationNumber: row.applicationNumber,
    approvedAmount: parseFloat(row.approvedAmount || row.requestedAmount),
    disbursementAccount: '',
    disbursementNote: ''
  };
  disburseDialogVisible.value = true;
}

/** 提交放款 */
function submitDisburse() {
  proxy.$refs["disburseFormRef"].validate(valid => {
    if (valid) {
      disburseLoading.value = true;
      
      // 准备放款数据
      const disburseData = {
        creditId: disburseForm.value.creditId,
        disbursementAccount: disburseForm.value.disbursementAccount,
        disbursementNote: disburseForm.value.disbursementNote
      };
      console.log(disburseForm.value.financingId)
      // 调用真实的放款API
      disburseFinancing(disburseForm.value.financingId, disburseData).then(response => {
        disburseLoading.value = false;
        disburseDialogVisible.value = false;
        proxy.$modal.msgSuccess("放款成功");
        getList(); // 刷新列表
      }).catch(error => {
        console.error('放款失败:', error);
        disburseLoading.value = false;
        proxy.$modal.msgError(error.msg || "放款失败，请稍后重试");
      });
    }
  });
}

/** 查看贷款详细信息 */
function handleViewDetails(row) {
  loanDetails.value = {
    applicationNumber: row.applicationNumber,
    requestedAmount: row.requestedAmount,
    approvedAmount: row.approvedAmount,
    contractNumber: row.contractNumber || row.contractId,
    disbursementTime: row.disbursementTime,
    interestRate: row.interestRate,
    financingTerm: row.financingTerm
  };
  detailsDialogVisible.value = true;
}

/** 计算利润 */
function calculateProfit(details) {
  if (!details.approvedAmount || !details.interestRate || !details.financingTerm) {
    return '计算中...';
  }
  
  const principal = parseFloat(details.approvedAmount);
  const rate = parseFloat(details.interestRate);
  const days = parseInt(details.financingTerm);
  
  // 简单利息计算：本金 × 利率 × 天数 / 365
  const profit = principal * rate * days / 365;
  
  return formatMoney(profit);
}

/** 查看验证详情 */
function viewValidationDetails(row) {
  validationDetails.value = {
    creditId: row.creditId,
    loanId: row.loanId,
    financingId: row.financingId,
    applicationNumber: row.applicationNumber,
    contractId: row.contractId,
    validationStatus: row.validationStatus,
    validationTime: row.validationTime,
    validationResult: row.validationResult,
    failureReason: row.failureReason,
    validationScore: row.validationScore,
    ruleVersion: row.ruleVersion,
    servicePeriodId: row.servicePeriodId
  };
  
  // 获取详细的验证信息和历史记录
  getLoanValidationStatus(row.loanId).then(response => {
    const data = response.data || {};
    validationDetails.value = {
      ...validationDetails.value,
      ...data
    };
    
    // 获取验证历史记录
    validationHistory.value = data.history || [];
  }).catch(error => {
    console.error('获取验证详情失败:', error);
    // 使用当前行数据作为默认值
    validationHistory.value = [];
  });
  
  validationDetailsVisible.value = true;
}

/** 从验证详情对话框重新验证 */
function handleRevalidateFromDetails() {
  revalidatingFromDetails.value = true;
  
  revalidateLoan(validationDetails.value.loanId).then(response => {
    revalidatingFromDetails.value = false;
    proxy.$modal.msgSuccess("重新验证已启动");
    
    // 延迟刷新验证详情
    setTimeout(() => {
      viewValidationDetails({ 
        loanId: validationDetails.value.loanId,
        financingId: validationDetails.value.financingId,
        applicationNumber: validationDetails.value.applicationNumber,
        contractId: validationDetails.value.contractId
      });
      getList(); // 同时刷新列表
    }, 1500);
  }).catch(error => {
    console.error('重新验证失败:', error);
    revalidatingFromDetails.value = false;
    proxy.$modal.msgError("重新验证失败，请稍后重试");
  });
}

/** 启动实时状态更新 */
function startStatusUpdates() {
  // 清除现有的定时器
  if (statusUpdateInterval.value) {
    clearInterval(statusUpdateInterval.value);
  }
  
  // 设置新的定时器，定期检查验证中的记录
  statusUpdateInterval.value = setInterval(() => {
    const validatingRecords = loanList.value.filter(
      item => item.validationStatus === 'VALIDATING' || item.validationStatus === 'PENDING'
    );
    
    if (validatingRecords.length > 0) {
      // 只更新验证中的记录，避免全量刷新
      updateValidatingRecords(validatingRecords);
    }
  }, VALIDATION_STATUS_UPDATE_INTERVAL);
}

/** 停止实时状态更新 */
function stopStatusUpdates() {
  if (statusUpdateInterval.value) {
    clearInterval(statusUpdateInterval.value);
    statusUpdateInterval.value = null;
  }
}

/** 更新验证中的记录状态 */
function updateValidatingRecords(validatingRecords) {
  const promises = validatingRecords.map(record => 
    getLoanValidationStatus(record.loanId)
      .then(response => {
        const data = response.data || {};
        // 更新列表中对应记录的状态
        const index = loanList.value.findIndex(item => 
          item.loanId === record.loanId
        );
        if (index !== -1) {
          loanList.value[index] = {
            ...loanList.value[index],
            validationStatus: data.validationStatus || record.validationStatus,
            validationTime: data.validationTime || record.validationTime,
            validationResult: data.validationResult || record.validationResult,
            failureReason: data.failureReason || record.failureReason,
            validationScore: data.validationScore || record.validationScore
          };
        }
        return data;
      })
      .catch(error => {
        console.warn(`更新记录 ${record.loanId} 状态失败:`, error);
        return null;
      })
  );
  
  Promise.allSettled(promises).then(results => {
    // 检查是否有状态变化，如果有则显示提示
    const updatedCount = results.filter(result => 
      result.status === 'fulfilled' && result.value
    ).length;
    
    if (updatedCount > 0) {
      console.log(`已更新 ${updatedCount} 条验证记录状态`);
      // 可以选择显示轻量级提示
      // proxy.$message.info(`已更新 ${updatedCount} 条验证记录状态`);
    }
  });
}

/** 格式化验证时间显示 */
function formatValidationTime(time) {
  if (!time) return '';
  
  const now = new Date();
  const validationTime = new Date(time);
  const diffMs = now - validationTime;
  const diffMins = Math.floor(diffMs / (1000 * 60));
  const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
  const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
  
  if (diffMins < 1) return '刚刚';
  if (diffMins < 60) return `${diffMins}分钟前`;
  if (diffHours < 24) return `${diffHours}小时前`;
  if (diffDays < 7) return `${diffDays}天前`;
  
  return parseTime(time, '{m}-{d}');
}

/** 获取验证得分颜色 */
function getScoreColor(score) {
  if (score >= 90) return '#67C23A';
  if (score >= 70) return '#E6A23C';
  if (score >= 50) return '#F56C6C';
  return '#909399';
}

/** 格式化验证结果显示 */
function formatValidationResult(result) {
  if (!result) return '';
  
  try {
    // 尝试解析JSON格式的结果
    const parsed = JSON.parse(result);
    return JSON.stringify(parsed, null, 2);
  } catch (e) {
    // 如果不是JSON，直接返回原文本
    return result;
  }
}

/** 获取失败原因描述 */
function getFailureDescription(reason) {
  const descriptions = {
    'CREDIT_NOT_FOUND': '未找到对应的债权凭证记录',
    'CREDIT_INVALID': '债权凭证已失效或状态异常',
    'SERVICE_PERIOD_MISMATCH': '服务周期与债权凭证信息不匹配',
    'CONTRACT_INCONSISTENT': '合同信息与服务周期记录不一致',
    'AMOUNT_MISMATCH': '金额信息不匹配',
    'DATE_RANGE_INVALID': '日期范围验证失败',
    'BLOCKCHAIN_VERIFICATION_FAILED': '区块链验证失败',
    'DATA_INTEGRITY_ERROR': '数据完整性检查失败'
  };
  
  return descriptions[reason] || reason || '未知验证失败原因';
}

/** 获取失败解决方案 */
function getFailureSolutions(reason) {
  const solutions = {
    'CREDIT_NOT_FOUND': [
      '检查债权凭证是否已正确生成',
      '确认债权凭证ID是否正确',
      '联系系统管理员检查数据同步状态'
    ],
    'CREDIT_INVALID': [
      '检查债权凭证的有效期',
      '确认债权凭证状态是否为有效',
      '重新生成债权凭证'
    ],
    'SERVICE_PERIOD_MISMATCH': [
      '检查服务周期的时间范围设置',
      '确认服务周期与合同的关联关系',
      '更新服务周期信息以匹配债权凭证'
    ],
    'CONTRACT_INCONSISTENT': [
      '检查合同信息的完整性',
      '确认合同金额、期限等关键信息',
      '重新提交正确的合同信息'
    ],
    'AMOUNT_MISMATCH': [
      '检查贷款金额与债权金额是否一致',
      '确认服务周期中的金额计算',
      '重新核算相关金额信息'
    ],
    'DATE_RANGE_INVALID': [
      '检查合同起止日期设置',
      '确认服务周期时间范围',
      '调整日期范围以符合业务规则'
    ],
    'BLOCKCHAIN_VERIFICATION_FAILED': [
      '检查区块链网络连接状态',
      '重新进行区块链验证',
      '联系技术支持检查区块链服务'
    ],
    'DATA_INTEGRITY_ERROR': [
      '检查数据的完整性和一致性',
      '重新同步相关数据',
      '联系系统管理员进行数据修复'
    ]
  };
  
  return solutions[reason] || [
    '请联系系统管理员获取帮助',
    '检查相关数据的完整性',
    '尝试重新验证或重新提交'
  ];
}

/** 获取时间线类型 */
function getTimelineType(status) {
  const typeMap = {
    'PASS': 'success',
    'PASSED': 'success',
    'FAIL': 'danger',
    'FAILED': 'danger',
    'PENDING': 'warning',
    'VALIDATING': 'primary'
  };
  return typeMap[status] || 'info';
}

/** 新增融资申请 */
function handleAdd() {
  addDialogVisible.value = true;
  addForm.value = {
    applicationNumber: '',
    creditId: '',
    creditNumber: '',
    applicantId: '',
    applicantName: '',
    financialInstitutionId: '',
    financialInstitutionName: '',
    requestedAmount: null,
    financingTerm: 30,
    applicationMaterials: '',
    remark: ''
  };
}

/** 提交新增申请 */
function submitAdd() {
  proxy.$refs["addFormRef"].validate(valid => {
    if (valid) {
      addLoading.value = true;
      
      applyFinancing(addForm.value).then(response => {
        addLoading.value = false;
        addDialogVisible.value = false;
        proxy.$modal.msgSuccess("融资申请提交成功");
        getList(); // 刷新列表
      }).catch(error => {
        console.error('提交申请失败:', error);
        addLoading.value = false;
        proxy.$modal.msgError(error.msg || "提交申请失败，请稍后重试");
      });
    }
  });
}

/** 风险评估操作 */
function handleRiskAssessment(row) {
  // 准备风险评估数据
  const assessmentData = {
    // 可以根据需要添加评估参数
  };
  
  riskAssessment(row.financingId, assessmentData).then(response => {
    proxy.$modal.msgSuccess("风险评估已启动");
    getList(); // 刷新列表
  }).catch(error => {
    console.error('风险评估失败:', error);
    proxy.$modal.msgError(error.msg || "风险评估失败，请稍后重试");
  });
}

/** 删除融资申请 */
function handleDelete(row) {
  proxy.$modal.confirm('是否确认删除该融资申请？').then(function() {
    return delFinancing(row.financingId);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(error => {
    console.error('删除失败:', error);
    if (error !== 'cancel') {
      proxy.$modal.msgError(error.msg || "删除失败");
    }
  });
}


/** 导出数据 */
function handleExport() {
  proxy.$modal.confirm('是否确认导出所有融资申请数据项？').then(function() {
    return exportFinancing(queryParams.value);
  }).then(response => {
    proxy.$download.excel(response, '融资申请列表.xlsx');
  }).catch(error => {
    console.error('导出失败:', error);
    if (error !== 'cancel') {
      proxy.$modal.msgError(error.msg || "导出失败");
    }
  });
}

/** 获取融资状态类型 */
function getFinancingStatusType(status) {
  const typeMap = {
    'PENDING': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger',
    'DISBURSED': 'primary',
    'SETTLED': 'info'
  };
  return typeMap[status] || 'info';
}

/** 获取融资状态文本 */
function getFinancingStatusText(status) {
  const statusMap = {
    'PENDING': '待审批',
    'APPROVED': '审批通过',
    'REJECTED': '审批拒绝',
    'DISBURSED': '已放款',
    'SETTLED': '已结清'
  };
  return statusMap[status] || status;
}

/** 获取风险等级类型 */
function getRiskLevelType(level) {
  const typeMap = {
    'LOW': 'success',
    'MEDIUM': 'warning',
    'HIGH': 'danger'
  };
  return typeMap[level] || 'info';
}

/** 获取风险等级文本 */
function getRiskLevelText(level) {
  const levelMap = {
    'LOW': '低风险',
    'MEDIUM': '中风险',
    'HIGH': '高风险'
  };
  return levelMap[level] || level;
}

/** 获取风险评分颜色 */
function getRiskScoreColor(score) {
  if (score >= 80) return '#67C23A'; // 绿色 - 低风险
  if (score >= 60) return '#E6A23C'; // 橙色 - 中风险
  if (score >= 40) return '#F56C6C'; // 红色 - 高风险
  return '#909399'; // 灰色 - 未知
}

/** 获取验证状态类型 */
function getValidationStatusType(status) {
  const typeMap = {
    'PASS': 'success',
    'PASSED': 'success',
    'FAIL': 'danger',
    'FAILED': 'danger',
    'PENDING': 'warning',
    'VALIDATING': 'info'
  };
  return typeMap[status] || 'info';
}

/** 获取验证状态图标 */
function getValidationStatusIcon(status) {
  const iconMap = {
    'PASS': 'CircleCheck',
    'PASSED': 'CircleCheck',
    'FAIL': 'CircleClose',
    'FAILED': 'CircleClose',
    'PENDING': 'Clock',
    'VALIDATING': 'Loading'
  };
  return iconMap[status] || 'QuestionFilled';
}

/** 获取验证状态文本 */
function getValidationStatusText(status) {
  const statusMap = {
    'PASS': '验证通过',
    'PASSED': '验证通过',
    'FAIL': '验证失败',
    'FAILED': '验证失败',
    'PENDING': '待验证',
    'VALIDATING': '验证中'
  };
  return statusMap[status] || '未知状态';
}

/** 获取债权状态类型 */
function getCreditStatusType(status) {
  const typeMap = {
    '已验证': 'success',
    '有效': 'success',
    '已失效': 'danger'
  };
  return typeMap[status] || 'info';
}

/** 获取债权状态文本 */
function getCreditStatusText(status) {
  return status;
}

/** 获取贷款状态类型 */
function getLoanStatusType(status) {
  const typeMap = {
    'PENDING': 'warning',
    'SUBMITTED': 'primary',
    'APPROVED': 'success',
    'DISBURSED': 'primary',
    'REJECTED': 'danger',
    'REPAID': 'info',
    'ACTIVE': 'success',
    'COMPLETED': 'info',
    'CANCELLED': 'danger'
  };
  return typeMap[status] || 'info';
}

/** 获取贷款状态文本 */
function getLoanStatusText(status) {
  const statusMap = {
    'PENDING': '待提交',
    'SUBMITTED': '已提交',
    'APPROVED': '已批准',
    'DISBURSED': '已放款',
    'REJECTED': '已拒绝',
    'REPAID': '已还款',
    'ACTIVE': '生效中',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || status;
}

/** 获取审批状态类型 */
function getApprovalStatusType(status) {
  const typeMap = {
    'PENDING': 'warning',
    'SUBMITTED': 'primary',
    'APPROVED': 'success',
    'REJECTED': 'danger'
  };
  return typeMap[status] || 'info';
}

/** 获取审批状态文本 */
function getApprovalStatusText(status) {
  const statusMap = {
    'PENDING': '待审批',
    'SUBMITTED': '已提交',
    'APPROVED': '已通过',
    'REJECTED': '已拒绝'
  };
  return statusMap[status] || status;
}

/** 格式化金额 */
function formatMoney(amount) {
  if (!amount) return '0.00';
  return new Intl.NumberFormat('zh-CN', {
    style: 'currency',
    currency: 'CNY'
  }).format(amount);
}

onMounted(() => {
  handleValidateAll()
  startStatusUpdates(); // 启动实时状态更新
});

onUnmounted(() => {
  stopStatusUpdates(); // 清理定时器
});
</script>

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

.card-header > div {
  display: flex;
  gap: 10px;
}

.stats-row {
  margin-bottom: 20px;
}

.stats-card {
  text-align: center;
}

.mb8 {
  margin-bottom: 8px;
}

.dialog-footer {
  text-align: right;
}

.el-table {
  margin-top: 20px;
}

/* 验证状态相关样式 */
.validation-status-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.validation-status-tag {
  margin-bottom: 2px;
}

.failure-reason-icon {
  cursor: pointer;
  font-size: 14px;
}

.validating-icon {
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.validation-time {
  font-size: 11px;
  color: #909399;
  text-align: center;
  line-height: 1.2;
}

.validation-score {
  font-size: 11px;
  color: #67C23A;
  text-align: center;
  line-height: 1.2;
  font-weight: 500;
}

/* 验证详情对话框样式 */
.validation-details-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.validation-basic-info,
.validation-result-details,
.validation-failure-details,
.validation-history {
  margin-bottom: 16px;
}

.validation-result-content {
  background-color: #f5f7fa;
  padding: 12px;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.validation-result-content pre {
  margin: 0;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  line-height: 1.4;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.failure-reason-content {
  margin-top: 8px;
}

.failure-reason-content p {
  margin: 8px 0;
}

.failure-reason-content ul {
  margin: 8px 0;
  padding-left: 20px;
}

.failure-reason-content li {
  margin: 4px 0;
}

/* 验证历史记录样式 */
.history-record {
  padding: 8px;
}

.record-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.record-score {
  font-size: 12px;
  color: #606266;
}

.record-content {
  margin: 8px 0;
  font-size: 13px;
  color: #606266;
  background-color: #f8f9fa;
  padding: 8px;
  border-radius: 4px;
}

.record-failure {
  margin-top: 8px;
  font-size: 13px;
}

/* 响应式布局调整 */
@media (max-width: 1200px) {
  .stats-row .el-col {
    margin-bottom: 10px;
  }
  
  .validation-status-container {
    gap: 2px;
  }
  
  .validation-time {
    font-size: 10px;
  }
}

/* 状态显示样式 */
.approval-status {
  font-size: 12px;
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 4px;
  border: 1px solid;
}

/* 已审批状态样式 */
.approval-status.approved {
  color: #409EFF;
  background-color: #ecf5ff;
  border-color: #b3d8ff;
}

/* 状态容器通用样式 */
.status-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  min-height: 60px;
  justify-content: center;
}

/* 操作按钮通用样式 */
.action-btn {
  font-weight: 500;
  padding: 4px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
  margin: 2px 0;
}

.action-btn:hover {
  transform: translateY(-1px);
}

/* 状态标签通用样式 */
.status-tag {
  font-weight: 500;
  border-radius: 12px;
  padding: 2px 8px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
  margin-top: 2px;
}



/* 已放款容器样式 */
.disbursed-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
  min-height: 60px;
  justify-content: center;
}

/* 详细按钮样式 */
.details-btn {
  font-weight: 500;
  padding: 4px 12px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

/* 已放款标签样式 */
.disbursed-tag {
  font-weight: 500;
  border-radius: 12px;
  padding: 2px 8px;
  box-shadow: 0 1px 3px rgba(103, 194, 58, 0.2);
}
</style>