<template>
  <div class="app-container">
    <el-card class="box-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>债权详情</span>
          <div class="header-actions">
            <!--<el-button type="primary" icon="Edit" @click="handleEdit" 
              v-hasPermi="['credit:credit:edit']" 
              v-if="creditInfo?.creditStatus === 'generated'">
              编辑
            </el-button>-->
            <el-button type="success" icon="Check" @click="handleValidate" 
              v-hasPermi="['credit:credit:validate']"
              v-if="creditInfo?.creditStatus === 'generated'">
              验证债权
            </el-button>
            <el-button type="info" icon="Back" @click="goBack">返回列表</el-button>
          </div>
        </div>
      </template>

      <!-- 基本信息 -->
      <div class="detail-section">
        <h3 class="section-title">
          <el-icon><Document /></el-icon>
          基本信息
        </h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="债权编号" :span="2">
            <el-tag type="primary" size="large">{{ creditInfo?.creditNumber || '未知' }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="债权状态">
            <el-tag :type="getStatusTagType(creditInfo?.creditStatus)" size="large">
              {{ getStatusText(creditInfo?.creditStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">
            {{ parseTime(creditInfo?.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="融资金额">
            <span class="amount-text">{{ formatMoney(creditInfo?.creditAmount) }}</span>
          </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="getRemainingDaysType(remainingDays)">
              {{ remainingDays > 0 ? `${remainingDays}天` : '已到期' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="债权描述" :span="2">
            {{ creditInfo?.description || '暂无描述' }}
          </el-descriptions-item>
          <el-descriptions-item label="备注信息" :span="2" v-if="creditInfo?.remark">
            {{ creditInfo.remark }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 关联合同信息 -->
      <div class="detail-section" v-if="creditInfo?.contractId">
        <h3 class="section-title">
          <el-icon><Files /></el-icon>
          关联合同信息
        </h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="合同编号">
            <el-link type="primary" @click="viewContract(creditInfo.contractId)">
              {{ creditInfo?.contractNumber || '未知' }}
            </el-link>
          </el-descriptions-item>
          <el-descriptions-item label="合同标题">
            {{ contractInfo?.title || '未知' }}
          </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(contractInfo?.contractAmount) }}
          </el-descriptions-item>
          <el-descriptions-item label="融资比例">
            <div class="credit-ratio-container">
              <el-progress 
                :percentage="Math.min(creditRatio, 100)" 
                :color="getCreditRatioColor(creditRatio)"
                :show-text="true"
                :format="formatCreditRatio"
              />
              <el-tooltip 
                content="融资比例 = 融资金额 ÷ 合同金额 × 100%，反映债权占合同总金额的比例"
                placement="top"
              >
                <el-icon class="info-icon"><QuestionFilled /></el-icon>
              </el-tooltip>
              <el-tag v-if="creditRatio > 100" type="warning" size="small">
                异常：超过100%
              </el-tag>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="合同期间" :span="2">
            {{ parseTime(contractInfo?.startDate, '{y}-{m}-{d}') }} 至 
            {{ parseTime(contractInfo?.endDate, '{y}-{m}-{d}') }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 数字签名信息 -->
      <div class="detail-section" v-if="creditInfo.digitalSignature">
        <h3 class="section-title">
          <el-icon><Key /></el-icon>
          数字签名信息
          <el-button type="text" @click="viewSignatureDetail" 
            v-hasPermi="['credit:credit:signature']">
            查看详情
          </el-button>
        </h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="签名状态">
            <el-tag type="success" size="large">
              <el-icon><Check /></el-icon>
              已签名
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="签名时间">
            {{ parseTime(signatureInfo?.signTime || creditInfo?.createTime) }}
          </el-descriptions-item>
          <el-descriptions-item label="签名算法">
            {{ signatureInfo?.algorithm || 'SHA-256' }}
          </el-descriptions-item>
          <el-descriptions-item label="证书序列号">
            {{ signatureInfo?.certSerialNumber || 'N/A' }}
          </el-descriptions-item>
          <el-descriptions-item label="数字签名" :span="2">
            <el-input 
              :value="creditInfo?.digitalSignature || '暂无数字签名'" 
              type="textarea" 
              :rows="3" 
              readonly
              class="signature-digest"
            />
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 区块链验证信息 -->
      <div class="detail-section" v-if="creditInfo?.blockchainHash">
        <h3 class="section-title">
          <el-icon><Link /></el-icon>
          区块链验证信息
          <el-button type="text" @click="refreshBlockchainInfo" :loading="blockchainLoading">
            刷新状态
          </el-button>
        </h3>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="上链状态">
            <el-tag :type="blockchainInfo?.status === 'confirmed' ? 'success' : 'warning'" size="large">
              <el-icon v-if="blockchainInfo?.status === 'confirmed'"><Check /></el-icon>
              <el-icon v-else><Clock /></el-icon>
              {{ getBlockchainStatusText(blockchainInfo?.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="确认数">
            {{ blockchainInfo?.confirmations || 0 }}
          </el-descriptions-item>
          <el-descriptions-item label="区块哈希">
            <el-link type="primary" @click="viewBlockchainTransaction">
              {{ creditInfo?.blockchainHash || '未知' }}
            </el-link>
          </el-descriptions-item>
          <el-descriptions-item label="上链时间">
            {{ parseTime(blockchainInfo?.timestamp) }}
          </el-descriptions-item>
          <el-descriptions-item label="交易费用">
            {{ blockchainInfo?.gasFee || '0' }} ETH
          </el-descriptions-item>
          <el-descriptions-item label="网络">
            {{ blockchainInfo?.network || 'Ethereum' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <!-- 操作按钮区域 -->
      <div class="action-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="action-card">
              <div class="action-content">
                <el-icon class="action-icon"><Download /></el-icon>
                <h4>导出债权</h4>
                <p>导出债权凭证文件</p>
                <el-button type="success" @click="handleExport" 
                  v-hasPermi="['credit:credit:export']">
                  导出凭证
                </el-button>
              </div>
            </el-card>
          </el-col>
          <!--<el-col :span="12">
            <el-card class="action-card">
              <div class="action-content">
                <el-icon class="action-icon"><View /></el-icon>
                <h4>查看日志</h4>
                <p>查看债权操作历史</p>
                <el-button type="info" @click="viewOperationLog" 
                  v-hasPermi="['system:operlog:query']">
                  操作日志
                </el-button>
              </div>
            </el-card>
          </el-col>-->
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script setup name="CreditDetail">
import { watch } from 'vue';
import { getCredit, getCreditSignature } from "@/api/credit/credit";
import { getContract } from "@/api/credit/contract";
import { QuestionFilled } from '@element-plus/icons-vue';

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

// 响应式数据
const loading = ref(true);
const blockchainLoading = ref(false);

const creditInfo = ref({});
const contractInfo = ref({});
const signatureInfo = ref({
  signTime: null,
  algorithm: null,
  certSerialNumber: null,
  digest: null
});
const blockchainInfo = ref({
  status: null,
  confirmations: 0,
  timestamp: null,
  gasFee: '0',
  network: 'Ethereum'
});

// 转让表单 - 移除转让相关功能

// 计算属性
const remainingDays = computed(() => {
  if (!creditInfo.value?.maturityDate) return 0;
  const maturityDate = new Date(creditInfo.value.maturityDate);
  const today = new Date();
  const diffTime = maturityDate - today;
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
});

const creditRatio = computed(() => {
  if (!creditInfo.value?.creditAmount || !contractInfo.value?.contractAmount) return 0;
  
  const creditAmount = parseFloat(creditInfo.value.creditAmount);
  const contractAmount = parseFloat(contractInfo.value.contractAmount);
  
  // 验证数值有效性
  if (isNaN(creditAmount) || isNaN(contractAmount) || contractAmount <= 0) return 0;
  
  // 计算比例，不限制上限以便显示异常情况
  const ratio = Math.round((creditAmount / contractAmount) * 100);
  return Math.max(ratio, 0); // 只限制下限为0
});

const securityCompanyName = computed(() => {
  return contractInfo.value?.securityCompanyName || '未知公司';
});

const clientCompanyName = computed(() => {
  return contractInfo.value?.clientCompanyName || '未知公司';
});

const canEdit = computed(() => {
  return creditInfo.value?.creditStatus === 'generated' || creditInfo.value?.creditStatus === 'active';
});

// 方法
/** 获取债权详情 */
async function getCreditDetail() {
  try {
    loading.value = true;
    const creditId = route.query.id;
    if (!creditId) {
      proxy.$modal.msgError("债权ID不能为空");
      goBack();
      return;
    }

    // 清空之前的数据，避免显示旧数据
    creditInfo.value = {};
    contractInfo.value = {};
    signatureInfo.value = {
      signTime: null,
      algorithm: null,
      certSerialNumber: null,
      digest: null
    };
    blockchainInfo.value = {
      status: null,
      confirmations: 0,
      timestamp: null,
      gasFee: '0',
      network: 'Ethereum'
    };

    // 获取债权基本信息 - 使用新的API格式
    const creditResponse = await getCredit(creditId);
    creditInfo.value = creditResponse.data;

    // 获取关联合同信息
    if (creditInfo.value.contractId) {
      const contractResponse = await getContract(creditInfo.value.contractId);
      contractInfo.value = contractResponse.data;
    }

    // 获取数字签名信息
    if (creditInfo.value.digitalSignature) {
      try {
        const signatureResponse = await getCreditSignature(creditId);
        signatureInfo.value = signatureResponse.data || {
          signTime: creditInfo.value.createTime,
          algorithm: 'SHA-256',
          certSerialNumber: 'N/A',
          digest: creditInfo.value.digitalSignature
        };
      } catch (error) {
        console.warn("获取数字签名信息失败:", error);
        // 使用债权信息中的数字签名作为默认值
        signatureInfo.value = {
          signTime: creditInfo.value.createTime,
          algorithm: 'SHA-256',
          certSerialNumber: 'N/A',
          digest: creditInfo.value.digitalSignature
        };
      }
    }

    // 获取区块链信息
    if (creditInfo.value.blockchainHash) {
      await getBlockchainInfo();
    }

  } catch (error) {
    proxy.$modal.msgError("获取债权详情失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
}

/** 获取区块链信息 */
async function getBlockchainInfo() {
  try {
    blockchainLoading.value = true;
    // 模拟区块链信息获取
    // 实际项目中应该调用区块链API
    blockchainInfo.value = {
      status: 'confirmed',
      confirmations: 12,
      timestamp: new Date().toISOString(),
      gasFee: '0.002',
      network: 'Ethereum'
    };
  } catch (error) {
    console.warn("获取区块链信息失败:", error);
  } finally {
    blockchainLoading.value = false;
  }
}

/** 刷新区块链信息 */
function refreshBlockchainInfo() {
  getBlockchainInfo();
}

/** 格式化债权状态 */
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 getRemainingDaysType(days) {
  if (days <= 0) return 'danger';
  if (days <= 30) return 'warning';
  return 'success';
}

/** 获取融资比例颜色 */
function getCreditRatioColor(ratio) {
  if (ratio >= 90) return '#f56c6c';  // 红色 - 高风险
  if (ratio >= 70) return '#e6a23c';  // 橙色 - 中等风险
  if (ratio >= 50) return '#409eff';  // 蓝色 - 正常
  return '#67c23a';                   // 绿色 - 低风险
}

/** 格式化融资比例 */
function formatCreditRatio(percentage) {
  // 对于进度条显示，限制在100%以内
  const displayPercentage = Math.min(percentage, 100);
  return `${creditRatio.value}%`; // 显示实际比例值
}

/** 获取区块链状态文本 */
function getBlockchainStatusText(status) {
  const statusMap = {
    'pending': '待确认',
    'confirmed': '已确认',
    'failed': '失败'
  };
  return statusMap[status] || status;
}

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

/** 编辑债权 */
function handleEdit() {
  router.push({ 
    path: '/credit/generate', 
    query: { id: creditInfo.value?.creditId } 
  });
}

/** 验证债权 */
function handleValidate() {
  router.push({ 
    path: '/credit/validate', 
    query: { id: creditInfo.value.creditId } 
  });
}

/** 查看合同 */
function viewContract(contractId) {
  router.push({ 
    path: '/digitalCredit/detail', 
    query: { id: contractId } 
  });
}

/** 查看数字签名详情 */
function viewSignatureDetail() {
  router.push({ 
    path: '/credit/signature', 
    query: { id: creditInfo.value?.creditId } 
  });
}

/** 查看区块链交易 */
function viewBlockchainTransaction() {
  // 打开区块链浏览器或内部区块链查询页面
  const url = `https://etherscan.io/tx/${creditInfo.value?.blockchainHash}`;
  window.open(url, '_blank');
}

/** 导出债权凭证 */
function handleExport() {
  proxy.download('/credit/export-certificate', {
    id: creditInfo.value?.creditId
  }, `credit_certificate_${creditInfo.value?.creditNumber || 'unknown'}.pdf`);
}

/** 查看操作日志 */
function viewOperationLog() {
  // 跳转到操作日志页面或打开对话框
  proxy.$modal.msgInfo("查看操作日志功能待实现");
}

/** 返回列表 */
function goBack() {
  router.push({ path: '/credit/creditList' });
}

/** 检查用户角色 */
function hasRole(roles) {
  return proxy.$auth.hasRole(roles);
}

// 生命周期
onMounted(async () => {
  await getCreditDetail();
});

// 监听路由变化，当ID改变时重新获取数据
watch(() => route.query.id, async (newId, oldId) => {
  if (newId && newId !== oldId) {
    await getCreditDetail();
  }
}, { immediate: false });
</script>

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

.header-actions {
  display: flex;
  gap: 10px;
}

.detail-section {
  margin-bottom: 30px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
  color: #303133;
  border-bottom: 2px solid #409eff;
  padding-bottom: 8px;
}

.amount-text {
  font-size: 18px;
  font-weight: bold;
  color: #e6a23c;
}

.credit-ratio-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-icon {
  color: #909399;
  cursor: help;
  font-size: 14px;
}

.signature-digest {
  font-family: 'Courier New', monospace;
  font-size: 12px;
}

.action-section {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

.action-card {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}

.action-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.action-content {
  padding: 20px;
}

.action-icon {
  font-size: 32px;
  color: #409eff;
  margin-bottom: 10px;
}

.action-content h4 {
  margin: 10px 0 5px 0;
  color: #303133;
}

.action-content p {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 14px;
}

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

:deep(.el-descriptions__label) {
  font-weight: bold;
  color: #303133;
  width: 120px;
}

:deep(.el-descriptions__content) {
  color: #606266;
}

:deep(.el-progress-bar__outer) {
  background-color: #f0f2f5;
}

:deep(.el-table) {
  margin-top: 15px;
}

:deep(.el-card__body) {
  padding: 15px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-actions {
    flex-direction: column;
    gap: 5px;
  }
  
  .action-section .el-col {
    margin-bottom: 15px;
  }
  
  :deep(.el-descriptions) {
    font-size: 14px;
  }
  
  :deep(.el-descriptions__label) {
    width: 100px;
  }
}
</style>