<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>{{ isEditMode ? '编辑合同' : '合同管理' }}</span>
          <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回列表</el-button>
        </div>
      </template>

      <!-- 合同创建模式选择 -->
      <el-card class="mode-selector" shadow="never">
        <el-radio-group v-model="contractMode" @change="handleModeChange" size="large">
          <el-radio-button label="ONLINE">线上创建合同</el-radio-button>
          <el-radio-button label="upload">线下上传合同</el-radio-button>
        </el-radio-group>
        <div class="mode-description">
          <p v-if="contractMode === 'ONLINE'">
            <el-icon><Edit /></el-icon>
            线上创建：填写合同信息，系统自动生成合同编号和状态
          </p>
          <p v-if="contractMode === 'upload'">
            <el-icon><Upload /></el-icon>
            线下上传：上传已签署的合同文件，系统提取合同信息
          </p>
        </div>
      </el-card>

      <!-- 线上创建合同表单 -->
      <el-form 
        v-if="contractMode === 'ONLINE'"
        ref="contractRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px" 
        v-loading="loading"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractNumber">
              <el-input v-model="form.contractNumber" placeholder="系统自动生成" disabled />
              <div class="form-tip">合同编号由系统自动生成</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同状态">
              <el-input v-model="contractStatusDisplay" placeholder="系统自动管理" disabled />
              <div class="form-tip">合同状态由系统自动管理，不可手动修改</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同来源">
              <el-input v-model="contractSourceDisplay" placeholder="系统自动识别" disabled />
              <div class="form-tip">合同来源由系统根据创建方式自动识别</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 空列，保持布局平衡 -->
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同标题" prop="title">
              <el-input v-model="form.title" placeholder="请输入合同标题" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务类型">
              <el-select v-model="form.serviceType" placeholder="请选择服务类型" style="width: 100%">
                <el-option
                  v-for="dict in dc_service_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="甲方单位" prop="clientCompany">
              <el-input
                v-model="form.clientCompany"
                placeholder="请输入甲方单位名称"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="安保公司" prop="securityCompany">
              <el-input
                v-model="form.securityCompany"
                placeholder="默认为当前用户单位，可手动修改"
                maxlength="100"
                show-word-limit
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同金额" prop="contractAmount">
              <el-input-number
                v-model="form.contractAmount"
                :precision="2"
                :min="0"
                :max="999999999.99"
                placeholder="请输入合同金额"
                style="width: 100%"
                @change="calculateAmountInWords"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额大写">
              <el-input v-model="amountInWords" placeholder="金额大写" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务开始日期" prop="startDate">
              <el-date-picker
                v-model="form.startDate"
                type="date"
                placeholder="选择服务开始日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled-date="disabledStartDate"
                @change="handleStartDateChange"
              />
              <div class="form-tip">
                建议选择合同签署后的工作日开始服务
                <el-button type="text" size="small" @click="setTomorrowAsStartDate" style="margin-left: 10px;">
                  明天开始
                </el-button>
                <el-button type="text" size="small" @click="setNextMondayAsStartDate" style="margin-left: 5px;">
                  下周一开始
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务结束日期" prop="endDate">
              <el-date-picker
                v-model="form.endDate"
                type="date"
                placeholder="选择服务结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled="form.contractTerm && !['custom'].includes(form.contractTerm) && ['12', '24', '36'].includes(form.contractTerm)"
                :disabled-date="disabledEndDate"
                @change="handleEndDateChange"
              />
              <div class="form-tip">{{ getEndDateTip() }}</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
        <el-col :span="12">
            <el-form-item label="合同期限" prop="contractTerm">
              <el-select v-model="form.contractTerm" placeholder="请选择合同期限" style="width: 100%" @change="calculateEndDate">
                <el-option label="1年" value="12" />
                <el-option label="2年" value="24" />
                <el-option label="3年" value="36" />
                <el-option label="自定义" value="custom" />
                <!-- 动态显示计算出的月数选项 -->
                <el-option 
                  v-if="form.contractTerm && form.contractTerm !== 'custom' && !['12', '24', '36'].includes(form.contractTerm)"
                  :label="`${form.contractTerm}个月（自定义）`" 
                  :value="form.contractTerm" 
                />
              </el-select>
              <div class="form-tip" v-if="form.contractTerm === 'custom'">
                选择自定义后，请设置服务开始和结束日期，系统将自动计算月数
              </div>
              <div class="form-tip" v-else-if="form.contractTerm && !['12', '24', '36'].includes(form.contractTerm)">
                根据服务期限自动计算：{{ form.contractTerm }}个月
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款到期日" prop="paymentDueDate">
              <el-date-picker
                v-model="form.paymentDueDate"
                type="date"
                placeholder="选择付款到期日"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled-date="disabledPaymentDate"
                @change="handlePaymentDateChange"
              />
              <div class="form-tip">
                {{ getPaymentDateTip() }}
                <el-button type="text" size="small" @click="setPaymentDate30Days" style="margin-left: 10px;" :disabled="!form.endDate">
                  结束后30天
                </el-button>
                <el-button type="text" size="small" @click="setPaymentDate60Days" style="margin-left: 5px;" :disabled="!form.endDate">
                  结束后60天
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="合同条款" prop="contractTerms">
          <el-input
            v-model="form.contractTerms"
            type="textarea"
            :rows="6"
            placeholder="请输入合同条款内容"
            maxlength="2000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="服务内容" prop="serviceContent">
          <el-input
            v-model="form.serviceContent"
            type="textarea"
            :rows="4"
            placeholder="请输入详细的服务内容描述"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="备注信息">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="合同文件">
          <file-upload
            v-model="form.fileUrl"
            :limit="1"
            :file-type="['pdf', 'doc', 'docx']"
            :file-size="10"
          />
        </el-form-item>

        <el-divider content-position="left">合同预览</el-divider>
        
        <el-card v-if="showPreview" class="contract-preview">
          <h3 style="text-align: center; margin-bottom: 20px;">{{ form.title || '合同标题' }}</h3>
          
          <div class="contract-info">
            <p><strong>合同编号：</strong>{{ form.contractNumber || '系统自动生成' }}</p>
            <p><strong>甲方：</strong>{{ form.clientCompany }}</p>
            <p><strong>乙方：</strong>{{ form.securityCompany }}</p>
            <p><strong>合同金额：</strong>{{ formatMoney(form.contractAmount) }} ({{ amountInWords }})</p>
            <p><strong>服务期限：</strong>{{ form.startDate }} 至 {{ form.endDate }}</p>
            <p><strong>付款到期日：</strong>{{ form.paymentDueDate }}</p>
            <p><strong>服务类型：</strong>{{ getDictLabel(dc_service_type, form.serviceType) }}</p>
          </div>
          
          <div class="contract-terms" v-if="form.contractTerms">
            <h4>合同条款：</h4>
            <div class="terms-content">{{ form.contractTerms }}</div>
          </div>
        </el-card>

        <el-form-item style="margin-top: 30px;">
          <el-button type="primary" @click="submitOnlineContract" :loading="submitLoading">
            <el-icon><Check /></el-icon>
            {{ isEditMode ? '更新合同' : '创建合同' }}
          </el-button>
          <el-button @click="handlePreview">
            <el-icon><View /></el-icon>
            {{ showPreview ? '隐藏预览' : '预览合同' }}
          </el-button>
          <el-button @click="resetForm">
            <el-icon><Refresh /></el-icon>
            重置表单
          </el-button>
          <el-button @click="goBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
        </el-form-item>
      </el-form>

      <!-- 线下上传合同表单 -->
      <el-form 
        v-if="contractMode === 'upload'"
        ref="uploadRef" 
        :model="uploadForm" 
        :rules="uploadRules" 
        label-width="120px" 
        v-loading="loading"
      >
        <el-alert
          title="线下上传说明"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom: 20px;"
        >
          <template #default>
            <p>1. 请上传已签署的合同文件（PDF、DOC、DOCX格式）</p>
            <p>2. 系统将自动提取合同信息并进行验证</p>
            <p>3. 合同编号和状态将由系统自动生成</p>
            <p>4. 请确保合同文件清晰完整，包含所有必要信息</p>
          </template>
        </el-alert>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号">
              <el-input v-model="uploadForm.contractNumber" placeholder="系统自动生成" disabled />
              <div class="form-tip">合同编号由系统自动生成</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同状态">
              <el-input v-model="uploadContractStatusDisplay" placeholder="系统自动管理" disabled />
              <div class="form-tip">合同状态由系统自动管理，不可手动修改</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同来源">
              <el-input v-model="uploadContractSourceDisplay" placeholder="系统自动识别" disabled />
              <div class="form-tip">合同来源由系统根据上传方式自动识别</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 空列，保持布局平衡 -->
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同标题" prop="title">
              <el-input v-model="uploadForm.title" placeholder="请输入合同标题" maxlength="100" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 空列，保持布局平衡 -->
          </el-col>
        </el-row>

        <el-form-item label="甲方单位" prop="clientCompany">
          <el-input
            v-model="uploadForm.clientCompany"
            placeholder="请输入甲方单位名称"
            maxlength="100"
            show-word-limit
          />
          <div class="form-tip">请输入与合同文件中一致的甲方单位</div>
        </el-form-item>

        <el-form-item label="安保公司" prop="securityCompany">
          <el-input
            v-model="uploadForm.securityCompany"
            placeholder="默认为当前用户单位，可手动修改"
            maxlength="100"
            show-word-limit
          />
          <div class="form-tip">请输入与合同文件中一致的安保公司</div>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同金额" prop="contractAmount">
              <el-input-number
                v-model="uploadForm.contractAmount"
                :precision="2"
                :min="0"
                :max="999999999.99"
                placeholder="请输入合同金额"
                style="width: 100%"
                @change="calculateUploadAmountInWords"
              />
              <div class="form-tip">请输入与合同文件中一致的金额</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额大写">
              <el-input v-model="uploadAmountInWords" placeholder="金额大写" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="服务开始日期" prop="startDate">
              <el-date-picker
                v-model="uploadForm.startDate"
                type="date"
                placeholder="选择服务开始日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled-date="disabledUploadStartDate"
                @change="handleUploadStartDateChange"
              />
              <div class="form-tip">请选择与合同文件中一致的服务开始日期</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务结束日期" prop="endDate">
              <el-date-picker
                v-model="uploadForm.endDate"
                type="date"
                placeholder="选择服务结束日期"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled-date="disabledUploadEndDate"
                @change="handleUploadEndDateChange"
              />
              <div class="form-tip">请选择与合同文件中一致的服务结束日期</div>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="付款到期日" prop="paymentDueDate">
              <el-date-picker
                v-model="uploadForm.paymentDueDate"
                type="date"
                placeholder="选择付款到期日"
                value-format="YYYY-MM-DD"
                style="width: 100%"
                :disabled-date="disabledUploadPaymentDate"
                @change="handleUploadPaymentDateChange"
              />
              <div class="form-tip">请选择与合同文件中一致的付款到期日</div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <!-- 空列，保持布局平衡 -->
          </el-col>
        </el-row>

        <el-form-item label="服务内容" prop="serviceContent">
          <el-input
            v-model="uploadForm.serviceContent"
            type="textarea"
            :rows="4"
            placeholder="请输入与合同文件中一致的服务内容"
            maxlength="1000"
            show-word-limit
          />
          <div class="form-tip">请输入与合同文件中一致的服务内容</div>
        </el-form-item>

        <el-form-item label="备注信息">
          <el-input
            v-model="uploadForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息（如合同签署情况、特殊说明等）"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 文件验证结果 -->
        <el-card v-if="fileValidationResult" class="validation-result" shadow="never">
          <template #header>
            <div class="card-header">
              <span>文件验证结果</span>
              <el-tag :type="fileValidationResult.status === 'success' ? 'success' : 'warning'">
                {{ fileValidationResult.status === 'success' ? '验证通过' : '需要确认' }}
              </el-tag>
            </div>
          </template>
          
          <div v-if="fileValidationResult.extractedInfo">
            <h4>提取的合同信息：</h4>
            <el-descriptions :column="2" border>
              <el-descriptions-item label="文件名">{{ fileValidationResult.extractedInfo.fileName }}</el-descriptions-item>
              <el-descriptions-item label="文件大小">{{ fileValidationResult.extractedInfo.fileSize }}</el-descriptions-item>
              <el-descriptions-item label="文件类型">{{ fileValidationResult.extractedInfo.fileType }}</el-descriptions-item>
              <el-descriptions-item label="页数">{{ fileValidationResult.extractedInfo.pageCount }}</el-descriptions-item>
            </el-descriptions>
          </div>
          
          <div v-if="fileValidationResult.warnings && fileValidationResult.warnings.length > 0" style="margin-top: 15px;">
            <h4>注意事项：</h4>
            <ul>
              <li v-for="warning in fileValidationResult.warnings" :key="warning" class="warning-item">
                <el-icon><Warning /></el-icon>
                {{ warning }}
              </li>
            </ul>
          </div>
        </el-card>

        <el-form-item style="margin-top: 30px;">
          <el-button type="primary" @click="submitUploadContract" :loading="submitLoading">
            <el-icon><Upload /></el-icon>
            {{ isEditMode ? '更新合同' : '上传合同' }}
          </el-button>
          <el-button @click="getValidateContractFile" :loading="validating" :disabled="!uploadForm.contractFile">
            <el-icon><DocumentChecked /></el-icon>
            验证文件
          </el-button>
          <el-button @click="resetUploadForm">
            <el-icon><Refresh /></el-icon>
            重置表单
          </el-button>
          <el-button @click="goBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup name="ContractCreate">
