<template>
  <el-drawer
    v-model="dialogVisible"
    class="my-drawer"
    :title="dialogTitle"
    direction="rtl"
    size="100%"
    :destroy-on-close="true"
    :with-header="true"
    :before-close="onClose"
  >
    <template #default>
      <!-- 主表单 -->
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
        v-loading="formLoading"
      >
        <el-divider content-position="left">合同基本信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="合同编号" prop="contractNo">
              <el-input v-model="formData.contractNo" placeholder="自动生成" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="formData.contractName" placeholder="请输入合同名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同版本" prop="contractVersion">
              <el-input v-model="formData.contractVersion" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="合同类别" prop="contractCategory">
              <el-select v-model="formData.contractCategory" placeholder="请选择">
                <el-option
                  v-for="item in contractCategoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同状态" prop="contractStatus">
              <el-select v-model="formData.contractStatus" placeholder="请选择">
                <el-option
                  v-for="item in contractStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="主合同标记" prop="isMainContract">
              <el-radio-group v-model="formData.isMainContract">
                <el-radio :value="1">是</el-radio>
                <el-radio :value="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 2. 合同主体信息 -->
        <el-divider content-position="left">合同主体信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="甲方公司" prop="partyACompany">
              <el-input v-model="formData.partyACompanyName" readonly>
                <template #append>
                  <el-button :icon="Search" @click="showCompanySelectDialog" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方公司" prop="partyBCompany">
              <el-input v-model="formData.partyBCompanyName" readonly>
                <template #append>
                  <el-button :icon="Search" @click="showCustomerSelectDialog" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="经办部门" prop="handlingDepartment">
              <el-input v-model="formData.handlingDepartment" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经办人" prop="handler">
              <el-input v-model="formData.handler" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 3. 合同财务信息 -->
        <el-divider content-position="left">合同财务信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="币种" prop="currency">
              <el-select v-model="formData.currency" placeholder="请选择币种">
                <el-option
                  v-for="item in currencyOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="本次合同金额" prop="currentContractAmount">
              <el-input v-model="formData.currentContractAmount" placeholder="请输入金额">
                <template #append>{{ formData.currency || '币种' }}</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="累计合同金额" prop="totalContractAmount">
              <el-input v-model="formData.totalContractAmount" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="已收金额" prop="paidAmount">
              <el-input v-model="formData.paidAmount" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="合同收款标记" prop="isContractPaymentMarked">
              <el-radio-group v-model="formData.isContractPaymentMarked">
                <el-radio :value="1">是</el-radio>
                <el-radio :value="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 4. 时间信息 -->
        <el-divider content-position="left">时间信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="生效日期" prop="effectiveDate">
              <el-date-picker
                v-model="formData.effectiveDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="失效日期" prop="expiryDate">
              <el-date-picker
                v-model="formData.expiryDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="乙方签期" prop="partyBSignDate">
              <el-date-picker
                v-model="formData.partyBSignDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 5. 项目关联信息 -->
        <el-divider content-position="left">项目关联信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目编码" prop="projectCode">
              <el-input v-model="formData.projectCode" readonly>
                <template #append>
                  <el-button :icon="Search" @click="showProjectSelectDialog" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="formData.projectName" disabled />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="主合同编号" prop="mainContractNo">
              <el-input v-model="formData.mainContractNo" readonly>
                <template #append>
                  <el-button :icon="Search" @click="showContractDialog" />
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="来源单号" prop="sourceDocumentNo">
              <el-input v-model="formData.sourceDocumentNo" placeholder="请输入来源单号" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 6. 合同终止信息 -->
        <el-divider content-position="left">合同终止信息</el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="终止日期" prop="terminationDate">
              <el-date-picker
                v-model="formData.terminationDate"
                type="date"
                placeholder="选择日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="终止原因" prop="terminationReason">
              <el-input v-model="formData.terminationReason" placeholder="请输入终止原因" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remarks">
          <el-input
            v-model="formData.remarks"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>

      <!-- Tab 页签：合同阶段、归档附件、收款跟踪、补充合同 -->
      <el-tabs v-model="activeTab" type="card" style="padding: 0 20px; margin-top: 20px">
        <!-- 合同阶段 -->
        <el-tab-pane name="phase" label="合同阶段">
          <div class="tab-toolbar">
            <el-button size="small" type="primary" @click="handleAddPhase" class="pl-8px m-b-8px"
              >新增</el-button
            >
          </div>
          <!-- 合同阶段表格 -->
          <el-table :data="phaseList" border>
            <el-table-column label="阶段名称" width="150">
              <template #default="{ row }">
                <el-input v-model="row.data.phaseName" @change="savePhase(row)" />
              </template>
            </el-table-column>
            <el-table-column label="款项比例" width="200">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.data.paymentRatio"
                  @change="savePhase(row)"
                  :min="0"
                  :max="100"
                  :precision="2"
                  :step="1"
                  style="width: 100%;"
                >
                  <template #suffix>
                    <span>%</span>
                  </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="收款时间" width="160">
              <template #default="{ row }">
                <el-date-picker
                  v-model="row.data.paymentTime"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  style="width: 100%"
                  @change="savePhase(row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="应收金额" width="200">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.data.payableAmount"
                  @change="savePhase(row)"
                  :min="0"
                  :precision="2"
                  :step="1"
                  style="width: 100%;"
                >
                  <template #suffix>
                    <span>元</span>
                  </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="实收金额" width="200">
              <template #default="{ row }">
                <el-input-number
                  v-model="row.data.actualPaymentAmount"
                  @change="savePhase(row)"
                  :min="0"
                  :precision="2"
                  :step="1"
                  style="width: 100%;"
                >
                  <template #suffix>
                    <span>元</span>
                  </template>
                </el-input-number>
              </template>
            </el-table-column>
            <el-table-column label="是否完成" width="120">
              <template #default="{ row }">
                <el-select
                  v-model="row.data.isCompleted"
                  style="width: 100%"
                  @change="savePhase(row)"
                >
                  <el-option label="未完成" :value="0" />
                  <el-option label="已完成" :value="1" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="验收附件" width="280">
              <template #default="{ row }">
                <div v-if="!row.data.acceptanceFileUrl" class="upload-area">
                  <input
                    type="file"
                    :accept="'.pdf'"
                    :ref="(el) => setFileInput(row, el)"
                    style="display: none"
                    @change="handleAcceptanceUpload(row)"
                  />
                  <el-button size="small" type="primary" @click="hanlderClick(row)">
                    上传
                  </el-button>
                </div>
                <div v-else class="uploaded-file">
                  <span style="margin-right: 10px">{{ row.data.acceptanceFileName }}</span>
                  <el-button
                    :icon="Download"
                    circle
                    type="default"
                    :underline="false"
                    @click="downloadFile(row.data.acceptanceFileUrl, row.data.acceptanceFileName)"
                  />
                  <el-button
                    type="default"
                    :icon="DocumentChecked"
                    circle
                    :underline="false"
                    @click="previewFile(row.data.acceptanceFileUrl, row.data.acceptanceFileName)"
                  />
                  <el-button size="small" type="primary" @click="hanlderClick(row)">
                    更换
                  </el-button>
                  <input
                    type="file"
                    :accept="'.pdf'"
                    :ref="(el) => setFileInput(row, el)"
                    style="display: none"
                    @change="handleAcceptanceUpload(row)"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column label="验收状态" width="120">
              <template #default="{ row }">
                <el-select
                  v-model="row.data.isAcceptanceCompleted"
                  style="width: 100%"
                  @change="savePhase(row)"
                >
                  <el-option label="未完成" :value="0" />
                  <el-option label="已完成" :value="1" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ $index }">
                <el-button
                  :icon="Delete"
                  circle
                  size="small"
                  type="danger"
                  @click="deleteRow(1, $index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 归档附件 -->
        <el-tab-pane name="archive" label="归档附件">
          <div class="tab-toolbar">
            <!-- 隐藏的文件输入框 -->
            <input
              ref="fileInputRef1"
              type="file"
              data-type="1"
              :accept="'.pdf'"
              style="display: none"
              @change="handleFileUpload"
            />
            <el-button
              size="small"
              type="primary"
              @click="$refs.fileInputRef1?.click()"
              class="pl-8px m-b-8px"
              >新增</el-button
            >
          </div>
          <el-table :data="archiveList" border>
            <el-table-column label="文件名">
              <template #default="{ row }">
                {{ row.data.attachmentName }}
              </template>
            </el-table-column>
            <el-table-column label="文件URL">
              <template #default="{ row }">
                {{ row.data.attachmentUrl }}
              </template>
            </el-table-column>
            <el-table-column label="上传时间">
              <template #default="{ row }">
                {{ formatDate(row.data.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row, $index }">
                <el-button
                  v-if="row.data.attachmentUrl"
                  :icon="Download"
                  circle
                  size="small"
                  type="primary"
                  :underline="false"
                  @click="downloadFile(row.data.attachmentUrl, row.data.attachmentName)"
                  style="margin-right: 8px"
                />
                <el-button
                  v-if="row.data.attachmentUrl"
                  :icon="DocumentChecked"
                  circle
                  size="small"
                  type="primary"
                  :underline="false"
                  @click="previewFile(row.data.attachmentUrl, row.data.attachmentName)"
                  style="margin-right: 8px"
                />
                <el-button
                  :icon="Delete"
                  circle
                  size="small"
                  type="danger"
                  @click="deleteRow(2, $index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 收款跟踪 -->
        <el-tab-pane name="payment" label="收款跟踪">
          <div class="tab-toolbar">
            <el-button size="small" type="primary" @click="handleAddPayment" class="pl-8px m-b-8px"
              >新增</el-button
            >
          </div>
          <!-- 收款跟踪表格 -->
          <el-table :data="paymentList" border>
            <el-table-column label="收款单号">
              <template #default="{ row }">
                <el-input v-model="row.data.paymentNo" size="small" @change="savePayment(row)" />
              </template>
            </el-table-column>
            <el-table-column label="金额">
              <template #default="{ row }">
                <el-input v-model="row.data.amount" size="small" @change="savePayment(row)" />
              </template>
            </el-table-column>
            <el-table-column label="收款日期">
              <template #default="{ row }">
                <el-date-picker
                  v-model="row.data.paymentDate"
                  type="date"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  size="small"
                  style="width: 100%"
                  @change="savePayment(row)"
                />
              </template>
            </el-table-column>
            <el-table-column label="状态">
              <template #default="{ row }">
                <el-select
                  v-model="row.data.status"
                  size="small"
                  style="width: 100%"
                  @change="savePayment(row)"
                >
                  <el-option label="待收款" value="待收款" />
                  <el-option label="已收款" value="已收款" />
                  <el-option label="已取消" value="已取消" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" fixed="right">
              <template #default="{ $index }">
                <el-button
                  :icon="Delete"
                  circle
                  size="small"
                  type="danger"
                  @click="deleteRow(3, $index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 补充合同 -->
        <el-tab-pane name="supplement" label="补充合同">
          <div class="tab-toolbar">
            <!-- 隐藏的文件输入框 -->
            <input
              ref="fileInputRef"
              type="file"
              data-type="2"
              :accept="'.pdf'"
              style="display: none"
              @change="handleFileUpload"
            />
            <el-button
              size="small"
              type="primary"
              @click="$refs.fileInputRef?.click()"
              class="pl-8px m-b-8px"
              >新增</el-button
            >
          </div>
          <el-table :data="supplementList" border>
            <el-table-column label="文件名">
              <template #default="{ row }">
                {{ row.data.attachmentName }}
              </template>
            </el-table-column>
            <el-table-column label="文件URL">
              <template #default="{ row }">
                {{ row.data.attachmentUrl }}
              </template>
            </el-table-column>
            <el-table-column label="上传日期">
              <template #default="{ row }">
                {{ formatDate(row.data.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180" fixed="right">
              <template #default="{ row, $index }">
                <el-button
                  v-if="row.data.attachmentUrl"
                  :icon="Download"
                  circle
                  type="primary"
                  size="small"
                  :underline="false"
                  @click="downloadFile(row.data.attachmentUrl, row.data.attachmentName)"
                  style="margin-right: 8px"
                />
                <el-button
                  v-if="row.data.attachmentUrl"
                  type="primary"
                  size="small"
                  :icon="DocumentChecked"
                  circle
                  :underline="false"
                  @click="previewFile(row.data.attachmentUrl, row.data.attachmentName)"
                  style="margin-right: 8px"
                />
                <el-button
                  :icon="Delete"
                  circle
                  size="small"
                  type="danger"
                  @click="deleteRow(4, $index)"
                />
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </template>

    <!-- 抽屉底部按钮 -->
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </template>
  </el-drawer>
  <!-- 公司选择弹框 -->
  <CompanySelectDialog
    v-model="companySelectVisible"
    :title="companySelectTitle"
    :multiple="multipleSelect"
    :selected="preselectedCompanies"
    @confirm="handleCompanySelect"
  />
  <!--   客户选择弹框 -->
  <SelectCustomerDialog
    v-model="customerSelectVisible"
    :title="customerSelectTitle"
    :multiple="multipleSelect"
    :selected="preselectedCustomers"
    @confirm="handleCustomerSelect"
  />
  <!-- 项目选择弹框 -->
  <ProjectSelectDialog
    v-model="projectSelectVisible"
    :title="projectSelectTitle"
    :multiple="multipleSelect"
    :selected="preselectedProjects"
    @confirm="handleProjectSelect"
  />
  <!--  销售合同选择弹框-->
  <ContractSelectDialog
    v-model="contractDialogVisible"
    title="请选择销售合同"
    :multiple="false"
    :default-query-params="{ contractType: 1 }"
    @confirm="handleContractSelect"
  />
  <PdfPreview ref="pdfPreviewRef" />
</template>

<script setup lang="ts">
import { getIntDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { ref, reactive } from 'vue'
import { Delete, DocumentChecked, Download, Search } from '@element-plus/icons-vue'
import { MainApi, MainVO } from '@/api/contract/contractsale'
import { ElMessageBox } from 'element-plus'
import { useI18n } from '@/hooks/web/useI18n'
import { useMessage } from '@/hooks/web/useMessage'
import { getUserProfile } from '@/api/system/user/profile'
import * as FileApi from '@/api/infra/file'
import { generateUUID } from '@/utils'
import CompanySelectDialog from '@/views/contract/company/SelectCompany.vue'
import SelectCustomerDialog from '@/views/contract/customer/SelectCustomer.vue'
import ProjectSelectDialog from '@/views/contract/project/SelectProject.vue'
import ContractSelectDialog from '@/views/contract/contractsale/SelectContractSaleSelect.vue'
import { PdfPreview } from '@/components/Pdf'

defineOptions({ name: 'ContractSaleForm' })

const { t } = useI18n()
const message = useMessage()
//字典数据
const contractStatusOptions = getStrDictOptions(DICT_TYPE.CONTRACT_CONTRACT_STATUS)
const contractCategoryOptions = getStrDictOptions(DICT_TYPE.CONTRACT_CONTRACT_CATEGORY)
const currencyOptions = getStrDictOptions(DICT_TYPE.CONTRACT_CURRENCY)
// 主表单
const dialogVisible = ref(false)
const dialogTitle = ref('')
const formLoading = ref(false)
const formType = ref('')
const contractId = ref<number | undefined>(undefined)
const activeTab = ref('phase')

const formData = ref({
  id: undefined,
  contractNo: undefined,
  partyACompany: undefined,
  partyACompanyName: undefined,
  contractType: 1,
  partyBCompany: undefined,
  partyBCompanyName: undefined,
  currency: undefined,
  effectiveDate: undefined,
  projectCode: undefined,
  contractName: undefined,
  handlingDepartment: undefined,
  paymentTerms: undefined,
  currentContractAmount: undefined,
  expiryDate: undefined,
  projectName: undefined,
  handler: undefined,
  contractStatus: undefined,
  contractCategory: undefined,
  isMainContract: 1,
  paidAmount: undefined,
  isContractPaymentMarked: undefined,
  approvalStatus: undefined,
  sourceDocumentNo: undefined,
  totalContractAmount: undefined,
  partyBSignDate: undefined,
  mainContractNo: '',
  contractVersion: 1,
  remarks: undefined,
  terminationDate: undefined,
  terminationReason: undefined
})

const formRules = reactive({
  contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
  contractCategory: [{ required: true, message: '合同类别不能为空', trigger: 'blur' }],
  partyACompany: [{ required: true, message: '甲方公司不能为空', trigger: 'blur' }],
  partyBSignDate: [{ required: true, message: '乙方签字日期不能为空', trigger: 'blur' }],
  currency: [{ required: true, message: '币种不能为空', trigger: 'blur' }],
  effectiveDate: [{ required: true, message: '生效日期不能为空', trigger: 'blur' }],
  expiryDate: [{ required: true, message: '失效日期不能为空', trigger: 'blur' }],
  partyBCompany: [{ required: true, message: '乙方公司不能为空', trigger: 'blur' }]
})
const formRef = ref()
// 文件输入框引用
const fileInputRef = ref<HTMLInputElement | null>(null)
const fileInputRef1 = ref<HTMLInputElement | null>(null)
// 用于存储每个 row 的 file input 引用
const fileInputRefs = ref<Record<string, HTMLInputElement>>({})

// 设置 ref（动态绑定）
const setFileInput = (row: EditableRow<Phase>, el: HTMLInputElement) => {
  if (el) {
    const key = `fileInput-${row.data.id || row._uid}`
    fileInputRefs.value[key] = el
  }
}
const hanlderClick = (row: EditableRow<Phase>) => {
  const key = `fileInput-${row.data.id || row._uid}`
  fileInputRefs.value[key].click()
}
const handleAcceptanceUpload = async (row: EditableRow<Phase>) => {
  const key = `fileInput-${row.data.id || row._uid}`
  const target = fileInputRefs.value[key] as HTMLInputElement
  const file = target?.files?.[0]
  if (!file) return

  // 校验文件类型
  const allowedExtensions = ['.pdf']
  const ext = file.name.slice(file.name.lastIndexOf('.')).toLowerCase()
  if (!allowedExtensions.includes(ext)) {
    message.error('仅支持 PDF、Word、图片文件！')
    target.value = ''
    return
  }

  const formData = new FormData()
  formData.append('file', file)

  try {
    formLoading.value = true
    const res = await FileApi.updateFile(formData) // 替换为你的 API

    // 更新该行数据
    row.data.acceptanceFileName = file.name
    row.data.acceptanceFileUrl = res.data // 假设返回 { fileUrl: 'https://...' }

    message.success('附件上传成功')
  } catch (error) {
    message.error('上传失败')
  } finally {
    formLoading.value = false
    target.value = '' // 清空 input
  }
}
// 上传文件
const handleFileUpload = async (e: Event) => {
  const target = e.target as HTMLInputElement & { dataset: { type?: string } }
  const file = target?.files?.[0]
  if (!file) return

  const formData = new FormData()
  formData.append('file', file)

  try {
    formLoading.value = true
    // 调用你的上传接口（示例）
    const res = await FileApi.updateFile(formData) // 替换为你的 API
    const dataType = target.dataset.type
    if (dataType === '1') {
      // 构造新数据
      const newItem: Archive = {
        attachmentName: file.name,
        attachmentUrl: res.data, // 假设返回 { fileUrl: 'https://...' }
        createTime: new Date()
      }

      // 添加到表格（默认不编辑）
      archiveList.value.unshift({
        data: newItem
      })
    } else if (dataType === '2') {
      // 构造新数据
      const newItem: Supplement = {
        attachmentName: file.name,
        attachmentUrl: res.data, // 假设返回 { fileUrl: 'https://...' }
        createTime: new Date()
      }
      // 添加到表格（默认不编辑）
      supplementList.value.unshift({
        data: newItem
      })
    }

    message.success('文件上传成功')
  } catch (error) {
    message.error('文件上传失败')
  } finally {
    formLoading.value = false
    // 重置 input，允许重复上传同一文件
    if (target) target.value = ''
  }
}
// 可编辑行结构
interface EditableRow<T> {
  _uid?: string
  data: T
}

// 合同阶段
interface Phase {
  id?: number
  phaseName: string
  paymentRatio: number | null
  paymentTime: Date | null
  payableAmount: number | null
  actualPaymentAmount: number | null
  isCompleted: number | null
  acceptanceFileUrl: string
  acceptanceFileName: string
  isAcceptanceCompleted: number | null
}
const phaseList = ref<EditableRow<Phase>[]>([])

// 归档附件
interface Archive {
  id?: number
  attachmentName: string
  attachmentUrl: string
  createTime: Date | null
}
const archiveList = ref<EditableRow<Archive>[]>([])

// 收款跟踪
interface Payment {
  id?: number
  paymentNo: string
  amount: string
  paymentDate: number | null
  status: string
}
const paymentList = ref<EditableRow<Payment>[]>([])

// 补充合同
interface Supplement {
  id?: number
  attachmentName: string
  attachmentUrl: string
  createTime: Date | null
}
const supplementList = ref<EditableRow<Supplement>[]>([])

const deleteRow = (type: number, index: number) => {
  ElMessageBox.confirm('确定删除该行？', '警告', { type: 'warning' })
    .then(() => {
      switch (type) {
        case 1:
          phaseList.value.splice(index, 1)
          break
        case 2:
          archiveList.value.splice(index, 1)
          break
        case 3:
          paymentList.value.splice(index, 1)
          break
        case 4:
          supplementList.value.splice(index, 1)
          break
      }
      message.success('删除成功')
    })
    .catch(() => {})
}

const formatDate = (timestamp: number | null): string => {
  return timestamp ? new Date(timestamp).toLocaleDateString() : '-'
}

// 合同阶段操作
const handleAddPhase = () => {
  phaseList.value.push({
    _uid: generateUUID(),
    data: {
      phaseName: '',
      paymentRatio: null,
      paymentTime: null,
      payableAmount: null,
      actualPaymentAmount: null,
      isCompleted: null,
      acceptanceFileUrl: '',
      acceptanceFileName: '',
      isAcceptanceCompleted: null
    }
  })
}

const savePhase = (row: EditableRow<Phase>) => {
  // 这里可以添加自动保存逻辑
  console.log('阶段数据已更新:', row.data)
}
const downloadFile = (fileUrl: string, fileName: string) => {
  message.info(`正在下载：${fileName}`)
  window.open(fileUrl, '_blank')
}
// 修改预览方法
const pdfPreviewRef = ref()
const previewFile = (fileUrl: string, fileName: string) => {
  if (fileName.toLowerCase().endsWith('.pdf')) {
    pdfPreviewRef.value.open(fileName, fileUrl)
  } else {
    message.warning('仅支持预览 PDF 文件')
  }
}

// 收款跟踪操作
const handleAddPayment = () => {
  paymentList.value.push({
    _uid: generateUUID(),
    data: {
      paymentNo: '',
      amount: '',
      paymentDate: null,
      status: '待收款'
    }
  })
}
const savePayment = (row: EditableRow<Payment>) => {
  // 这里可以添加自动保存逻辑
  console.log('收款数据已更新:', row.data)
}

// 打开弹窗
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  contractId.value = id
  resetForm()

  if (id) {
    formLoading.value = true
    try {
      let value = await MainApi.getMain(id)
      formData.value = value
      //需要把阶段和文件组装成需要的格式
      const stages = value['stages']
      phaseList.value = stages.map((item) => ({
        _uid: generateUUID(), // 生成唯一ID
        data: item // 原数组项作为data
      }))
      const attachments = value['attachments']
      archiveList.value = attachments
        .filter((item) => item.attachmentType == '1')
        .map((item) => ({
          _uid: generateUUID(), // 生成唯一ID
          data: item // 原数组项作为data
        }))

      supplementList.value = attachments
        .filter((item) => item.attachmentType == '2')
        .map((item) => ({
          _uid: generateUUID(), // 生成唯一ID
          data: item // 原数组项作为data
        }))
    } finally {
      formLoading.value = false
    }
  }
  // 如果是新增，自动填充 经办人 和 经办部门
  if (!id) {
    try {
      const profile = await getUserProfile()
      formData.value.handler = profile.nickname
      formData.value.handlingDepartment = profile.dept.name || ''
    } catch (error) {
      console.warn('获取用户信息失败', error)
      // 可选择忽略，或提示
      message.warning('无法获取当前用户信息')
    }
  }
  await nextTick()
}

// 关闭前
const onClose = () => {
  dialogVisible.value = false
}

defineExpose({ open })

// 提交主表单
const emit = defineEmits(['success'])
const submitForm = async () => {
  await formRef.value.validate()
  formLoading.value = true
  try {
    const data = formData.value as unknown as MainVO
    //还需要获取下方tab页的数据,需要把这些数据的data获取出来然后放到
    const extractedDataArray = phaseList.value.map((item) => item.data)
    data['stages'] = extractedDataArray

    const files = archiveList.value.map((item) => ({
      ...item.data,
      attachmentType: 1
    }))

    const files1 = supplementList.value.map((item) => ({
      ...item.data,
      attachmentType: 2
    }))
    const combinedFiles = [...files, ...files1]
    data['attachments'] = combinedFiles
    if (formType.value === 'create') {
      await MainApi.createMain(data)
      message.success(t('common.createSuccess'))
    } else {
      await MainApi.updateMain(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 重置表单
const resetForm = () => {
  formData.value = {
    id: undefined,
    contractNo: undefined,
    partyACompany: undefined,
    contractType: 1,
    partyBCompany: undefined,
    currency: undefined,
    effectiveDate: undefined,
    projectCode: undefined,
    contractName: undefined,
    handlingDepartment: undefined,
    paymentTerms: undefined,
    currentContractAmount: undefined,
    expiryDate: undefined,
    projectName: undefined,
    handler: undefined,
    contractStatus: undefined,
    contractCategory: undefined,
    isMainContract: 1,
    paidAmount: undefined,
    isContractPaymentMarked: undefined,
    approvalStatus: undefined,
    sourceDocumentNo: undefined,
    totalContractAmount: undefined,
    partyBSignDate: undefined,
    mainContractNo: '',
    contractVersion: 1,
    remarks: undefined,
    terminationDate: undefined,
    terminationReason: undefined
  }
  phaseList.value = []
  archiveList.value = []
  paymentList.value = []
  supplementList.value = []
  formRef.value?.resetFields()
}
// 公司单选模式
const companySelectVisible = ref(false)
const companySelectTitle = ref('选择公司（单选）')
const multipleSelect = ref(false)
const selectedCompany = ref(null)
const preselectedCompanies = ref([])
const showCompanySelectDialog = () => {
  companySelectVisible.value = true
  // 设置默认选中项（可选）
  preselectedCompanies.value = selectedCompany.value ? [selectedCompany.value] : []
}

const handleCompanySelect = (company) => {
  // 公司单选模式回调
  selectedCompany.value = company
  formData.value.partyACompany = company.companyCode
  formData.value.partyACompanyName = company.companyName
}

// 供应商单选模式
const customerSelectVisible = ref(false)
const customerSelectTitle = ref('选择供应商（单选）')
const selectedCustomer = ref(null)
const preselectedCustomers = ref([])

const showCustomerSelectDialog = () => {
  customerSelectVisible.value = true
  // 设置默认选中项（可选）
  preselectedCustomers.value = selectedCustomer.value ? [selectedCustomer.value] : []
}

const handleCustomerSelect = (customer) => {
  // 供应商单选模式回调
  selectedCustomer.value = customer
  formData.value.partyBCompany = customer.customerCode
  formData.value.partyBCompanyName = customer.customerName
}

// 单选模式
const projectSelectVisible = ref(false)
const projectSelectTitle = ref('选择项目（单选）')
const selectedProject = ref(null)
const preselectedProjects = ref([])

const showProjectSelectDialog = () => {
  projectSelectVisible.value = true
  // 设置默认选中项（可选）
  preselectedProjects.value = selectedProject.value ? [selectedProject.value] : []
}

const handleProjectSelect = (project) => {
  // 单选模式回调
  selectedProject.value = project
  formData.value.projectCode = project.projectCode
  formData.value.projectName = project.projectName
}

const contractDialogVisible = ref(false)
const selectedContract = ref<MainVO | null>(null)

const showContractDialog = () => {
  contractDialogVisible.value = true
}

const handleContractSelect = (contract: MainVO) => {
  selectedContract.value = contract
  formData.value.mainContractNo = contract.contractNo
}
</script>

<style scoped>
.myheader {
  margin-bottom: 5px;
}

/* 新增样式 */
.form-section {
  margin-bottom: 20px;
}

.section-header {
  font-size: 16px;
  font-weight: bold;
  color: var(--el-text-color-primary);
}

.form-tabs {
  margin-top: 20px;
}

/* Add border and spacing to the drawer footer */
.drawer-footer {
  padding-top: 8px;
  margin-top: 12px;
  border-top: 1px solid #ebeef5;
}
</style>
<style>
.el-drawer__body {
  padding-top: 0 !important;
}

.el-drawer__header {
  margin-bottom: 0 !important;
}
</style>
