<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 icon="Back" @click="goBack">返回</el-button>
          </div>
        </div>
      </template>

      <div class="confirm-container" v-if="contractInfo.contractId">
        <!-- 确认提示 -->
        <el-alert
          title="合同确认说明"
          type="warning"
          :closable="false"
          show-icon
          class="confirm-alert"
        >
          <template #default>
            <p>请仔细核对以下合同信息，确认无误后点击"确认合同"按钮。</p>
            <p>合同一旦确认，将无法撤销，请谨慎操作。</p>
            <p>确认后合同状态将变更为"已确认"，可以进行后续的债权生成等操作。</p>
          </template>
        </el-alert>

        <!-- 合同基本信息确认 -->
        <el-card class="confirm-section" shadow="never">
          <template #header>
            <div class="section-header">
              <el-icon><Document /></el-icon>
              <span class="section-title">合同基本信息</span>
              <el-tag :type="getStatusType(contractInfo.contractStatus)">
                {{ getStatusText(contractInfo.contractStatus) }}
              </el-tag>
            </div>
          </template>
          
          <el-descriptions :column="2" border>
            <el-descriptions-item label="合同编号">
              <el-tag type="primary" size="large">{{ contractInfo.contractNumber }}</el-tag>
            </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="甲方单位" :span="2">
              <div class="company-info">
                <el-icon><OfficeBuilding /></el-icon>
                <span class="company-name">{{ clientCompanyName }}</span>
                <el-tag size="small" type="success" v-if="isCurrentUserCompany('client')">
                  当前确认方
                </el-tag>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="安保公司" :span="2">
              <div class="company-info">
                <el-icon><OfficeBuilding /></el-icon>
                <span class="company-name">{{ securityCompanyName }}</span>
              </div>
            </el-descriptions-item>
            <el-descriptions-item label="创建时间">
              {{ parseTime(contractInfo.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}
            </el-descriptions-item>
            <el-descriptions-item label="创建人">
              {{ contractInfo.createBy || '系统' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 合同金额确认 -->
        <el-card class="confirm-section" shadow="never">
          <template #header>
            <div class="section-header">
              <el-icon><Money /></el-icon>
              <span class="section-title">合同金额确认</span>
              <el-button 
                type="text" 
                icon="Calculator" 
                @click="showAmountCalculator = !showAmountCalculator"
                size="small"
              >
                {{ showAmountCalculator ? '隐藏' : '显示' }}计算器
              </el-button>
            </div>
          </template>
          
          <div class="amount-section">
            <div class="amount-display">
              <div class="amount-item">
                <label>合同金额（数字）：</label>
                <span class="amount-number">{{ formatMoney(contractInfo.contractAmount) }}</span>
              </div>
              <div class="amount-item">
                <label>合同金额（大写）：</label>
                <span class="amount-chinese">{{ convertToChineseNumber(contractInfo.contractAmount) }}</span>
              </div>
              <div class="amount-item">
                <label>付款到期日：</label>
                <span class="due-date">{{ parseTime(contractInfo.paymentDueDate, '{y}-{m}-{d}') }}</span>
                <el-tag 
                  :type="getDueDateType()" 
                  size="small" 
                  style="margin-left: 8px;"
                >
                  {{ getDueDateStatus() }}
                </el-tag>
              </div>
            </div>
            
            <!-- 金额计算器 -->
            <el-collapse-transition>
              <div v-show="showAmountCalculator" class="amount-calculator">
                <el-divider content-position="left">金额验证计算器</el-divider>
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-input-number
                      v-model="calculatorAmount"
                      :precision="2"
                      :min="0"
                      placeholder="输入金额进行验证"
                      style="width: 100%"
                      @change="calculateChineseAmount"
                    />
                  </el-col>
                  <el-col :span="12">
                    <el-input
                      v-model="calculatorChinese"
                      placeholder="大写金额"
                      readonly
                      style="width: 100%"
                    />
                  </el-col>
                </el-row>
                <div class="calculator-result" v-if="calculatorAmount">
                  <el-tag 
                    :type="calculatorAmount === contractInfo.contractAmount ? 'success' : 'danger'"
                    size="small"
                  >
                    {{ calculatorAmount === contractInfo.contractAmount ? '金额匹配' : '金额不匹配' }}
                  </el-tag>
                </div>
              </div>
            </el-collapse-transition>
          </div>
        </el-card>

        <!-- 服务期限确认 -->
        <el-card class="confirm-section" shadow="never">
          <template #header>
            <div class="section-header">
              <el-icon><Calendar /></el-icon>
              <span class="section-title">服务期限确认</span>
            </div>
          </template>
          
          <el-descriptions :column="2" border>
            <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">{{ calculateServiceDuration() }}</span>
            </el-descriptions-item>
            <el-descriptions-item label="距离开始">
              <span :class="getStartDateClass()">{{ calculateDaysToStart() }}</span>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- 服务内容确认 -->
        <el-card class="confirm-section" shadow="never" v-if="contractInfo.serviceContent">
          <template #header>
            <div class="section-header">
              <el-icon><List /></el-icon>
              <span class="section-title">服务内容确认</span>
            </div>
          </template>
          
          <div class="service-content">
            <div class="content-display">
              {{ contractInfo.serviceContent }}
            </div>
          </div>
        </el-card>

        <!-- 合同文件确认 -->
        <el-card 
          class="confirm-section" 
          shadow="never" 
          v-if="contractInfo.attachmentId || contractInfo.fileUrl"
        >
          <template #header>
            <div class="section-header">
              <el-icon><Paperclip /></el-icon>
              <span class="section-title">合同文件确认</span>
            </div>
          </template>
          
          <div class="file-section">
            <div class="file-info">
              <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 class="file-actions">
                  <el-button type="primary" icon="View" @click="handlePreview" size="small">
                    预览
                  </el-button>
                  <el-button type="success" icon="Download" @click="handleDownload" size="small">
                    下载
                  </el-button>
                </div>
              </div>
            </div>
            
            <!-- 文件确认检查项 -->
            <div class="file-checklist">
              <el-divider content-position="left">文件确认检查</el-divider>
              <el-checkbox-group v-model="fileChecklist">
                <el-checkbox label="content" size="large">
                  我已仔细阅读合同文件内容
                </el-checkbox>
                <el-checkbox label="parties" size="large">
                  合同双方信息与系统显示一致
                </el-checkbox>
                <el-checkbox label="amount" size="large">
                  合同金额与系统显示一致
                </el-checkbox>
                <el-checkbox label="terms" size="large">
                  服务期限与系统显示一致
                </el-checkbox>
                <el-checkbox label="signature" size="large" v-if="contractInfo.contractType === 'OFFLINE'">
                  合同已由双方正式签署
                </el-checkbox>
              </el-checkbox-group>
            </div>
          </div>
        </el-card>

        <!-- 确认操作区域 -->
        <el-card class="confirm-section confirm-action" shadow="never">
          <template #header>
            <div class="section-header">
              <el-icon><CircleCheck /></el-icon>
              <span class="section-title">确认操作</span>
            </div>
          </template>
          
          <div class="confirm-form">
            <el-form ref="confirmFormRef" :model="confirmForm" :rules="confirmRules" label-width="120px">
              <el-form-item label="确认备注" prop="confirmNote">
                <el-input
                  v-model="confirmForm.confirmNote"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入确认备注（可选）"
                  maxlength="500"
                  show-word-limit
                />
              </el-form-item>
              
              <el-form-item label="安全验证" prop="securityCode" v-if="requireSecurityCode">
                <el-row :gutter="10">
                  <el-col :span="12">
                    <el-input
                      v-model="confirmForm.securityCode"
                      placeholder="请输入验证码"
                      maxlength="6"
                    />
                  </el-col>
                  <el-col :span="12">
                    <el-button 
                      @click="sendSecurityCode" 
                      :loading="sendingCode"
                      :disabled="codeSent && countdown > 0"
                    >
                      {{ codeSent && countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
                    </el-button>
                  </el-col>
                </el-row>
              </el-form-item>
              
              <el-form-item>
                <div class="confirm-checkbox">
                  <el-checkbox v-model="confirmForm.agreeTerms" size="large">
                    <span class="checkbox-text">
                      我已仔细核对上述合同信息，确认无误，同意确认此合同。
                      我理解合同一旦确认将无法撤销。
                    </span>
                  </el-checkbox>
                </div>
              </el-form-item>
            </el-form>
            
            <!-- 确认按钮 -->
            <div class="confirm-buttons">
              <!--<el-button 
                type="danger" 
                size="large" 
                icon="CircleClose"
                @click="handleReject('SECURITY_COMPANY')"
                v-if="canReject"
              >
                拒绝合同
              </el-button>-->
              <el-button 
                type="primary" 
                size="large" 
                icon="CircleCheck"
                @click="handleConfirm('CLIENT_COMPANY')"
                :loading="confirming"
                :disabled="!canConfirmContract"
              >
                确认合同
              </el-button>
              <el-button size="large" @click="goBack">
                取消
              </el-button>
            </div>
          </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>

    <!-- 确认成功对话框 -->
    <el-dialog 
      v-model="successVisible" 
      title="合同确认成功" 
      width="500px" 
      :show-close="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <div class="success-content">
        <el-result icon="success" title="合同确认成功">
          <template #sub-title>
            <p>合同 {{ contractInfo.contractNumber }} 已成功确认</p>
            <p>确认时间：{{ parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}') }}</p>
          </template>
        </el-result>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="goToDetail">查看详情</el-button>
          <el-button @click="goBack">返回列表</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

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

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

// 响应式数据
const loading = ref(false);
const confirming = ref(false);
const previewLoading = ref(false);
const sendingCode = ref(false);
const previewVisible = ref(false);
const successVisible = ref(false);
const previewUrl = ref('');
const previewError = ref(false);
const showAmountCalculator = ref(false);
const requireSecurityCode = ref(true);
const codeSent = ref(false);
const countdown = ref(0);
const calculatorAmount = ref(null);
const calculatorChinese = ref('');

const contractInfo = ref({});
const clientCompanyName = ref('');
const securityCompanyName = ref('');
const fileChecklist = ref([]);

// 表单数据
const confirmForm = ref({
  confirmNote: '',
  securityCode: '',
  agreeTerms: false
});

// 表单验证规则
const confirmRules = {
  securityCode: [
    { required: true, message: "请输入验证码", trigger: "blur" },
    { len: 6, message: "验证码长度为6位", trigger: "blur" }
  ]
};

// 计算属性
const canConfirmContract = computed(() => {
  const basicChecks = confirmForm.value.agreeTerms;
  const fileChecks = !contractInfo.value.attachmentId || fileChecklist.value.length >= 4;
  const securityCheck = !requireSecurityCode.value || confirmForm.value.securityCode;
  
  return basicChecks && fileChecks && securityCheck;
});

const canReject = computed(() => {
  // 只有管理员可以拒绝合同
  const userRoles = userStore.roles;
  return userRoles.includes('admin');
});

/** 获取合同详情 */
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;
    
    // 检查权限
    // if (!checkConfirmPermission()) {
    //  proxy.$modal.msgError("您没有权限确认此合同");
    //  goBack();
    //  return;
    //}
    
    // 检查合同状态
    if (contractInfo.value.contractStatus !== 'PENDING') {
      proxy.$modal.msgError("只能确认待确认状态的合同");
      goBack();
      return;
    }
    
    // 获取公司名称
    getCompanyNames();
    
    loading.value = false;
  }).catch(() => {
    loading.value = false;
    proxy.$modal.msgError("获取合同详情失败");
  });
}

/** 检查确认权限 */
function checkConfirmPermission() {
  const userRoles = userStore.roles;
  
  // 管理员可以确认所有合同
  if (userRoles.includes('admin')) {
    return true;
  }
  
  // 甲方单位只能确认与自己相关的合同
  if (userRoles.includes('client_company')) {
    // 由于现在使用公司名称，这里需要根据实际业务逻辑调整
    // 可以通过用户信息中的公司名称来匹配
    const userCompanyName = userStore.user?.companyName || userStore.user?.deptName;
    return contractInfo.value.clientCompany === userCompanyName;
  }
  
  return false;
}

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

/** 判断是否为当前用户公司 */
function isCurrentUserCompany(type) {
  const userCompanyName = userStore.user?.companyName || userStore.user?.deptName;
  if (type === 'client') {
    return contractInfo.value.clientCompany === userCompanyName;
  } else if (type === 'security') {
    return contractInfo.value.securityCompany === userCompanyName;
  }
  return false;
}

/** 获取状态类型 */
function getStatusType(status) {
  const statusMap = {
    'DRAFT': 'info',
    'PENDING': 'warning',
    'CONFIRMED': 'success',
    'COMPLETED': 'success',
    'CANCELLED': 'danger'
  };
  return statusMap[status] || 'info';
}

/** 获取状态文本 */
function getStatusText(status) {
  const statusMap = {
    'DRAFT': '草稿',
    'PENDING': '待确认',
    'CONFIRMED': '已确认',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  };
  return statusMap[status] || status;
}

/** 获取到期日类型 */
function getDueDateType() {
  if (!contractInfo.value.paymentDueDate) return 'info';
  
  const dueDate = new Date(contractInfo.value.paymentDueDate);
  const today = new Date();
  const diffDays = Math.ceil((dueDate - today) / (1000 * 60 * 60 * 24));
  
  if (diffDays < 0) return 'danger';
  if (diffDays <= 7) return 'warning';
  if (diffDays <= 30) return 'primary';
  return 'success';
}

/** 获取到期日状态 */
function getDueDateStatus() {
  if (!contractInfo.value.paymentDueDate) return '未设置';
  
  const dueDate = new Date(contractInfo.value.paymentDueDate);
  const today = new Date();
  const diffDays = Math.ceil((dueDate - today) / (1000 * 60 * 60 * 24));
  
  if (diffDays < 0) return `已逾期${Math.abs(diffDays)}天`;
  if (diffDays === 0) return '今天到期';
  if (diffDays <= 7) return `${diffDays}天内到期`;
  if (diffDays <= 30) return `${diffDays}天后到期`;
  return `${diffDays}天后到期`;
}

/** 计算服务期限 */
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 calculateDaysToStart() {
  if (!contractInfo.value.startDate) return '未设置';
  
  const startDate = new Date(contractInfo.value.startDate);
  const today = new Date();
  const diffDays = Math.ceil((startDate - today) / (1000 * 60 * 60 * 24));
  
  if (diffDays < 0) return `已开始${Math.abs(diffDays)}天`;
  if (diffDays === 0) return '今天开始';
  return `${diffDays}天后开始`;
}

/** 获取开始日期样式类 */
function getStartDateClass() {
  if (!contractInfo.value.startDate) return '';
  
  const startDate = new Date(contractInfo.value.startDate);
  const today = new Date();
  const diffDays = Math.ceil((startDate - today) / (1000 * 60 * 60 * 24));
  
  if (diffDays < 0) return 'started';
  if (diffDays <= 7) return 'soon';
  return 'future';
}

/** 数字转中文大写 */
function convertToChineseNumber(num) {
  if (!num) return '零元整';
  
  const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  const units = ['', '拾', '佰', '仟', '万', '拾', '佰', '仟', '亿'];
  
  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 calculateChineseAmount() {
  if (calculatorAmount.value) {
    calculatorChinese.value = convertToChineseNumber(calculatorAmount.value);
  } else {
    calculatorChinese.value = '';
  }
}

/** 格式化金额 */
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 sendSecurityCode() {
  sendingCode.value = true;
  
  // 模拟发送验证码
  setTimeout(() => {
    sendingCode.value = false;
    codeSent.value = true;
    countdown.value = 60;
    
    // 倒计时
    const timer = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer);
        codeSent.value = false;
      }
    }, 1000);
    
    proxy.$modal.msgSuccess("验证码已发送到您的手机");
  }, 1000);
}

/** 处理预览 */
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 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 handleConfirm(partyType) {
  proxy.$refs["confirmFormRef"].validate(valid => {
    if (valid) {
      proxy.$modal.confirm('确认要确认此合同吗？确认后将无法撤销。', "系统提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        confirming.value = true;
        
        const confirmData = {
          confirmNote: confirmForm.value.confirmNote,
          securityCode: confirmForm.value.securityCode,
          partyType: partyType
        };
        
        confirmContract(contractInfo.value.contractId, confirmData).then(response => {
          confirming.value = false;
          successVisible.value = true;
        }).catch(() => {
          confirming.value = false;
        });
      });
    }
  });
}