import { addContract, uploadContract, validateContractFile, getContract, updateContract } from "@/api/credit/contract";
import { getUserProfile } from "@/api/system/user";

const { proxy } = getCurrentInstance();
const { dc_service_type } = proxy.useDict("dc_service_type");
const route = useRoute();

const loading = ref(false);
const submitLoading = ref(false);
const validating = ref(false);
const showPreview = ref(false);
const contractMode = ref('ONLINE'); // 'ONLINE' 或 'upload'
const amountInWords = ref('');
const uploadAmountInWords = ref('');
const fileValidationResult = ref(null);
const isEditMode = ref(false);
const contractId = ref(null);

// 合同状态显示
const contractStatusDisplay = computed(() => {
  if (!form.value.contractStatus) return '待确认';
  const statusMap = {
    'DRAFT': '草稿',
    'PENDING': '待确认', 
    'CONFIRMED': '已确认',
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  };
  return statusMap[form.value.contractStatus] || form.value.contractStatus;
});

// 合同来源显示（线上创建）
const contractSourceDisplay = computed(() => {
  if (!form.value.contractSource) return '平台创建';
  const sourceMap = {
    'PLATFORM_CREATED': '平台创建',
    'UPLOADED': '线下上传'
  };
  return sourceMap[form.value.contractSource] || form.value.contractSource;
});

