<template>
  <div class="p-2">
    <!-- 内容变更生成的新合同：与合同订单激活页提示一致，便于经办人理解后续流程 -->
    <el-alert
      v-if="isFromContentChangeContract"
      type="info"
      :closable="false"
      show-icon
      style="margin-bottom: 12px"
    >
      本合同由合同内容变更生成；在合同订单激活时将继承原合同关联项目，并对原合同作停用处理。请在本页完成合同维护与审批。
    </el-alert>
    <el-card shadow="never" style="margin-top: 0">
      <!--      <template #header>-->
      <!--        <div style="text-align: left; font-weight: bold; font-size: 24px">合同{{ form.contractId ? ' - 修改' : ' - 新增' }}</div>-->
      <!--      </template>-->
      <!-- 审批按钮组件 -->
      <approvalButton
        @submitForm="submitForm"
        @approvalVerifyOpen="approvalVerifyOpen"
        @handleApprovalRecord="handleApprovalRecord"
        :buttonLoading="buttonLoading"
        :id="form.contractId"
        :status="form.flowStatus"
        :pageType="routeParams.type"
        :mode="false"
      />
    </el-card>
    <el-card shadow="never" style="margin-top: 0">
      <el-form ref="contractInfoFormRef" :model="form" :loading="buttonLoading" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractCode">
              <el-input v-model="form.contractCode" placeholder="请输入合同编号" :disabled="isFormDisabled">
                <template #append>
                  <el-button type="primary" @click="generateContractCode" :disabled="isCodeGenerated">生成合同编号
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" placeholder="请输入合同名称" :disabled="isFormDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同大类" prop="contractCategory">
              <el-select v-model="form.contractCategory" placeholder="请选择合同大类" disabled>
                <el-option v-for="dict in contract_category" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.contractCategory !== '3'">
            <el-form-item label="关联框架合同" prop="isFrameworkContract">
              <el-radio-group v-model="form.isFrameworkContract" :disabled="isFormDisabled">
                <el-radio v-for="dict in is_framework_contract" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.contractCategory === '3'">
            <el-form-item label="框架合同有效期" prop="frameworkValidPeriod">
              <el-date-picker
                v-model="form.frameworkValidPeriod"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择框架合同有效期"
                :disabled="isFormDisabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="form.contractCategory !== '3' && form.isFrameworkContract === '1'">
            <el-form-item label="关联框架合同" prop="frameworkContractId">
              <div class="flex gap-2 items-center" style="width: 100%">
                <el-input :model-value="frameworkContractDisplay" placeholder="请选择框架合同" readonly :disabled="isFormDisabled" />
                <el-button type="primary" plain :disabled="isFormDisabled" @click="openFrameworkContractDialog">选择</el-button>
                <el-button :disabled="isFormDisabled || !form.frameworkContractId" @click="clearFrameworkContract">清空</el-button>
              </div>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="合同类型" prop="contractType">-->
          <!--              <el-select v-model="form.contractType" placeholder="请选择合同类型">-->
          <!--                <el-option v-for="dict in contract_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="业务方向" prop="businessDirection">
              <el-select v-model="form.businessDirection" placeholder="请选择业务方向" :disabled="isFormDisabled">
                <el-option v-for="dict in business_direction" :key="dict.value" :label="dict.label"
                           :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同负责人" prop="contractManagerId">
              <el-select v-model="form.contractManagerId" placeholder="请选择该合同客户经理或签订人"
                         :disabled="isFormDisabled" filterable>
                <el-option v-for="item in userInfoList" :key="item.userId" :label="item.nickName"
                           :value="item.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方公司" prop="oneCustomerId">
              <el-select v-model="form.oneCustomerId" placeholder="请选择甲方公司" :disabled="isFormDisabled"
                         filterable>
                <el-option v-for="item in customerInfoList" :key="item.customerId" :label="item.customerName"
                           :value="item.customerId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方公司" prop="twoCustomerId">
              <el-select v-model="form.twoCustomerId" placeholder="请选择乙方公司" :disabled="isFormDisabled"
                         filterable>
                <el-option v-for="item in customerInfoList" :key="item.customerId" :label="item.customerName"
                           :value="item.customerId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方授权代表" prop="oneRepresent">
              <el-input v-model="form.oneRepresent" placeholder="请输入甲方法人或其授权代表"
                        :disabled="isFormDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方授权代表" prop="twoRepresent">
              <el-input v-model="form.twoRepresent" placeholder="请输入乙方法人或其授权代表"
                        :disabled="isFormDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="甲方签字日期" prop="oneDate">
              <el-date-picker
                clearable
                v-model="form.oneDate"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择甲方签字日期"
                :disabled="isFormDisabled"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="乙方签字日期" prop="twoDate">
              <el-date-picker
                clearable
                v-model="form.twoDate"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="请选择乙方签字日期"
                :disabled="isFormDisabled"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同签订日期" prop="contractDate">
              <el-date-picker
                clearable
                v-model="form.contractDate"
                type="date"
                value-format="YYYY-MM-DD HH:mm:ss"
                :disabled="isFormDisabled"
                placeholder="请选择合同时间"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同属地" prop="contractTerritorialFlag">
              <div style="display: flex; align-items: center; width: 100%; gap: 12px">
                <el-radio-group v-model="form.contractTerritorialFlag" :disabled="isFormDisabled">
                  <el-radio v-for="dict in contract_territorial_flag" :key="dict.value" :value="dict.value">{{ dict.label }}</el-radio>
                </el-radio-group>
                <el-select
                  v-if="form.contractTerritorialFlag === '2'"
                  v-model="form.contractTerritorialCountry"
                  placeholder="请选择国家/地区"
                  :disabled="isFormDisabled"
                  filterable
                  clearable
                  style="flex: 1"
                >
                  <el-option v-for="dict in country_region" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结算币种" prop="settlementCurrency">
              <el-select v-model="form.settlementCurrency" placeholder="请选择结算币种" :disabled="isFormDisabled" clearable>
                <el-option v-for="dict in currency_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="对人民币汇率" prop="rmbExchangeRate">
              <el-input-number
                v-model="form.rmbExchangeRate"
                :min="0"
                :precision="6"
                :step="0.0001"
                :disabled="isFormDisabled"
                placeholder="请输入对人民币汇率"
                style="width: 100%"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="付款账户" prop="paymentAccountId">
              <el-select v-model="form.paymentAccountId" placeholder="请选择付款账户" :disabled="isFormDisabled"
                         clearable >
                <el-option v-for="item in paymentAccountList" :key="item.paymentAccountId"
                           :label="`${item.accountType || ''} - ${item.accountNumber || ''}`"
                           :value="item.paymentAccountId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同状态" prop="contractStatus">
              <el-radio-group v-model="form.contractStatus" disabled>
                <el-radio v-for="dict in contract_status" :key="dict.value" :value="dict.value">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <template v-if="isContractActivated">
            <el-col :span="12">
              <el-form-item label="客户合同编号">
                <el-input v-model="form.customerContractCode" disabled placeholder="-" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最终客户">
                <el-input :model-value="finalCustomerDisplay" disabled placeholder="-" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="对人民币汇率">
                <el-input-number
                  v-model="form.rmbExchangeRate"
                  :min="0"
                  :precision="4"
                  :step="0.0001"
                  controls-position="right"
                  disabled
                  placeholder="-"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="激活抄送人员">
                <el-input :model-value="activatePeopleDisplay" disabled placeholder="-" />
              </el-form-item>
            </el-col>
          </template>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="流程状态" prop="flowStatus">-->
          <!--              <el-input v-model="form.flowStatus" placeholder="请输入流程状态" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="合同模板标识" prop="contractTemplateFlag">
              <el-radio-group v-model="form.contractTemplateFlag" :disabled="isFormDisabled">
                <el-radio v-for="dict in contract_template_flag" :key="dict.value" :value="dict.value">{{ dict.label
                  }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-show="form.contractTemplateFlag !== '1'">
            <el-form-item label="合同模板" prop="templateId">
              <div class="flex gap-2 items-center" style="width: 100%">
                <el-select v-model="form.templateId" placeholder="请选择合同模板" :disabled="isFormDisabled" filterable style="flex: 1">
                  <el-option
                    v-for="item in printTemplateList"
                    :key="item.templateId"
                    :label="item.templateName + '-' + item.version"
                    :value="item.templateId"
                  />
                </el-select>
                <el-button
                  link
                  type="primary"
                  icon="Download"
                  :disabled="!form.templateId || !form.contractId"
                  @click="handleContractTemplateDownload"
                  style="font-weight: 600"
                >
                  合同查看
                </el-button>
              </div>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="合同大写金额" prop="capitalizedAmount">
              <el-input v-model="form.capitalizedAmount" placeholder="请输入合同大写金额" />
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="质保期描述" prop="warrantyPeriodDescription">
              <el-input
                v-model="form.warrantyPeriodDescription"
                placeholder="请完整输入质保期描述（如：验收合格后12个月或发货后18个月等）"
                :disabled="isFormDisabled"
              >
                <template #append>
                  <el-button type="primary" :disabled="isFormDisabled" @click="openWarrantyTemplateDialog">选择模板</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货地点" prop="deliveryLocation">
              <el-input
                v-model="form.deliveryLocation"
                placeholder="请输入交货地点（如：甲方指定仓库/项目现场等）"
                :disabled="isFormDisabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="运输方式" prop="shipMethod">
              <el-input
                v-model="form.shipMethod"
                placeholder="请输入运输方式（如：汽运、空运、海运等）"
                :disabled="isFormDisabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签订地点" prop="signingPlace">
              <el-input v-model="form.signingPlace" placeholder="请输入签订地点" :disabled="isFormDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发货/交货期" prop="deliveryStart">
              <el-input
                v-model="form.deliveryStart"
                placeholder="请完整输入发货/交货期（如：自合同签订并生效之日起30天发货等）"
                :disabled="isFormDisabled"
              >
                <template #append>
                  <el-button type="primary" :disabled="isFormDisabled" @click="openDeliveryStartTemplateDialog">选择模板</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注（该处备注信息不体现在合同模板）" :disabled="isFormDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="附件" prop="ossId">
              <div style="display: flex; width: 100%; gap: 16px; align-items: flex-start">
                <!--              <el-button type="primary" plain icon="Upload" @click="handleFile">上传合同附件</el-button>-->
                <div style="flex: 1; min-width: 0">
                  <FileUpload
                    v-model="ossIdString"
                    :limit="5"
                    :fileSize="20"
                    :fileType="['doc', 'docx', 'pdf', 'xls', 'xlsx']"
                    :disabled="isFormDisabled"
                    :isShowTip="true"
                  />
                </div>
                <div style="width: 230px; display: flex; flex-direction: column; align-items: flex-start; padding-top: 2px">
                  <el-checkbox
                    v-model="form.effectiveCustomerOrderFlag"
                    true-value="1"
                    false-value="0"
                    :disabled="isFormDisabled"
                  >
                    <span style="font-weight: 600">已生效客户订单</span>
                  </el-checkbox>
                  <div style="color: #909399; font-size: 12px; line-height: 1.4; margin-top: 4px">
                    （无需盖章或签字，即刻生效的客户订单）
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 合同付款方式维护 -->
    <el-card shadow="never" style="margin-top: 0">
      <template #header>
        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 8px 16px;
            width: 100%;
          "
        >
          <div style="text-align: left; font-weight: bold; font-size: 18px">合同付款方式</div>
          <div style="color: #e6a23c; font-size: 13px; line-height: 1.5; text-align: left; flex: 1; min-width: 220px">
            （请务必填写清楚付款节点及比例、付款账期、开票节点及比例。）
          </div>
        </div>
      </template>
      <div style="margin-bottom: 16px; display: flex; align-items: center; gap: 12px">
        <el-button type="primary" icon="Plus" v-if="!isFormDisabled" @click="handleAddPaymentMethod"
        >新增付款方式
        </el-button>
        <el-form
          ref="contractPaymentFormRef"
          :model="form"
          :rules="rules"
          label-width="120px"
          style="margin-bottom: 0; width: 360px"
        >
          <el-form-item label="付款形式" prop="paymentMethod" style="margin-bottom: 0">
            <el-select
              v-model="form.paymentMethod"
              placeholder="请选择付款形式"
              :disabled="isFormDisabled"
              clearable
              style="width: 100%"
            >
              <el-option
                v-for="item in paymentMethodOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <el-table :data="contractPaymentMethodList" v-loading="buttonLoading" border>
        <el-table-column label="序号" align="center" prop="sortOrder" width="80" />
        <!--        <el-table-column label="付款节点" align="center" prop="paymentMethod" width="140" min-width="120" />-->
        <!--        <el-table-column label="支付期限（天）" align="center" prop="paymentDeadline" width="100" />-->
        <!--        <el-table-column label="支付比例（%）" align="center" prop="paymentPercentage" width="100" />-->
        <!--        <el-table-column label="发票比例（%）" align="center" prop="invoicePercentage" width="100" />-->
        <el-table-column label="付款条款" align="center" prop="paymentDescription" min-width="120" />
        <el-table-column label="操作" align="center" fixed="right" width="150" v-if="!isFormDisabled">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleEditPaymentMethod(scope.row, scope.$index)">编辑</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDeletePaymentMethod(scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 合同物料区域 -->
    <el-card shadow="never" style="margin-top: 0">
      <template #header>
        <div
          style="
            display: flex;
            align-items: center;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 8px 16px;
            width: 100%;
          "
        >
          <div style="text-align: left; font-weight: bold; font-size: 18px">合同物料</div>
          <div style="display: flex; align-items: center; gap: 8px; flex-wrap: wrap; margin-left: auto">
            <span style="font-size: 14px; font-weight: 600; color: #606266">合同总价</span>
            <el-input
              v-model="form.totalPrice"
              placeholder="根据合同物料自动计算"
              disabled
              style="width: 200px"
            >
              <template #append>元</template>
            </el-input>
          </div>
        </div>
      </template>

      <!-- 合同物料表格 -->
      <div style="margin-bottom: 16px">
        <el-button type="primary" icon="Plus" v-if="!isFormDisabled" @click="handleAddMaterial"
        >新增合同物料
        </el-button>
        <el-button type="success" icon="Plus" v-if="!isFormDisabled" @click="handleAddMaterialInfo"
                   v-hasPermi="['oa/base:materialInfo:contractAdd']"
        >添加SAP物料
        </el-button>
      </div>

      <el-table :data="contractMaterialList" v-loading="buttonLoading" border>
        <el-table-column label="物料编号" align="center" prop="materialCode" width="120" />
        <el-table-column label="物料名称" align="center" prop="materialName" width="120" />
        <el-table-column label="销售物料名称" align="center" prop="saleMaterialName" width="120" />
        <el-table-column label="产品名称(合同显示)" align="center" prop="productName" min-width="160" />
        <el-table-column label="规格描述" align="center" prop="specificationDescription" min-width="120" />
        <el-table-column label="数量" align="center" prop="amount" width="80">
          <template #default="scope">
            {{ scope.row.amount ? Number(scope.row.amount).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="单位" align="center" prop="unitName" width="60" />
        <el-table-column label="未税单价" align="center" prop="beforePrice" width="100">
          <template #default="scope">
            {{ scope.row.beforePrice ? Number(scope.row.beforePrice).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="税率(%)" align="center" prop="taxRate" width="80">
          <template #default="scope">
            {{ scope.row.taxRate ? Number(scope.row.taxRate).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="含税单价" align="center" prop="includingPrice" width="100">
          <template #default="scope">
            {{ scope.row.includingPrice ? Number(scope.row.includingPrice).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="小计" align="center" prop="subtotal" width="80">
          <template #default="scope">
            {{ scope.row.subtotal ? Number(scope.row.subtotal).toFixed(2) : '0.00' }}
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center" prop="remark" min-width="100" />
        <el-table-column label="操作" align="center" fixed="right" width="150" v-if="!isFormDisabled">
          <template #default="scope">
            <el-button link type="primary" icon="Edit" @click="handleEditMaterial(scope.row, scope.$index)">编辑</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDeleteMaterial(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 合同物料备注 -->
      <el-form-item label="合同物料备注" prop="materialRemark" style="margin-bottom: 16px">
        <el-input v-model="form.materialRemark" type="textarea" :rows="3" placeholder="请输入合同物料备注（如税率、是否包含安装调试等需要特殊注意的内容）"
                  :disabled="isFormDisabled" />
      </el-form-item>

    </el-card>

    <!-- 合同物料编辑对话框 -->
    <el-dialog :title="materialDialog.title" v-model="materialDialog.visible" width="800px" append-to-body>
      <el-form ref="materialFormRef" :model="materialForm" :rules="materialRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标准物料标识" prop="materialFlag">
              <el-radio-group v-model="materialForm.materialFlag">
                <el-radio v-for="dict in material_flag" :key="dict.value" :value="dict.value">{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName" v-if="materialForm.materialFlag === '1'">
              <el-input v-model="materialForm.materialName" placeholder="请点击右侧图标检索物料">
                <template #suffix>
                  <el-icon style="cursor: pointer" @click="openSaleMaterialSelect">
                    <Search />
                  </el-icon>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料编号" prop="materialCode" v-if="materialForm.materialFlag === '1'">
              <el-input v-model="materialForm.materialCode" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerName" v-if="materialForm.materialFlag === '1'">
              <el-input v-model="materialForm.customerName" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="materialForm.productName" placeholder="请输入产品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格描述" prop="specificationDescription">
              <el-input v-model="materialForm.specificationDescription" placeholder="请输入规格描述" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="数量" prop="amount">
              <el-input-number
                v-model="materialForm.amount"
                placeholder="请输入数量"
                style="width: 100%"
                @change="calculateSubtotal"
                :precision="2"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料单位" prop="unitId">
              <el-select v-model="materialForm.unitId" placeholder="请选择物料单位">
                <el-option v-for="item in unitInfoList" :key="item.unitId" :label="item.unitName"
                           :value="item.unitId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="税率(%)" prop="taxRate">
              <el-select
                v-model="materialForm.taxRate"
                placeholder="请选择或输入税率"
                style="width: 100%"
                @change="calculateBeforePrice"
                filterable
                allow-create
                default-first-option
              >
                <el-option label="0" :value="0"></el-option>
                <el-option label="6" :value="6"></el-option>
                <el-option label="9" :value="9"></el-option>
                <el-option label="13" :value="13"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="未税单价" prop="beforePrice">
              <el-input-number
                v-model="materialForm.beforePrice"
                placeholder="自动计算"
                style="width: 100%"
                :precision="2"
                :controls="false"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="含税单价" prop="includingPrice">
              <el-input-number
                v-model="materialForm.includingPrice"
                placeholder="请输入含税单价"
                style="width: 100%"
                :precision="2"
                @change="calculateBeforePrice"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="小计" prop="subtotal">
              <el-input-number
                v-model="materialForm.subtotal"
                placeholder="自动计算"
                style="width: 100%"
                readonly
                :precision="2"
                :controls="false"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="materialForm.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMaterialForm">确 定</el-button>
          <el-button @click="cancelMaterial">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 合同付款方式编辑对话框 -->
    <el-dialog :title="paymentMethodDialog.title" v-model="paymentMethodDialog.visible" width="500px" append-to-body>
      <el-form ref="paymentMethodFormRef" :model="paymentMethodForm" :rules="paymentMethodRules" label-width="120px">
        <el-form-item label="序号" prop="sortOrder">
          <el-input-number v-model="paymentMethodForm.sortOrder" placeholder="根据顺序自动生成" style="width: 100%"
                           :min="1" readonly :controls="false" />
        </el-form-item>
        <el-form-item label="付款节点" prop="paymentStageId">
          <el-select
            v-model="paymentMethodForm.paymentStageId"
            placeholder="请选择付款节点"
            style="width: 100%"
            filterable
            @change="onPaymentStageChange"
          >
            <el-option
              v-for="item in paymentStageList"
              :key="item.paymentStageId"
              :label="item.paymentMethod"
              :value="item.paymentStageId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="支付期限（天）" prop="paymentDeadline">
          <el-input-number v-model="paymentMethodForm.paymentDeadline" placeholder="请输入支付期限（天）"
                           style="width: 100%" :min="0" @change="refreshPaymentDescription" />
        </el-form-item>
        <el-form-item label="支付比例（%）" prop="paymentPercentage">
          <el-input-number v-model="paymentMethodForm.paymentPercentage" placeholder="请输入支付比例（如：30）"
                           style="width: 100%" :min="0" :max="100" @change="refreshPaymentDescription" />
        </el-form-item>
        <el-form-item label="发票比例（%）" prop="invoicePercentage">
          <el-input-number v-model="paymentMethodForm.invoicePercentage" placeholder="请输入发票比例（如：30）"
                           style="width: 100%" :min="0" :max="100" @change="refreshPaymentDescription" />
        </el-form-item>
        <el-form-item label="付款条款" prop="paymentDescription">
          <el-input
            v-model="paymentMethodForm.paymentDescription"
            type="textarea"
            :rows="5"
            placeholder="选择付款节点后自动带出条款模板，可修改"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitPaymentMethodForm">确 定</el-button>
          <el-button @click="cancelPaymentMethod">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 销售物料选择 -->
    <SaleMaterialSelect ref="saleMaterialSelectRef" :multiple="false"
                        @confirm-call-back="saleMaterialSelectCallBack"></SaleMaterialSelect>

    <FrameworkContractSelectDialog
      v-model:visible="frameworkContractDialogVisible"
      :current-contract-id="form.contractId"
      @confirm="onFrameworkContractConfirm"
    />

    <!-- 添加SAP物料对话框 -->
    <el-dialog title="添加SAP物料" v-model="materialInfoDialog.visible" width="800px" append-to-body>
      <el-form ref="materialInfoFormRef" :model="materialInfoForm" :rules="materialInfoRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="SAP物料名称" prop="materialName">
              <el-input v-model="materialInfoForm.materialName" placeholder="请输入SAP物料名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料品牌" prop="materialBrand">
              <el-input v-model="materialInfoForm.materialBrand" placeholder="请输入物料品牌" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料型号" prop="materialModel">
              <el-input v-model="materialInfoForm.materialModel" placeholder="请输入物料型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料单位" prop="unitId">
              <el-select v-model="materialInfoForm.unitId" placeholder="请选择物料单位" style="width: 100%">
                <el-option v-for="item in unitInfoList" :key="item.unitId" :label="item.unitName"
                           :value="item.unitId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料参数" prop="materialParameter">
              <el-input v-model="materialInfoForm.materialParameter" placeholder="请输入物料参数" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="materialInfoForm.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMaterialInfoForm" :loading="materialInfoLoading">确 定</el-button>
          <el-button @click="cancelMaterialInfo">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加或修改OSS对象存储对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" append-to-body>
      <el-form ref="ossFormRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件名">
          <fileUpload v-model="ossFileModel" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitOss">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 发货/交货期模板选择对话框 -->
    <el-dialog title="选择发货/交货期模板" v-model="deliveryStartTemplateDialog.visible" width="720px" append-to-body>
      <el-table
        :data="deliveryStartTemplates"
        border
        highlight-current-row
        max-height="360px"
        @row-click="selectDeliveryStartTemplate"
      >
        <el-table-column type="index" width="55" label="序号" align="center" />
        <el-table-column prop="content" label="模板内容" min-width="520" show-overflow-tooltip />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deliveryStartTemplateDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 质保期描述模板选择对话框 -->
    <el-dialog title="选择质保期描述模板" v-model="warrantyTemplateDialog.visible" width="720px" append-to-body>
      <el-table
        :data="warrantyPeriodDescriptionTemplates"
        border
        highlight-current-row
        max-height="360px"
        @row-click="selectWarrantyTemplate"
      >
        <el-table-column type="index" width="55" label="序号" align="center" />
        <el-table-column prop="content" label="模板内容" min-width="520" show-overflow-tooltip />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="warrantyTemplateDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 提交审批组件 -->
    <submitVerify ref="submitVerifyRef" :task-variables="taskVariables" @submit-callback="submitCallback" />
    <!-- 审批记录 -->
    <approvalRecord ref="approvalRecordRef" />
  </div>
</template>

<script setup name="ContractInfoEdit" lang="ts">
import {
  addContractInfo,
  contractSubmitAndFlowStart,
  getContractInfo,
  updateContractInfo
} from '@/api/oa/erp/contractInfo';
import { ContractInfoForm } from '@/api/oa/erp/contractInfo/types';
import { ContractMaterialVO, ContractMaterialForm } from '@/api/oa/erp/contractMaterial/types';
import { ContractPaymentMethodForm } from '@/api/oa/erp/contractPaymentMethod/types';
import { getBaseUnitInfoList } from '@/api/oa/base/unitInfo';
import { getRuleGenerateCode } from '@/api/system/codeRule';
import { startWorkFlow } from '@/api/workflow/task';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import SaleMaterialSelect from '@/components/SaleMaterialSelect/index.vue';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import ApprovalButton from '@/components/Process/approvalButton.vue';
import FrameworkContractSelectDialog from '@/views/oa/components/FrameworkContractSelectDialog.vue';
import { ref } from 'vue';
import { allListDept, listDept } from '@/api/system/dept';
import { getCrmCustomerInfoList } from '@/api/oa/crm/customerInfo';
import { getBasePrintTemplateList } from '@/api/oa/base/printTemplate';
import { getUserList } from '@/api/system/user';
import { CodeRuleEnum, FlowCodeEnum } from '@/enums/OAEnum';
import { getInfo } from '@/api/login';
import FileUpload from '@/components/FileUpload/index.vue';
import { contractAddMaterialInfo } from '@/api/oa/base/materialInfo';
import { MaterialInfoForm } from '@/api/oa/base/materialInfo/types';
import { getBasePaymentStageList } from '@/api/oa/base/paymentStage';
import type { PaymentStageVO } from '@/api/oa/base/paymentStage/types';
import { getCrmPaymentAccountList } from '@/api/oa/crm/paymentAccount';
import { listContractOrder } from '@/api/oa/erp/contractOrder';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();
const routeParams = ref<Record<string, any>>({ ...(route.query as Record<string, any>) });

const {
  contract_category,
  business_direction,
  contract_flag,
  contract_type,
  account_type,
  contract_status,
  material_flag,
  contract_template_flag,
  is_framework_contract,
  contract_territorial_flag,
  country_region,
  currency_type
} = toRefs<any>(
  proxy?.useDict(
    'contract_category',
    'business_direction',
    'contract_flag',
    'contract_type',
    'account_type',
    'contract_status',
    'material_flag',
    'contract_template_flag',
    'is_framework_contract',
    'contract_territorial_flag',
    'country_region',
    'currency_type'
  )
);

/** 付款方式下拉选项（存储中文） */
const paymentMethodOptions = [
  '电汇',
  '银行承兑（6个月内）',
  '电汇/银行承兑（6个月内）',
  '商业承兑'
];

const buttonLoading = ref(false);
const contractInfoFormRef = ref<ElFormInstance>();
const contractPaymentFormRef = ref<ElFormInstance>();

// 审批相关组件引用
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();

// 流程相关数据
const submitFormData = ref<StartProcessBo>({
  businessId: '',
  flowCode: '',
  variables: {},
  bizExt: {}
});

// 任务变量
const taskVariables = ref<Record<string, any>>({});
const flowInstanceBizExtBo = ref<Record<string, any>>({});

const type = ref(0);
const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

// OSS 上传内部 v-model 中转，避免直接绑定到 form 的未知属性
const ossFileModel = ref<string | string[] | undefined>(undefined);

// 合同编号生成状态
const isCodeGenerated = ref(false);

// 合同物料相关
const materialFormRef = ref<ElFormInstance>();

// 合同物料列表计算属性
const contractMaterialList = computed(() => {
  return (form.value as any).contractMaterialList || [];
});

// 合同付款方式列表计算属性
const contractPaymentMethodList = computed(() => {
  return (form.value as any).contractPaymentMethodList || [];
});

/** 查询打印模板下拉框结构 */
const printTemplateList = ref([]);
const getPrintTemplateListSelect = async () => {
  const res = await getBasePrintTemplateList({ templateType: '1' });
  printTemplateList.value = res.data;
};

/** 合同模板下载/查看 */
const handleContractTemplateDownload = () => {
  if (!form.value.templateId) return;
  router.push({
    path: '/contract/contractView',
    query: { templateId: form.value.templateId, contractId: form.value.contractId }
  });
};

/** 查询单位信息下拉框结构 */
const unitInfoList = ref([]);
const getUnitInfoListSelect = async () => {
  const res = await getBaseUnitInfoList(null);
  unitInfoList.value = res.data;
};

/** 查询部门信息下拉框结构 */
const deptInfoList = ref([]);
const getDeptInfoListSelect = async () => {
  const params = { deptCategory: '03' } as any;
  const res = await allListDept(params);
  deptInfoList.value = res.data;
};

/** 查询客户信息下拉框结构 */
const customerInfoList = ref([]);
const getCustomerInfoListSelect = async () => {
  const res = await getCrmCustomerInfoList(null);
  customerInfoList.value = res.data;
};

/** 查询用户信息下拉框结构 */
const userInfoList = ref([]);
const getUserInfoListSelect = async () => {
  const params = { } as any;
  const res = await getUserList(params);
  userInfoList.value = res.data;
};

/** 合同激活抄送人员 ID 列表（来自合同订单项目） */
const activatePeopleIds = ref<string[]>([]);

/** 合同是否已激活 */
const isContractActivated = computed(() => String(form.value.contractStatus) === '5');

/** 最终客户展示名称 */
const finalCustomerDisplay = computed(() => {
  const name = (form.value as any).finalCustomerName;
  if (name) return name;
  const id = (form.value as any).finalCustomerId;
  if (!id) return '';
  const customer = customerInfoList.value.find((c: any) => String(c.customerId) === String(id));
  return customer?.customerName || String(id);
});

/** 合同激活抄送人员展示名称 */
const activatePeopleDisplay = computed(() => {
  if (!activatePeopleIds.value.length) return '';
  return activatePeopleIds.value
    .map((id) => {
      const user = userInfoList.value.find((u: any) => String(u.userId) === String(id));
      return user?.nickName || id;
    })
    .join(',');
});

/** 加载合同激活抄送人员 */
const loadActivatePeople = async (contractId: string | number) => {
  try {
    const orderRes = await listContractOrder({ contractId, pageNum: 1, pageSize: 10 } as any);
    const orders = (orderRes as any).rows || [];
    const peopleId = orders[0]?.peopleId;
    if (peopleId) {
      activatePeopleIds.value = String(peopleId)
        .split(',')
        .map((id) => id.trim())
        .filter(Boolean);
    } else {
      activatePeopleIds.value = [];
    }
  } catch {
    activatePeopleIds.value = [];
  }
};

/** 付款节点下拉列表（回款阶段） */
const paymentStageList = ref<PaymentStageVO[]>([]);
const getPaymentStageListSelect = async () => {
  const params = { } as any;
  const res = await getBasePaymentStageList(params);
  paymentStageList.value = res.data || [];
};

/** 付款账户下拉列表 */
const paymentAccountList = ref<any[]>([]);
const getPaymentAccountListSelect = async () => {
  const res = await getCrmPaymentAccountList({});
  paymentAccountList.value = res.data || [];
};

const frameworkContractDialogVisible = ref(false);

// 合同物料对话框
const materialDialog = reactive({
  visible: false,
  title: ''
});
const editingMaterialIndex = ref<number | null>(null);

// 合同物料表单数据
const initMaterialFormData: ContractMaterialForm = {
  contractMaterialId: undefined,
  materialFlag: '2',
  contractId: undefined,
  productName: undefined,
  specificationDescription: undefined,
  materialId: undefined,
  relationMaterialId: undefined,
  saleMaterialName: undefined,
  amount: undefined,
  unitId: undefined,
  beforePrice: undefined,
  taxRate: undefined,
  includingPrice: undefined,
  subtotal: undefined,
  remark: undefined,
  activeFlag: '1'
};

const materialForm = ref<ContractMaterialForm>({ ...initMaterialFormData });

// 合同物料表单验证规则
const materialRules = {
  productName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
  amount: [{ required: true, message: '数量不能为空', trigger: 'blur' }],
  taxRate: [{ required: true, message: '税率不能为空', trigger: 'blur' }]
};

/** 发货/交货期预设模板 */
const deliveryStartTemplates = [
  { content: '自合同签订并生效之日起XX天发货' },
  { content: '自合同签订并生效之日起30天发货' },
  { content: '自合同签订并生效之日起60天发货' }
];

const deliveryStartTemplateDialog = reactive({
  visible: false
});

/** 打开发货/交货期模板选择弹窗 */
const openDeliveryStartTemplateDialog = () => {
  deliveryStartTemplateDialog.visible = true;
};

/** 选择发货/交货期模板 */
const selectDeliveryStartTemplate = (row: { content: string }) => {
  form.value.deliveryStart = row.content;
  deliveryStartTemplateDialog.visible = false;
  contractInfoFormRef.value?.validateField('deliveryStart');
};

/** 质保期描述预设模板 */
const warrantyPeriodDescriptionTemplates = [
  { content: '设备自XX之日起提供XX月的质保期服务' },
  { content: '设备自到货之日起提供12个月的质保期服务' },
  { content: '设备自验收合格之日起提供12个月的质保期服务' },
  { content: '设备自发货之日起提供18个月的质保期服务' },
];

const warrantyTemplateDialog = reactive({
  visible: false
});

/** 打开质保期描述模板选择弹窗 */
const openWarrantyTemplateDialog = () => {
  warrantyTemplateDialog.visible = true;
};

/** 选择质保期描述模板 */
const selectWarrantyTemplate = (row: { content: string }) => {
  form.value.warrantyPeriodDescription = row.content;
  warrantyTemplateDialog.visible = false;
  contractInfoFormRef.value?.validateField('warrantyPeriodDescription');
};

// 合同付款方式对话框
const paymentMethodDialog = reactive({
  visible: false,
  title: ''
});
const editingPaymentMethodIndex = ref<number | null>(null);

// 合同付款方式表单数据
const initPaymentMethodFormData: ContractPaymentMethodForm = {
  paymentMethodId: undefined,
  contractId: undefined,
  sortOrder: undefined,
  paymentStageId: undefined,
  paymentDeadline: undefined,
  paymentPercentage: undefined,
  invoicePercentage: 0,
  paymentAmount: undefined,
  paymentDescription: undefined,
  remark: undefined,
  activeFlag: '1'
};

const paymentMethodForm = ref<ContractPaymentMethodForm>({ ...initPaymentMethodFormData });

const paymentMethodFormRef = ref<ElFormInstance>();

// 合同付款方式表单验证规则
const paymentMethodRules = {
  paymentStageId: [{ required: true, message: '请选择付款节点', trigger: 'change' }],
  paymentDeadline: [{ required: true, message: '支付期限（天）不能为空', trigger: 'blur' }],
  paymentPercentage: [{ required: true, message: '支付比例不能为空', trigger: 'blur' }],
  invoicePercentage: [{ required: true, message: '发票比例不能为空', trigger: 'blur' }]
};

/** 付款条款模板占位符映射：模板中的占位符 -> 数据字段名 */
const PAYMENT_TEMPLATE_PLACEHOLDERS: Record<string, string> = {
  '{序号}': 'sortOrder',
  '{支付期限}': 'paymentDeadline',
  '{支付比例}': 'paymentPercentage',
  '{发票比例}': 'invoicePercentage'
};

/**
 * 通用方法：将付款条款模板中的占位符替换为实际数据
 * @param template 模板字符串，可含 {序号}、{支付期限}、{支付比例}、{发票比例}
 * @param data 数据对象，需含 sortOrder、paymentDeadline、paymentPercentage、invoicePercentage
 * @returns 替换后的字符串
 */
const replacePaymentTemplate = (template: string | undefined, data: Record<string, any>): string => {
  if (template == null || template === '') return '';
  let result = template;
  for (const [placeholder, fieldKey] of Object.entries(PAYMENT_TEMPLATE_PLACEHOLDERS)) {
    const value = data[fieldKey];
    result = result.replaceAll(placeholder, value !== undefined && value !== null ? String(value) : '');
  }
  return result;
};

/**
 * 当发票比例为 0 时，删除付款条款中从「且」到「后」之间的内容（含「且」「后」）
 * @param text 付款条款文本
 * @param invoicePercentage 发票比例
 * @returns 处理后的文本
 */
const removeSegmentWhenInvoiceZero = (text: string, invoicePercentage: any): string => {
  if (text == null || text === '') return text;
  const isZero = invoicePercentage === 0 || invoicePercentage === '0' || Number(invoicePercentage) === 0;
  if (!isZero) return text;
  const startChar = '且';
  const endChar = '后';
  const idxStart = text.indexOf(startChar);
  if (idxStart === -1) return text;
  const idxEnd = text.indexOf(endChar, idxStart);
  if (idxEnd === -1) return text;
  return text.slice(0, idxStart) + text.slice(idxEnd + endChar.length);
};

/**
 * 替换占位符并视发票比例删除「且…后」段落
 */
const applyPaymentDescription = (template: string | undefined, data: Record<string, any>): string => {
  const replaced = replacePaymentTemplate(template, data);
  return removeSegmentWhenInvoiceZero(replaced, data.invoicePercentage);
};

/** 当前付款方式弹窗使用的条款模板原文（用于字段变更时重新替换） */
const paymentMethodTemplateRaw = ref<string | null>(null);

/** 根据当前表单数据刷新付款条款（占位符替换 + 发票为0时删「且…后」） */
const refreshPaymentDescription = () => {
  if (paymentMethodTemplateRaw.value) {
    paymentMethodForm.value.paymentDescription = applyPaymentDescription(
      paymentMethodTemplateRaw.value,
      paymentMethodForm.value as Record<string, any>
    );
  }
};

/** 选择付款节点后带出该节点的付款条款模板并做字段匹配 */
const onPaymentStageChange = (paymentStageId: string | number | undefined) => {
  if (paymentStageId == null) return;
  const stage = paymentStageList.value.find((s) => s.paymentStageId === paymentStageId || String(s.paymentStageId) === String(paymentStageId));
  if (stage?.paymentTemplate) {
    paymentMethodTemplateRaw.value = stage.paymentTemplate;
    paymentMethodForm.value.paymentDescription = applyPaymentDescription(
      stage.paymentTemplate,
      paymentMethodForm.value as Record<string, any>
    );
  }
};

type ContractInfoFormEx = ContractInfoForm & { file?: any };

const initFormData: ContractInfoFormEx = {
  contractId: undefined,
  contractFlag: '1',
  contractCode: undefined,
  contractName: undefined,
  contractCategory: '1',
  contractType: undefined,
  businessDirection: undefined,
  contractDeptId: undefined,
  contractDate: undefined,
  contractTerritorialFlag: '1',
  contractTerritorialCountry: undefined,
  settlementCurrency: 'CNY',
  rmbExchangeRate: 1,
  effectiveCustomerOrderFlag: '0',
  totalPrice: 0,
  oneCustomerId: undefined,
  oneRepresent: undefined,
  oneDate: undefined,
  twoCustomerId: undefined,
  twoRepresent: undefined,
  twoDate: undefined,
  contractStatus: '1',
  flowStatus: undefined,
  templateId: undefined,
  ossId: undefined,
  paymentAccountId: undefined,
  paymentMethod: undefined,
  signatureAppendix: undefined,
  taxRate: undefined,
  remark: undefined,
  contractManagerId: undefined,
  capitalizedAmount: undefined,
  contractTemplateFlag: '2',
  isFrameworkContract: '0',
  frameworkContractId: undefined,
  frameworkContractCode: undefined,
  frameworkContractName: undefined,
  frameworkValidPeriod: undefined,
  flowCode: undefined,
  bizExt: undefined,
  variables: undefined,
  activeFlag: '1',
  contractMaterialList: [],
  contractPaymentMethodList: [],
  file: undefined,
  signingPlace: undefined,
  materialRemark: undefined,
  warrantyPeriodDescription: undefined,
  deliveryLocation: undefined,
  shipMethod: undefined,
  deliveryStart: undefined,
  originalContractId: undefined
} as any;

const data = reactive<{ form: ContractInfoFormEx; rules: any }>({
  form: { ...initFormData },
  rules: {
    contractCode: [{ required: true, message: '合同编号不能为空', trigger: 'blur' }],
    contractName: [{ required: true, message: '合同名称不能为空', trigger: 'blur' }],
    businessDirection: [{ required: true, message: '业务方向不能为空', trigger: 'blur' }],
    contractManagerId: [{ required: true, message: '合同负责人不能为空', trigger: 'blur' }],
    oneCustomerId: [{ required: true, message: '请选择甲方公司', trigger: 'change' }],
    twoCustomerId: [{ required: true, message: '请选择乙方公司', trigger: 'change' }],
    contractTerritorialFlag: [{ required: true, message: '合同属地标识不能为空', trigger: 'change' }],
    contractTerritorialCountry: [
      {
        validator: (_rule: any, _value: any, callback: (err?: Error) => void) => {
          if (form.value.contractTerritorialFlag === '2' && !form.value.contractTerritorialCountry) {
            callback(new Error('合同属地标识为“其他”时，国家/地区不能为空'));
            return;
          }
          callback();
        },
        trigger: 'change'
      }
    ],
    settlementCurrency: [{ required: true, message: '结算币种不能为空', trigger: 'change' }],
    rmbExchangeRate: [{ required: true, message: '对人民币汇率不能为空', trigger: 'blur' }],
    ossId: [
      {
        validator: (_rule: any, _value: any, callback: (err?: Error) => void) => {
          if (form.value.effectiveCustomerOrderFlag === '1' && !form.value.ossId) {
            callback(new Error('已生效客户订单必须上传附件'));
            return;
          }
          callback();
        },
        trigger: 'change'
      }
    ],
    contractTemplateFlag: [{ required: true, message: '合同模板标识不能为空', trigger: 'blur' }],
    templateId: [
      {
        validator: (_rule: any, _value: any, callback: (err?: Error) => void) => {
          if (form.value.contractTemplateFlag === '2' && !form.value.templateId) {
            callback(new Error('合同模板不能为空'));
            return;
          }
          callback();
        },
        trigger: 'change'
      }
    ],
    isFrameworkContract: [{ required: true, message: '请选择关联框架合同', trigger: 'change' }],
    frameworkValidPeriod: [
      {
        validator: (_rule: any, _value: any, callback: (err?: Error) => void) => {
          if (form.value.isFrameworkContract === '1' && !form.value.frameworkValidPeriod) {
            callback(new Error('请填写框架合同有效期'));
            return;
          }
          callback();
        },
        trigger: 'change'
      }
    ],
    paymentAccountId: [{ required: true, message: '请选择付款账户', trigger: 'blur' }],
    warrantyPeriodDescription: [{ required: true, message: '质保期描述不能为空', trigger: 'blur' }],
    deliveryLocation: [{ required: true, message: '交货地点不能为空', trigger: 'blur' }],
    shipMethod: [{ required: true, message: '运输方式不能为空', trigger: 'blur' }],
    deliveryStart: [{ required: true, message: '发货/交货期不能为空', trigger: 'blur' }],
    signingPlace: [{ required: true, message: '签订地点不能为空', trigger: 'blur' }],
    paymentMethod: [{ required: true, message: '请选择付款形式', trigger: 'change' }]
  }
});

// 判断表单是否禁用（查看或审批模式；reapprove 为审批通过未激活后修改重提，可编辑）
const isFormDisabled = computed(() => {
  return routeParams.value.type === 'view' || routeParams.value.type === 'approval';
});

// 附件ID字符串转换（用于FileUpload组件）
const ossIdString = computed({
  get() {
    const v = form.value.ossId as any;
    return v === undefined || v === null ? '' : String(v);
  },
  set(val: string) {
    form.value.ossId = val || (undefined as any);
  }
});

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

const frameworkContractDisplay = computed(() => {
  const code = form.value.frameworkContractCode || '';
  const name = form.value.frameworkContractName || '';
  return `${code} ${name}`.trim();
});

/** 是否为由「合同内容变更」生成的新合同（后端 originalContractId 非空） */
const isFromContentChangeContract = computed(() => {
  const id = (form.value as any).originalContractId;
  return id != null && id !== '';
});

// 监听contractFlag变化
watch(
  () => form.value.contractFlag,
  (newVal) => {
    if (newVal === '2') {
      // 当选择"无合同"时，清空合同编号并重置生成状态
      form.value.contractCode = undefined;
      isCodeGenerated.value = false;
    }
  }
);

watch(
  () => form.value.contractCategory,
  (newVal) => {
    if (newVal === '3') {
      form.value.isFrameworkContract = '0';
      form.value.frameworkContractId = undefined;
      form.value.frameworkContractCode = undefined;
      form.value.frameworkContractName = undefined;
    } else {
      form.value.frameworkValidPeriod = undefined;
    }
  }
);

watch(
  () => form.value.contractTerritorialFlag,
  (newVal) => {
    // 合同属地标识为“其他”时，新增物料默认税率为0
    initMaterialFormData.taxRate = newVal === '2' ? 0 : 13;
    if (newVal === '2') {
      materialForm.value.taxRate = 0;
    } else {
      form.value.contractTerritorialCountry = undefined;
    }
  },
  { immediate: true }
);

watch(
  () => form.value.contractTemplateFlag,
  (newVal) => {
    if (newVal === '1') {
      form.value.templateId = undefined;
    }
    nextTick(() => contractInfoFormRef.value?.validateField('templateId'));
  }
);

watch(
  () => form.value.settlementCurrency,
  (newVal) => {
    if (newVal === 'CNY') {
      form.value.rmbExchangeRate = 1 as any;
    }
  },
  { immediate: true }
);

// 生成合同编号
const generateContractCode = async () => {
  if (isCodeGenerated.value) return; // 如果已经生成过，直接返回
  try {
    const params = { codeRuleCode: CodeRuleEnum.CONTRACT } as any;
    const res = await getRuleGenerateCode(params);
    form.value.contractCode = res.msg;
    isCodeGenerated.value = true; // 标记为已生成
    proxy?.$modal.msgSuccess('合同编号生成成功');
  } catch (error) {
    console.error('生成合同编号失败:', error);
    proxy?.$modal.msgError('生成合同编号失败');
  }
};

const saleMaterialSelectRef = ref<InstanceType<typeof SaleMaterialSelect>>();

// 物料信息对话框
const materialInfoDialog = reactive({
  visible: false,
  title: '添加SAP物料'
});

// 物料信息表单数据
const materialInfoForm = ref<MaterialInfoForm>({
  materialName: undefined,
  materialBrand: undefined,
  materialModel: undefined,
  unitId: undefined,
  materialParameter: undefined,
  stockingPeriod: undefined,
  remark: undefined,
  addMethod: '2', // 2表示从合同页面添加
  activeFlag: '1'
});

// 物料信息表单验证规则
const materialInfoRules = {
  materialName: [{ required: true, message: 'SAP物料名称不能为空', trigger: 'blur' }]
};

const materialInfoFormRef = ref<ElFormInstance>();
const materialInfoLoading = ref(false);

//打开销售物料选择
const openSaleMaterialSelect = () => {
  saleMaterialSelectRef.value.open();
};

//确认选择申请人
const saleMaterialSelectCallBack = (data: any) => {
  const materialList = data;
  if (materialList.length > 0) {
    materialForm.value.materialId = materialList[0].materialId;
    materialForm.value.materialCode = materialList[0].materialCode;
    materialForm.value.materialName = materialList[0].materialName;
    materialForm.value.productName = materialList[0].saleMaterialName;
    materialForm.value.saleMaterialName = materialList[0].saleMaterialName;
    materialForm.value.relationMaterialId = materialList[0].relationMaterialId;
    materialForm.value.customerName = materialList[0].customerName;
  }
};

/** 取消按钮 */
function cancel() {
  dialog.visible = false;
}

/** 文件按钮操作 */
const handleFile = () => {
  type.value = 0;
  dialog.visible = true;
  dialog.title = '上传合同附件';
  // 打开时回显已有附件
  ossFileModel.value = form.value.ossId as any;
};

const validateFormRef = (formRef: ElFormInstance | undefined) =>
  new Promise<boolean>((resolve) => {
    if (!formRef) {
      resolve(true);
      return;
    }
    formRef.validate((valid: boolean) => resolve(valid));
  });

/** 提交按钮 */
const submitForm = async (status: string, mode: boolean) => {
  try {
    const [mainValid, paymentValid] = await Promise.all([
      validateFormRef(contractInfoFormRef.value),
      validateFormRef(contractPaymentFormRef.value)
    ]);
    if (!mainValid || !paymentValid) {
      return;
    }
    const paymentList = (form.value as any).contractPaymentMethodList;
    if (!Array.isArray(paymentList) || paymentList.length === 0) {
      proxy?.$modal.msgWarning('请维护合同付款方式');
      return;
    }
    const materialList = (form.value as any).contractMaterialList;
    if (!Array.isArray(materialList) || materialList.length === 0) {
      proxy?.$modal.msgWarning('请维护合同物料');
      return;
    }
    buttonLoading.value = true;
    // 设置后端发起和不等于草稿状态 直接走流程发起
    if (status != 'draft') {
      // 走流程所需的 flowCode/variables/bizExt/状态字段，由后端 contractSubmitAndFlowStart 统一补齐并落库
      const res = await contractSubmitAndFlowStart(form.value).finally(() => (buttonLoading.value = false));
      form.value = res.data;
      proxy?.$modal.msgSuccess('操作成功');
      proxy?.$tab.closePage();
      router.go(-1);
    } else {
      if (status === 'draft') {
        form.value.contractStatus = '1';
        form.value.flowStatus = 'draft';
      }
      if (form.value.contractId) {
        await updateContractInfo(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addContractInfo(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('暂存成功');
      proxy?.$tab.closePage();
      router.go(-1);
    }
  } catch (e) {
    console.error(e);
  } finally {
    buttonLoading.value = false;
  }
};

// 提交申请
const handleStartWorkFlow = async (data: ContractInfoForm) => {
  try {
    submitFormData.value.flowCode = FlowCodeEnum.CONTRACT_CODE;
    submitFormData.value.businessId = data.contractId;

    // 流程变量
    taskVariables.value = {
      contractId: data.contractId,
      contractName: data.contractName,
      totalPrice: data.totalPrice,
      businessDirection: data.businessDirection,
      contractDeptId: data.contractDeptId,
      contractCode: data.contractCode
    };

    // 流程实例业务扩展字段
    flowInstanceBizExtBo.value = {
      businessTitle: '合同审批',
      businessCode: data.contractCode
    };

    submitFormData.value.variables = taskVariables.value;
    submitFormData.value.bizExt = flowInstanceBizExtBo.value;

    const resp = await startWorkFlow(submitFormData.value);

    if (submitVerifyRef.value) {
      buttonLoading.value = false;
      await submitVerifyRef.value.openDialog(resp.data.taskId);
    }
  } finally {
    buttonLoading.value = false;
    router.go(-1);
  }
};

// 确认上传，仅关闭弹窗并依赖 v-model 同步到 ossId
const submitOss = () => {
  // 将上传组件返回的 ossId 串写回表单
  form.value.ossId = ossFileModel.value as any;
  dialog.visible = false;
  proxy?.$modal.msgSuccess('附件已更新');
};

// 新增物料（新增合同时也可添加，不依赖contractId）
const handleAddMaterial = () => {
  resetMaterialForm();
  editingMaterialIndex.value = null;
  materialForm.value.contractId = form.value.contractId;
  materialDialog.visible = true;
  materialDialog.title = '新增合同物料';
};

// 编辑物料
const handleEditMaterial = (row: ContractMaterialVO, rowIndex: number) => {
  resetMaterialForm();
  editingMaterialIndex.value = rowIndex;
  materialForm.value = { ...row };
  materialDialog.visible = true;
  materialDialog.title = '编辑合同物料';
};

// 删除物料
const handleDeleteMaterial = async (row: ContractMaterialVO) => {
  await proxy?.$modal.confirm('是否确认删除该合同物料？');
  try {
    // 确保contractMaterialList存在
    if (!(form.value as any).contractMaterialList) {
      (form.value as any).contractMaterialList = [];
    }

    // 从本地数据中删除
    const index = (form.value as any).contractMaterialList.findIndex((item: any) => item.contractMaterialId === row.contractMaterialId);
    if (index !== -1) {
      (form.value as any).contractMaterialList.splice(index, 1);
    }

    // 更新合同总价
    calculateTotalPrice();

    proxy?.$modal.msgSuccess('删除成功');
  } catch (error) {
    console.error('删除合同物料失败:', error);
  }
};

// 重置物料表单
const resetMaterialForm = () => {
  materialForm.value = { ...initMaterialFormData };
  materialFormRef.value?.resetFields();
  // 合同属地标识=2 物料税率默认0
  materialForm.value.taxRate = form.value.contractTerritorialFlag === '2' ? 0 : 13;
};

// 取消物料编辑
const cancelMaterial = () => {
  resetMaterialForm();
  editingMaterialIndex.value = null;
  materialDialog.visible = false;
};

// 新增付款方式（序号 = 当前条数 + 1）
const handleAddPaymentMethod = () => {
  resetPaymentMethodForm();
  editingPaymentMethodIndex.value = null;
  paymentMethodForm.value.contractId = form.value.contractId as any;
  const list = (form.value as any).contractPaymentMethodList || [];
  paymentMethodForm.value.sortOrder = list.length + 1;
  paymentMethodDialog.visible = true;
  paymentMethodDialog.title = '新增付款方式';
};

// 编辑付款方式
const handleEditPaymentMethod = (row: any, rowIndex: number) => {
  resetPaymentMethodForm();
  editingPaymentMethodIndex.value = rowIndex;
  paymentMethodForm.value = { ...row };
  // 根据当前行的付款节点恢复条款模板，使编辑时修改支付期限等字段能联动刷新付款条款
  const stage = paymentStageList.value.find(
    (s) => s.paymentStageId === row.paymentStageId || String(s.paymentStageId) === String(row.paymentStageId)
  );
  if (stage?.paymentTemplate) {
    paymentMethodTemplateRaw.value = stage.paymentTemplate;
  }
  paymentMethodDialog.visible = true;
  paymentMethodDialog.title = '编辑付款方式';
};

// 删除付款方式
const handleDeletePaymentMethod = async (rowIndex: number) => {
  await proxy?.$modal.confirm('是否确认删除该付款方式？');
  try {
    if (!(form.value as any).contractPaymentMethodList) {
      (form.value as any).contractPaymentMethodList = [];
    }

    const list = (form.value as any).contractPaymentMethodList;
    if (rowIndex >= 0 && rowIndex < list.length) {
      list.splice(rowIndex, 1);
      list.forEach((item: any, i: number) => {
        item.sortOrder = i + 1;
      });
    }

    proxy?.$modal.msgSuccess('删除成功');
  } catch (error) {
    console.error('删除付款方式失败:', error);
  }
};

// 重置付款方式表单
const resetPaymentMethodForm = () => {
  paymentMethodForm.value = { ...initPaymentMethodFormData };
  paymentMethodTemplateRaw.value = null;
  paymentMethodFormRef.value?.resetFields();
};

// 取消付款方式编辑
const cancelPaymentMethod = () => {
  resetPaymentMethodForm();
  editingPaymentMethodIndex.value = null;
  paymentMethodDialog.visible = false;
};

// 提交付款方式表单
const submitPaymentMethodForm = () => {
  paymentMethodFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (!(form.value as any).contractPaymentMethodList) {
        (form.value as any).contractPaymentMethodList = [];
      }
      const list = (form.value as any).contractPaymentMethodList;
      const data = { ...paymentMethodForm.value };
      // 付款条款占位符替换为当前字段值后再保存
      data.paymentDescription = applyPaymentDescription(data.paymentDescription || '', data as Record<string, any>);
      const editIndex = editingPaymentMethodIndex.value;
      if (editIndex !== null && editIndex >= 0 && editIndex < list.length) {
        list[editIndex] = data;
      } else if (data.paymentMethodId) {
        const index = list.findIndex((item: any) => item.paymentMethodId === data.paymentMethodId);
        if (index !== -1) {
          list[index] = data;
        }
      } else {
        // 新增
        list.push({ ...data, paymentMethodId: undefined });
      }
      editingPaymentMethodIndex.value = null;
      // 按顺序自动赋值序号，并重新替换付款条款中的 {序号}
      list.forEach((item: any, index: number) => {
        item.sortOrder = index + 1;
        item.paymentDescription = applyPaymentDescription(item.paymentDescription || '', item);
      });
      proxy?.$modal.msgSuccess('操作成功');
      paymentMethodDialog.visible = false;
    }
  });
};

// 计算未税单价（由含税与税率推未税）
const calculateBeforePrice = () => {
  const tax = Number(materialForm.value.taxRate);
  const including = Number(materialForm.value.includingPrice);
  if (!isNaN(tax) && !isNaN(including)) {
    const divisor = 1 + tax / 100;
    if (divisor > 0) {
      materialForm.value.beforePrice = Number((including / divisor).toFixed(2));
    }
  }
  // 未税变更后联动小计
  calculateSubtotal();
};

// 计算小计（数量 × 含税单价）
const calculateSubtotal = () => {
  const amount = Number(materialForm.value.amount);
  const including = Number(materialForm.value.includingPrice);
  if (!isNaN(amount) && !isNaN(including)) {
    materialForm.value.subtotal = Number((amount * including).toFixed(2));
  }
  // 计算小计后更新合同总价
  calculateTotalPrice();
};

// 计算合同总价（所有物料小计相加）
const calculateTotalPrice = () => {
  const materialList = (form.value as any).contractMaterialList || [];
  const total = materialList.reduce((sum: number, material: any) => {
    const subtotal = Number(material.subtotal) || 0;
    return sum + subtotal;
  }, 0);
  form.value.totalPrice = Number(total.toFixed(2));
};

// 提交物料表单 - 直接保存到本地数组
const submitMaterialForm = () => {
  materialFormRef.value?.validate((valid: boolean) => {
    if (valid) {
      // 确保contractMaterialList存在
      if (!(form.value as any).contractMaterialList) {
        (form.value as any).contractMaterialList = [];
      }

      const unitInfo = unitInfoList.value.find((item: any) => item.unitId === materialForm.value.unitId);
      const unitName = unitInfo ? unitInfo.unitName : '';
      const materialData = {
        ...materialForm.value,
        unitName: unitName
      };

      const editIndex = editingMaterialIndex.value;
      if (editIndex !== null && editIndex >= 0 && editIndex < (form.value as any).contractMaterialList.length) {
        // 优先按行索引回写，兼容框架合同带出但无主键ID的物料
        (form.value as any).contractMaterialList[editIndex] = materialData;
      } else if (materialForm.value.contractMaterialId) {
        // 编辑模式：更新现有物料
        const index = (form.value as any).contractMaterialList.findIndex(
          (item: any) => item.contractMaterialId === materialForm.value.contractMaterialId
        );
        if (index !== -1) {
          (form.value as any).contractMaterialList[index] = materialData;
        }
      } else {
        // 新增模式：添加新物料
        const newMaterial = {
          ...materialData,
          contractMaterialId: Date.now() // 临时ID
        };
        (form.value as any).contractMaterialList.push(newMaterial);
      }

      // 更新合同总价
      calculateTotalPrice();

      proxy?.$modal.msgSuccess('操作成功');
      editingMaterialIndex.value = null;
      materialDialog.visible = false;
    }
  });
};

//初始化调用
const loadSelectOptions = () => {
  getUnitInfoListSelect();
  getDeptInfoListSelect();
  getCustomerInfoListSelect();
  getPrintTemplateListSelect();
  getPaymentAccountListSelect();
  getUserInfoListSelect();
  getPaymentStageListSelect();
};

const openFrameworkContractDialog = () => {
  frameworkContractDialogVisible.value = true;
};

const onFrameworkContractConfirm = async (selected: any) => {
  if (!selected?.contractId) return;

  const res = await getContractInfo(selected.contractId);
  const frameworkDetail = (res?.data || {}) as any;
  const currentContractId =  form.value.contractId;

  const { contractMaterialList, contractPaymentMethodList, ...mainData } = frameworkDetail;
  const excludeMainKeys = new Set(['contractId', 'contractCode',  'contractStatus', 'flowStatus', 'contractName', 'contractCategory', 'isFrameworkContract']);
  Object.entries(mainData).forEach(([key, value]) => {
    if (excludeMainKeys.has(key)) return;
    (form.value as any)[key] = value;
  });

  // 子表赋值时排除各表主键，避免带入历史记录主键造成更新冲突
  (form.value as any).contractMaterialList = Array.isArray(contractMaterialList)
    ? contractMaterialList.map((item: any) => {
        const cloned = { ...item };
        delete cloned.contractMaterialId;
        cloned.contractId = currentContractId;
        return cloned;
      })
    : [];

  (form.value as any).contractPaymentMethodList = Array.isArray(contractPaymentMethodList)
    ? contractPaymentMethodList.map((item: any) => {
        const cloned = { ...item };
        delete cloned.paymentMethodId;
        cloned.contractId = currentContractId;
        return cloned;
      })
    : [];

  // 显式记录本次关联的框架合同
  form.value.frameworkContractId = selected.contractId;
  form.value.frameworkContractCode = selected.contractCode;
  form.value.frameworkContractName = selected.contractName;

  frameworkContractDialogVisible.value = false;
  proxy?.$modal.msgSuccess('框架合同信息已带出');
};

const clearFrameworkContract = () => {
  form.value.frameworkContractId = undefined;
  form.value.frameworkContractCode = undefined;
  form.value.frameworkContractName = undefined;
};

onMounted(async () => {
  nextTick(async () => {
    // 获取路由参数
    routeParams.value = route.query;
    loadSelectOptions();
    const id = routeParams.value.id as string | number;
    if (
      id &&
      (routeParams.value.type === 'update' ||
        routeParams.value.type === 'reapprove' ||
        routeParams.value.type === 'view' ||
        routeParams.value.type === 'approval')
    ) {
      proxy?.$modal.loading('正在加载数据，请稍后...');
      const res = await getContractInfo(id);
      Object.assign(form.value, res.data);
      if (isContractActivated.value) {
        await loadActivatePeople(id);
      }

      proxy?.$modal.closeLoading();

      // 编辑模式：如果已有合同编号，禁用生成按钮
      if (form.value.contractCode) {
        isCodeGenerated.value = true;
      } else if (form.value.contractFlag === '1') {
        // 如果有合同但没有编号，允许生成
        isCodeGenerated.value = false;
      }
    } else {
      try {
        // 新增模式：获取登录用户部门ID并自动赋值
        // const userInfoRes = await getInfo();
        // if (userInfoRes.data?.user?.deptId && !form.value.contractDeptId) {
        //   form.value.contractDeptId = userInfoRes.data.user.deptId;
        // }
        form.value.contractCategory = routeParams.value.contractCategory as string;
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }

      // 新增模式：如果已有合同编号，禁用生成按钮
      if (form.value.contractCode) {
        isCodeGenerated.value = true;
      } else if (form.value.contractFlag === '1') {
        // 如果有合同但没有编号，允许生成
        isCodeGenerated.value = false;
      }
    }
  });
});

// 审批记录
const handleApprovalRecord = () => {
  approvalRecordRef.value.init(form.value.contractId);
};

// 提交回调
const submitCallback = async () => {
  await proxy.$tab.closePage(route);
  router.go(-1);
};

// 审批
const approvalVerifyOpen = async () => {
  await submitVerifyRef.value.openDialog(routeParams.value.taskId);
};

// 监听上传组件返回的文件（ossId 串）并同步到表单字段
// 同步表单初值到上传模型
watch(
  () => form.value.ossId,
  (val) => {
    if (!dialog.visible) {
      ossFileModel.value = val as any;
    }
  }
);

// 打开添加SAP物料对话框
const handleAddMaterialInfo = () => {
  materialInfoForm.value = {
    materialName: undefined,
    materialBrand: undefined,
    materialModel: undefined,
    unitId: undefined,
    materialParameter: undefined,
    stockingPeriod: undefined,
    remark: undefined,
    addMethod: '2',
    activeFlag: '1'
  };
  materialInfoFormRef.value?.resetFields();
  materialInfoDialog.visible = true;
};

// 取消添加SAP物料
const cancelMaterialInfo = () => {
  materialInfoForm.value = {
    materialName: undefined,
    materialBrand: undefined,
    materialModel: undefined,
    unitId: undefined,
    materialParameter: undefined,
    stockingPeriod: undefined,
    remark: undefined,
    addMethod: '2',
    activeFlag: '1'
  };
  materialInfoFormRef.value?.resetFields();
  materialInfoDialog.visible = false;
};

// 提交物料信息表单
const submitMaterialInfoForm = async () => {
  materialInfoFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      try {
        materialInfoLoading.value = true;
        const res = await contractAddMaterialInfo(materialInfoForm.value);
        // const newMaterial = res.data;

        // 添加成功后，自动填充到合同物料表格
        // if (!(form.value as any).contractMaterialList) {
        //   (form.value as any).contractMaterialList = [];
        // }

        // 创建新的合同物料项
        // const newContractMaterial = {
        //   contractMaterialId: Date.now(), // 临时ID
        //   contractId: form.value.contractId,
        //   materialFlag: '1', // 标准物料标识
        //   materialId: newMaterial.materialId,
        //   materialCode: newMaterial.materialCode || '',
        //   materialName: newMaterial.materialName,
        //   productName: newMaterial.materialName, // 使用物料名称作为产品名称
        //   specificationDescription: '',
        //   saleMaterialName: newMaterial.materialName,
        //   amount: undefined,
        //   unitId: newMaterial.unitId,
        //   unitName: unitInfoList.value.find((item: any) => item.unitId === newMaterial.unitId)?.unitName || '',
        //   beforePrice: undefined,
        //   taxRate: undefined,
        //   includingPrice: undefined,
        //   subtotal: undefined,
        //   remark: '',
        //   activeFlag: '1'
        // };
        //
        // (form.value as any).contractMaterialList.push(newContractMaterial);
        //
        // proxy?.$modal.msgSuccess('物料信息添加成功，已自动填充到合同物料表格');
        materialInfoDialog.visible = false;
        cancelMaterialInfo();
      } catch (error) {
        console.error('添加SAP物料失败:', error);
        proxy?.$modal.msgError('添加SAP物料失败');
      } finally {
        materialInfoLoading.value = false;
      }
    }
  });
};

</script>