/** 处理拒绝 
 * @param {string} partyType - 确认方类型 (SECURITY_COMPANY/CLIENT_COMPANY)
 */
function handleReject(partyType) {
  proxy.$modal.prompt('请输入拒绝原因：', '拒绝合同', {
    confirmButtonText: '确定拒绝',
    cancelButtonText: '取消',
    inputType: 'textarea',
    inputPlaceholder: '请输入拒绝原因（必填）',
    inputValidator: (value) => {
      if (!value || value.trim().length === 0) {
        return '请输入拒绝原因';
      }
      if (value.trim().length > 500) {
        return '拒绝原因不能超过500个字符';
      }
      return true;
    }
  }).then(({ value }) => {
    const rejectData = {
      rejectNote: value.trim(),
      partyType: partyType
    };
    
    rejectContract(contractInfo.value.contractId, rejectData).then(response => {
      proxy.$modal.msgSuccess("合同已拒绝");
      goBack();
    }).catch(() => {
      proxy.$modal.msgError("拒绝合同失败");
    });
  }).catch(() => {
    // 用户取消操作
  });
}

/** 跳转到详情页 */
function goToDetail() {
  router.push({
    path: '/digitalCredit/detail/',
    query: { id: contractInfo.value.contractId }
  });
}

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

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

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