const uploadContractStatusDisplay = computed(() => {
  if (!uploadForm.value.contractStatus) return '已确认';
  const statusMap = {
    'DRAFT': '草稿',
    'PENDING': '待确认',
    'CONFIRMED': '已确认', 
    'COMPLETED': '已完成',
    'CANCELLED': '已取消'
  };
  return statusMap[uploadForm.value.contractStatus] || uploadForm.value.contractStatus;
});

// 合同来源显示（线下上传）
const uploadContractSourceDisplay = computed(() => {
  if (!uploadForm.value.contractSource) return '线下上传';
  const sourceMap = {
    'PLATFORM_CREATED': '平台创建',
    'UPLOADED': '线下上传'
  };
  return sourceMap[uploadForm.value.contractSource] || uploadForm.value.contractSource;
});

// 线上创建合同表单数据
const data = reactive({
  form: {
    title: '',
    contractNumber: '',
    clientCompany: '',
    securityCompany: '',
    contractAmount: null, // 修改字段名以匹配后端
    serviceContent: '', // 添加服务内容字段
    startDate: '',
    endDate: '',
    paymentDueDate: '',
    contractTerm: '',
    serviceType: '',
    contractTerms: '',
    remark: '',
    fileUrl: '',
    contractType: 'ONLINE', // 标识合同类型
    contractStatus: '', // 合同状态
    contractSource: '' // 合同来源
  },
  rules: {
    title: [
      { required: true, message: "合同标题不能为空", trigger: "blur" },
      { min: 5, max: 100, message: "合同标题长度在5到100个字符", trigger: "blur" }
    ],
    clientCompany: [
      { required: true, message: "甲方单位不能为空", trigger: "blur" },
      { min: 2, max: 100, message: "甲方单位名称长度在2到100个字符", trigger: "blur" }
    ],
    securityCompany: [
      { required: true, message: "安保公司不能为空", trigger: "blur" },
      { min: 2, max: 100, message: "安保公司名称长度在2到100个字符", trigger: "blur" }
    ],
    contractAmount: [
      { required: true, message: "合同金额不能为空", trigger: "blur" },
      { type: 'number', min: 0.01, message: "合同金额必须大于0", trigger: "blur" }
    ],
    startDate: [
      { required: true, message: "服务开始日期不能为空", trigger: "blur" }
    ],
    endDate: [
      { required: true, message: "服务结束日期不能为空", trigger: "blur" }
    ],
    paymentDueDate: [
      { required: true, message: "付款到期日不能为空", trigger: "blur" }
    ],
    contractTerm: [
      { required: true, message: "请选择合同期限", trigger: "change" }
    ],
    serviceType: [
      { required: true, message: "请选择服务类型", trigger: "change" }
    ],
    contractTerms: [
      { required: true, message: "合同条款不能为空", trigger: "blur" },
      { min: 10, message: "合同条款至少10个字符", trigger: "blur" }
    ],
    serviceContent: [
      { required: true, message: "服务内容不能为空", trigger: "blur" },
      { min: 5, message: "服务内容至少5个字符", trigger: "blur" }
    ]
  }
});

