<template>
  <div class="loan-management">
    <!-- 贷款信息查询表单 -->
    <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="80px" class="search-form">
      <el-form-item label="贷款状态" prop="loanStatus">
        <el-select v-model="queryParams.loanStatus" placeholder="请选择贷款状态" clearable style="width: 150px">
          <el-option label="待提交" value="PENDING" />
          <el-option label="已提交银行" value="SUBMITTED" />
          <el-option label="银行已审批" value="APPROVED" />
          <el-option label="银行已拒绝" value="REJECTED" />
          <el-option label="已放款" value="DISBURSED" />
          <el-option label="已还款" value="REPAID" />
        </el-select>
      </el-form-item>
      <el-form-item label="银行机构" prop="bankInstitutionName">
        <el-input
          v-model="queryParams.bankInstitutionName"
          placeholder="请输入银行机构名称"
          clearable
          style="width: 180px"
        />
      </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" icon="Plus" @click="handleApplyLoan">申请贷款</el-button>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button type="success" icon="Calculator" @click="handleCalculateLoanAmount">计算贷款金额</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" icon="Bank" @click="handleBankMatching">银行匹配</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" icon="Document" @click="handleGenerateReport">生成报表</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="Download" @click="handleExportReport">导出报表</el-button>
      </el-col>-->
    </el-row>

    <!-- 贷款列表表格 -->
    <el-table
      v-loading="loading"
      element-loading-text="正在加载贷款数据..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(0, 0, 0, 0.8)"
      :data="loanList"
      @selection-change="handleSelectionChange"
      height="400"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="贷款编号" align="center" prop="loanNumber" width="150" />
      <el-table-column label="贷款金额" align="center" prop="loanAmount" width="120">
        <template #default="scope">
          <span class="loan-amount">¥{{ formatAmount(scope.row.loanAmount) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="银行机构" align="center" prop="bankInstitutionName" width="120" />
      <el-table-column label="利率" align="center" prop="interestRate" width="80">
        <template #default="scope">
          <span>{{ formatRate(scope.row.interestRate) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="期限" align="center" prop="loanTermMonths" width="80">
        <template #default="scope">
          <span>{{ scope.row.loanTermMonths }}个月</span>
        </template>
      </el-table-column>
      <el-table-column label="月还款额" align="center" prop="monthlyPayment" width="120">
        <template #default="scope">
          <span class="monthly-payment">¥{{ formatAmount(scope.row.monthlyPayment) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="贷款状态" align="center" prop="loanStatus" width="100">
        <template #default="scope">
          <el-tag :type="getLoanStatusType(scope.row.loanStatus)">
            {{ getLoanStatusText(scope.row.loanStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="提交状态" align="center" prop="approvalStatus" width="100">
        <template #default="scope">
          <el-tag :type="getApprovalStatusType(scope.row.approvalStatus)">
            {{ getApprovalStatusText(scope.row.approvalStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="银行选择状态" align="center" width="120">
        <template #default="scope">
          <el-tag :type="getBankSelectionStatusType(scope.row)" size="small">
            {{ getBankSelectionStatusText(scope.row) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="贷款用途" align="center" prop="loanPurpose" width="150" show-overflow-tooltip />
      <el-table-column label="申请时间" align="center" prop="createTime" width="160">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="250" fixed="right">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleDetail(scope.row)">详情</el-button>
          <el-button 
            v-if="scope.row.loanStatus === 'PENDING'"
            link 
            type="success" 
            icon="Edit" 
            @click="handleUpdate(scope.row)"
          >
            修改
          </el-button>
          <el-button 
            v-if="scope.row.loanStatus === 'PENDING' && scope.row.bankInstitutionId && scope.row.submitComments"
            link 
            type="warning" 
            icon="Upload" 
            @click="handleQuickSubmitFromList(scope.row)"
          >
            一键提交
          </el-button>
          <el-button 
            v-if="scope.row.loanStatus === 'SUBMITTED'"
            link 
            type="info" 
            icon="Clock"
            disabled
          >
            审批中
          </el-button>
          <el-button 
            v-if="scope.row.loanStatus === 'APPROVED'"
            link 
            type="success" 
            icon="Check"
            disabled
          >
            已通过
          </el-button>
          <el-button 
            v-if="scope.row.loanStatus === 'REJECTED'"
            link 
            type="danger" 
            icon="Close"
            disabled
          >
            已拒绝
          </el-button>
          <el-button 
            v-if="['PENDING', 'REJECTED'].includes(scope.row.loanStatus)"
            link 
            type="danger" 
            icon="Delete" 
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 贷款统计信息 -->
    <div class="loan-statistics" v-if="loanList.length > 0">
      <el-row :gutter="20" class="statistics-row">
        <el-col :span="6">
          <el-statistic title="贷款总数" :value="loanList.length" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="贷款总额" :value="totalLoanAmount" prefix="¥" :precision="2" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="银行已审批数量" :value="approvedCount" />
        </el-col>
        <el-col :span="6">
          <el-statistic title="月还款总额" :value="totalMonthlyPayment" prefix="¥" :precision="2" />
        </el-col>
      </el-row>
    </div>

    <!-- 贷款申请对话框 -->
    <el-dialog :title="currentLoan ? '修改贷款' : '申请贷款'" v-model="loanApplicationVisible" width="1000px" append-to-body>
      <el-form ref="loanApplicationRef" :model="loanApplicationForm" :rules="loanApplicationRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="贷款金额" prop="loanAmount">
              <el-input-number 
                v-model="loanApplicationForm.loanAmount" 
                :min="0" 
                :step="1000"
                :precision="2"
                placeholder="请输入贷款金额" 
                style="width: 100%"
                @change="handleLoanAmountChange"
              />
              <div class="form-tip">建议金额: ¥{{ formatAmount(calculatedLoanAmount) }}</div>
              <div class="form-tip" v-if="allowedAmountRange.minAmount">
                允许范围: ¥{{ formatAmount(allowedAmountRange.minAmount) }} - ¥{{ formatAmount(allowedAmountRange.maxAmount) }}
              </div>
              <div class="form-warning" v-if="amountValidationMessage">
                {{ amountValidationMessage }}
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="贷款期限" prop="loanTermMonths">
              <el-input-number 
                v-model="loanApplicationForm.loanTermMonths" 
                :min="1" 
                :max="60"
                placeholder="请输入贷款期限（月）" 
                style="width: 100%"
                @change="handleLoanTermChange"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="贷款用途" prop="loanPurpose">
          <el-input 
            v-model="loanApplicationForm.loanPurpose" 
            type="textarea" 
            :rows="3"
            placeholder="请输入贷款用途"
          />
        </el-form-item>
        
        <!-- 银行选择和贷款详情 -->
        <el-form-item label="选择银行" prop="selectedBankId" v-if="availableBanksForApplication.length > 0">
          <el-table 
            :data="availableBanksForApplication" 
            size="small" 
            max-height="300"
            @current-change="handleBankSelectionForApplication"
            highlight-current-row
          >
            <el-table-column type="index" width="50" label="序号" />
            <el-table-column label="银行名称" prop="bankName" width="120" />
            <el-table-column label="产品名称" prop="productName" width="150" />
            <el-table-column label="利率" prop="interestRate" width="80">
              <template #default="scope">
                <span class="interest-rate">{{ formatRate(scope.row.interestRate) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="期限" prop="termMonths" width="80">
              <template #default="scope">
                {{ scope.row.termMonths }}个月
              </template>
            </el-table-column>
            <el-table-column label="月还款额" prop="monthlyPayment" width="120">
              <template #default="scope">
                <span class="monthly-payment-preview">¥{{ formatAmount(scope.row.monthlyPayment) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="总利息" prop="totalInterest" width="120">
              <template #default="scope">
                <span class="total-interest">¥{{ formatAmount(scope.row.totalInterest) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="匹配度" prop="termMatch" width="100">
              <template #default="scope">
                <el-tag :type="getMatchType(scope.row.termMatch)" size="small">
                  {{ getMatchText(scope.row.termMatch) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
          <div class="form-tip" v-if="!selectedBankForApplication">
            请点击选择一家银行以继续申请流程
          </div>
        </el-form-item>

        <!-- 银行选择确认后显示提交说明 -->
        <el-form-item label="提交说明" prop="submitComments" v-if="selectedBankForApplication">
          <el-input 
            v-model="loanApplicationForm.submitComments" 
            type="textarea" 
            :rows="3"
            placeholder="请输入提交给银行的说明信息，例如：资金用途、还款计划等"
            maxlength="500"
            show-word-limit
          />
          <div class="form-tip">
            此说明将随贷款申请一起提交给 {{ selectedBankForApplication.bankName }}，请详细描述资金用途和还款计划
          </div>
        </el-form-item>

        <!-- 选中银行的详细信息 -->
        <el-form-item label="贷款详情" v-if="selectedBankForApplication">
          <el-card class="loan-details-card">
            <div class="loan-summary-horizontal">
              <div class="summary-item-horizontal">
                <div class="label">选择银行</div>
                <div class="value bank-name">{{ selectedBankForApplication.bankName }}</div>
              </div>
              <div class="summary-item-horizontal">
                <div class="label">贷款金额</div>
                <div class="value amount">¥{{ formatAmount(loanApplicationForm.loanAmount) }}</div>
              </div>
              <div class="summary-item-horizontal">
                <div class="label">月还款额</div>
                <div class="value monthly">¥{{ formatAmount(selectedBankForApplication.monthlyPayment) }}</div>
              </div>
              <div class="summary-item-horizontal">
                <div class="label">总利息</div>
                <div class="value interest">¥{{ formatAmount(selectedBankForApplication.totalInterest) }}</div>
              </div>
            </div>
          </el-card>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="loanApplicationVisible = false">取 消</el-button>
          <el-button 
            type="primary" 
            @click="submitLoanApplication"
            :disabled="!selectedBankForApplication || !loanApplicationForm.submitComments"
          >
            {{ currentLoan ? '保存修改' : '创建贷款申请' }}
          </el-button>
          <div class="form-tip" v-if="!selectedBankForApplication || !loanApplicationForm.submitComments" style="margin-top: 8px; text-align: center;">
            <span v-if="!selectedBankForApplication">请先选择银行</span>
            <span v-else-if="!loanApplicationForm.submitComments">请填写提交说明</span>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 贷款详情对话框 -->
    <el-dialog title="贷款详情" v-model="loanDetailVisible" width="1000px" append-to-body>
      <div v-if="currentLoan">
        <!-- 基本信息 -->
        <el-descriptions :column="2" border>
          <el-descriptions-item label="贷款编号">{{ currentLoan.loanNumber }}</el-descriptions-item>
          <el-descriptions-item label="贷款金额">¥{{ formatAmount(currentLoan.loanAmount) }}</el-descriptions-item>
          <el-descriptions-item label="贷款期限">{{ currentLoan.loanTermMonths }}个月</el-descriptions-item>
          <el-descriptions-item label="月还款额">¥{{ formatAmount(currentLoan.monthlyPayment) }}</el-descriptions-item>
          <el-descriptions-item label="贷款状态">
            <el-tag :type="getLoanStatusType(currentLoan.loanStatus)">
              {{ getLoanStatusText(currentLoan.loanStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="提交状态">
            <el-tag :type="getApprovalStatusType(currentLoan.approvalStatus)">
              {{ getApprovalStatusText(currentLoan.approvalStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请时间">{{ parseTime(currentLoan.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
          <el-descriptions-item label="贷款用途" :span="2">{{ currentLoan.loanPurpose }}</el-descriptions-item>
        </el-descriptions>

        <!-- 银行选择信息显示区域 -->
        <div style="margin-top: 20px;">
          <el-divider content-position="left">银行选择信息</el-divider>
          
          <div v-if="currentLoan.bankInstitutionId && currentLoan.bankInstitutionName">
            <el-card class="bank-info-card">
              <div class="bank-info-content">
                <div class="bank-info-item">
                  <div class="bank-info-label">选择银行</div>
                  <div class="bank-info-value bank-name">{{ currentLoan.bankInstitutionName }}</div>
                </div>
                <div class="bank-info-item">
                  <div class="bank-info-label">利率</div>
                  <div class="bank-info-value interest-rate">{{ formatRate(currentLoan.interestRate) }}</div>
                </div>
                <div class="bank-info-item">
                  <div class="bank-info-label">银行选择状态</div>
                  <div class="bank-info-value">
                    <el-tag :type="getBankSelectionStatusType(currentLoan)" size="small">
                      {{ getBankSelectionStatusText(currentLoan) }}
                    </el-tag>
                  </div>
                </div>
                <div class="bank-info-item" v-if="currentLoan.bankSelectedTime">
                  <div class="bank-info-label">选择时间</div>
                  <div class="bank-info-value">{{ parseTime(currentLoan.bankSelectedTime, '{y}-{m}-{d} {h}:{i}') }}</div>
                </div>
              </div>
            </el-card>
            
            <!-- 提交说明显示 -->
            <div v-if="currentLoan.submitComments" style="margin-top: 15px;">
              <el-card class="submit-comments-card">
                <template #header>
                  <div class="card-header">
                    <span>提交说明</span>
                  </div>
                </template>
                <div class="submit-comments-content">
                  {{ currentLoan.submitComments }}
                </div>
              </el-card>
            </div>
          </div>
          
          <div v-else>
            <el-alert
              title="尚未选择银行"
              description="请修改贷款信息以选择银行和填写提交说明"
              type="warning"
              :closable="false"
              show-icon
            />
          </div>
        </div>

        <!-- 银行选择修改功能 -->
        <div v-if="currentLoan.loanStatus === 'PENDING'" style="margin-top: 20px;">
          <el-divider content-position="left">银行选择修改</el-divider>
          
          <!-- 银行选择变更历史 -->
          <div v-if="currentLoan.bankSelectionHistory" style="margin-bottom: 15px;">
            <el-card class="history-card" size="small">
              <template #header>
                <div class="card-header">
                  <el-icon><Clock /></el-icon>
                  <span style="margin-left: 5px;">银行选择变更历史</span>
                </div>
              </template>
              <div class="history-content">
                <div 
                  v-for="(historyItem, index) in parseBankSelectionHistory(currentLoan.bankSelectionHistory)" 
                  :key="index"
                  class="history-item"
                >
                  <el-timeline-item 
                    :timestamp="historyItem.timestamp" 
                    placement="top"
                    type="primary"
                    size="small"
                  >
                    {{ historyItem.description }}
                  </el-timeline-item>
                </div>
              </div>
            </el-card>
          </div>
          
          <div v-if="showBankModification">
            <el-alert
              title="修改银行选择"
              description="您可以重新选择银行或修改提交说明，修改后需要重新提交审批"
              type="info"
              :closable="false"
              show-icon
              class="mb-4"
            />
            
            <!-- 银行选择表格 -->
            <el-table 
              :data="availableBanksForDetail" 
              size="small" 
              max-height="250"
              @current-change="handleBankSelectionForDetail"
              highlight-current-row
              v-loading="bankModificationLoading"
              element-loading-text="正在加载银行信息..."
              element-loading-spinner="el-icon-loading"
            >
              <el-table-column type="index" width="50" label="序号" />
              <el-table-column label="银行名称" prop="bankName" width="120" />
              <el-table-column label="产品名称" prop="productName" width="150" />
              <el-table-column label="利率" prop="interestRate" width="80">
                <template #default="scope">
                  <span class="interest-rate">{{ formatRate(scope.row.interestRate) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="期限" prop="termMonths" width="80">
                <template #default="scope">
                  {{ scope.row.termMonths }}个月
                </template>
              </el-table-column>
              <el-table-column label="月还款额" prop="monthlyPayment" width="120">
                <template #default="scope">
                  <span class="monthly-payment-preview">¥{{ formatAmount(scope.row.monthlyPayment) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="总利息" prop="totalInterest" width="120">
                <template #default="scope">
                  <span class="total-interest">¥{{ formatAmount(scope.row.totalInterest) }}</span>
                </template>
              </el-table-column>
              <el-table-column label="匹配度" prop="termMatch" width="100">
                <template #default="scope">
                  <el-tag :type="getMatchType(scope.row.termMatch)" size="small">
                    {{ getMatchText(scope.row.termMatch) }}
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 提交说明修改 -->
            <div v-if="selectedBankForDetail" style="margin-top: 15px;">
              <el-form-item label="提交说明">
                <el-input 
                  v-model="modifiedSubmitComments" 
                  type="textarea" 
                  :rows="3"
                  placeholder="请输入提交给银行的说明信息"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
            </div>
            
            <!-- 修改操作按钮 -->
            <div style="text-align: center; margin-top: 15px;">
              <el-button 
                type="primary" 
                @click="handleSaveBankModification"
                :disabled="!selectedBankForDetail || !modifiedSubmitComments"
              >
                保存修改
              </el-button>
              <el-button @click="handleCancelBankModification">取消修改</el-button>
            </div>
          </div>
          
          <div v-else>
            <el-button 
              type="warning" 
              icon="Edit" 
              @click="handleStartBankModification"
              :disabled="!currentLoan.bankInstitutionId"
            >
              修改银行选择
            </el-button>
          </div>
        </div>

        <!-- 一键提交功能 -->
        <div v-if="currentLoan.loanStatus === 'PENDING'" style="margin-top: 20px;">
          <el-divider content-position="left">一键提交银行审批</el-divider>
          
          <div v-if="currentLoan.bankInstitutionId && currentLoan.submitComments">
            <el-alert
              title="贷款申请信息已完整，可以直接提交给银行审批"
              type="success"
              :closable="false"
              show-icon
              class="mb-4"
            />
            <div class="quick-submit-summary">
              <div class="summary-row">
                <span class="summary-label">提交银行：</span>
                <span class="summary-value">{{ currentLoan.bankInstitutionName }}</span>
              </div>
              <div class="summary-row">
                <span class="summary-label">贷款金额：</span>
                <span class="summary-value">¥{{ formatAmount(currentLoan.loanAmount) }}</span>
              </div>
              <div class="summary-row">
                <span class="summary-label">月还款额：</span>
                <span class="summary-value">¥{{ formatAmount(currentLoan.monthlyPayment) }}</span>
              </div>
            </div>
          </div>
          
          <div v-else>
            <el-alert
              title="贷款申请信息不完整"
              description="请先选择银行和填写提交说明后再提交审批"
              type="warning"
              :closable="false"
              show-icon
              class="mb-4"
            />
          </div>
        </div>
        
        <!-- 操作按钮区域 -->
        <div class="loan-detail-actions" style="margin-top: 30px; text-align: center;">
          <el-button 
            v-if="currentLoan.loanStatus === 'PENDING' && currentLoan.bankInstitutionId && currentLoan.submitComments"
            type="primary" 
            size="large"
            icon="Upload" 
            @click="handleDirectSubmitToBank"
          >
            一键提交银行审批
          </el-button>
          <el-button 
            v-if="currentLoan.loanStatus === 'PENDING'"
            type="success" 
            icon="Edit" 
            @click="handleUpdateFromDetail"
          >
            修改贷款信息
          </el-button>
          <el-button 
            v-if="['PENDING', 'REJECTED'].includes(currentLoan.loanStatus)"
            type="danger" 
            icon="Delete" 
            @click="handleDeleteFromDetail"
          >
            删除贷款
          </el-button>
          <el-button @click="loanDetailVisible = false">关闭</el-button>
        </div>
      </div>
    </el-dialog>



    <!-- 银行匹配结果对话框 -->
    <el-dialog title="银行融资条件匹配" v-model="bankMatchingVisible" width="900px" append-to-body>
      <div class="bank-matching-content">
        <el-alert
          title="根据合同期限为您匹配最适合的银行融资方案"
          type="info"
          :closable="false"
          show-icon
          class="mb-4"
        />
        
        <el-table :data="matchedBanks" v-loading="bankMatchingLoading" element-loading-text="正在匹配银行产品..." element-loading-spinner="el-icon-loading">
          <el-table-column label="银行名称" prop="bankName" width="120" />
          <el-table-column label="产品名称" prop="productName" width="150" />
          <el-table-column label="利率" prop="interestRate" width="80">
            <template #default="scope">
              {{ formatRate(scope.row.interestRate) }}
            </template>
          </el-table-column>
          <el-table-column label="期限" prop="termMonths" width="80">
            <template #default="scope">
              {{ scope.row.termMonths }}个月
            </template>
          </el-table-column>
          <el-table-column label="最大额度" prop="maxAmount" width="120">
            <template #default="scope">
              ¥{{ formatAmount(scope.row.maxAmount) }}
            </template>
          </el-table-column>
          <el-table-column label="匹配度" prop="termMatch" width="100">
            <template #default="scope">
              <el-tag :type="getMatchType(scope.row.termMatch)">
                {{ getMatchText(scope.row.termMatch) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="月还款额" prop="monthlyPayment" width="120">
            <template #default="scope">
              ¥{{ formatAmount(scope.row.monthlyPayment) }}
            </template>
          </el-table-column>
          <el-table-column label="总利息" prop="totalInterest" width="120">
            <template #default="scope">
              ¥{{ formatAmount(scope.row.totalInterest) }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>

    <!-- 报表生成对话框 -->
    <el-dialog title="生成贷款报表" v-model="reportDialogVisible" width="500px" append-to-body>
      <el-form ref="reportFormRef" :model="reportForm" label-width="100px">
        <el-form-item label="报表类型">
          <el-select v-model="reportForm.reportType" placeholder="请选择报表类型" style="width: 100%">
            <el-option label="综合报表" value="COMPREHENSIVE" />
            <el-option label="贷款统计" value="LOAN_STATISTICS" />
            <el-option label="出勤关联" value="ATTENDANCE_CORRELATION" />
            <el-option label="银行分析" value="BANK_ANALYSIS" />
          </el-select>
        </el-form-item>
        <el-form-item label="导出格式">
          <el-select v-model="reportForm.format" placeholder="请选择导出格式" style="width: 100%">
            <el-option label="Excel" value="EXCEL" />
            <el-option label="PDF" value="PDF" />
            <el-option label="CSV" value="CSV" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="reportDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="generateReport">生成报表</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, getCurrentInstance } from 'vue';
import { 
  getServicePeriodLoans, 
  addServicePeriodLoan, 
  updateServicePeriodLoan, 
  deleteServicePeriodLoan,
  applyLoanBasedOnAttendance,
  calculateLoanAmountBasedOnAttendance,
  validateLoanAmountAndGetRange,
  selectBankFinancingByContractTerm,
  generateServicePeriodLoanReport,
  exportLoanAttendanceReport,
  // 新增：银行选择逻辑优化相关API
  applyLoanWithBankSelection,
  quickSubmitLoanToBank,
  updateBankSelection,
  getLoanDetails
} from "@/api/digitalCredit/servicePeriod";
import { parseTime } from "@/utils/ruoyi";
import { errorHandler, retryRequest, showFriendlyError, ErrorTypes } from '@/utils/digitalCredit/errorHandler';
import { ElMessage, ElMessageBox, ElNotification, ElLoading } from 'element-plus';

const props = defineProps({
  servicePeriodId: {
    type: [String, Number],
    required: true
  }
});

const emit = defineEmits(['close', 'loan-changed']);

const { proxy } = getCurrentInstance();

// 增强的用户反馈工具函数
const userFeedback = {
  // 成功消息增强
  showSuccess(message, options = {}) {
    const defaultOptions = {
      duration: 3000,
      showClose: true,
      type: 'success'
    };
    
    if (options.detailed) {
      ElNotification({
        title: '操作成功',
        message: message,
        type: 'success',
        duration: 4000,
        position: 'top-right',
        ...options
      });
    } else {
      ElMessage({
        message: message,
        ...defaultOptions,
        ...options
      });
    }
  },

  // 错误消息增强
  showError(message, options = {}) {
    const defaultOptions = {
      duration: 5000,
      showClose: true,
      type: 'error'
    };
    
    if (options.detailed) {
      ElNotification({
        title: '操作失败',
        message: message,
        type: 'error',
        duration: 6000,
        position: 'top-right',
        ...options
      });
    } else {
      ElMessage({
        message: message,
        ...defaultOptions,
        ...options
      });
    }
  },

  // 警告消息增强
  showWarning(message, options = {}) {
    const defaultOptions = {
      duration: 4000,
      showClose: true,
      type: 'warning'
    };
    
    if (options.detailed) {
      ElNotification({
        title: '注意',
        message: message,
        type: 'warning',
        duration: 5000,
        position: 'top-right',
        ...options
      });
    } else {
      ElMessage({
        message: message,
        ...defaultOptions,
        ...options
      });
    }
  },

  // 信息消息增强
  showInfo(message, options = {}) {
    const defaultOptions = {
      duration: 3000,
      showClose: true,
      type: 'info'
    };
    
    ElMessage({
      message: message,
      ...defaultOptions,
      ...options
    });
  },

  // 增强的确认对话框
  async confirmAction(message, title = '确认操作', options = {}) {
    const defaultOptions = {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
      showClose: false,
      closeOnClickModal: false,
      closeOnPressEscape: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true;
          instance.confirmButtonText = '处理中...';
          setTimeout(() => {
            done();
          }, 300);
        } else {
          done();
        }
      }
    };

    try {
      await ElMessageBox.confirm(message, title, { ...defaultOptions, ...options });
      return true;
    } catch {
      return false;
    }
  },

  // 带进度的操作确认
  async confirmWithProgress(message, title, asyncOperation, options = {}) {
    const confirmed = await this.confirmAction(message, title, options);
    if (!confirmed) return false;

    const loading = ElLoading.service({
      lock: true,
      text: '正在处理...',
      background: 'rgba(0, 0, 0, 0.7)'
    });

    try {
      const result = await asyncOperation();
      loading.close();
      return result;
    } catch (error) {
      loading.close();
      throw error;
    }
  },

  // 操作进度提示
  showProgress(text = '正在处理...', options = {}) {
    return ElLoading.service({
      lock: true,
      text: text,
      background: 'rgba(0, 0, 0, 0.7)',
      ...options
    });
  }
};

// 响应式数据
const loading = ref(false);
const loanList = ref([]);
const selectedLoans = ref([]);
const calculatedLoanAmount = ref(0);
const recommendedBanks = ref([]);
const matchedBanks = ref([]);
const currentLoan = ref(null);
const allowedAmountRange = ref({
  minAmount: null,
  maxAmount: null,
  calculatedAmount: null
});
const amountValidationMessage = ref('');

// 新增：申请贷款时的银行选择
const availableBanksForApplication = ref([]);
const selectedBankForApplication = ref(null);

// 新增：详情页面银行选择
const availableBanksForDetail = ref([]);

// 新增：银行选择修改相关状态
const showBankModification = ref(false);
const selectedBankForDetail = ref(null);
const modifiedSubmitComments = ref('');
const bankModificationLoading = ref(false);

// 对话框状态
const loanApplicationVisible = ref(false);
const loanDetailVisible = ref(false);
const bankMatchingVisible = ref(false);
const bankMatchingLoading = ref(false);
const reportDialogVisible = ref(false);

// 查询参数
const queryParams = ref({
  loanStatus: null,
  bankInstitutionName: null
});

// 贷款申请表单 - 扩展以包含银行选择和提交说明
const loanApplicationForm = ref({
  loanAmount: null,
  loanTermMonths: 12,
  loanPurpose: '服务周期人工成本融资',
  submitComments: '', // 新增：提交说明
  selectedBankId: null, // 新增：选择的银行ID
  bankInstitutionName: '', // 新增：银行名称
  interestRate: null, // 新增：利率
  monthlyPayment: null // 新增：月还款额
});

// 详情页面提交表单 - 简化数据结构
const detailSubmitForm = ref({
  quickSubmit: false // 简化为快速提交标志
});

// 可选银行列表
const availableBanks = ref([]);

// 报表表单
const reportForm = ref({
  reportType: 'COMPREHENSIVE',
  format: 'EXCEL'
});

// 表单验证规则
const loanApplicationRules = {
  loanAmount: [{ required: true, message: "贷款金额不能为空", trigger: "blur" }],
  loanTermMonths: [{ required: true, message: "贷款期限不能为空", trigger: "blur" }],
  loanPurpose: [{ required: true, message: "贷款用途不能为空", trigger: "blur" }],
  selectedBankId: [{ required: true, message: "请选择银行", trigger: "change" }],
  submitComments: [
    { required: true, message: "提交说明不能为空", trigger: "blur" },
    { min: 10, message: "提交说明至少需要10个字符", trigger: "blur" },
    { max: 500, message: "提交说明不能超过500个字符", trigger: "blur" }
  ]
};

const detailSubmitRules = {
  // 简化后的验证规则，主要用于快速提交
};

// 计算属性
const totalLoanAmount = computed(() => {
  return loanList.value.reduce((sum, loan) => sum + (loan.loanAmount || 0), 0);
});

const approvedCount = computed(() => {
  return loanList.value.filter(loan => loan.approvalStatus === 'APPROVED').length;
});

const totalMonthlyPayment = computed(() => {
  return loanList.value.reduce((sum, loan) => sum + (loan.monthlyPayment || 0), 0);
});

// 银行选择状态计算函数
const getBankSelectionStatus = (loan) => {
  if (!loan.bankInstitutionId) return 'NOT_SELECTED';
  if (loan.loanStatus === 'PENDING') return 'SELECTED_PENDING';
  if (loan.loanStatus === 'SUBMITTED') return 'SUBMITTED';
  return 'UNKNOWN';
};

// 状态文本映射
const bankSelectionStatusText = {
  'NOT_SELECTED': '未选择银行',
  'SELECTED_PENDING': '已选择银行，待提交',
  'SUBMITTED': '已提交至银行',
  'UNKNOWN': '状态未知'
};

// 获取银行选择状态文本
const getBankSelectionStatusText = (loan) => {
  const status = getBankSelectionStatus(loan);
  return bankSelectionStatusText[status] || status;
};

// 获取银行选择状态标签类型
const getBankSelectionStatusType = (loan) => {
  const status = getBankSelectionStatus(loan);
  const typeMap = {
    'NOT_SELECTED': 'info',
    'SELECTED_PENDING': 'warning',
    'SUBMITTED': 'success',
    'UNKNOWN': 'danger'
  };
  return typeMap[status] || 'info';
};

// 方法定义
/** 查询贷款列表 */
function getLoanList() {
  loading.value = true;
  
  // 使用自动重试机制
  retryRequest(
    () => getServicePeriodLoans(props.servicePeriodId),
    { operation: '获取贷款列表' }
  ).then(response => {
    loanList.value = response.data || [];
    loading.value = false;
  }).catch(async (error) => {
    loading.value = false;
    
    // 使用错误处理器处理错误
    const result = await errorHandler.handleApiError(error, {
      operation: '获取贷款列表',
      servicePeriodId: props.servicePeriodId
    });
    
    // 根据处理结果执行相应操作
    if (result.action === 'retry_now') {
      setTimeout(() => getLoanList(), result.waitTime || 0);
    } else if (result.action === 'auto_repair') {
      // 如果是数据不一致，尝试自动修复
      console.log('尝试自动修复数据不一致问题');
    } else {
      // 显示友好的错误提示
      userFeedback.showError('获取贷款列表失败', {
        detailed: true,
        title: '数据加载失败',
        message: '无法获取贷款列表数据，请检查网络连接或稍后重试。\n如问题持续存在，请联系系统管理员。'
      });
    }
  });
}

/** 搜索按钮操作 */
function handleQuery() {
  getLoanList();
}

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

/** 选择变化 */
function handleSelectionChange(selection) {
  selectedLoans.value = selection;
}

/** 申请贷款 */
function handleApplyLoan() {
  // 清空当前贷款信息（确保是新增模式）
  currentLoan.value = null;
  
  // 重置表单和数据 - 包含新增字段
  loanApplicationForm.value = {
    loanAmount: null,
    loanTermMonths: 12,
    loanPurpose: '服务周期人工成本融资',
    submitComments: '', // 新增：提交说明
    selectedBankId: null, // 新增：选择的银行ID
    bankInstitutionName: '', // 新增：银行名称
    interestRate: null, // 新增：利率
    monthlyPayment: null // 新增：月还款额
  };
  availableBanksForApplication.value = [];
  selectedBankForApplication.value = null;
  
  // 先计算建议贷款金额
  calculateLoanAmountBasedOnAttendance(props.servicePeriodId).then(response => {
    if (response.data) {
      calculatedLoanAmount.value = response.data.calculatedAmount || 0;
      loanApplicationForm.value.loanAmount = calculatedLoanAmount.value;
      
      // 获取允许申请金额范围
      if (calculatedLoanAmount.value > 0) {
        validateLoanAmountAndGetRange(props.servicePeriodId, calculatedLoanAmount.value).then(rangeResponse => {
          if (rangeResponse.data) {
            allowedAmountRange.value = {
              minAmount: rangeResponse.data.minAllowedAmount,
              maxAmount: rangeResponse.data.maxAllowedAmount,
              calculatedAmount: rangeResponse.data.calculatedAmount
            };
          }
        }).catch(() => {
          // 如果获取范围失败，不影响主流程
        });
      }
      
      // 自动加载银行匹配信息
      loadBankOptionsForUpdate();
    }
  });
  
  loanApplicationVisible.value = true;
}

/** 加载修改贷款时的银行选项 */
function loadBankOptionsForUpdate() {
  if (!loanApplicationForm.value.loanAmount || !loanApplicationForm.value.loanTermMonths) {
    return;
  }
  
  // 获取银行匹配信息
  selectBankFinancingByContractTerm(props.servicePeriodId, loanApplicationForm.value.loanTermMonths).then(response => {
    if (response.data && response.data.matchedProducts) {
      availableBanksForApplication.value = response.data.matchedProducts.map(product => {
        // 计算月还款额和总利息
        const monthlyPayment = calculateMonthlyPaymentForUI(
          loanApplicationForm.value.loanAmount, 
          product.interestRate, 
          product.termMonths
        );
        const totalInterest = monthlyPayment * product.termMonths - loanApplicationForm.value.loanAmount;
        
        return {
          ...product,
          bankId: product.bankId || Math.random(),
          monthlyPayment: monthlyPayment,
          totalInterest: totalInterest
        };
      });
      
      // 如果是修改模式，预选当前银行
      if (currentLoan.value && currentLoan.value.bankInstitutionId) {
        const currentBank = availableBanksForApplication.value.find(bank => 
          bank.bankId === currentLoan.value.bankInstitutionId || 
          bank.bankName === currentLoan.value.bankInstitutionName
        );
        if (currentBank) {
          selectedBankForApplication.value = currentBank;
          loanApplicationForm.value.selectedBankId = currentBank.bankId;
        }
      }
    }
  }).catch(() => {
    proxy.$modal.msgError('获取银行信息失败');
  });
}

/** 前端计算月还款额 */
function calculateMonthlyPaymentForUI(loanAmount, annualRate, termMonths) {
  if (!loanAmount || !annualRate || !termMonths || termMonths <= 0) {
    return 0;
  }
  
  const monthlyRate = annualRate / 12;
  if (monthlyRate === 0) {
    return loanAmount / termMonths;
  }
  
  const factor = Math.pow(1 + monthlyRate, termMonths);
  const monthlyPayment = loanAmount * monthlyRate * factor / (factor - 1);
  
  return Math.round(monthlyPayment * 100) / 100; // 保留两位小数
}

/** 贷款金额变化处理 */
function handleLoanAmountChange(value) {
  if (value && allowedAmountRange.value.minAmount && allowedAmountRange.value.maxAmount) {
    if (value < allowedAmountRange.value.minAmount || value > allowedAmountRange.value.maxAmount) {
      amountValidationMessage.value = `申请金额超出允许范围，请输入 ¥${formatAmount(allowedAmountRange.value.minAmount)} - ¥${formatAmount(allowedAmountRange.value.maxAmount)} 之间的金额`;
    } else {
      amountValidationMessage.value = '';
    }
  }
  
  // 重新计算银行选项
  loadBankOptionsForUpdate();
}

/** 贷款期限变化处理 */
function handleLoanTermChange(value) {
  // 重新计算银行选项
  loadBankOptionsForUpdate();
}

/** 银行选择处理 */
function handleBankSelectionForApplication(currentRow) {
  selectedBankForApplication.value = currentRow;
  if (currentRow) {
    // 更新表单中的银行相关字段
    loanApplicationForm.value.selectedBankId = currentRow.bankId;
    loanApplicationForm.value.bankInstitutionName = currentRow.bankName;
    loanApplicationForm.value.interestRate = currentRow.interestRate;
    loanApplicationForm.value.monthlyPayment = currentRow.monthlyPayment;
    
    // 银行选择确认提示 - 使用增强的反馈
    userFeedback.showSuccess(`已选择 ${currentRow.bankName}`, {
      detailed: true,
      title: '银行选择成功',
      message: `利率：${formatRate(currentRow.interestRate)}\n月还款额：¥${formatAmount(currentRow.monthlyPayment)}\n\n请填写提交说明以完成申请。`,
      duration: 4000
    });
    
    // 自动聚焦到提交说明输入框
    proxy.$nextTick(() => {
      const submitCommentsInput = document.querySelector('textarea[placeholder*="请输入提交给银行的说明信息"]');
      if (submitCommentsInput) {
        submitCommentsInput.focus();
      }
    });
  } else {
    // 清空银行相关字段
    loanApplicationForm.value.selectedBankId = null;
    loanApplicationForm.value.bankInstitutionName = '';
    loanApplicationForm.value.interestRate = null;
    loanApplicationForm.value.monthlyPayment = null;
    loanApplicationForm.value.submitComments = ''; // 清空提交说明
  }
}

/** 计算贷款金额 */
function handleCalculateLoanAmount() {
  loading.value = true;
  calculateLoanAmountBasedOnAttendance(props.servicePeriodId).then(response => {
    loading.value = false;
    if (response.data) {
      const details = response.data.attendanceDetails;
      proxy.$modal.msgSuccess(
        `计算完成！\n` +
        `员工数量: ${details.totalEmployees}人\n` +
        `总工作天数: ${details.totalWorkDays}天\n` +
        `人工成本: ¥${formatAmount(details.totalLaborCost)}\n` +
        `建议贷款金额: ¥${formatAmount(details.calculatedAmount)}`
      );
      calculatedLoanAmount.value = details.calculatedAmount;
    } else {
      proxy.$modal.msgError(response.message || '计算失败');
    }
  }).catch(() => {
    loading.value = false;
  });
}

/** 银行匹配 */
function handleBankMatching() {
  bankMatchingVisible.value = true;
  bankMatchingLoading.value = true;
  
  // 假设合同期限为12个月，实际应该从服务周期获取
  selectBankFinancingByContractTerm(props.servicePeriodId, 12).then(response => {
    bankMatchingLoading.value = false;
    if (response.data) {
      matchedBanks.value = response.data.matchedProducts || [];
    } else {
      proxy.$modal.msgError(response.message || '银行匹配失败');
    }
  }).catch(() => {
    bankMatchingLoading.value = false;
  });
}

/** 银行选择 */
function handleBankSelection(selection) {
  if (selection.length > 0) {
    const selectedBank = selection[0];
    recommendedBanks.value = [selectedBank];
  }
}

/** 提交贷款申请 */
function submitLoanApplication() {
  // 先检查银行选择
  if (!selectedBankForApplication.value) {
    userFeedback.showError('请先选择银行', { detailed: true, title: '银行选择缺失' });
    return;
  }
  
  // 再检查提交说明
  if (!loanApplicationForm.value.submitComments || loanApplicationForm.value.submitComments.trim().length < 10) {
    userFeedback.showError('请填写至少10个字符的提交说明', { 
      detailed: true, 
      title: '提交说明不完整',
      message: '提交说明是银行审批的重要参考信息，请详细描述资金用途和还款计划。'
    });
    return;
  }
  
  proxy.$refs["loanApplicationRef"].validate(valid => {
    if (valid) {
      const loanRequest = {
        loanAmount: loanApplicationForm.value.loanAmount,
        loanTermMonths: loanApplicationForm.value.loanTermMonths,
        loanPurpose: loanApplicationForm.value.loanPurpose,
        bankInstitutionId: loanApplicationForm.value.selectedBankId,
        bankInstitutionName: loanApplicationForm.value.bankInstitutionName,
        interestRate: loanApplicationForm.value.interestRate,
        monthlyPayment: loanApplicationForm.value.monthlyPayment,
        submitComments: loanApplicationForm.value.submitComments.trim(), // 去除首尾空格
        contractTermMatch: selectedBankForApplication.value.termMatch
      };
      
      // 判断是新增还是修改
      if (currentLoan.value && currentLoan.value.linkId) {
        // 修改模式 - 使用原有的更新API
        loanRequest.linkId = currentLoan.value.linkId;
        loanRequest.loanNumber = currentLoan.value.loanNumber; // 保持原贷款编号
        
        const loading = userFeedback.showProgress('正在保存贷款修改...');
        
        updateServicePeriodLoan(currentLoan.value.linkId, loanRequest).then(response => {
          loading.close();
          if (response) {
            userFeedback.showSuccess(`贷款信息修改成功！已选择 ${loanRequest.bankInstitutionName}`, { 
              detailed: true,
              title: '修改成功',
              message: `贷款编号：${loanRequest.loanNumber}\n银行：${loanRequest.bankInstitutionName}\n金额：¥${formatAmount(loanRequest.loanAmount)}`
            });
            loanApplicationVisible.value = false;
            currentLoan.value = null; // 清空当前贷款信息
            getLoanList();
            emit('loan-changed');
          } else {
            userFeedback.showError(response.message || '修改失败，请检查输入信息后重试');
          }
        }).catch(() => {
          loading.close();
          userFeedback.showError('修改失败，请检查网络连接后重试', { detailed: true });
        });
      } else {
        // 新增模式 - 使用新的银行选择API
        const loading = userFeedback.showProgress('正在创建贷款申请...');
        
        retryRequest(
          () => applyLoanWithBankSelection(props.servicePeriodId, loanRequest),
          { operation: '申请贷款' }
        ).then(response => {
          loading.close();
          if (response.data) {
            userFeedback.showSuccess(`贷款申请创建成功！`, { 
              detailed: true,
              title: '申请成功',
              message: `已选择 ${loanRequest.bankInstitutionName}\n贷款金额：¥${formatAmount(loanRequest.loanAmount)}\n月还款额：¥${formatAmount(loanRequest.monthlyPayment)}\n\n您可以在详情页面一键提交审批。`
            });
            loanApplicationVisible.value = false;
            getLoanList();
            emit('loan-changed');
          } else {
            userFeedback.showError(response.message || '申请失败，请检查输入信息后重试');
          }
        }).catch(async (error) => {
          loading.close();
          console.error('申请贷款失败:', error);
          
          // 使用错误处理器处理错误
          const result = await errorHandler.handleApiError(error, {
            operation: '申请贷款',
            bankName: loanRequest.bankInstitutionName,
            loanAmount: loanRequest.loanAmount
          });
          
          // 根据处理结果执行相应操作
          if (result.action === 'fix_bank_info') {
            // 引导用户重新选择银行
            showFriendlyError(ErrorTypes.BANK_INFO_MISSING, '请完善银行选择信息', result.data?.suggestions || []);
          } else if (result.action === 'select_alternative' && result.data?.alternatives) {
            // 显示备选银行
            handleBankServiceUnavailable(result.data.alternatives);
          } else if (result.action === 'retry_now') {
            // 立即重试
            setTimeout(() => submitLoanApplication(), result.waitTime || 0);
          } else if (result.action === 'auto_repair') {
            // 尝试自动修复数据
            userFeedback.showWarning('检测到数据不一致，正在尝试自动修复...', { detailed: true });
          }
        });
      }
    } else {
      userFeedback.showError('请完善贷款信息', { 
        detailed: true,
        title: '信息不完整',
        message: '请检查并填写所有必填项，确保信息准确无误。'
      });
    }
  });
}

/** 查看详情 */
function handleDetail(row) {
  currentLoan.value = row;
  
  // 重置银行修改相关状态
  showBankModification.value = false;
  selectedBankForDetail.value = null;
  modifiedSubmitComments.value = row.submitComments || '';
  availableBanksForDetail.value = [];
  
  // 如果是待提交状态，预加载银行选项
  if (row.loanStatus === 'PENDING') {
    // 重置详情页面表单 - 使用简化的数据结构
    detailSubmitForm.value = {
      quickSubmit: false // 简化为快速提交标志
    };
  }
  
  loanDetailVisible.value = true;
}

/** 开始银行选择修改 */
function handleStartBankModification() {
  showBankModification.value = true;
  bankModificationLoading.value = true;
  
  // 重置修改相关状态
  selectedBankForDetail.value = null;
  modifiedSubmitComments.value = currentLoan.value.submitComments || '';
  
  // 获取可选银行列表
  selectBankFinancingByContractTerm(props.servicePeriodId, currentLoan.value.loanTermMonths || 12).then(response => {
    bankModificationLoading.value = false;
    if (response.data && response.data.matchedProducts) {
      availableBanksForDetail.value = response.data.matchedProducts.map(product => {
        // 重新计算月还款额和总利息（基于当前贷款金额）
        const monthlyPayment = calculateMonthlyPaymentForUI(
          currentLoan.value.loanAmount, 
          product.interestRate, 
          product.termMonths
        );
        const totalInterest = monthlyPayment * product.termMonths - currentLoan.value.loanAmount;
        
        return {
          ...product,
          bankId: product.bankId || Math.random(),
          monthlyPayment: monthlyPayment,
          totalInterest: totalInterest
        };
      });
      
      // 预选当前银行（如果存在）
      if (currentLoan.value.bankInstitutionId) {
        const currentBank = availableBanksForDetail.value.find(bank => 
          bank.bankId === currentLoan.value.bankInstitutionId || 
          bank.bankName === currentLoan.value.bankInstitutionName
        );
        if (currentBank) {
          selectedBankForDetail.value = currentBank;
        }
      }
      
      // 显示银行选择变更历史（如果有）
      if (currentLoan.value.bankSelectionHistory) {
        console.log('银行选择变更历史:', currentLoan.value.bankSelectionHistory);
      }
    }
  }).catch(() => {
    bankModificationLoading.value = false;
    userFeedback.showError('获取银行信息失败', {
      detailed: true,
      title: '银行信息加载失败',
      message: '无法获取可选银行列表，请检查网络连接或稍后重试。'
    });
  });
}

/** 详情页面银行选择处理 */
function handleBankSelectionForDetail(currentRow) {
  selectedBankForDetail.value = currentRow;
  if (currentRow) {
    userFeedback.showSuccess(`已选择 ${currentRow.bankName}`, {
      detailed: true,
      title: '银行选择成功',
      message: `利率：${formatRate(currentRow.interestRate)}\n月还款额：¥${formatAmount(currentRow.monthlyPayment)}\n\n请确认提交说明后保存修改。`,
      duration: 3000
    });
  }
}

/** 保存银行选择修改 */
async function handleSaveBankModification() {
  if (!selectedBankForDetail.value) {
    userFeedback.showError('请选择银行', {
      detailed: true,
      title: '银行未选择',
      message: '请从上方表格中点击选择一家银行。'
    });
    return;
  }
  
  if (!modifiedSubmitComments.value || modifiedSubmitComments.value.trim().length < 10) {
    userFeedback.showError('请填写至少10个字符的提交说明', {
      detailed: true,
      title: '提交说明不完整',
      message: '提交说明是银行审批的重要参考信息，请详细描述资金用途和还款计划。'
    });
    return;
  }
  
  // 检查是否有实际变更
  const hasChanges = 
    selectedBankForDetail.value.bankId !== currentLoan.value.bankInstitutionId ||
    selectedBankForDetail.value.bankName !== currentLoan.value.bankInstitutionName ||
    modifiedSubmitComments.value.trim() !== (currentLoan.value.submitComments || '').trim();
  
  if (!hasChanges) {
    userFeedback.showWarning('没有检测到任何变更', {
      detailed: true,
      title: '无变更内容',
      message: '当前选择的银行和提交说明与原有信息相同，无需保存。'
    });
    return;
  }
  
  // 确认修改操作
  const changeMessage = [];
  if (selectedBankForDetail.value.bankName !== currentLoan.value.bankInstitutionName) {
    changeMessage.push(`• 银行: ${currentLoan.value.bankInstitutionName || '未选择'} → ${selectedBankForDetail.value.bankName}`);
  }
  if (selectedBankForDetail.value.interestRate !== currentLoan.value.interestRate) {
    changeMessage.push(`• 利率: ${formatRate(currentLoan.value.interestRate)} → ${formatRate(selectedBankForDetail.value.interestRate)}`);
  }
  if (selectedBankForDetail.value.monthlyPayment !== currentLoan.value.monthlyPayment) {
    changeMessage.push(`• 月还款额: ¥${formatAmount(currentLoan.value.monthlyPayment)} → ¥${formatAmount(selectedBankForDetail.value.monthlyPayment)}`);
  }
  if (modifiedSubmitComments.value.trim() !== (currentLoan.value.submitComments || '').trim()) {
    changeMessage.push('• 提交说明已修改');
  }
  
  const confirmMessage = `确认修改银行选择吗？

📝 变更内容：
${changeMessage.join('\n')}

⚠️ 修改后需要重新提交审批，请确认变更内容无误。`;

  const confirmed = await userFeedback.confirmAction(
    confirmMessage,
    '确认修改银行选择',
    {
      confirmButtonText: '确认修改',
      cancelButtonText: '取消',
      type: 'warning'
    }
  );

  if (!confirmed) return;

  // 构建更新数据
  const updateData = {
    bankInstitutionId: selectedBankForDetail.value.bankId,
    bankInstitutionName: selectedBankForDetail.value.bankName,
    interestRate: selectedBankForDetail.value.interestRate,
    monthlyPayment: selectedBankForDetail.value.monthlyPayment,
    submitComments: modifiedSubmitComments.value.trim()
  };
  
  const loading = userFeedback.showProgress('正在保存银行选择修改...');
  
  try {
    const response = await updateBankSelection(currentLoan.value.linkId, updateData);
    loading.close();
    
    if (response.data || response.code === 200) {
      userFeedback.showSuccess('银行选择修改成功！', {
        detailed: true,
        title: '修改成功',
        message: `已切换到 ${selectedBankForDetail.value.bankName}\n系统已记录变更历史\n\n新的月还款额：¥${formatAmount(selectedBankForDetail.value.monthlyPayment)}\n新的利率：${formatRate(selectedBankForDetail.value.interestRate)}`
      });
      
      // 更新当前贷款信息
      currentLoan.value = {
        ...currentLoan.value,
        ...updateData,
        bankSelectedTime: new Date().toISOString(),
        contractTermMatch: selectedBankForDetail.value.termMatch
      };
      
      // 关闭修改界面
      showBankModification.value = false;
      selectedBankForDetail.value = null;
      
      // 刷新列表
      getLoanList();
      emit('loan-changed');
    } else {
      userFeedback.showError(response.message || '修改失败，请重试', {
        detailed: true,
        title: '修改失败'
      });
    }
  } catch (error) {
    loading.close();
    console.error('修改银行选择失败:', error);
    userFeedback.showError('修改失败，请检查网络连接后重试', {
      detailed: true,
      title: '修改失败',
      message: '网络连接异常或服务器暂时不可用，请稍后重试。'
    });
  }
}

/** 从列表一键提交 */
async function handleQuickSubmitFromList(row) {
  // 数据验证：检查是否已有银行选择信息
  if (!row.bankInstitutionId || !row.submitComments) {
    userFeedback.showError('贷款申请信息不完整，请先修改贷款信息', {
      detailed: true,
      title: '信息不完整',
      message: '一键提交需要完整的银行选择和提交说明信息。\n请点击"修改"按钮完善信息后再提交。'
    });
    return;
  }
  
  // 状态验证：只有待提交状态才能提交
  if (row.loanStatus !== 'PENDING') {
    userFeedback.showWarning('只有待提交状态的贷款才能提交', {
      detailed: true,
      title: '状态不符',
      message: `当前状态：${getLoanStatusText(row.loanStatus)}\n只有"待提交"状态的贷款才能进行提交操作。`
    });
    return;
  }
  
  // 增强的确认提交对话框
  const confirmMessage = `确认提交贷款申请到 ${row.bankInstitutionName} 进行审批吗？

📋 贷款详情：
• 贷款编号：${row.loanNumber}
• 贷款金额：¥${formatAmount(row.loanAmount)}
• 月还款额：¥${formatAmount(row.monthlyPayment)}
• 贷款期限：${row.loanTermMonths}个月
• 利率：${formatRate(row.interestRate)}

⚠️ 提交后将无法修改，请确认信息无误。`;

  const confirmed = await userFeedback.confirmAction(
    confirmMessage,
    '确认一键提交',
    {
      confirmButtonText: '确认提交',
      cancelButtonText: '取消',
      type: 'warning',
      dangerouslyUseHTMLString: false
    }
  );

  if (!confirmed) return;

  // 使用新的一键提交API
  const loading = userFeedback.showProgress('正在提交到银行审批...');
  
  try {
    const response = await retryRequest(
      () => quickSubmitLoanToBank(row.linkId),
      { operation: '一键提交贷款' }
    );
    
    loading.close();
    
    if (response.data && response.data.success) {
      userFeedback.showSuccess(`提交成功！`, {
        detailed: true,
        title: '提交成功',
        message: `已成功提交给 ${row.bankInstitutionName} 审批！\n\n贷款编号：${row.loanNumber}\n预计审批时间：3-5个工作日\n\n您可以在贷款列表中查看审批进度。`
      });
      getLoanList();
      emit('loan-changed');
    } else {
      userFeedback.showError(response.data?.message || response.message || '提交失败，请重试', {
        detailed: true,
        title: '提交失败'
      });
    }
  } catch (error) {
    loading.close();
    console.error('一键提交失败:', error);
    
    // 使用错误处理器处理错误
    const result = await errorHandler.handleApiError(error, {
      operation: '一键提交贷款',
      loanNumber: row.loanNumber,
      bankName: row.bankInstitutionName
    });
    
    // 根据处理结果执行相应操作
    if (result.action === 'select_alternative' && result.data?.alternatives) {
      // 银行服务不可用，显示备选银行
      handleBankServiceUnavailable(result.data.alternatives, row);
    } else if (result.action === 'auto_repair') {
      // 尝试自动修复数据不一致
      userFeedback.showWarning('检测到数据不一致，正在尝试自动修复后重新提交...', { detailed: true });
      // 可以调用后端的自动修复接口
    } else if (result.action === 'retry_now') {
      // 立即重试
      setTimeout(() => handleQuickSubmitFromList(row), result.waitTime || 0);
    } else if (result.action === 'fix_validation') {
      // 验证失败，显示详细错误信息
      const errors = result.data?.errors || [];
      if (errors.length > 0) {
        showFriendlyError(ErrorTypes.VALIDATION_ERROR, '提交验证失败', errors);
      }
    }
  }
}

/** 取消银行选择修改 */
function handleCancelBankModification() {
  showBankModification.value = false;
  selectedBankForDetail.value = null;
  modifiedSubmitComments.value = currentLoan.value.submitComments || '';
  availableBanksForDetail.value = [];
}

/** 修改贷款 */
function handleUpdate(row) {
  // 检查贷款状态，只有待提交状态的贷款才能修改
  if (row.loanStatus !== 'PENDING') {
    userFeedback.showWarning('只有待提交状态的贷款才能修改', {
      detailed: true,
      title: '状态不符',
      message: `当前状态：${getLoanStatusText(row.loanStatus)}\n\n只有"待提交"状态的贷款才能进行修改操作。\n如需修改已提交的贷款，请联系银行或系统管理员。`
    });
    return;
  }
  
  // 设置当前贷款信息
  currentLoan.value = row;
  
  // 填充修改表单数据 - 包含新增字段
  loanApplicationForm.value = {
    loanAmount: row.loanAmount,
    loanTermMonths: row.loanTermMonths,
    loanPurpose: row.loanPurpose,
    selectedBankId: row.bankInstitutionId,
    submitComments: row.submitComments || '', // 新增：提交说明
    bankInstitutionName: row.bankInstitutionName || '', // 新增：银行名称
    interestRate: row.interestRate, // 新增：利率
    monthlyPayment: row.monthlyPayment // 新增：月还款额
  };
  
  // 重置银行选择相关数据
  availableBanksForApplication.value = [];
  selectedBankForApplication.value = null;
  
  // 获取允许申请金额范围
  if (row.loanAmount > 0) {
    validateLoanAmountAndGetRange(props.servicePeriodId, row.loanAmount).then(rangeResponse => {
      if (rangeResponse.data) {
        allowedAmountRange.value = {
          minAmount: rangeResponse.data.minAllowedAmount,
          maxAmount: rangeResponse.data.maxAllowedAmount,
          calculatedAmount: rangeResponse.data.calculatedAmount
        };
      }
    }).catch(() => {
      // 如果获取范围失败，不影响主流程
    });
  }
  
  // 加载银行选项并预选当前银行
  loadBankOptionsForUpdate();
  
  // 显示修改对话框（复用申请贷款对话框）
  loanApplicationVisible.value = true;
}

/** 直接提交银行审批（从详情页面） - 使用已保存的银行信息 */
async function handleDirectSubmitToBank() {
  // 数据验证：检查是否已有银行选择信息
  if (!currentLoan.value.bankInstitutionId || !currentLoan.value.submitComments) {
    userFeedback.showError('贷款申请信息不完整', {
      detailed: true,
      title: '信息不完整',
      message: '请先选择银行和填写提交说明后再提交审批。\n您可以点击"修改银行选择"来完善信息。'
    });
    return;
  }
  
  // 状态验证：只有待提交状态才能提交
  if (currentLoan.value.loanStatus !== 'PENDING') {
    userFeedback.showWarning('只有待提交状态的贷款才能提交', {
      detailed: true,
      title: '状态不符',
      message: `当前状态：${getLoanStatusText(currentLoan.value.loanStatus)}\n只有"待提交"状态的贷款才能进行提交操作。`
    });
    return;
  }
  
  // 金额验证：确保贷款金额有效
  if (!currentLoan.value.loanAmount || currentLoan.value.loanAmount <= 0) {
    userFeedback.showError('贷款金额无效，无法提交', {
      detailed: true,
      title: '数据异常',
      message: '检测到贷款金额异常，请联系系统管理员处理。'
    });
    return;
  }
  
  // 增强的确认提交对话框
  const submitCommentPreview = currentLoan.value.submitComments.length > 50 
    ? currentLoan.value.submitComments.substring(0, 50) + '...' 
    : currentLoan.value.submitComments;

  const confirmMessage = `确认提交贷款申请到 ${currentLoan.value.bankInstitutionName} 进行审批吗？

📋 贷款详情：
• 贷款金额：¥${formatAmount(currentLoan.value.loanAmount)}
• 月还款额：¥${formatAmount(currentLoan.value.monthlyPayment)}
• 贷款期限：${currentLoan.value.loanTermMonths}个月
• 利率：${formatRate(currentLoan.value.interestRate)}
• 提交说明：${submitCommentPreview}

⚠️ 提交后将无法修改，请确认信息无误。
📅 预计审批时间：3-5个工作日`;

  const confirmed = await userFeedback.confirmAction(
    confirmMessage,
    '确认一键提交',
    {
      confirmButtonText: '确认提交',
      cancelButtonText: '取消',
      type: 'warning'
    }
  );

  if (!confirmed) return;

  const loading = userFeedback.showProgress('正在提交到银行审批...');
  
  try {
    const response = await quickSubmitLoanToBank(currentLoan.value.linkId);
    loading.close();
    
    if (response.data && response.data.success) {
      userFeedback.showSuccess('提交成功！', {
        detailed: true,
        title: '提交成功',
        message: `已成功提交给 ${currentLoan.value.bankInstitutionName} 审批！\n\n贷款编号：${currentLoan.value.loanNumber}\n预计审批时间：3-5个工作日\n\n您可以在贷款列表中查看审批进度。`
      });
      
      // 更新当前贷款状态
      currentLoan.value.loanStatus = 'SUBMITTED';
      currentLoan.value.approvalStatus = 'SUBMITTED';
      
      loanDetailVisible.value = false;
      getLoanList();
      emit('loan-changed');
    } else {
      userFeedback.showError(response.data?.message || response.message || '提交失败，请重试', {
        detailed: true,
        title: '提交失败'
      });
    }
  } catch (error) {
    loading.close();
    console.error('一键提交失败:', error);
    userFeedback.showError('提交失败，请检查网络连接后重试', {
      detailed: true,
      title: '提交失败',
      message: '网络连接异常或服务器暂时不可用，请稍后重试。'
    });
  }
}



/** 从详情页面修改贷款 */
function handleUpdateFromDetail() {
  loanDetailVisible.value = false;
  handleUpdate(currentLoan.value);
}

/** 从详情页面删除贷款 */
function handleDeleteFromDetail() {
  loanDetailVisible.value = false;
  handleDelete(currentLoan.value);
}

/** 删除贷款 */
async function handleDelete(row) {
  const confirmMessage = `确认删除此贷款申请吗？

📋 贷款信息：
• 贷款编号：${row.loanNumber}
• 贷款金额：¥${formatAmount(row.loanAmount)}
• 银行：${row.bankInstitutionName || '未选择'}
• 状态：${getLoanStatusText(row.loanStatus)}

⚠️ 删除后无法恢复，请谨慎操作！`;

  const confirmed = await userFeedback.confirmAction(
    confirmMessage,
    '确认删除贷款',
    {
      confirmButtonText: '确认删除',
      cancelButtonText: '取消',
      type: 'error'
    }
  );

  if (!confirmed) return;

  const loading = userFeedback.showProgress('正在删除贷款申请...');
  
  try {
    await deleteServicePeriodLoan(row.linkId);
    loading.close();
    
    getLoanList();
    userFeedback.showSuccess('贷款申请删除成功', {
      detailed: true,
      title: '删除成功',
      message: `贷款编号 ${row.loanNumber} 已成功删除`
    });
    emit('loan-changed');
  } catch (error) {
    loading.close();
    userFeedback.showError('删除失败，请重试', {
      detailed: true,
      title: '删除失败',
      message: '删除操作失败，请检查网络连接或稍后重试。'
    });
  }
}

/** 生成报表 */
function handleGenerateReport() {
  reportDialogVisible.value = true;
}

/** 导出报表 */
function handleExportReport() {
  exportLoanAttendanceReport(props.servicePeriodId, 'EXCEL').then(response => {
    if (response.data) {
      proxy.$modal.msgSuccess("报表导出成功！");
      // 这里应该处理文件下载
    } else {
      proxy.$modal.msgError(response.message || '导出失败');
    }
  });
}

/** 生成报表 */
function generateReport() {
  generateServicePeriodLoanReport(props.servicePeriodId, reportForm.value.reportType).then(response => {
    if (response.data) {
      proxy.$modal.msgSuccess("报表生成成功！");
      reportDialogVisible.value = false;
      // 这里可以显示报表内容或下载链接
    } else {
      proxy.$modal.msgError(response.message || '生成失败');
    }
  });
}

/** 处理银行服务不可用情况 */
async function handleBankServiceUnavailable(alternatives, currentLoan = null) {
  if (!alternatives || alternatives.length === 0) {
    proxy.$modal.msgError('暂时没有可用的备选银行，请稍后重试');
    return;
  }

  // 构建备选银行选项
  const options = alternatives.slice(0, 5).map((bank, index) => ({
    label: `${bank.bankName} (利率: ${(bank.interestRate * 100).toFixed(2)}%, 期限: ${bank.termMonths}个月)`,
    value: bank.bankId,
    bank: bank
  }));

  try {
    const { value: selectedBankId } = await proxy.$modal.prompt(
      `所选银行服务暂时不可用，请选择备选银行：\n\n${options.map((opt, idx) => `${idx + 1}. ${opt.label}`).join('\n')}`,
      '选择备选银行',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'select',
        inputOptions: options,
        inputValidator: (value) => {
          if (!value) {
            return '请选择一个银行';
          }
          return true;
        }
      }
    );

    const selectedBank = alternatives.find(bank => bank.bankId == selectedBankId);
    if (selectedBank && currentLoan) {
      // 如果是在提交过程中遇到问题，自动更新银行选择
      await updateLoanBankSelection(currentLoan, selectedBank);
    } else if (selectedBank) {
      // 如果是在申请过程中，更新表单中的银行选择
      updateApplicationBankSelection(selectedBank);
    }
  } catch (error) {
    console.log('用户取消选择备选银行');
  }
}

/** 更新贷款的银行选择 */
async function updateLoanBankSelection(loan, newBank) {
  try {
    const updateData = {
      bankInstitutionId: newBank.bankId,
      bankInstitutionName: newBank.bankName,
      interestRate: newBank.interestRate,
      monthlyPayment: calculateMonthlyPayment(loan.loanAmount, newBank.interestRate, newBank.termMonths),
      submitComments: loan.submitComments || '由于原银行服务不可用，自动切换到备选银行'
    };

    const response = await updateBankSelection(loan.linkId, updateData);
    if (response.data || response.code === 200) {
      proxy.$modal.msgSuccess(`已切换到 ${newBank.bankName}，请重新提交`);
      getLoanList();
      emit('loan-changed');
    } else {
      proxy.$modal.msgError('切换银行失败: ' + (response.message || '未知错误'));
    }
  } catch (error) {
    console.error('更新银行选择失败:', error);
    proxy.$modal.msgError('切换银行失败，请手动修改');
  }
}

/** 更新申请表单的银行选择 */
function updateApplicationBankSelection(newBank) {
  // 更新表单中的银行信息
  loanApplicationForm.value.selectedBankId = newBank.bankId;
  loanApplicationForm.value.bankInstitutionName = newBank.bankName;
  loanApplicationForm.value.interestRate = newBank.interestRate;
  
  // 重新计算月还款额
  if (loanApplicationForm.value.loanAmount && loanApplicationForm.value.loanTermMonths) {
    loanApplicationForm.value.monthlyPayment = calculateMonthlyPayment(
      loanApplicationForm.value.loanAmount,
      newBank.interestRate,
      loanApplicationForm.value.loanTermMonths
    );
  }

  // 更新选中的银行
  selectedBankForApplication.value = newBank;
  
  proxy.$modal.msgSuccess(`已切换到 ${newBank.bankName}，请继续完成申请`);
}

/** 计算月还款额 */
function calculateMonthlyPayment(loanAmount, annualRate, termMonths) {
  if (!loanAmount || !annualRate || !termMonths || termMonths <= 0) {
    return 0;
  }
  
  const monthlyRate = annualRate / 12;
  if (monthlyRate === 0) {
    return loanAmount / termMonths;
  }
  
  const factor = Math.pow(1 + monthlyRate, termMonths);
  const monthlyPayment = loanAmount * monthlyRate * factor / (factor - 1);
  
  return Math.round(monthlyPayment * 100) / 100; // 保留两位小数
}

// 格式化方法
function formatAmount(amount) {
  if (!amount) return '0.00';
  return Number(amount).toLocaleString('zh-CN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
}

function formatRate(rate) {
  if (!rate) return '0.00%';
  return (Number(rate) * 100).toFixed(2) + '%';
}

/** 解析银行选择变更历史 */
function parseBankSelectionHistory(historyString) {
  if (!historyString) return [];
  
  const historyItems = [];
  const lines = historyString.split('\n').filter(line => line.trim());
  
  for (const line of lines) {
    // 解析格式: [时间] 描述
    const match = line.match(/^\[([^\]]+)\]\s*(.+)$/);
    if (match) {
      historyItems.push({
        timestamp: match[1],
        description: match[2]
      });
    } else {
      // 如果格式不匹配，直接显示原文
      historyItems.push({
        timestamp: '未知时间',
        description: line
      });
    }
  }
  
  // 按时间倒序排列（最新的在前）
  return historyItems.reverse();
}

function getLoanStatusText(status) {
  const statusMap = {
    'PENDING': '待提交',
    'SUBMITTED': '已提交银行',
    'APPROVED': '银行已审批',
    'REJECTED': '银行已拒绝',
    'DISBURSED': '已放款',
    'REPAID': '已还款'
  };
  return statusMap[status] || status;
}

function getLoanStatusType(status) {
  const typeMap = {
    'PENDING': 'info',
    'SUBMITTED': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger',
    'DISBURSED': 'primary',
    'REPAID': 'info'
  };
  return typeMap[status] || 'info';
}

function getApprovalStatusText(status) {
  const statusMap = {
    'PENDING': '待提交',
    'SUBMITTED': '已提交银行',
    'APPROVED': '银行已通过',
    'REJECTED': '银行已拒绝'
  };
  return statusMap[status] || status;
}

function getApprovalStatusType(status) {
  const typeMap = {
    'PENDING': 'info',
    'SUBMITTED': 'warning',
    'APPROVED': 'success',
    'REJECTED': 'danger'
  };
  return typeMap[status] || 'info';
}

function getMatchText(match) {
  const matchMap = {
    'PERFECT': '完美匹配',
    'GOOD': '良好匹配',
    'ACCEPTABLE': '可接受',
    'POOR': '匹配度低'
  };
  return matchMap[match] || match;
}

function getMatchType(match) {
  const typeMap = {
    'PERFECT': 'success',
    'GOOD': 'primary',
    'ACCEPTABLE': 'warning',
    'POOR': 'danger'
  };
  return typeMap[match] || 'info';
}

onMounted(() => {
  getLoanList();
});
</script>

<style scoped>
.loan-management {
  padding: 20px;
}

.search-form {
  background-color: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.mb8 {
  margin-bottom: 8px;
}

.mb-4 {
  margin-bottom: 16px;
}

.loan-amount {
  font-weight: 600;
  color: #E6A23C;
}

.monthly-payment {
  font-weight: 600;
  color: #67C23A;
}

.loan-statistics {
  margin-top: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 6px;
}

.statistics-row {
  text-align: center;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.form-warning {
  font-size: 12px;
  color: #F56C6C;
  margin-top: 5px;
}

.interest-rate {
  color: #E6A23C;
  font-weight: 600;
}

.monthly-payment-preview {
  color: #67C23A;
  font-weight: 600;
}

.total-interest {
  color: #F56C6C;
  font-weight: 600;
}

.loan-details-card {
  margin-top: 15px;
}

.loan-summary-horizontal {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.summary-item {
  text-align: center;
  flex: 1;
  min-width: 120px;
}

.summary-label {
  display: block;
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.summary-value {
  display: block;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.submit-comments-card {
  margin-top: 15px;
}

.submit-comments-content {
  line-height: 1.6;
  color: #606266;
}

.card-header {
  display: flex;
  align-items: center;
  font-weight: 600;
}

.quick-submit-summary {
  background-color: #f0f9ff;
  padding: 15px;
  border-radius: 6px;
  border-left: 4px solid #409EFF;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.summary-row:last-child {
  margin-bottom: 0;
}

.summary-label {
  color: #606266;
  font-weight: 500;
}

.summary-value {
  color: #303133;
  font-weight: 600;
}

.loan-detail-actions {
  border-top: 1px solid #EBEEF5;
  padding-top: 20px;
}

/* 银行选择变更历史样式 */
.history-card {
  background-color: #fafafa;
  border: 1px solid #e4e7ed;
}

.history-card .card-header {
  color: #606266;
  font-size: 14px;
}

.history-content {
  max-height: 200px;
  overflow-y: auto;
}

.history-item {
  margin-bottom: 10px;
}

.history-item:last-child {
  margin-bottom: 0;
}

:deep(.el-timeline-item__timestamp) {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

:deep(.el-timeline-item__content) {
  font-size: 13px;
  color: #606266;
  line-height: 1.4;
}

.form-warning {
  font-size: 12px;
  color: #F56C6C;
  margin-top: 4px;
  font-weight: 500;
}

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

.bank-matching-content {
  padding: 10px 0;
}

/* 表格样式优化 */
:deep(.el-table) {
  font-size: 12px;
}

:deep(.el-table .cell) {
  padding: 0 5px;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  font-weight: bold;
}

/* 统计卡片样式 */
:deep(.el-statistic) {
  text-align: center;
}

:deep(.el-statistic__head) {
  font-size: 14px;
  color: #909399;
}

:deep(.el-statistic__content) {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

/* 贷款申请对话框样式 */
.interest-rate {
  color: #E6A23C;
  font-weight: 600;
}

.monthly-payment-preview {
  color: #67C23A;
  font-weight: 600;
}

.total-interest {
  color: #F56C6C;
  font-weight: 600;
}

.loan-details-card {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border: none;
}

.loan-summary-horizontal {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  gap: 15px;
  flex-wrap: nowrap;
}

.summary-item-horizontal {
  text-align: center;
  min-width: 0; /* 允许flex项目收缩 */
}

/* 银行名称 - 固定宽度 */
.summary-item-horizontal:nth-child(1) {
  flex: 0 0 120px;
}

/* 贷款金额 - 动态宽度，最小宽度 */
.summary-item-horizontal:nth-child(2) {
  flex: 1 1 auto;
  min-width: 100px;
}

/* 月还款额 - 动态宽度，最小宽度 */
.summary-item-horizontal:nth-child(3) {
  flex: 1 1 auto;
  min-width: 100px;
}

/* 总利息 - 动态宽度，最小宽度 */
.summary-item-horizontal:nth-child(4) {
  flex: 1 1 auto;
  min-width: 100px;
}

.summary-item-horizontal .label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 8px;
  white-space: nowrap;
}

.summary-item-horizontal .value {
  font-size: 14px;
  font-weight: bold;
  color: #303133;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 1.2;
}

.summary-item-horizontal .value.bank-name {
  color: #409EFF;
  font-size: 15px;
}

.summary-item-horizontal .value.amount {
  color: #E6A23C;
  font-size: 15px;
}

.summary-item-horizontal .value.monthly {
  color: #67C23A;
  font-size: 15px;
}

.summary-item-horizontal .value.interest {
  color: #F56C6C;
  font-size: 15px;
}

/* 响应式设计 - 小屏幕时调整 */
@media (max-width: 768px) {
  .loan-summary-horizontal {
    flex-wrap: wrap;
    gap: 10px;
    padding: 10px 15px;
  }
  
  .summary-item-horizontal {
    flex: 1 1 45% !important; /* 小屏幕时每行两个，覆盖上面的设置 */
    min-width: 100px !important;
  }
  
  .summary-item-horizontal .value {
    font-size: 13px;
  }
  
  .summary-item-horizontal .label {
    font-size: 11px;
  }
}

@media (max-width: 480px) {
  .loan-summary-horizontal {
    flex-direction: column;
    gap: 8px;
  }
  
  .summary-item-horizontal {
    flex: 1 1 100% !important;
    min-width: auto !important;
  }
}

/* 保留原有样式用于其他地方 */
.loan-summary {
  padding: 10px;
}

.summary-item {
  text-align: center;
  padding: 10px;
}

.summary-item .label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 5px;
}

.summary-item .value {
  font-size: 16px;
  font-weight: bold;
  color: #303133;
}

.summary-item .value.amount {
  color: #E6A23C;
}

.summary-item .value.monthly {
  color: #67C23A;
}

.summary-item .value.interest {
  color: #F56C6C;
}

.loan-detail-actions {
  border-top: 1px solid #EBEEF5;
  padding-top: 20px;
}

.quick-submit-info {
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 6px;
  padding: 15px;
  margin: 10px 0;
}

.quick-submit-info p {
  margin: 5px 0;
  color: #1e40af;
}

.mb-4 {
  margin-bottom: 16px;
}

/* 银行信息卡片样式 */
.bank-info-card {
  background: linear-gradient(135deg, #e8f5e8 0%, #f0f9ff 100%);
  border: 1px solid #d1fae5;
}

.bank-info-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
  flex-wrap: wrap;
}

.bank-info-item {
  text-align: center;
  min-width: 120px;
}

.bank-info-label {
  font-size: 12px;
  color: #6b7280;
  margin-bottom: 8px;
  font-weight: 500;
}

.bank-info-value {
  font-size: 14px;
  font-weight: bold;
  color: #374151;
}

.bank-info-value.bank-name {
  color: #059669;
  font-size: 16px;
}

.bank-info-value.interest-rate {
  color: #dc2626;
}

/* 提交说明卡片样式 */
.submit-comments-card {
  background: #fefce8;
  border: 1px solid #fde047;
}

.submit-comments-card .card-header {
  font-weight: 600;
  color: #a16207;
}

.submit-comments-content {
  color: #a16207;
  line-height: 1.6;
  padding: 10px 0;
  background: #fffbeb;
  border-radius: 4px;
  padding: 15px;
  margin-top: 10px;
}

/* 一键提交摘要样式 */
.quick-submit-summary {
  background: #f0f9ff;
  border: 1px solid #bae6fd;
  border-radius: 8px;
  padding: 20px;
  margin: 15px 0;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin: 8px 0;
  padding: 5px 0;
}

.summary-label {
  font-weight: 500;
  color: #374151;
  min-width: 100px;
}

.summary-value {
  font-weight: bold;
  color: #1e40af;
  text-align: right;
}

/* 银行修改表格样式 */
.bank-modification-table {
  margin: 15px 0;
}

/* 增强的用户反馈样式 */
:deep(.el-message) {
  min-width: 300px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

:deep(.el-notification) {
  min-width: 350px;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.12);
}

:deep(.el-notification__title) {
  font-weight: 600;
  font-size: 16px;
}

:deep(.el-notification__content) {
  line-height: 1.6;
  white-space: pre-line;
}

:deep(.el-message-box) {
  border-radius: 8px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
}

:deep(.el-message-box__title) {
  font-weight: 600;
  font-size: 18px;
}

:deep(.el-message-box__content) {
  line-height: 1.6;
  white-space: pre-line;
}

:deep(.el-message-box__btns) {
  padding: 15px 20px 20px;
}

:deep(.el-message-box__btns .el-button) {
  min-width: 80px;
  padding: 8px 16px;
}

/* 加载状态增强样式 */
:deep(.el-loading-mask) {
  background-color: rgba(0, 0, 0, 0.8);
}

:deep(.el-loading-text) {
  font-size: 14px;
  font-weight: 500;
  margin-top: 10px;
}

/* 表格加载状态样式 */
:deep(.el-table .el-loading-mask) {
  background-color: rgba(255, 255, 255, 0.9);
}

:deep(.el-table .el-loading-text) {
  color: #606266;
}

/* 确认对话框样式增强 */
:deep(.el-message-box.is-center) {
  text-align: left;
}

:deep(.el-message-box.is-center .el-message-box__header) {
  text-align: center;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-message-box.is-center .el-message-box__content) {
  padding-top: 20px;
  text-align: left;
}

/* 成功消息样式 */
:deep(.el-message--success) {
  background-color: #f0f9ff;
  border-color: #b3e5fc;
  color: #0277bd;
}

:deep(.el-message--success .el-message__icon) {
  color: #4caf50;
}

/* 错误消息样式 */
:deep(.el-message--error) {
  background-color: #fef2f2;
  border-color: #fecaca;
  color: #dc2626;
}

:deep(.el-message--error .el-message__icon) {
  color: #f56565;
}

/* 警告消息样式 */
:deep(.el-message--warning) {
  background-color: #fffbeb;
  border-color: #fed7aa;
  color: #d97706;
}

:deep(.el-message--warning .el-message__icon) {
  color: #f59e0b;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .bank-info-content {
    flex-direction: column;
    gap: 15px;
  }
  
  .bank-info-item {
    min-width: auto;
    width: 100%;
  }
  
  .summary-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .summary-label {
    min-width: auto;
  }
  
  .summary-value {
    text-align: left;
  }
  
  /* 移动端消息样式调整 */
  :deep(.el-message) {
    min-width: 280px;
    max-width: 90vw;
  }
  
  :deep(.el-notification) {
    min-width: 300px;
    max-width: 90vw;
  }
  
  :deep(.el-message-box) {
    width: 90vw;
    max-width: 400px;
  }
}

.submit-comments-section {
  background-color: #f8fdf8;
  border: 1px solid #d1fae5;
  border-radius: 6px;
  padding: 15px;
  margin-top: 15px;
}

.submit-comments-section .el-form-item {
  margin-bottom: 0;
}

/* 表单提示样式增强 */
.form-tip.bank-selected {
  color: #67c23a;
  font-weight: 500;
}

/* 对话框底部提示样式 */
.dialog-footer .form-tip {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 8px;
}
</style>