<template>
  <div class="app-container">
    <el-card class="box-card" v-loading="loading">
      <template #header>
        <div class="card-header">
          <span>合同详情</span>
          <div class="header-buttons">
            <el-button 
              type="primary" 
              icon="Edit" 
              @click="handleEdit"
              v-if="canEdit"
              v-hasPermi="['credit:contract:edit']"
            >编辑</el-button>
            <el-button 
              type="success" 
              icon="Check" 
              @click="handleConfirm"
              v-if="canConfirm"
              v-hasPermi="['credit:contract:confirm']"
            >确认合同</el-button>
            <el-button 
              type="info" 
              icon="Download" 
              @click="handleDownload"
              v-if="contractInfo.attachmentId || contractInfo.fileUrl"
            >下载合同</el-button>
            <el-button 
              type="warning" 
              icon="View" 
              @click="handlePreview"
              v-if="contractInfo.attachmentId || contractInfo.fileUrl"
            >预览合同</el-button>
            <el-button icon="Back" @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <div class="contract-detail" v-if="contractInfo.contractId">
        <!-- 基本信息 -->
        <el-descriptions title="基本信息" :column="2" border class="detail-section">
          <el-descriptions-item label="合同编号">
            <el-tag type="primary" size="large">{{ contractInfo.contractNumber }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="合同状态">
            <dict-tag :options="dc_contract_status" :value="contractInfo.contractStatus" />
          </el-descriptions-item>
          <el-descriptions-item label="合同类型">
            <el-tag :type="contractInfo.contractType === 'ONLINE' ? 'success' : 'info'">
              {{ contractInfo.contractType === 'ONLINE' ? '线上创建' : '线下签署' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="合同来源">
            <el-tag :type="contractInfo.contractSource === 'PLATFORM_CREATED' ? 'primary' : 'warning'">
              {{ contractInfo.contractSource === 'PLATFORM_CREATED' ? '平台创建' : '文件上传' }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="甲方单位" :span="2">
            <span class="company-name">{{ clientCompanyName }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="安保公司" :span="2">
            <span class="company-name">{{ securityCompanyName }}</span>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 合同金额信息 -->
        <el-descriptions title="金额信息" :column="2" border class="detail-section">
          <el-descriptions-item label="合同金额">
            <span class="amount-text">{{ formatMoney(contractInfo.contractAmount) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="金额大写">
            <span class="amount-chinese">{{ convertToChineseNumber(contractInfo.contractAmount) }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="付款到期日">
            <span class="date-text">{{ parseTime(contractInfo.paymentDueDate, '{y}-{m}-{d}') }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="付款状态">
            <el-tag type="warning">待付款</el-tag>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 服务期限信息 -->
        <el-descriptions title="服务期限" :column="2" border class="detail-section">
          <el-descriptions-item label="服务开始日期">
            <span class="date-text">{{ parseTime(contractInfo.startDate, '{y}-{m}-{d}') }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="服务结束日期">
            <span class="date-text">{{ parseTime(contractInfo.endDate, '{y}-{m}-{d}') }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="合同期限">
            <span class="duration-text">{{ contractInfo.contractTerm ? contractInfo.contractTerm + '个月' : calculateServiceDuration() }}</span>
          </el-descriptions-item>
          <el-descriptions-item label="剩余天数">
            <span class="remaining-days" :class="getRemainingDaysClass()">
              {{ calculateRemainingDays() }}
            </span>
          </el-descriptions-item>
        </el-descriptions>

        <!-- 服务内容 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <span class="section-title">服务内容</span>
          </template>
          <div class="service-content">
            <p v-if="contractInfo.serviceContent">{{ contractInfo.serviceContent }}</p>
            <p v-else class="no-content">暂无服务内容描述</p>
          </div>
        </el-card>

        <!-- 合同条款 -->
        <el-card class="detail-section" shadow="never" v-if="contractInfo.contractTerms">
          <template #header>
            <span class="section-title">合同条款</span>
          </template>
          <div class="contract-terms">
            <div class="terms-content">{{ contractInfo.contractTerms }}</div>
          </div>
        </el-card>

        <!-- 合同文件信息 -->
        <el-card class="detail-section" shadow="never" v-if="contractInfo.attachmentId || contractInfo.fileUrl">
          <template #header>
            <span class="section-title">合同文件</span>
          </template>
          <div class="file-info">
            <el-row :gutter="20">
              <el-col :span="12">
                <div class="file-item">
                  <el-icon class="file-icon"><Document /></el-icon>
                  <div class="file-details">
                    <div class="file-name">{{ getFileName() }}</div>
                    <div class="file-meta">
                      <span>文件ID: {{ contractInfo.attachmentId || '系统生成' }}</span>
                      <span v-if="contractInfo.signDate">
                        签署时间: {{ parseTime(contractInfo.signDate, '{y}-{m}-{d} {h}:{i}:{s}') }}
                      </span>
                    </div>
                  </div>
                </div>
              </el-col>
              <el-col :span="12">
                <div class="file-actions">
                  <el-button type="primary" icon="View" @click="handlePreview">预览</el-button>
                  <el-button type="success" icon="Download" @click="handleDownload">下载</el-button>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <!-- 区块链信息 -->
        <el-card class="detail-section" shadow="never" v-if="contractInfo.blockchainHash">
          <template #header>
            <span class="section-title">区块链信息</span>
          </template>
          <el-descriptions :column="1" border>
            <el-descriptions-item label="区块链哈希">
              <div class="hash-container">
                <code class="hash-text">{{ contractInfo.blockchainHash }}</code>
                <el-button 
                  type="text" 
                  icon="CopyDocument" 
                  @click="copyToClipboard(contractInfo.blockchainHash)"
                  size="small"
                >复制</el-button>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="数据完整性">
              <el-tag type="success" v-if="contractInfo.dataHash">
                <el-icon><CircleCheck /></el-icon>
                已验证
              </el-tag>
              <el-tag type="info" v-else>
                <el-icon><Warning /></el-icon>
                未验证
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 提取信息（仅线下上传合同显示） -->
        <el-card 
          class="detail-section" 
          shadow="never" 
          v-if="contractInfo.contractType === 'OFFLINE' && contractInfo.extractedInfo"
        >
          <template #header>
            <span class="section-title">文件提取信息</span>
          </template>
          <div class="extracted-info">
            <pre>{{ contractInfo.extractedInfo }}</pre>
          </div>
        </el-card>

        <!-- 操作记录 -->
        <el-card class="detail-section" shadow="never">
          <template #header>
            <span class="section-title">操作记录</span>
          </template>
          <el-timeline>
            <el-timeline-item 
              timestamp="创建时间" 
              :time-timestamp="contractInfo.createTime"
              type="primary"
            >
              <div class="timeline-content">
                <h4>合同创建</h4>
                <p>创建人: {{ contractInfo.createBy || '系统' }}</p>
                <p>创建时间: {{ parseTime(contractInfo.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</p>
              </div>
            </el-timeline-item>
            <el-timeline-item 
              v-if="contractInfo.updateTime && contractInfo.updateTime !== contractInfo.createTime"
              timestamp="更新时间" 
              :time-timestamp="contractInfo.updateTime"
              type="warning"
            >
              <div class="timeline-content">
                <h4>合同更新</h4>
                <p>更新人: {{ contractInfo.updateBy || '系统' }}</p>
                <p>更新时间: {{ parseTime(contractInfo.updateTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</p>
              </div>
            </el-timeline-item>
            <el-timeline-item 
              v-if="contractInfo.signDate"
              timestamp="签署时间" 
              :time-timestamp="contractInfo.signDate"
              type="success"
            >
              <div class="timeline-content">
                <h4>合同签署</h4>
                <p>签署时间: {{ parseTime(contractInfo.signDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</p>
              </div>
            </el-timeline-item>
          </el-timeline>
        </el-card>

        <!-- 备注信息 -->
        <el-card class="detail-section" shadow="never" v-if="contractInfo.remark">
          <template #header>
            <span class="section-title">备注信息</span>
          </template>
          <div class="remark-content">
            <p>{{ contractInfo.remark }}</p>
          </div>
        </el-card>
      </div>

      <!-- 空状态 -->
      <el-empty v-else description="合同信息不存在" />
    </el-card>

    <!-- 文件预览对话框 -->
    <el-dialog 
      v-model="previewVisible" 
      title="合同文件预览" 
      width="80%" 
      :before-close="handlePreviewClose"
    >
      <div class="file-preview-container" v-loading="previewLoading">
        <iframe 
          v-if="previewUrl && !previewError" 
          :src="previewUrl" 
          class="file-preview-iframe"
          @load="handlePreviewLoad"
          @error="handlePreviewError"
        ></iframe>
        <el-empty 
          v-else-if="previewError" 
          description="文件预览失败，请尝试下载查看"
        >
          <el-button type="primary" @click="handleDownload">下载文件</el-button>
        </el-empty>
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="ContractDetail">
import { getContract } from "@/api/credit/contract";
import { parseTime } from "@/utils/ruoyi";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();
const { dc_contract_status } = proxy.useDict("dc_contract_status");
const route = useRoute();
const router = useRouter();
const userStore = useUserStore();

// 响应式数据
const loading = ref(false);
const previewLoading = ref(false);
const previewVisible = ref(false);
const previewUrl = ref('');
const previewError = ref(false);
const contractInfo = ref({});
const clientCompanyName = ref('');
const securityCompanyName = ref('');

// 计算属性 - 权限控制
const canEdit = computed(() => {
  // 基于角色的编辑权限控制
  const userRoles = userStore.roles;
  const contractStatus = contractInfo.value.contractStatus;
  
  // 管理员可以编辑所有状态的合同
  if (userRoles.includes('admin')) {
    return true;
  }
  
  // 安保公司只能编辑自己创建的草稿状态合同
  if (userRoles.includes('security_company')) {
    return contractStatus === 'DRAFT' && 
           contractInfo.value.createBy === userStore.name;
  }
  
  return false;
});

const canConfirm = computed(() => {
  // 基于角色的确认权限控制
  const userRoles = userStore.roles;
  const contractStatus = contractInfo.value.contractStatus;
  
  // 只有甲方单位和管理员可以确认合同
  if (userRoles.includes('admin')) {
    return contractStatus === 'PENDING';
  }
  
  if (userRoles.includes('client_company')) {
    return contractStatus === 'PENDING';
  }
  
  return false;
});

/** 获取合同详情 */
function getContractDetail() {
  const contractId = route.query.id;
  if (!contractId) {
    proxy.$modal.msgError("合同ID不能为空");
    goBack();
    return;
  }
  
  loading.value = true;
  getContract(contractId).then(response => {
    contractInfo.value = response.data;
    
    // 获取公司名称
    getCompanyNames();
    
    loading.value = false;
  }).catch(() => {
    loading.value = false;
    proxy.$modal.msgError("获取合同详情失败");
  });
}

/** 获取公司名称 */
function getCompanyNames() {
  // 直接使用合同中的公司名称字段
  clientCompanyName.value = contractInfo.value.clientCompany || '未知单位';
  securityCompanyName.value = contractInfo.value.securityCompany || '未知公司';
}

/** 计算服务期限 */
function calculateServiceDuration() {
  if (!contractInfo.value.startDate || !contractInfo.value.endDate) {
    return '未设置';
  }
  
  const startDate = new Date(contractInfo.value.startDate);
  const endDate = new Date(contractInfo.value.endDate);
  const diffTime = Math.abs(endDate - startDate);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffDays < 30) {
    return `${diffDays}天`;
  } else if (diffDays < 365) {
    const months = Math.floor(diffDays / 30);
    const remainingDays = diffDays % 30;
    return remainingDays > 0 ? `${months}个月${remainingDays}天` : `${months}个月`;
  } else {
    const years = Math.floor(diffDays / 365);
    const remainingDays = diffDays % 365;
    const months = Math.floor(remainingDays / 30);
    return `${years}年${months > 0 ? months + '个月' : ''}`;
  }
}

/** 计算剩余天数 */
function calculateRemainingDays() {
  if (!contractInfo.value.endDate) {
    return '未设置';
  }
  
  const endDate = new Date(contractInfo.value.endDate);
  const today = new Date();
  const diffTime = endDate - today;
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffDays < 0) {
    return `已过期${Math.abs(diffDays)}天`;
  } else if (diffDays === 0) {
    return '今天到期';
  } else {
    return `剩余${diffDays}天`;
  }
}

/** 获取剩余天数样式类 */
function getRemainingDaysClass() {
  if (!contractInfo.value.endDate) {
    return '';
  }
  
  const endDate = new Date(contractInfo.value.endDate);
  const today = new Date();
  const diffTime = endDate - today;
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  
  if (diffDays < 0) {
    return 'expired';
  } else if (diffDays <= 7) {
    return 'warning';
  } else if (diffDays <= 30) {
    return 'attention';
  } else {
    return 'normal';
  }
}

/** 数字转中文大写 */
function convertToChineseNumber(num) {
  if (!num) return '零元整';
  
  const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  const units = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿'];
  const decimalUnits = ['角', '分'];
  
  if (num === 0) return '零元整';
  
  const numStr = num.toFixed(2);
  const [integerPart, decimalPart] = numStr.split('.');
  
  let result = '';
  
  // 处理整数部分
  if (parseInt(integerPart) === 0) {
    result = '零';
  } else {
    const integerStr = integerPart.split('').reverse();
    for (let i = 0; i < integerStr.length; i++) {
      const digit = parseInt(integerStr[i]);
      if (digit !== 0) {
        result = digits[digit] + units[i] + result;
      } else if (result && !result.startsWith('零')) {
        result = '零' + result;
      }
    }
  }
  
  result += '元';
  
  // 处理小数部分
  if (decimalPart && parseInt(decimalPart) > 0) {
    const jiao = parseInt(decimalPart[0]);
    const fen = parseInt(decimalPart[1]);
    
    if (jiao > 0) {
      result += digits[jiao] + '角';
    }
    if (fen > 0) {
      result += digits[fen] + '分';
    }
  } else {
    result += '整';
  }
  
  return result;
}

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

/** 获取文件名 */
function getFileName() {
  if (contractInfo.value.fileUrl) {
    return contractInfo.value.fileUrl.split('/').pop() || '合同文件';
  }
  return `合同文件_${contractInfo.value.contractNumber}.pdf`;
}

/** 复制到剪贴板 */
function copyToClipboard(text) {
  if (navigator.clipboard) {
    navigator.clipboard.writeText(text).then(() => {
      proxy.$modal.msgSuccess("已复制到剪贴板");
    }).catch(() => {
      proxy.$modal.msgError("复制失败");
    });
  } else {
    // 兼容旧浏览器
    const textArea = document.createElement('textarea');
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    try {
      document.execCommand('copy');
      proxy.$modal.msgSuccess("已复制到剪贴板");
    } catch (err) {
      proxy.$modal.msgError("复制失败");
    }
    document.body.removeChild(textArea);
  }
}

/** 处理编辑 */
function handleEdit() {
  router.push({
    path: '/digitalCredit/create/',
    query: { id : route.query.id }
  });
}

/** 处理确认 */
function handleConfirm() {
  router.push({
    path: '/digitalCredit/confirm/',
    query: { id : route.query.id }
  });
}

/** 处理下载 */
function handleDownload() {
  if (!contractInfo.value.attachmentId && !contractInfo.value.fileUrl) {
    proxy.$modal.msgError("暂无可下载的合同文件");
    return;
  }
  
  // 构建下载URL
  let downloadUrl = '';
  if (contractInfo.value.fileUrl) {
    downloadUrl = contractInfo.value.fileUrl;
  } else {
    downloadUrl = `/api/common/download?fileName=${contractInfo.value.contractNumber}.pdf&attachmentId=${contractInfo.value.attachmentId}`;
  }
  
  // 创建下载链接
  const link = document.createElement('a');
  link.href = downloadUrl;
  link.download = getFileName();
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  
  proxy.$modal.msgSuccess("文件下载已开始");
}

/** 处理预览 */
function handlePreview() {
  if (!contractInfo.value.attachmentId && !contractInfo.value.fileUrl) {
    proxy.$modal.msgError("暂无可预览的合同文件");
    return;
  }
  
  previewVisible.value = true;
  previewLoading.value = true;
  previewError.value = false;
  
  // 构建预览URL
  if (contractInfo.value.fileUrl) {
    previewUrl.value = contractInfo.value.fileUrl;
  } else {
    previewUrl.value = `/api/common/preview?attachmentId=${contractInfo.value.attachmentId}`;
  }
}

/** 预览加载完成 */
function handlePreviewLoad() {
  previewLoading.value = false;
}

/** 预览加载错误 */
function handlePreviewError() {
  previewLoading.value = false;
  previewError.value = true;
}

/** 关闭预览 */
function handlePreviewClose() {
  previewVisible.value = false;
  previewUrl.value = '';
  previewError.value = false;
}

/** 返回列表 */
function goBack() {
  router.push('/digitalCredit/list');
}

// 生命周期
onMounted(() => {
  getContractDetail();
});
</script>

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

.header-buttons {
  display: flex;
  gap: 8px;
}

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

.section-title {
  font-weight: 600;
  color: #303133;
}

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

.amount-chinese {
  color: #909399;
  font-style: italic;
}

.company-name {
  font-weight: 500;
  color: #409eff;
}

.date-text {
  color: #606266;
}

.duration-text {
  font-weight: 500;
  color: #67c23a;
}

.remaining-days {
  font-weight: 600;
}

.remaining-days.normal {
  color: #67c23a;
}

.remaining-days.attention {
  color: #e6a23c;
}

.remaining-days.warning {
  color: #f56c6c;
}

.remaining-days.expired {
  color: #f56c6c;
  text-decoration: line-through;
}

.service-content {
  line-height: 1.8;
  color: #606266;
}

.contract-terms {
  padding: 10px 0;
}

.terms-content {
  background-color: #fafafa;
  padding: 20px;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  line-height: 1.8;
  color: #606266;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.no-content {
  color: #c0c4cc;
  font-style: italic;
  text-align: center;
  padding: 20px 0;
}

.file-info {
  padding: 10px 0;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.file-icon {
  font-size: 32px;
  color: #409eff;
}

.file-details {
  flex: 1;
}

.file-name {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.file-meta {
  font-size: 12px;
  color: #909399;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.file-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
  align-items: center;
}

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

.hash-text {
  background-color: #f5f7fa;
  padding: 4px 8px;
  border-radius: 4px;
  font-family: 'Courier New', monospace;
  font-size: 12px;
  color: #606266;
  word-break: break-all;
  flex: 1;
}

.extracted-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.extracted-info pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
  font-family: inherit;
  color: #606266;
  line-height: 1.6;
}

.timeline-content h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 14px;
}

.timeline-content p {
  margin: 4px 0;
  color: #606266;
  font-size: 13px;
}

.remark-content {
  line-height: 1.8;
  color: #606266;
  background-color: #f9f9f9;
  padding: 15px;
  border-radius: 4px;
  border-left: 4px solid #409eff;
}

.file-preview-container {
  height: 600px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.file-preview-iframe {
  width: 100%;
  height: 100%;
  border: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .header-buttons {
    flex-direction: column;
    gap: 4px;
  }
  
  .file-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .file-actions {
    justify-content: flex-start;
    width: 100%;
  }
  
  .hash-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .hash-text {
    width: 100%;
  }
}

/* 打印样式 */
@media print {
  .header-buttons,
  .file-actions {
    display: none;
  }
  
  .detail-section {
    break-inside: avoid;
  }
}

/* 深色主题适配 */
@media (prefers-color-scheme: dark) {
  .service-content,
  .extracted-info,
  .remark-content {
    background-color: #2d2d2d;
    color: #e4e7ed;
  }
  
  .hash-text {
    background-color: #2d2d2d;
    color: #e4e7ed;
  }
}

/* 动画效果 */
.detail-section {
  animation: fadeInUp 0.3s ease-out;
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 加载状态优化 */
.el-loading-mask {
  border-radius: 4px;
}

/* 标签样式增强 */
.el-tag {
  font-weight: 500;
}

/* 描述列表样式优化 */
.el-descriptions {
  margin-bottom: 0;
}

.el-descriptions__label {
  font-weight: 600;
}

/* 时间轴样式优化 */
.el-timeline-item__timestamp {
  font-weight: 500;
  color: #909399;
}
</style>