// 线下上传合同表单数据
const uploadData = reactive({
  uploadForm: {
    title: '',
    contractNumber: '',
    clientCompany: '',
    securityCompany: '',
    contractAmount: null, // 修改字段名以匹配后端
    serviceContent: '', // 添加服务内容字段
    startDate: '',
    endDate: '',
    paymentDueDate: '',
    contractFile: '',
    remark: '',
    contractType: 'upload', // 标识合同类型
    contractStatus: '', // 合同状态
    contractSource: '' // 合同来源
  },
  uploadRules: {
    title: [
      { required: true, message: "合同标题不能为空", trigger: "blur" },
      { min: 5, max: 100, message: "合同标题长度在5到100个字符", trigger: "blur" }
    ],
    contractFile: [
      { required: true, message: "请上传合同文件", trigger: "change" }
    ],
    clientCompany: [
      { required: true, message: "甲方单位不能为空", trigger: "blur" },
      { min: 2, max: 100, message: "甲方单位名称长度在2到100个字符", trigger: "blur" }
    ],
    securityCompany: [
      { required: true, message: "安保公司不能为空", trigger: "blur" },
      { min: 2, max: 100, message: "安保公司名称长度在2到100个字符", trigger: "blur" }
    ],
    contractAmount: [
      { required: true, message: "合同金额不能为空", trigger: "blur" },
      { type: 'number', min: 0.01, message: "合同金额必须大于0", trigger: "blur" }
    ],
    startDate: [
      { required: true, message: "服务开始日期不能为空", trigger: "blur" }
    ],
    endDate: [
      { required: true, message: "服务结束日期不能为空", trigger: "blur" }
    ],
    paymentDueDate: [
      { required: true, message: "付款到期日不能为空", trigger: "blur" }
    ],
    serviceContent: [
      { required: true, message: "服务内容不能为空", trigger: "blur" },
      { min: 5, message: "服务内容至少5个字符", trigger: "blur" }
    ]
  }
});

const { form, rules } = toRefs(data);
const { uploadForm, uploadRules } = toRefs(uploadData);

/** 模式切换处理 */
function handleModeChange(mode) {
  contractMode.value = mode;
  // 重置表单数据
  resetForm();
  resetUploadForm();
  fileValidationResult.value = null;
  
  // 重新生成合同编号
  generateContractNumber();
  
  // 重新设置默认安保公司（仅在新建模式下）
  if (!isEditMode.value) {
    getUserInfoAndSetDefaults();
  }
  
  // 不设置默认日期，让用户自己选择
}

/** 获取公司列表 */
function getCompanyList() {
  // 不再需要获取公司列表，因为改为输入框形式
  return Promise.resolve();
}

/** 计算金额大写 */
function calculateAmountInWords() {
  if (form.value.contractAmount) {
    amountInWords.value = convertToChineseNumber(form.value.contractAmount);
  } else {
    amountInWords.value = '';
  }
}

/** 计算上传模式金额大写 */
function calculateUploadAmountInWords() {
  if (uploadForm.value.contractAmount) {
    uploadAmountInWords.value = convertToChineseNumber(uploadForm.value.contractAmount);
  } else {
    uploadAmountInWords.value = '';
  }
}

/** 根据开始日期和合同期限计算结束日期 */
function calculateEndDate() {
  if (form.value.startDate && form.value.contractTerm && form.value.contractTerm !== 'custom') {
    const startDate = new Date(form.value.startDate);
    const months = parseInt(form.value.contractTerm);
    
    // 创建新的日期对象来计算结束日期，避免修改原始日期
    const endDate = new Date(startDate);
    endDate.setMonth(endDate.getMonth() + months);
    form.value.endDate = endDate.toISOString().split('T')[0];
    
    // 自动设置付款到期日（服务结束后30天）
    const paymentDate = new Date(endDate);
    paymentDate.setDate(paymentDate.getDate() + 30);
    form.value.paymentDueDate = paymentDate.toISOString().split('T')[0];
  } else if (form.value.contractTerm === 'custom') {
    // 自定义期限时，如果已有开始和结束日期，计算月数并更新contractTerm
    if (form.value.startDate && form.value.endDate) {
      const calculatedMonths = calculateMonthsBetweenDates(form.value.startDate, form.value.endDate);
      if (calculatedMonths > 0) {
        form.value.contractTerm = calculatedMonths.toString();
      }
    }
    
    // 如果有结束日期，更新付款到期日
    if (form.value.endDate) {
      const endDate = new Date(form.value.endDate);
      const paymentDate = new Date(endDate);
      paymentDate.setDate(paymentDate.getDate() + 30);
      form.value.paymentDueDate = paymentDate.toISOString().split('T')[0];
    }
  }
}

/** 计算两个日期之间的月数 */
function calculateMonthsBetweenDates(startDate, endDate) {
  const start = new Date(startDate);
  const end = new Date(endDate);
  
  if (end <= start) {
    return 0;
  }
  
  let months = (end.getFullYear() - start.getFullYear()) * 12;
  months += end.getMonth() - start.getMonth();
  
  // 如果结束日期的日数小于开始日期的日数，减去一个月
  if (end.getDate() < start.getDate()) {
    months--;
  }
  
  return Math.max(0, months);
}

/** 获取下一个工作日 */
function getNextWorkday(date) {
  const nextDay = new Date(date);
  nextDay.setDate(nextDay.getDate() + 1);
  
  // 如果是周六(6)或周日(0)，调整到下周一
  while (nextDay.getDay() === 0 || nextDay.getDay() === 6) {
    nextDay.setDate(nextDay.getDate() + 1);
  }
  
  return nextDay;
}

