<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>债权验证</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
        </div>
      </template>

      <!-- 债权基本信息 -->
      <el-descriptions title="债权基本信息" :column="2" border>
        <el-descriptions-item label="债权编号">{{ creditInfo.creditNumber }}</el-descriptions-item>
        <el-descriptions-item label="关联合同">{{ creditInfo.contractNumber }}</el-descriptions-item>
        <el-descriptions-item label="债权人">{{ creditInfo.creditorName }}</el-descriptions-item>
        <el-descriptions-item label="债务人">{{ creditInfo.debtorName }}</el-descriptions-item>
        <el-descriptions-item label="债权金额">{{ formatMoney(creditInfo.creditAmount) }}</el-descriptions-item>
        <el-descriptions-item label="发行日期">{{ parseTime(creditInfo.issueDate, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="到期日期">{{ parseTime(creditInfo.maturityDate, '{y}-{m}-{d}') }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">
          <el-tag :type="getStatusTagType(creditInfo.creditStatus)">
            {{ getStatusText(creditInfo.creditStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ parseTime(creditInfo.createTime) }}</el-descriptions-item>
      </el-descriptions>

      <!-- 验证操作区域 -->
      <el-divider content-position="left">债权验证</el-divider>
      
      <div class="validation-section">
        <el-alert 
          title="债权验证说明" 
          type="info" 
          :closable="false"
          show-icon>
          <p>系统将自动验证债权凭证的完整性、数字签名和区块链数据。</p>
          <p>验证成功后将自动通知银行系统，符合条件的债权可进行贷款申请。</p>
        </el-alert>
        
        <div class="validation-actions">
          <el-button 
            type="primary" 
            size="large"
            @click="handleValidate" 
            :loading="validating"
            :disabled="creditInfo.creditStatus === 'verified'">
            <el-icon><Check /></el-icon>
            {{ creditInfo.creditStatus === 'verified' ? '已验证' : '开始验证' }}
          </el-button>
          
          <el-tag v-if="creditInfo.creditStatus === 'verified'" type="success" size="large">
            <el-icon><SuccessFilled /></el-icon>
            债权已验证，银行可进行贷款审批
          </el-tag>
        </div>
      </div>

      <!-- 验证结果展示 -->
      <el-card v-if="validationResult" class="validation-result-card">
        <el-result 
          :icon="validationResult.success ? 'success' : 'error'"
          :title="validationResult.success ? '验证通过' : '验证失败'"
          :sub-title="validationResult.message">
          <template #extra>
            <el-button type="primary" @click="goToLoanManagement" v-if="validationResult.success">
              前往银行贷款管理
            </el-button>
            <el-button @click="retryValidation" v-if="!validationResult.success">
              重新验证
            </el-button>
          </template>
        </el-result>
      </el-card>
    </el-card>
  </div>
</template>

<script setup name="CreditValidate">
import { validateCredit, getCredit } from "@/api/credit/credit";

const { proxy } = getCurrentInstance();
const route = useRoute();

// 响应式数据
const creditInfo = ref({});
const validating = ref(false);
const validationResult = ref(null);

/** 获取债权信息 */
function getCreditInfo() {
  const creditId = route.query.id;
  if (!creditId) {
    proxy.$modal.msgError("缺少债权ID参数");
    goBack();
    return;
  }

  getCredit(creditId).then(response => {
    creditInfo.value = response.data;
  }).catch(() => {
    proxy.$modal.msgError("获取债权信息失败");
    goBack();
  });
}

/** 执行债权验证 */
function handleValidate() {
  validating.value = true;
  const creditId = route.query.id;

  // 后端自动验证，不需要传递验证参数
  validateCredit(creditId).then(response => {
    const result = {
      success: response.data.valid || false,
      message: response.data.message || response.msg || '',
      credit: response.data.credit || {},
      validatedAt: new Date()
    };
    
    validationResult.value = result;
    validating.value = false;
    
    if (result.success) {
      proxy.$modal.msgSuccess("债权验证通过，已通知银行系统");
      // 更新债权信息状态
      creditInfo.value.creditStatus = 'verified';
    } else {
      proxy.$modal.msgWarning("债权验证失败：" + result.message);
    }
  }).catch(() => {
    validating.value = false;
    proxy.$modal.msgError("验证请求失败");
  });
}

/** 重新验证 */
function retryValidation() {
  validationResult.value = null;
  handleValidate();
}

/** 前往银行贷款管理 */
function goToLoanManagement() {
  // 跳转到银行贷款管理页面
  proxy.$router.push({ 
    path: '/financing/loan-management',
  });
}

/** 格式化债权状态 */
function getStatusText(status) {
  const statusMap = {
    'generated': '已生成',
    'active': '有效',
    'transferred': '已转让',
    'settled': '已结算',
    'expired': '已失效',
    'verified': '已验证'
  };
  return statusMap[status] || status;
}

/** 获取状态标签类型 */
function getStatusTagType(status) {
  const typeMap = {
    'generated': 'info',
    'active': 'success',
    'transferred': 'warning',
    'settled': 'primary',
    'expired': 'danger',
    'verified': 'success'
  };
  return typeMap[status] || 'info';
}

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

/** 返回上一页 */
function goBack() {
  proxy.$router.push({ path: '/credit/creditList' });
}

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

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

.validation-section {
  margin: 20px 0;
}

.validation-actions {
  margin-top: 20px;
  text-align: center;
}

.validation-actions .el-button {
  margin-right: 20px;
}

.validation-result-card {
  margin: 20px 0;
}

.el-descriptions {
  margin-bottom: 20px;
}

.el-divider {
  margin: 30px 0 20px 0;
}
</style>