.confirm-alert {
  margin-bottom: 20px;
}

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

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
}

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

.company-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

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

.amount-section {
  padding: 10px 0;
}

.amount-display {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 20px;
}

.amount-item {
  display: flex;
  align-items: center;
  gap: 10px;
}

.amount-item label {
  font-weight: 500;
  color: #606266;
  min-width: 140px;
}

.amount-number {
  font-size: 20px;
  font-weight: 600;
  color: #e6a23c;
}

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

.due-date {
  color: #606266;
}

.amount-calculator {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
  margin-top: 15px;
}

.calculator-result {
  margin-top: 10px;
  text-align: center;
}

.date-text {
  color: #606266;
}

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

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

.soon {
  color: #e6a23c;
  font-weight: 500;
}

.future {
  color: #409eff;
}

.service-content {
  padding: 10px 0;
}

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

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

.file-info {
  margin-bottom: 20px;
}

.file-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.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;
}

.file-checklist {
  margin-top: 15px;
}

.file-checklist .el-checkbox {
  display: block;
  margin-bottom: 12px;
}

.confirm-action {
  border: 2px solid #409eff;
}

.confirm-form {
  padding: 10px 0;
}

.confirm-checkbox {
  background-color: #f0f9ff;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #b3d8ff;
}

.checkbox-text {
  color: #303133;
  line-height: 1.6;
}

.confirm-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

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

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

.success-content {
  text-align: center;
}

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

/* 响应式设计 */
@media (max-width: 768px) {
  .section-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .amount-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .amount-item label {
    min-width: auto;
  }
  
  .file-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .file-actions {
    width: 100%;
    justify-content: flex-start;
  }
  
  .confirm-buttons {
    flex-direction: column;
    gap: 10px;
  }
  
  .confirm-buttons .el-button {
    width: 100%;
  }
}

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

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

/* 状态样式 */
.el-tag {
  font-weight: 500;
}

/* 表单样式优化 */
.el-form-item {
  margin-bottom: 22px;
}

/* 检查列表样式 */
.el-checkbox-group .el-checkbox {
  line-height: 2;
}

.el-checkbox__label {
  font-size: 14px;
  line-height: 1.6;
}

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

/* 成功对话框样式 */
.el-result {
  padding: 20px 0;
}

/* 计算器样式 */
.amount-calculator .el-input-number,
.amount-calculator .el-input {
  width: 100%;
}

/* 倒计时按钮样式 */
.el-button:disabled {
  opacity: 0.6;
}
</style>