/** 获取建议的服务开始日期（明天或下一个工作日） */
function getSuggestedStartDate() {
  const today = new Date();
  const tomorrow = new Date(today);
  tomorrow.setDate(tomorrow.getDate() + 1);
  
  // 如果明天是工作日，返回明天；否则返回下一个工作日
  if (tomorrow.getDay() >= 1 && tomorrow.getDay() <= 5) {
    return tomorrow;
  } else {
    return getNextWorkday(tomorrow);
  }
}

/** 禁用服务开始日期的规则 */
function disabledStartDate(time) {
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  
  // 禁用今天之前的日期
  return time.getTime() < today.getTime();
}

/** 禁用服务结束日期的规则 */
function disabledEndDate(time) {
  if (!form.value.startDate) return false;
  
  const startDate = new Date(form.value.startDate);
  startDate.setHours(0, 0, 0, 0);
  
  // 禁用开始日期当天及之前的日期
  return time.getTime() <= startDate.getTime();
}

/** 禁用付款到期日的规则 */
function disabledPaymentDate(time) {
  // 如果有结束日期，禁用结束日期及之前的日期
  if (form.value.endDate) {
    const endDate = new Date(form.value.endDate);
    endDate.setHours(0, 0, 0, 0);
    return time.getTime() <= endDate.getTime();
  }
  
  // 如果没有结束日期，禁用今天之前的日期
  const today = new Date();
  today.setHours(0, 0, 0, 0);
  return time.getTime() < today.getTime();
}

/** 处理服务开始日期变更 */
function handleStartDateChange(value) {
  if (value) {
    // 自动计算结束日期
    calculateEndDate();
    
    // 如果是自定义期限且已有结束日期，重新计算月数
    if (form.value.contractTerm === 'custom' && form.value.endDate) {
      const calculatedMonths = calculateMonthsBetweenDates(value, form.value.endDate);
      if (calculatedMonths > 0) {
        form.value.contractTerm = calculatedMonths.toString();
      }
    }
    
    // 如果还没有设置付款到期日，根据结束日期自动设置
    if (!form.value.paymentDueDate && form.value.endDate) {
      const paymentDate = new Date(form.value.endDate);
      paymentDate.setDate(paymentDate.getDate() + 30);
      form.value.paymentDueDate = paymentDate.toISOString().split('T')[0];
    } else if (!form.value.paymentDueDate && !form.value.endDate) {
      // 如果没有结束日期，临时设置为开始日期后60天
      const paymentDate = new Date(value);
      paymentDate.setDate(paymentDate.getDate() + 60);
      form.value.paymentDueDate = paymentDate.toISOString().split('T')[0];
    }
    
    // 如果结束日期早于或等于开始日期，清空结束日期和付款日期
    if (form.value.endDate && new Date(form.value.endDate) <= new Date(value)) {
      form.value.endDate = '';
      form.value.paymentDueDate = '';
      // 如果是自定义期限，重置为custom
      if (form.value.contractTerm !== '12' && form.value.contractTerm !== '24' && form.value.contractTerm !== '36') {
        form.value.contractTerm = 'custom';
      }
    }
  }
}

/** 处理服务结束日期变更 */
function handleEndDateChange(value) {
  if (value && form.value.startDate) {
    const startDate = new Date(form.value.startDate);
    const endDate = new Date(value);
    
    // 验证结束日期必须晚于开始日期
    if (endDate <= startDate) {
      proxy.$modal.msgError("服务结束日期必须晚于开始日期");
      form.value.endDate = '';
      return;
    }
    
    // 如果是自定义期限，自动计算月数并更新contractTerm
    if (form.value.contractTerm === 'custom') {
      const calculatedMonths = calculateMonthsBetweenDates(form.value.startDate, value);
      if (calculatedMonths > 0) {
        form.value.contractTerm = calculatedMonths.toString();
      }
    }
    
    // 自动设置付款到期日为结束日期后30天
    const paymentDate = new Date(endDate);
    paymentDate.setDate(paymentDate.getDate() + 30);
    form.value.paymentDueDate = paymentDate.toISOString().split('T')[0];
  }
}

/** 处理付款到期日变更 */
function handlePaymentDateChange(value) {
  if (value) {
    const paymentDate = new Date(value);
    
    // 如果有结束日期，验证付款日期必须晚于结束日期
    if (form.value.endDate) {
      const endDate = new Date(form.value.endDate);
      if (paymentDate <= endDate) {
        proxy.$modal.msgError("付款到期日必须晚于服务结束日期");
        form.value.paymentDueDate = '';
        return;
      }
    }
    
    // 如果有开始日期，验证付款日期不要早于开始日期
    if (form.value.startDate) {
      const startDate = new Date(form.value.startDate);
      if (paymentDate < startDate) {
        proxy.$modal.msgWarning("付款到期日不应早于服务开始日期");
      }
    }
  }
}

/** 快速设置明天为开始日期 */
function setTomorrowAsStartDate() {
  const tomorrow = new Date();
  tomorrow.setDate(tomorrow.getDate() + 1);
  form.value.startDate = tomorrow.toISOString().split('T')[0];
  handleStartDateChange(form.value.startDate);
}

/** 快速设置下周一为开始日期 */
function setNextMondayAsStartDate() {
  const today = new Date();
  const nextMonday = new Date(today);
  const daysUntilMonday = (8 - today.getDay()) % 7 || 7; // 如果今天是周一，则是下周一
  nextMonday.setDate(today.getDate() + daysUntilMonday);
  form.value.startDate = nextMonday.toISOString().split('T')[0];
  handleStartDateChange(form.value.startDate);
}

/** 快速设置付款日期为结束日期后30天 */
function setPaymentDate30Days() {
  if (form.value.endDate) {
    const paymentDate = new Date(form.value.endDate);
    paymentDate.setDate(paymentDate.getDate() + 30);
    form.value.paymentDueDate = paymentDate.toISOString().split('T')[0];
    handlePaymentDateChange(form.value.paymentDueDate);
  } else {
    proxy.$modal.msgWarning("请先设置服务结束日期");
  }
}

/** 快速设置付款日期为结束日期后60天 */
function setPaymentDate60Days() {
  if (form.value.endDate) {
    const paymentDate = new Date(form.value.endDate);
    paymentDate.setDate(paymentDate.getDate() + 60);
    form.value.paymentDueDate = paymentDate.toISOString().split('T')[0];
    handlePaymentDateChange(form.value.paymentDueDate);
  } else {
    proxy.$modal.msgWarning("请先设置服务结束日期");
  }
}

/** 获取结束日期提示信息 */
function getEndDateTip() {
  if (!form.value.startDate) {
    return "请先选择服务开始日期";
  }
  
  if (form.value.contractTerm && form.value.contractTerm !== 'custom' && ['12', '24', '36'].includes(form.value.contractTerm)) {
    const months = parseInt(form.value.contractTerm);
    return `根据合同期限${months}个月自动计算，不可修改`;
  }
  
  if (form.value.contractTerm === 'custom') {
    return "自定义期限，请手动选择服务结束日期，系统将自动计算月数";
  }
  
  if (form.value.contractTerm && !['12', '24', '36', 'custom'].includes(form.value.contractTerm)) {
    return `已根据服务期限自动计算为${form.value.contractTerm}个月`;
  }
  
  return "请选择服务结束日期，必须晚于开始日期";
}

/** 获取付款到期日提示信息 */
function getPaymentDateTip() {
  if (!form.value.endDate) {
    return "请先设置服务结束日期，付款到期日应晚于服务结束日期";
  }
  
  if (form.value.endDate && !form.value.startDate) {
    return "付款到期日应晚于服务结束日期，建议设置为结束后30天";
  }
  
  if (form.value.startDate && form.value.endDate) {
    return "付款到期日必须晚于服务结束日期";
  }
  
  return "请选择付款到期日";
}

// 上传模式的日期处理函数
/** 禁用上传模式服务开始日期的规则 */
function disabledUploadStartDate(time) {
  // 上传模式允许选择过去的日期（因为可能是已签署的合同）
  const oneYearAgo = new Date();
  oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
  
  // 禁用一年前的日期
  return time.getTime() < oneYearAgo.getTime();
}

/** 禁用上传模式服务结束日期的规则 */
function disabledUploadEndDate(time) {
  if (!uploadForm.value.startDate) return false;
  
  const startDate = new Date(uploadForm.value.startDate);
  startDate.setHours(0, 0, 0, 0);
  
  // 禁用开始日期当天及之前的日期
  return time.getTime() <= startDate.getTime();
}

/** 禁用上传模式付款到期日的规则 */
function disabledUploadPaymentDate(time) {
  // 上传模式允许选择过去的日期
  const oneYearAgo = new Date();
  oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1);
  
  return time.getTime() < oneYearAgo.getTime();
}

/** 处理上传模式服务开始日期变更 */
function handleUploadStartDateChange(value) {
  if (value && uploadForm.value.endDate) {
    const startDate = new Date(value);
    const endDate = new Date(uploadForm.value.endDate);
    
    if (endDate <= startDate) {
      uploadForm.value.endDate = '';
      proxy.$modal.msgWarning("服务结束日期已清空，请重新选择");
    }
  }
}

/** 处理上传模式服务结束日期变更 */
function handleUploadEndDateChange(value) {
  if (value && uploadForm.value.startDate) {
    const startDate = new Date(uploadForm.value.startDate);
    const endDate = new Date(value);
    
    if (endDate <= startDate) {
      proxy.$modal.msgError("服务结束日期必须晚于开始日期");
      uploadForm.value.endDate = '';
      return;
    }
  }
}

/** 处理上传模式付款到期日变更 */
function handleUploadPaymentDateChange(value) {
  if (value && uploadForm.value.endDate) {
    const paymentDate = new Date(value);
    const endDate = new Date(uploadForm.value.endDate);
    
    if (paymentDate > endDate) {
      proxy.$modal.msgWarning("付款到期日晚于服务结束日期，请确认是否正确");
    }
  }
}

/** 加载合同数据（编辑模式） */
function loadContractData(id) {
  loading.value = true;
  getContract(id).then(response => {
    const contractData = response.data;
    
    // 根据合同类型设置模式
    contractMode.value = contractData.contractType || 'ONLINE';
    
    if (contractMode.value === 'ONLINE') {
      // 填充线上创建表单
      Object.assign(form.value, {
        contractId: contractData.contractId || contractData.id,
        title: contractData.title,
        contractNumber: contractData.contractNumber,
        clientCompany: contractData.clientCompany,
        securityCompany: contractData.securityCompany,
        contractAmount: contractData.contractAmount,
        serviceContent: contractData.serviceContent,
        startDate: contractData.startDate,
        endDate: contractData.endDate,
        paymentDueDate: contractData.paymentDueDate,
        contractTerm: contractData.contractTerm,
        serviceType: contractData.serviceType,
        contractTerms: contractData.contractTerms,
        remark: contractData.remark,
        fileUrl: contractData.fileUrl,
        contractType: contractData.contractType,
        contractStatus: contractData.contractStatus,
        contractSource: contractData.contractSource
      });
      
      // 计算金额大写
      calculateAmountInWords();
    } else {
      // 填充线下上传表单
      Object.assign(uploadForm.value, {
        contractId: contractData.contractId || contractData.id,
        title: contractData.title,
        contractNumber: contractData.contractNumber,
        clientCompany: contractData.clientCompany,
        securityCompany: contractData.securityCompany,
        contractAmount: contractData.contractAmount,
        serviceContent: contractData.serviceContent,
        startDate: contractData.startDate,
        endDate: contractData.endDate,
        paymentDueDate: contractData.paymentDueDate,
        contractFile: contractData.fileUrl,
        remark: contractData.remark,
        contractType: contractData.contractType,
        contractStatus: contractData.contractStatus,
        contractSource: contractData.contractSource
      });
      
      // 计算金额大写
      calculateUploadAmountInWords();
    }
    
    loading.value = false;
  }).catch(() => {
    loading.value = false;
    proxy.$modal.msgError("加载合同数据失败");
  });
}

/** 生成合同编号 */
function generateContractNumber() {
  // 编辑模式下不重新生成合同编号
  if (isEditMode.value) return;
  
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
  const contractNumber = `HT${year}${month}${day}${random}`;
  
  form.value.contractNumber = contractNumber;
  uploadForm.value.contractNumber = contractNumber;
}

/** 文件变更处理 */
function handleFileChange(fileUrl) {
  uploadForm.value.contractFile = fileUrl;
  // 清除之前的验证结果
  fileValidationResult.value = null;
}

/** 验证合同文件 */
function getValidateContractFile() {
  if (!uploadForm.value.contractFile) {
    proxy.$modal.msgError("请先上传合同文件");
    return;
  }
  
  validating.value = true;
  
  // 创建FormData对象
  const formData = new FormData();
  formData.append('contractFile', uploadForm.value.contractFile);
  
  // 调用后端API进行文件验证和信息提取
  validateContractFile(formData).then(response => {
    fileValidationResult.value = response.data;
    proxy.$modal.msgSuccess("文件验证完成");
  }).catch(error => {
    // 如果API不可用，使用模拟数据
    console.warn("文件验证API不可用，使用模拟数据:", error);
    fileValidationResult.value = {
      status: 'success',
      extractedInfo: {
        fileName: uploadForm.value.contractFile.split('/').pop() || '合同文件.pdf',
        fileSize: '2.5MB',
        fileType: 'PDF',
        pageCount: 8
      },
      warnings: [
        '请确认合同中的甲方单位与所选择的一致',
        '请核对合同金额是否正确',
        '建议检查合同签署日期和服务期限'
      ]
    };
    proxy.$modal.msgSuccess("文件验证完成（模拟模式）");
  }).finally(() => {
    validating.value = false;
  });
}

/** 数字转中文大写 */
function convertToChineseNumber(num) {
  const digits = ['零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖'];
  const units = ['', '拾', '佰', '仟'];
  const bigUnits = ['', '万', '亿'];
  const decimalUnits = ['角', '分'];
  
  if (num === 0) return '零元整';
  
  const numStr = num.toFixed(2);
  const [integerPart, decimalPart] = numStr.split('.');
  
  let result = '';
  
  // 处理整数部分
  if (parseInt(integerPart) === 0) {
    result = '零';
  } else {
    // 将整数部分按4位分组处理
    const integerStr = integerPart;
    const groups = [];
    
    // 从右往左每4位分一组
    for (let i = integerStr.length; i > 0; i -= 4) {
      const start = Math.max(0, i - 4);
      groups.unshift(integerStr.slice(start, i));
    }
    
    // 处理每一组
    for (let groupIndex = 0; groupIndex < groups.length; groupIndex++) {
      const group = groups[groupIndex];
      const groupNum = parseInt(group);
      
      if (groupNum === 0) {
        // 如果这一组是0，需要判断是否添加零
        if (result && groupIndex < groups.length - 1) {
          result += '零';
        }
        continue;
      }
      
      let groupResult = '';
      const groupStr = group.padStart(4, '0');
      
      // 处理千位
      if (groupStr[0] !== '0') {
        groupResult += digits[parseInt(groupStr[0])] + units[3];
      }
      
      // 处理百位
      if (groupStr[1] !== '0') {
        groupResult += digits[parseInt(groupStr[1])] + units[2];
      } else if (groupResult && (groupStr[2] !== '0' || groupStr[3] !== '0')) {
        groupResult += '零';
      }
      
      // 处理十位
      if (groupStr[2] !== '0') {
        groupResult += digits[parseInt(groupStr[2])] + units[1];
      } else if (groupResult && groupStr[3] !== '0') {
        groupResult += '零';
      }
      
      // 处理个位
      if (groupStr[3] !== '0') {
        groupResult += digits[parseInt(groupStr[3])];
      }
      
      // 添加大单位
      const bigUnitIndex = groups.length - 1 - groupIndex;
      if (groupResult && bigUnitIndex > 0 && bigUnitIndex < bigUnits.length) {
        groupResult += bigUnits[bigUnitIndex];
      }
      
      result += groupResult;
    }
  }
  
  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 handlePreview() {
  showPreview.value = !showPreview.value;
}

/** 提交线上创建合同 */
function submitOnlineContract() {
  proxy.$refs["contractRef"].validate(valid => {
    if (valid) {
      submitLoading.value = true;
      
      // 表单验证通过后的额外验证
      if (new Date(form.value.endDate) <= new Date(form.value.startDate)) {
        proxy.$modal.msgError("服务结束日期必须大于开始日期");
        submitLoading.value = false;
        return;
      }
      
      // 设置合同类型为线上创建
      const contractData = {
        ...form.value,
        contractType: 'ONLINE'
      };
      
      // 编辑模式下添加合同ID
      if (isEditMode.value && contractId.value) {
        contractData.contractId = contractId.value;
      }
      
      // 安全措施：移除状态和来源字段，确保由后端控制
      delete contractData.contractStatus;
      delete contractData.contractSource;
      
      // 根据是否为编辑模式选择API
      const apiCall = isEditMode.value ? updateContract(contractData) : addContract(contractData);
      const successMessage = isEditMode.value ? "合同更新成功" : "合同创建成功";
      
      apiCall.then(response => {
        const id = isEditMode.value ? response.contractId : response.data.contractId;
        proxy.$modal.msgSuccess(successMessage);
        console.log(id)
        proxy.$router.push({ 
          path: '/digitalCredit/detail', 
          query: { id: id } 
        });
      }).catch(() => {
        submitLoading.value = false;
      }).finally(() => {
        submitLoading.value = false;
      });
    }
  });
}

/** 提交线下上传合同 */
function submitUploadContract() {
  proxy.$refs["uploadRef"].validate(valid => {
    if (valid) {
      submitLoading.value = true;
      
      // 表单验证通过后的额外验证
      if (new Date(uploadForm.value.endDate) <= new Date(uploadForm.value.startDate)) {
        proxy.$modal.msgError("服务结束日期必须大于开始日期");
        submitLoading.value = false;
        return;
      }
      
      // 创建FormData对象用于文件上传
      const formData = new FormData();
      
      // 添加合同信息
      Object.keys(uploadForm.value).forEach(key => {
        if (uploadForm.value[key] !== null && uploadForm.value[key] !== '' && 
            key !== 'contractStatus' && key !== 'contractSource') {
          formData.append(key, uploadForm.value[key]);
        }
      });
      
      // 设置合同类型为线下上传
      formData.append('contractType', 'upload');
      
      uploadContract(formData).then(response => {
        proxy.$modal.msgSuccess("合同上传成功");
        proxy.$router.push({ 
          path: '/digitalCredit/detail', 
          query: { id: response.data.contractId } 
        });
      }).catch(() => {
        submitLoading.value = false;
      }).finally(() => {
        submitLoading.value = false;
      });
    }
  });
}

/** 重置线上创建表单 */
function resetForm() {
  if (proxy.$refs["contractRef"]) {
    proxy.$refs["contractRef"].resetFields();
  }
  amountInWords.value = '';
  showPreview.value = false;
  generateContractNumber();
}

/** 重置线下上传表单 */
function resetUploadForm() {
  if (proxy.$refs["uploadRef"]) {
    proxy.$refs["uploadRef"].resetFields();
  }
  uploadAmountInWords.value = '';
  fileValidationResult.value = null;
  generateContractNumber();
}

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

/** 获取字典标签 */
function getDictLabel(dicts, value) {
  if (!value || !dicts) return '';
  const dict = dicts.find(item => item.value === value);
  return dict ? dict.label : value;
}

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

/** 获取用户信息并设置默认安保公司 */
function getUserInfoAndSetDefaults() {
  getUserProfile().then(response => {
    const userInfo = response.data;
    // 如果用户有部门信息，设置为默认安保公司
    if (userInfo.dept && userInfo.dept.deptName) {
      // 只在新建模式下设置默认值，编辑模式不覆盖
      if (!isEditMode.value) {
        form.value.securityCompany = userInfo.dept.deptName;
        uploadForm.value.securityCompany = userInfo.dept.deptName;
      }
    }
  }).catch(error => {
    console.warn("获取用户信息失败:", error);
  });
}

onMounted(() => {
  // 检查是否为编辑模式
  const id = route.query.id;
  if (id) {
    isEditMode.value = true;
    contractId.value = id;
    // 编辑模式下直接加载合同数据
    loadContractData(id);
  } else {
    isEditMode.value = false;
    contractId.value = null;
    generateContractNumber();
    // 新合同不设置默认日期，让用户自己选择
    // 获取用户信息并设置默认安保公司
    getUserInfoAndSetDefaults();
  }
});
</script>

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

.mode-selector {
  margin-bottom: 20px;
  text-align: center;
}

.mode-description {
  margin-top: 15px;
  color: #606266;
  font-size: 14px;
}

.mode-description p {
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

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

.contract-preview {
  margin-top: 20px;
  background-color: #fafafa;
}

.contract-info p {
  margin: 10px 0;
  line-height: 1.6;
}

.contract-terms {
  margin-top: 20px;
}

.terms-content {
  background-color: #fff;
  padding: 15px;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  white-space: pre-wrap;
  line-height: 1.6;
}

.validation-result {
  margin-top: 20px;
  border: 1px solid #e1f3d8;
}

.validation-result .card-header {
  background-color: #f0f9ff;
  padding: 10px 15px;
  border-bottom: 1px solid #e1f3d8;
}

.warning-item {
  margin: 8px 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #e6a23c;
}

.el-upload__tip {
  color: #606266;
  font-size: 12px;
  margin-top: 7px;
  display: flex;
  align-items: center;
  gap: 5px;
}

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

.el-alert p {
  margin: 5px 0;
  line-height: 1.5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .mode-selector {
    text-align: left;
  }
  
  .mode-description p {
    justify-content: flex-start;
  }
  
  .el-col {
    margin-bottom: 15px;
  }
}

/* 表单项间距优化 */
.el-form-item {
  margin-bottom: 22px;
}

/* 表单提示样式增强 */
.form-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
  line-height: 1.4;
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.form-tip .el-button--text {
  padding: 0 4px;
  font-size: 12px;
  color: #409eff;
  height: auto;
  line-height: 1.2;
}

.form-tip .el-button--text:hover {
  color: #66b1ff;
}

.form-tip .el-button--text:disabled {
  color: #c0c4cc;
}

/* 按钮组样式 */
.el-form-item:last-child {
  margin-top: 30px;
  text-align: center;
}

.el-form-item:last-child .el-button {
  margin: 0 8px;
}

/* 文件验证结果样式 */
.validation-result .el-descriptions {
  margin-top: 15px;
}

.validation-result h4 {
  margin: 15px 0 10px 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.validation-result ul {
  margin: 10px 0;
  padding-left: 0;
  list-style: none;
}

/* 模式选择器样式增强 */
.el-radio-group {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.el-radio-button {
  margin: 0;
}

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

/* 成功状态样式 */
.validation-result.success {
  border-color: #67c23a;
}

.validation-result.success .card-header {
  background-color: #f0f9ff;
  border-color: #67c23a;
}
</style>