<template>
  <div class="p-2">
    <!-- 内容变更生成的新合同：提示激活后将继承原合同关联项目并作废原合同 -->
    <el-alert
      v-if="isFromContentChange"
      type="info"
      :closable="false"
      show-icon
      style="margin-bottom: 12px"
    >
      本合同由合同内容变更生成，激活后将继承原合同关联项目并作废原合同；下方关联项目已预填原合同项目。
    </el-alert>
    <el-alert
      v-if="partyACustomerValidate && !partyACustomerValidate.valid"
      type="warning"
      :closable="false"
      show-icon
      style="margin-bottom: 12px"
    >
      <template #default>
        <span>
          合同甲方客户【{{ partyACustomerValidate.customerName || '—' }}】信息不完整，缺少：{{ partyACustomerMissingText }}。订单激活前请先完善客户信息。
        </span>
        <el-button v-if="!isFormDisabled" type="primary" link style="margin-left: 8px" @click="openPartyACustomerDialog">
          维护客户信息
        </el-button>
      </template>
    </el-alert>
    <el-card shadow="never" style="margin-top: 0">
      <approvalButton
        @submitForm="submitForm"
        @approvalVerifyOpen="approvalVerifyOpen"
        @handleApprovalRecord="handleApprovalRecord"
        :buttonLoading="buttonLoading"
        :id="form.projectId"
        :status="form.flowStatus"
        :pageType="routeParams.type"
        :mode="false"
      />
    </el-card>

    <!-- 关联项目（erp_project_contracts） -->
    <el-card shadow="never" style="margin-top: 0">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <span class="card-title">关联项目</span>
          </el-col>
          <el-col :span="1.5" v-if="!isFormDisabled">
            <el-button type="primary" plain icon="Plus" @click="handleAddProject" size="small">新增项目</el-button>
          </el-col>
          <el-col :span="1.5" v-if="!isFormDisabled">
            <el-button type="success" plain icon="Select" @click="handleSelectExistProject" size="small">选择已有项目</el-button>
          </el-col>
        </el-row>
      </template>

      <el-table v-loading="projectListLoading" border :data="projectList" max-height="320">
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="项目来源" align="center" prop="projectSource" min-width="100">
          <template #default="scope">
            <dict-tag :options="project_source" :value="scope.row.projectSource" />
          </template>
        </el-table-column>
        <el-table-column label="项目编号" align="center" prop="projectCode" min-width="120" />
        <el-table-column label="项目名称" align="center" prop="projectName" min-width="160" show-overflow-tooltip />
        <el-table-column label="部门" align="center" prop="deptName" min-width="140" />
        <el-table-column label="项目经理" align="center" prop="managerName" min-width="120" />
        <el-table-column label="金额" align="center" prop="amount" min-width="120" />
        <el-table-column label="操作" width="140" align="center" fixed="right" v-if="!isFormDisabled">
          <template #default="scope">
            <el-button
              v-if="scope.row.projectSource === PROJECT_SOURCE_NEW"
              type="primary"
              link
              icon="Edit"
              @click="handleEditProject(scope.row)"
            >
              编辑
            </el-button>
            <el-button type="danger" link icon="Delete" @click="handleRemoveProject(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card shadow="never" style="margin-top: 0">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <span class="card-title">合同订单信息</span>
          </el-col>
        </el-row>
      </template>
      <el-form ref="projectInfoFormRef" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="订单编号" prop="projectCode">
              <el-input v-model="form.projectCode" placeholder="自动生成订单编号" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单名称" prop="projectName">
              <el-input v-model="form.projectName" placeholder="请输入订单名称" :disabled="isFormDisabled" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="业务方向" prop="businessDirection">
              <el-select v-model="form.businessDirection" placeholder="请选择业务方向" :disabled="true">
                <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="projectCategory">-->
<!--              <el-select v-model="form.projectCategory" placeholder="请选择订单类别" disabled>-->
<!--                <el-option v-for="dict in project_category" :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="spareFlag">
              <el-radio-group v-model="form.spareFlag" disabled>
                <el-radio v-for="dict in spare_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="orderType">
              <el-select v-model="form.orderType" placeholder="请选择订单类型" style="width: 100%" :disabled="isFormDisabled" clearable>
                <el-option v-for="dict in erp_order_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="12">-->
          <!--            <el-form-item label="付款方式" prop="paymentMethod">-->
          <!--              <el-input v-model="form.paymentMethod" placeholder="请输入付款方式（如：3-3-3-1）" />-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <!-- <el-col :span="12">
            <el-form-item label="项目经理" prop="managerId">
              <el-select v-model="form.managerId" placeholder="请选择项目经理" :disabled="isFormDisabled" clearable filterable>
                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
              </el-select>
            </el-form-item>
          </el-col> -->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="部门负责人" prop="chargeId">-->
<!--              <el-select v-model="form.chargeId" placeholder="请选择部门负责人" :disabled="true">-->
<!--                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="分管副总" prop="deputyId">-->
<!--              <el-select v-model="form.deputyId" placeholder="请选择分管副总" :disabled="true">-->
<!--                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />-->
<!--              </el-select>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
          <el-col :span="12">
            <el-form-item label="合同编号" prop="contractCode">
              <el-input v-model="form.contractCode" placeholder="请输入合同编号" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同名称" prop="contractName">
              <el-input v-model="form.contractName" placeholder="请输入合同名称" :disabled="true" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户合同编号" prop="customerContractCode">
              <el-input
                v-model="form.customerContractCode"
                placeholder="请输入客户合同编号，若无填写‘/’"
                :disabled="isFormDisabled"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最终客户" prop="finalCustomerId">
              <el-select
                v-model="form.finalCustomerId"
                placeholder="请选择最终客户"
                :disabled="isFormDisabled"
                filterable
                clearable
                style="width: 100%"
              >
                <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="rmbExchangeRate">
              <el-input-number
                v-model="form.rmbExchangeRate"
                :min="0"
                :precision="4"
                :step="0.0001"
                controls-position="right"
                placeholder="请输入对人民币汇率"
                style="width: 100%"
                :disabled="isFormDisabled || form.settlementCurrency === 'CNY'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="合同总价" prop="amount">
              <el-input v-model="form.amount" placeholder="请输入合同总价" :disabled="true">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抄送人员" prop="peopleId">
              <el-select v-model="form.peopleId" placeholder="请选择抄送人员" :disabled="isFormDisabled" clearable filterable multiple>
                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="订单状态" prop="projectStatus">
              <el-input
                :value="(project_status || []).find((d: any) => d.value === form.projectStatus)?.label || ''"
                disabled
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="终版合同上传" prop="ossId">
              <FileUpload
                v-model="ossIdString"
                :limit="10"
                :fileSize="20"
                :fileType="['doc', 'docx', 'pdf', 'xls', 'xlsx']"
                :disabled="routeParams.type === 'view' || routeParams.type === 'approval'"
                :isShowTip="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" :disabled="isFormDisabled" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 项目阶段计划 -->
    <el-card shadow="never" style="margin-top: 0">
      <template #header>
        <el-row :gutter="10">
          <el-col :span="1.5">
            <span class="card-title">回款信息</span>
          </el-col>
        </el-row>
      </template>

      <el-table :data="planStageList" border stripe max-height="400">
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="回款阶段" width="220" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.paymentStageId" placeholder="请选择回款阶段" clearable style="width: 100%" :disabled="isFormDisabled">
              <el-option v-for="stage in paymentStageList" :key="stage.paymentStageId" :label="stage.stageName" :value="String(stage.paymentStageId)" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="预计回款比例(%)" width="220" align="center">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.repaymentRate"
              :min="0"
              :max="100"
              :precision="2"
              controls-position="right"
              style="width: 100%"
              :disabled="isFormDisabled"
            />
          </template>
        </el-table-column>
        <el-table-column label="预计回款金额(元)" width="220" align="center">
          <template #default="scope">
            <el-input :model-value="formatRepaymentAmount(scope.row.repaymentAmount)" disabled />
          </template>
        </el-table-column>
        <el-table-column label="预计回款日期" width="220" align="center">
          <template #default="scope">
            <el-date-picker
              v-model="scope.row.repaymentTime"
              type="date"
              value-format="YYYY-MM-DD"
              placeholder="选择日期"
              style="width: 100%"
              :disabled="isFormDisabled"
            />
          </template>
        </el-table-column>
        <!--        <el-table-column label="回款延期天数" width="130" align="center">-->
        <!--          <template #default="scope">-->
        <!--            <el-input-number v-model="scope.row.delayDay" :min="0" controls-position="right" style="width: 100%" :disabled="isFormDisabled" />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="应收款日期" width="160" align="center">-->
        <!--          <template #default="scope">-->
        <!--            <el-date-picker-->
        <!--              v-model="scope.row.receivableDate"-->
        <!--              type="date"-->
        <!--              value-format="YYYY-MM-DD"-->
        <!--              placeholder="选择日期"-->
        <!--              style="width: 100%"-->
        <!--              :disabled="isFormDisabled"-->
        <!--            />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="原因说明" min-width="200" align="center">-->
        <!--          <template #default="scope">-->
        <!--            <el-input v-model="scope.row.reasonsExplanation" placeholder="请输入原因说明" :disabled="isFormDisabled" />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="进度备注" min-width="200" align="center">-->
        <!--          <template #default="scope">-->
        <!--            <el-input v-model="scope.row.scheduleRemark" placeholder="请输入进度备注" :disabled="isFormDisabled" />-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column label="备注" min-width="150" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.remark" placeholder="请输入备注" :disabled="isFormDisabled" />
          </template>
        </el-table-column>
<!--        <el-table-column v-if="!isFormDisabled" label="操作" width="80" align="center" fixed="right">-->
<!--          <template #default="scope">-->
<!--            <el-button type="danger" link icon="Delete" @click="handleDeletePlanStage(scope.$index)">删除</el-button>-->
<!--          </template>-->
<!--        </el-table-column>-->
      </el-table>
    </el-card>

    <!-- 新增/编辑项目弹窗 -->
    <el-dialog
      :title="addProjectDialog.mode === 'edit' ? '编辑项目' : '新增项目'"
      v-model="addProjectDialog.visible"
      width="800px"
      append-to-body
      destroy-on-close
      @close="resetAddProjectForm"
    >
      <el-form ref="addProjectFormRef" :model="addProjectForm" :rules="addProjectRules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="项目编号" prop="projectCode">
              <el-input v-model="addProjectForm.projectCode" placeholder="请输入项目编号">
                <template #append>
                  <el-button type="primary" @click="generateAddProjectCode" :disabled="addProjectCodeGenerated">生成</el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目名称" prop="projectName">
              <el-input v-model="addProjectForm.projectName" placeholder="请输入项目名称" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="项目类别" prop="projectCategory">
              <el-select v-model="addProjectForm.projectCategory" placeholder="请选择项目类别" style="width: 100%">
                <el-option
                  v-for="dict in addProjectCategoryOptions"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="销售项目类型" prop="projectTypeId">
              <el-cascader
                v-model="addProjectForm.projectTypeId"
                :options="projectTypeOptions"
                :props="{ value: 'projectTypeId', label: 'typeName', children: 'children', emitPath: false }"
                placeholder="请选择销售项目类型"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门" prop="deptId">
              <el-select v-model="addProjectForm.deptId" placeholder="请选择部门" style="width: 100%">
                <el-option v-for="item in deptInfoList" :key="item.deptId" :label="item.deptName" :value="item.deptId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目经理" prop="managerId">
              <el-select v-model="addProjectForm.managerId" placeholder="请选择项目经理" style="width: 100%" clearable filterable>
                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="部门负责人" prop="chargeId">
              <el-select v-model="addProjectForm.chargeId" placeholder="请选择部门负责人" style="width: 100%" clearable filterable>
                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分管副总" prop="deputyId">
              <el-select v-model="addProjectForm.deputyId" placeholder="请选择分管副总" style="width: 100%" clearable filterable>
                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="抄送人员" prop="peopleId">
              <el-select v-model="addProjectForm.peopleId" placeholder="请选择抄送人员" style="width: 100%" clearable filterable multiple>
                <el-option v-for="user in userList" :key="user.userId" :label="user.nickName" :value="user.userId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="金额" prop="amount">
              <el-input v-model="addProjectForm.amount" placeholder="请输入金额" style="width: 100%">
                <template #append>元</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="addProjectForm.remark" type="textarea" placeholder="请输入备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="submitAddProject" :loading="addProjectSubmitLoading">确 定</el-button>
        <el-button @click="addProjectDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

    <!-- 选择已有项目（使用 ProjectSelect 组件）  projectStatus: '3'  -->
    <ProjectSelect
      ref="projectSelectRef"
      :multiple="true"
      :default-query-params="{}"
      @confirm-call-back="projectSelectCallback"
    />

    <!-- 维护甲方客户信息 -->
    <el-dialog
      v-model="partyACustomerDialog.visible"
      title="维护甲方客户信息"
      width="640px"
      append-to-body
      destroy-on-close
    >
      <el-form ref="partyACustomerFormRef" :model="partyACustomerForm" :rules="partyACustomerRules" label-width="100px">
        <el-form-item label="客户名称">
          <el-input v-model="partyACustomerForm.customerName" disabled />
        </el-form-item>
        <el-form-item label="税号" prop="taxNumber">
          <el-input v-model="partyACustomerForm.taxNumber" placeholder="请输入税号" />
        </el-form-item>
        <el-form-item label="开户银行" prop="bankAccountOpening">
          <el-input v-model="partyACustomerForm.bankAccountOpening" placeholder="请输入开户银行" />
        </el-form-item>
        <el-form-item label="银行账号" prop="bankNumber">
          <el-input v-model="partyACustomerForm.bankNumber" placeholder="请输入银行账号" />
        </el-form-item>
        <el-form-item label="开票附件" prop="ossId">
          <div>
            <FileUpload
              v-model="partyACustomerOssIdString"
              :limit="5"
              :fileType="['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'txt', 'pdf', 'zip', 'rar', 'jpg', 'jpeg', 'png']"
            />
            <div style="margin-top: 4px; color: #909399; font-size: 30px">
              请上传营业执照和开票资料！
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" :loading="partyACustomerDialog.loading" @click="submitPartyACustomerForm">保 存</el-button>
        <el-button @click="partyACustomerDialog.visible = false">取 消</el-button>
      </template>
    </el-dialog>

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

<script setup name="ProjectInfoEdit" lang="ts">
import { ref, reactive, computed, toRefs, getCurrentInstance, onMounted, nextTick, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import type { ComponentInternalInstance } from 'vue';
import { getErpProjectInfoList, getProjectInfo } from '@/api/oa/erp/projectInfo';
import { saveContractOrder, updateContractOrder, submitContractOrderAndFlowStart, validPartyACustomerForOrderActivate } from '@/api/oa/erp/contractOrder';
import type { PartyACustomerValidateVO } from '@/api/oa/erp/contractOrder/types';
import { ProjectInfoForm, ProjectInfoVO } from '@/api/oa/erp/projectInfo/types';
import { getErpProjectContractsList } from '@/api/oa/erp/projectContracts';
import { ProjectContractsVO } from '@/api/oa/erp/projectContracts/types';
import { getRuleGenerateCode } from '@/api/system/codeRule';
import { startWorkFlow } from '@/api/workflow/task';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import ApprovalButton from '@/components/Process/approvalButton.vue';
import { allListDept } from '@/api/system/dept';
import { listProjectType } from '@/api/oa/erp/projectType';
import { ProjectTypeVO } from '@/api/oa/erp/projectType/types';
import { listUser } from '@/api/system/user';
import { UserQuery } from '@/api/system/user/types';
import { CodeRuleEnum, FlowCodeEnum, ProjectCategoryEnum } from '@/enums/OAEnum';
import type { FormInstance } from 'element-plus';
import { getErpProjectPlanStageList, listErpProjectPlanStage } from '@/api/oa/erp/erpProjectPlanStage';
import { ErpProjectPlanStageForm, ErpProjectPlanStageQuery } from '@/api/oa/erp/erpProjectPlanStage/types';
import { listContractInfo, getContractInfo } from '@/api/oa/erp/contractInfo';
import { getCrmCustomerInfoList, getCustomerInfo, updateCustomerInfo } from '@/api/oa/crm/customerInfo';
import type { CustomerInfoForm } from '@/api/oa/crm/customerInfo/types';
import { getBasePaymentStageList } from '@/api/oa/base/paymentStage';
import { PaymentStageVO } from '@/api/oa/base/paymentStage/types';
import { getInfo } from '@/api/login';
import FileUpload from '@/components/FileUpload/index.vue';
import ProjectSelect from '@/components/ProjectSelect/index.vue';

// ---------------------------------------------------------------------------
// 常量：项目来源、提交状态
// ---------------------------------------------------------------------------
/** 项目来源：新增项目（本页创建） */
const PROJECT_SOURCE_NEW = '1';
/** 项目来源：选择已有项目 */
const PROJECT_SOURCE_EXIST = '0';
/** 提交状态：暂存 */
const SUBMIT_STATUS_DRAFT = 'draft';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const route = useRoute();
const router = useRouter();

// ---------------------------------------------------------------------------
// 页面状态：路由、字典、加载状态
// ---------------------------------------------------------------------------
const routeParams = ref<Record<string, any>>({});
const { business_direction, project_status, contract_flag, project_category, spare_flag, contract_status, project_phases, project_source, erp_order_type } = toRefs<any>(
  proxy?.useDict(
    'business_direction',
    'project_status',
    'contract_flag',
    'project_category',
    'spare_flag',
    'contract_status',
    'project_phases',
    'project_source',
    'erp_order_type'
  )
);
const addProjectCategoryOptions = computed(() => (project_category.value || []).filter((item: any) => Number(item.value) >= 0 && Number(item.value) <= 2));

const buttonLoading = ref(false);
const projectInfoFormRef = ref<FormInstance>();
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 isCodeGenerated = ref(false);

// ---------------------------------------------------------------------------
// 关联项目（erp_project_contracts）：列表、新增弹窗、选择已有项目弹窗
// ---------------------------------------------------------------------------
/** 关联项目行类型：projectSource 区分新增/已有；_projectForm 仅新增项目暂存时的表单快照 */
type ProjectRow = ProjectContractsVO & {
  projectTypeId?: string | number;
  _projectForm?: any;
};

const projectList = ref<ProjectRow[]>([]);
const projectListLoading = ref(false);
/** 本合同是否由内容变更生成（有原合同ID），用于展示提示并预填原合同关联项目 */
const isFromContentChange = ref(false);

// ----- 新增/编辑项目弹窗 -----
const addProjectDialog = reactive<{
  visible: boolean;
  mode: 'add' | 'edit';
  currentRow: ProjectRow | null;
}>({
  visible: false,
  mode: 'add',
  currentRow: null
});
const addProjectFormRef = ref<FormInstance>();
const addProjectCodeGenerated = ref(false);
const addProjectSubmitLoading = ref(false);
const addProjectForm = reactive<Record<string, any>>({
  projectCode: undefined,
  projectName: undefined,
  projectCategory: undefined,
  projectTypeId: undefined,
  deptId: undefined,
  managerId: undefined,
  chargeId: undefined,
  deputyId: undefined,
  peopleId: undefined,
  amount: undefined,
  remark: undefined
});
const addProjectRules = {
  projectCode: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }],
  projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
  projectTypeId: [{ required: true, message: '销售项目类型不能为空', trigger: 'change' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'change' }],
  managerId: [{ required: true, message: '项目经理不能为空', trigger: 'change' }],
  deputyId: [{ required: true, message: '分管副总不能为空', trigger: 'change' }],
  chargeId: [{ required: true, message: '部门负责人不能为空', trigger: 'change' }]
};

const generateAddProjectCode = async () => {
  if (addProjectCodeGenerated.value) return;
  try {
    const codeRuleCode = CodeRuleEnum.PROJECT;
    const res = await getRuleGenerateCode({ codeRuleCode } as any);
    addProjectForm.projectCode = res.msg;
    addProjectCodeGenerated.value = true;
    proxy?.$modal.msgSuccess('项目编号生成成功');
  } catch (e) {
    console.error(e);
    proxy?.$modal.msgError('生成项目编号失败');
  }
};

const resetAddProjectForm = () => {
  addProjectForm.projectCode = undefined;
  addProjectForm.projectName = undefined;
  addProjectForm.projectCategory = undefined;
  addProjectForm.projectTypeId = undefined;
  addProjectForm.deptId = undefined;
  addProjectForm.managerId = undefined;
  addProjectForm.chargeId = undefined;
  addProjectForm.deputyId = undefined;
  addProjectForm.peopleId = undefined;
  addProjectForm.amount = undefined;
  addProjectForm.remark = undefined;
  addProjectCodeGenerated.value = false;
};

/** 新增/编辑项目确定：校验后加入或更新 projectList，提交时由 submitForm 统一保存 */
const submitAddProject = () => {
  addProjectFormRef.value?.validate((valid: boolean) => {
    if (!valid) return;
    const dept = deptInfoList.value.find((d: any) => d.deptId === addProjectForm.deptId);
    const manager = userList.value.find((u: any) => u.userId === addProjectForm.managerId);
    if (addProjectDialog.mode === 'edit' && addProjectDialog.currentRow) {
      // 编辑已有“新增项目”行
      const row = addProjectDialog.currentRow;
      row._projectForm = { ...addProjectForm };
      row.remark = addProjectForm.remark;
      row.projectCode = addProjectForm.projectCode;
      row.projectName = addProjectForm.projectName;
      row.deptName = dept ? dept.deptName : undefined;
      row.managerName = manager ? manager.nickName : undefined;
      row.amount = addProjectForm.amount as any;
      row.projectCategory = addProjectForm.projectCategory;
      row.projectTypeId = addProjectForm.projectTypeId;
      proxy?.$modal.msgSuccess('项目修改成功');
    } else {
      // 新增项目行
      const row: ProjectRow = {
        projectContractsId: undefined as any,
        projectId: undefined as any,
        contractId: form.value.contractId as any,
        sortOrder: projectList.value.length + 1,
        remark: addProjectForm.remark,
        activeFlag: '1',
        projectCode: addProjectForm.projectCode,
        projectName: addProjectForm.projectName,
        deptName: dept ? dept.deptName : undefined,
        managerName: manager ? manager.nickName : undefined,
        amount: addProjectForm.amount as any,
        projectCategory: addProjectForm.projectCategory,
        projectTypeId: addProjectForm.projectTypeId,
        projectSource: PROJECT_SOURCE_NEW,
        _projectForm: { ...addProjectForm }
      };
      projectList.value.push(row);
      proxy?.$modal.msgSuccess('已添加到待保存列表，请在提交时一并保存');
    }
    addProjectDialog.visible = false;
  });
};

const handleAddProject = () => {
  addProjectDialog.mode = 'add';
  addProjectDialog.currentRow = null;
  resetAddProjectForm();
  // 新增项目时默认把合同总价带入金额
  addProjectForm.amount = form.value.amount;
  addProjectDialog.visible = true;
};

/** 编辑“新增项目”行：仅对 projectSource=新增 的行开放 */
const handleEditProject = (row: ProjectRow) => {
  if (row.projectSource !== PROJECT_SOURCE_NEW) {
    return;
  }
  addProjectDialog.mode = 'edit';
  addProjectDialog.currentRow = row;
  const pf = row._projectForm || {};
  addProjectForm.projectCode = pf.projectCode ?? row.projectCode;
  addProjectForm.projectName = pf.projectName ?? row.projectName;
  addProjectForm.projectCategory = pf.projectCategory ?? row.projectCategory;
  addProjectForm.projectTypeId = pf.projectTypeId ?? row.projectTypeId;
  addProjectForm.deptId = pf.deptId ?? (row as any).deptId ?? undefined;
  addProjectForm.managerId = pf.managerId ?? (row as any).managerId ?? undefined;
  addProjectForm.chargeId = pf.chargeId ?? (row as any).chargeId ?? undefined;
  addProjectForm.deputyId = pf.deputyId ?? (row as any).deputyId ?? undefined;
  const peopleIdVal = pf.peopleId ?? (row as any).peopleId;
  if (peopleIdVal) {
    addProjectForm.peopleId = Array.isArray(pf.peopleId)
      ? pf.peopleId
      : String(peopleIdVal)
          .split(',')
          .map((id: string) => id.trim())
          .filter((id: string) => id) as any;
  } else {
    addProjectForm.peopleId = undefined as any;
  }
  addProjectForm.amount = pf.amount ?? row.amount;
  addProjectForm.remark = pf.remark ?? row.remark;
  addProjectCodeGenerated.value = !!addProjectForm.projectCode;
  addProjectDialog.visible = true;
};

/** 删除关联项目：从列表中移除（未保存的仅前端移除；已保存的由提交时新列表覆盖） */
const handleRemoveProject = async (row: ProjectRow) => {
  try {
    await proxy?.$modal.confirm('是否确认删除该关联项目？');
    const index = projectList.value.indexOf(row);
    if (index > -1) {
      projectList.value.splice(index, 1);
    }
  } catch (e) {
    if (e !== 'cancel') console.error(e);
  }
};

/** 按合同加载关联项目列表，projectSource 由后端返回 */
const loadProjectContractsList = async () => {
  const contractId = form.value.contractId;
  if (!contractId) {
    projectList.value = [];
    return;
  }
  projectListLoading.value = true;
  try {
    const res = await getErpProjectContractsList({ contractId } as any);
    projectList.value = (res.data || []).map((item: ProjectContractsVO) => {
      const row = { ...(item as any) } as ProjectRow;
      if (row.projectSource === PROJECT_SOURCE_NEW) {
        const peopleIdVal = (row as any).peopleId;
        row._projectForm = {
          projectCode: row.projectCode,
          projectName: row.projectName,
          projectCategory: row.projectCategory,
          projectTypeId: row.projectTypeId,
          deptId: (row as any).deptId,
          managerId: (row as any).managerId,
          chargeId: (row as any).chargeId,
          deputyId: (row as any).deputyId,
          peopleId: Array.isArray(peopleIdVal)
            ? peopleIdVal
            : String(peopleIdVal || '')
                .split(',')
                .map((id: string) => id.trim())
                .filter((id: string) => id),
          amount: row.amount,
          remark: row.remark
        };
      }
      return row;
    });
  } catch (e) {
    console.error(e);
    projectList.value = [];
  } finally {
    projectListLoading.value = false;
  }
};

// ----- 选择已有项目（ProjectSelect 组件） -----
const projectSelectRef = ref<InstanceType<typeof ProjectSelect>>();

/** 打开选择已有项目弹窗 */
const handleSelectExistProject = () => {
  const contractId = form.value.contractId;
  if (!contractId) {
    proxy?.$modal.msgWarning('请先选择合同');
    return;
  }
  projectSelectRef.value?.open();
};

/** ProjectSelect 确定回调：将选中项加入 projectList（projectSource=已有），提交时统一保存 */
const projectSelectCallback = (selectedProjects: ProjectInfoVO[]) => {
  if (!selectedProjects || selectedProjects.length === 0) return;
  const contractId = form.value.contractId;
  if (!contractId) {
    proxy?.$modal.msgWarning('请先选择合同');
    return;
  }
  const existIds = projectList.value.map((p) => p.projectId);
  let added = 0;
  selectedProjects.forEach((p) => {
    if (existIds.includes(p.projectId)) return;
    const row: ProjectRow = {
      projectContractsId: undefined as any,
      projectId: p.projectId as any,
      contractId: contractId as any,
      sortOrder: projectList.value.length + added + 1,
      remark: '',
      activeFlag: '1',
      projectCode: p.projectCode,
      projectName: p.projectName,
      deptName: p.deptName,
      managerName: p.managerName,
      amount: p.amount as any,
      projectSource: PROJECT_SOURCE_EXIST
    };
    projectList.value.push(row);
    existIds.push(p.projectId);
    added++;
  });
  proxy?.$modal.msgSuccess(added > 0 ? '已添加到待保存列表' : '所选项目已在列表中');
};

// ---------------------------------------------------------------------------
// 下拉与字典：部门、用户、回款阶段
// ---------------------------------------------------------------------------
const deptInfoList = ref([]);
const getDeptInfoListSelect = async () => {
  const params = { deptCategory: '03' } as any;
  const res = await allListDept(params);
  deptInfoList.value = res.data;
};

// 新增/编辑项目弹窗中：选择部门后，自动回填部门负责人和分管副总
watch(
  () => addProjectForm.deptId,
  (newDeptId) => {
    if (!newDeptId) {
      addProjectForm.chargeId = undefined;
      addProjectForm.deputyId = undefined;
      return;
    }
    const deptInfo = deptInfoList.value.find((dept: any) => dept.deptId === newDeptId);
    if (deptInfo) {
      addProjectForm.chargeId = deptInfo.leader;
      addProjectForm.deputyId = deptInfo.vicePresident;
    }
  }
);

const userList = ref([]);
const getUserList = async () => {
  const params: UserQuery = { pageNum: 1, pageSize: 9999 };
  const res = await listUser(params);
  userList.value = res.rows;
};

/** 客户下拉（最终客户） */
const customerInfoList = ref<any[]>([]);
const getCustomerInfoListSelect = async () => {
  const res = await getCrmCustomerInfoList(null as any);
  customerInfoList.value = res.data || [];
};

const paymentStageList = ref<PaymentStageVO[]>([]);
const getPaymentStageList = async () => {
  try {
    const res = await getBasePaymentStageList({ pageNum: 1, pageSize: 9999 });
    paymentStageList.value = res.data || [];
  } catch (error) {
    console.error('查询回款阶段列表失败:', error);
    paymentStageList.value = [];
  }
};

const projectTypeOptions = ref<ProjectTypeVO[]>([]);
const projectTypeList = ref<ProjectTypeVO[]>([]);
const getProjectTypeList = async () => {
  const res = await listProjectType({} as any);
  projectTypeList.value = res.data || [];
  projectTypeOptions.value = proxy?.handleTree<ProjectTypeVO>(res.data || [], 'projectTypeId', 'parentId') || [];
};

/** 销售项目类型父级ID -> 项目类别 映射 */
function mapProjectCategoryByParentId(parentId: string | number | undefined): string | undefined {
  const parentIdStr = parentId === undefined || parentId === null ? '' : String(parentId);
  const categoryMap: Record<string, string> = {
    '1': ProjectCategoryEnum.SALE_IMPLEMENT,
    '8': ProjectCategoryEnum.SALE_LOGISTICS,
    '11': ProjectCategoryEnum.SALE_SPARE
  };
  return categoryMap[parentIdStr];
}

/** 根据销售项目类型自动回填项目类别（parentId: 1->实施, 8->物流, 11->备件） */
function syncProjectCategoryByProjectType(projectTypeId: string | number | undefined): void {
  if (projectTypeId === undefined || projectTypeId === null || projectTypeId === '') return;
  const type = projectTypeList.value.find((item) => String(item.projectTypeId) === String(projectTypeId));
  if (!type) return;
  const mappedCategory = mapProjectCategoryByParentId(type.parentId);
  if (mappedCategory !== undefined) {
    addProjectForm.projectCategory = mappedCategory;
  }
}

watch(
  () => addProjectForm.projectTypeId,
  (newProjectTypeId) => {
    syncProjectCategoryByProjectType(newProjectTypeId);
  }
);

// ---------------------------------------------------------------------------
// 主表单：合同订单（项目）信息、校验规则、计算属性
// ---------------------------------------------------------------------------
type ProjectInfoFormEx = ProjectInfoForm & {
  flowCode?: string;
  variables?: any;
  bizExt?: any;
  contractCode?: string;
  contractName?: string;
  customerContractCode?: string;
  finalCustomerId?: string | number;
  effectiveCustomerOrderFlag?: string;
  contractTerritorialFlag?: string;
  settlementCurrency?: string;
  rmbExchangeRate?: number;
  planStageList?: ErpProjectPlanStageForm[];
  projectContractsList?: any[];
};

const initFormData: ProjectInfoFormEx = {
  projectId: undefined,
  contractFlag: '1',
  projectCode: undefined,
  projectName: undefined,
  businessDirection: undefined,
  projectCategory: '9',
  spareFlag: '1',
  projectTypeId: undefined,
  orderType: undefined,
  paymentMethod: undefined,
  deptId: undefined,
  managerId: undefined,
  chargeId: undefined,
  deputyId: undefined,
  peopleId: undefined,
  amount: undefined,
  projectStatus: '1',
  flowStatus: undefined,
  sortOrder: 0,
  contractId: undefined,
  contractCode: undefined,
  contractName: undefined,
  customerContractCode: undefined,
  finalCustomerId: undefined,
  contractTerritorialFlag: undefined,
  settlementCurrency: undefined,
  rmbExchangeRate: undefined,
  remark: undefined,
  ossId: undefined,
  activeFlag: '1',
  flowCode: undefined,
  variables: undefined,
  bizExt: undefined
};

const data = reactive<{ form: ProjectInfoFormEx; rules: any }>({
  form: { ...initFormData },
  rules: {
    contractFlag: [{ required: true, message: '有无合同不能为空', trigger: 'change' }],
    projectName: [{ required: true, message: '订单名称不能为空', trigger: 'blur' }],
    businessDirection: [{ required: true, message: '业务方向不能为空', trigger: 'change' }],
    projectCategory: [{ required: true, message: '订单类别不能为空', trigger: 'change' }],
    orderType: [{ required: true, message: '订单类型不能为空', trigger: 'change' }],
    customerContractCode: [{ required: true, message: '客户合同编号不能为空', trigger: 'blur' }],
    rmbExchangeRate: [{ required: true, message: '对人民币汇率不能为空', trigger: 'blur' }],
    peopleId:  [{ required: true, message: '抄送人员不能为空', trigger: 'change' }],
    ossId: [{ required: true, message: '请上传终版合同', trigger: 'change' }]
  }
});

const { form, rules } = toRefs(data);
const REPAYMENT_RATE_TOTAL = 100;
const REPAYMENT_RATE_EPSILON = 0.01;

/** 是否禁用表单（查看/审批模式） */
const isFormDisabled = computed(() => routeParams.value.type === 'view' || routeParams.value.type === 'approval');

// ---------------------------------------------------------------------------
// 甲方客户信息校验与维护
// ---------------------------------------------------------------------------
const partyACustomerValidate = ref<PartyACustomerValidateVO | null>(null);
const partyACustomerFormRef = ref<FormInstance>();
const partyACustomerFullData = ref<CustomerInfoForm | null>(null);
const partyACustomerDialog = reactive({
  visible: false,
  loading: false
});
const partyACustomerForm = reactive({
  customerName: '',
  taxNumber: '',
  bankAccountOpening: '',
  bankNumber: '',
  ossId: undefined as string | number | undefined
});
const partyACustomerRules = {
  taxNumber: [{ required: true, message: '税号不能为空', trigger: 'blur' }],
  bankAccountOpening: [{ required: true, message: '开户银行不能为空', trigger: 'blur' }],
  bankNumber: [{ required: true, message: '银行账号不能为空', trigger: 'blur' }],
  ossId: [{ required: true, message: '请上传开票附件', trigger: 'change' }]
};

const partyACustomerOssIdString = computed({
  get() {
    const v = partyACustomerForm.ossId;
    return v === undefined || v === null ? '' : String(v);
  },
  set(val: string) {
    partyACustomerForm.ossId = val || undefined;
  }
});

const partyACustomerMissingText = computed(() => {
  const result = partyACustomerValidate.value;
  if (!result) return '';
  const labels: string[] = [];
  if (result.ossIdMissing) labels.push('附件');
  if (result.taxNumberMissing) labels.push('税号');
  if (result.bankAccountOpeningMissing) labels.push('开户银行');
  if (result.bankNumberMissing) labels.push('银行账号');
  return labels.join('、') || '—';
});

const checkPartyACustomerForOrderActivate = async () => {
  const contractId = form.value.contractId || routeParams.value.contractId;
  if (!contractId) {
    partyACustomerValidate.value = null;
    return;
  }
  try {
    const res = await validPartyACustomerForOrderActivate(contractId);
    partyACustomerValidate.value = res.data;
  } catch (error) {
    console.error('校验甲方客户信息失败:', error);
    partyACustomerValidate.value = null;
  }
};

const openPartyACustomerDialog = async () => {
  const customerId = partyACustomerValidate.value?.oneCustomerId;
  if (!customerId) {
    proxy?.$modal.msgWarning('未获取到甲方客户信息');
    return;
  }
  try {
    const res = await getCustomerInfo(customerId);
    partyACustomerFullData.value = { ...(res.data || {}) };
    partyACustomerForm.customerName = res.data?.customerName || '';
    partyACustomerForm.taxNumber = res.data?.taxNumber || '';
    partyACustomerForm.bankAccountOpening = res.data?.bankAccountOpening || '';
    partyACustomerForm.bankNumber = res.data?.bankNumber || '';
    partyACustomerForm.ossId = res.data?.ossId;
    partyACustomerDialog.visible = true;
  } catch (error) {
    console.error('加载客户信息失败:', error);
    proxy?.$modal.msgError('加载客户信息失败');
  }
};

const submitPartyACustomerForm = () => {
  partyACustomerFormRef.value?.validate(async (valid: boolean) => {
    if (!valid || !partyACustomerFullData.value?.customerId) return;
    partyACustomerDialog.loading = true;
    try {
      await updateCustomerInfo({
        ...partyACustomerFullData.value,
        taxNumber: partyACustomerForm.taxNumber,
        bankAccountOpening: partyACustomerForm.bankAccountOpening,
        bankNumber: partyACustomerForm.bankNumber,
        ossId: partyACustomerForm.ossId
      });
      proxy?.$modal.msgSuccess('客户信息保存成功');
      partyACustomerDialog.visible = false;
      await checkPartyACustomerForOrderActivate();
    } catch (error) {
      console.error('保存客户信息失败:', error);
    } finally {
      partyACustomerDialog.loading = false;
    }
  });
};

/** 附件 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 goBack = () => {
  proxy.$tab.closePage(route);
  router.go(-1);
};

/**
 * 将关联项目行转为提交给后端的 DTO（含 projectSource，新增项目时带 _projectForm 字段）
 */
function buildProjectContractsPayload(row: ProjectRow, index: number): Record<string, any> {
  const isNewProject = row.projectSource === PROJECT_SOURCE_NEW;
  const base: Record<string, any> = {
    projectContractsId: row.projectContractsId,
    projectId: row.projectId,
    projectCategory: row.projectCategory,
    spareFlag: row.projectCategory === ProjectCategoryEnum.SALE_SPARE ? '1' : '0',
    contractId: form.value.contractId,
    sortOrder: row.sortOrder ?? index + 1,
    remark: row.remark,
    activeFlag: row.activeFlag ?? '1',
    projectSource: isNewProject ? PROJECT_SOURCE_NEW : PROJECT_SOURCE_EXIST
  };
  if (isNewProject && row._projectForm) {
    const pf = row._projectForm;
    base.projectCode = pf.projectCode;
    base.projectName = pf.projectName;
    base.projectTypeId = pf.projectTypeId;
    base.deptId = pf.deptId;
    base.managerId = pf.managerId;
    base.chargeId = pf.chargeId;
    base.deputyId = pf.deputyId;
    base.peopleId = normalizeProjectContractsPeopleId(pf.peopleId);
    base.amount = pf.amount;
  }
  return base;
}

/** 抄送人员：数组转逗号分隔字符串（提交用），非数组原样返回 */
function normalizePeopleId(value: string | string[] | number | undefined): string | number | undefined {
  return Array.isArray(value) ? value.join(',') : value;
}

/** 关联项目抄送：后端 ErpProjectContractsBo.peopleId 为 String，禁止提交 JSON 数组（含空数组） */
function normalizeProjectContractsPeopleId(value: string | string[] | number | undefined): string | undefined {
  const raw = normalizePeopleId(value);
  if (raw === undefined || raw === null || raw === '') return undefined;
  return String(raw);
}

/** 校验回款比例之和是否为 100% */
function isRepaymentRateTotalValid(): boolean {
  const totalRate = planStageList.value.reduce((sum, item) => sum + toNumber(item.repaymentRate), 0);
  return Math.abs(totalRate - REPAYMENT_RATE_TOTAL) < REPAYMENT_RATE_EPSILON;
}

/** 提交按钮：暂存走 save/update，正式提交走 submitContractOrderAndFlowStart，关联项目一并提交 */
const submitForm = (status: string, mode: boolean) => {
  projectInfoFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) return;
    if (!isFormDisabled.value && partyACustomerValidate.value && !partyACustomerValidate.value.valid) {
      proxy?.$modal.msgWarning('请先完善合同甲方客户信息（附件、税号、开户银行、银行账号）');
      return;
    }
    if (!isRepaymentRateTotalValid()) {
      proxy?.$modal.msgWarning('回款信息预计回款比例之和必须为100%');
      return;
    }
    if (!projectList.value?.length) {
      proxy?.$modal.msgWarning('合同订单需新建项目或者关联已有项目！');
      return;
    }
    const isDraft = status === SUBMIT_STATUS_DRAFT;
    buttonLoading.value = true;
    try {
      const submitData = { ...form.value };
      submitData.peopleId = normalizePeopleId(submitData.peopleId);
      submitData.planStageList = planStageList.value.map((item) => ({ ...item, projectId: form.value.projectId }));
      submitData.projectContractsList = projectList.value.map((row, index) => buildProjectContractsPayload(row, index));

      if (isDraft) {
        submitData.projectStatus = '1';
        submitData.flowStatus = 'draft';
        if (submitData.projectId) {
          await updateContractOrder(submitData);
        } else {
          await saveContractOrder(submitData);
        }
      } else {
        // 是否有关联“选择已有项目”（仅走合同订单提交流程，不走 xzxm）
        const hasExistProject = projectList.value.some((row) => row.projectSource === PROJECT_SOURCE_EXIST);
        submitData.flowCode = FlowCodeEnum.CONTRACT_ORDER_KEY;
        submitData.variables = {
          projectId: submitData.projectId,
          projectCode: submitData.projectCode,
          projectName: submitData.projectName,
          businessDirection: submitData.businessDirection,
          contractManagerId: submitData.peopleId,
          hasExistProject
        };
        submitData.bizExt = { businessTitle: '合同订单激活' };
        // 有关联“选择已有项目”时主订单为审批中(2)、待办(waiting)，否则为可用(3)、完成(finish)
        submitData.projectStatus = hasExistProject ? '2' : '3';
        submitData.flowStatus = hasExistProject ? 'waiting' : 'finish';
        const res = await submitContractOrderAndFlowStart(submitData);
        if (res?.data) form.value = res.data;
      }
      proxy?.$modal.msgSuccess(isDraft ? '暂存成功' : '操作成功');
      proxy?.$tab.closePage();
      router.go(-1);
    } catch (e) {
      console.error(e);
    } finally {
      buttonLoading.value = false;
    }
  });
};

// ---------------------------------------------------------------------------
// 数据加载：合同信息、关联项目、项目阶段计划
// ---------------------------------------------------------------------------
const loadSelectOptions = async () => {
  await Promise.all([getUserList(), getDeptInfoListSelect(), getPaymentStageList(), getCustomerInfoListSelect(), getProjectTypeList()]);
};

/** 日期格式化为 YYYY-MM-DD */
const formatDateToYmd = (date: Date): string => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};

/** 计算预计回款日期：默认当天；若 paymentDeadline/payment_deadline 有值则当天 + 天数 */
const getDefaultRepaymentDate = (paymentMethod?: Record<string, any>): string => {
  const deadline = paymentMethod?.paymentDeadline;
  const days = toNumber(deadline);
  const target = new Date();
  if (days > 0) {
    target.setDate(target.getDate() + Math.trunc(days));
  }
  return formatDateToYmd(target);
};

/** 回填合同扩展字段：属地标识、结算币种、对人民币汇率 */
const fillContractExtraFields = (contractData: any) => {
  form.value.effectiveCustomerOrderFlag = contractData?.effectiveCustomerOrderFlag;
  form.value.contractTerritorialFlag = contractData?.contractTerritorialFlag;
  form.value.settlementCurrency = contractData?.settlementCurrency;
  form.value.rmbExchangeRate = contractData?.rmbExchangeRate;
  // 已有终版合同附件时优先回显；否则勾选“已生效客户订单”时自动带入合同附件
  if (contractData?.signatureAppendix) {
    form.value.ossId = contractData.signatureAppendix;
  } else if (contractData?.effectiveCustomerOrderFlag === '1' && contractData?.ossId) {
    form.value.ossId = contractData.ossId;
  }
};

/** 根据路由 contractId 加载合同信息并回填表单；有项目则加载主项目+阶段+关联项目，无则从合同带出 */
const loadContractInfo = async () => {
  isFromContentChange.value = false;
  const contractId = routeParams.value.contractId as string | number;
  if (contractId) {
    try {
      // 先通过 contractId 查询项目
      const projectRes = await getErpProjectInfoList({ contractId: contractId } as any);
      if (projectRes.data && projectRes.data.length > 0) {
        // 合同订单主数据：取第一个项目赋值 form
        const projectData = (projectRes.data as any[])[0];
        if (projectData.flowStatus === 'finish') {
          routeParams.value.type = 'view';
        }
        Object.assign(form.value, projectData);
        if (form.value.peopleId && typeof form.value.peopleId === 'string') {
          form.value.peopleId = (form.value.peopleId as string).split(',').map((id) => String(id.trim())) as any;
        }
        const contractRes = await getContractInfo(contractId);
        if (contractRes?.data) {
          fillContractExtraFields(contractRes.data);
        }
        await getPlanStageList();
      } else {
        // 如果没有查询到项目，则查询合同信息并赋值相关字段
        const contractRes = await getContractInfo(contractId);
        if (contractRes.data) {
          const contractData = contractRes.data;
          form.value.contractId = contractData.contractId;
          form.value.projectName = contractData.contractName;
          form.value.businessDirection = contractData.businessDirection;
          form.value.deptId = contractData.contractDeptId;
          form.value.contractCode = contractData.contractCode;
          form.value.contractName = contractData.contractName;
          form.value.customerContractCode = contractData.customerContractCode;
          form.value.finalCustomerId = contractData.finalCustomerId;
          fillContractExtraFields(contractData);
          form.value.amount = contractData.totalPrice;

          // 根据部门ID查找部门信息，获取部门负责人和分管副总
          const deptInfo = deptInfoList.value.find((dept: any) => dept.deptId === contractData.contractDeptId);
          if (deptInfo) {
            form.value.chargeId = deptInfo.leader;
            form.value.deputyId = deptInfo.vicePresident;
          }
          // 将抄送人员字符串转换为数组，用于多选下拉框显示
          if (contractData.contractManagerId) {
            form.value.peopleId = String(contractData.contractManagerId)
              .split(',')
              .map((id) => {
                return String(id.trim());
              }) as any;
          }
          // 新增时：合同付款方式赋值到回款阶段表格
          const list = (contractData as any).contractPaymentMethodList;
          if (list && Array.isArray(list) && list.length > 0) {
            planStageList.value = list.map((pm: any, index: number) => {
              return {
                planStageId: undefined,
                projectId: form.value.projectId,
                projectPlanId: undefined,
                projectPhases: '',
                planStartTime: undefined,
                planEndTime: undefined,
                paymentStageId: pm.paymentStageId != null && pm.paymentStageId !== '' ? String(pm.paymentStageId) : undefined,
                repaymentRate: pm.paymentPercentage ?? undefined,
                repaymentAmount: undefined,
                repaymentTime: getDefaultRepaymentDate(pm),
                delayDay: pm.paymentDeadline,
                receivableDate: undefined,
                reasonsExplanation: '',
                scheduleRemark: '',
                sortOrder: pm.sortOrder ?? index + 1,
                remark: pm.remark ?? '',
                activeFlag: '1'
              } as ErpProjectPlanStageForm;
            });
          }
          // 本合同由内容变更生成时：预填原合同关联项目，并展示提示
          const originalId = (contractData as any).originalContractId;
          if (originalId != null && originalId !== '') {
            isFromContentChange.value = true;
            projectListLoading.value = true;
            try {
              const projRes = await getErpProjectContractsList({ contractId: originalId } as any);
              // 原合同下的关联均为已有项目，项目来源固定为「0 选择已有项目」
              projectList.value = (projRes.data || []).map((item: any) => ({
                ...item,
                projectSource: PROJECT_SOURCE_EXIST
              }));
            } finally {
              projectListLoading.value = false;
            }
          }
        }
      }
      // 关联项目列表从 erp_project_contracts 加载（若已从原合同预填则不再覆盖）
      if (!isFromContentChange.value) {
        await loadProjectContractsList();
      }
    } catch (error) {
      console.error('查询合同信息失败:', error);
    }
  }
};

// ---------------------------------------------------------------------------
// 生命周期与审批
// ---------------------------------------------------------------------------
onMounted(async () => {
  nextTick(async () => {
    routeParams.value = route.query;
    proxy?.$modal.loading('正在加载数据，请稍后...');
    await loadSelectOptions();
    const id = routeParams.value.id as string | number;
    const isEditMode = id && (routeParams.value.type === 'update' || routeParams.value.type === 'view' || routeParams.value.type === 'approval');
    if (isEditMode) {
      const res = await getProjectInfo(id);
      Object.assign(form.value, res.data);
      if (form.value.contractId) {
        const contractRes = await getContractInfo(form.value.contractId as string | number);
        if (contractRes?.data) {
          fillContractExtraFields(contractRes.data);
        }
      }
      if (form.value.peopleId && typeof form.value.peopleId === 'string') {
        form.value.peopleId = (form.value.peopleId as string).split(',').map((id) => String(id.trim())) as any;
      }
      await getPlanStageList();
      await loadProjectContractsList();
    } else {
      planStageList.value = [];
      try {
        await loadContractInfo();
      } catch (error) {
        console.error('获取合同信息失败:', error);
      }
    }
    await checkPartyACustomerForOrderActivate();
    proxy?.$modal.closeLoading();
  });
});

const handleApprovalRecord = () => {
  approvalRecordRef.value.init(form.value.projectId);
};

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

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

// ---------------------------------------------------------------------------
// 项目阶段计划（回款阶段表格）
// ---------------------------------------------------------------------------
const planStageList = ref<ErpProjectPlanStageForm[]>([]);

/** 将任意值转为数字；非法值返回 0 */
const toNumber = (value: unknown): number => {
  const n = Number(value);
  return Number.isFinite(n) ? n : 0;
};

/** 保留两位小数并避免浮点误差 */
const calcRepaymentAmount = (totalAmount: unknown, repaymentRate: unknown): number => {
  const amount = toNumber(totalAmount);
  const rate = toNumber(repaymentRate);
  return Math.round(((amount * rate) / 100) * 100) / 100;
};

/** 表格展示格式化 */
const formatRepaymentAmount = (value: unknown): string => {
  if (value === undefined || value === null || value === '') return '';
  const n = Number(value);
  return Number.isFinite(n) ? n.toFixed(2) : '';
};

/** 根据合同总价和预计回款比例，实时刷新每行预计回款金额 */
const recalculateRepaymentAmounts = () => {
  const totalAmount = form.value.amount;
  planStageList.value.forEach((item) => {
    item.repaymentAmount = calcRepaymentAmount(totalAmount, item.repaymentRate) as any;
  });
};

watch(
  [() => form.value.amount, () => planStageList.value.map((item) => item.repaymentRate)],
  () => {
    recalculateRepaymentAmounts();
  },
  { deep: true }
);

const getPlanStageList = async () => {
  if (!form.value.projectId) {
    planStageList.value = [];
    return;
  }

  try {
    const params = { projectId: form.value.projectId };
    const res = await getErpProjectPlanStageList(params);
    planStageList.value = (res.data || []).map((item: any) => ({
      ...item,
      // 确保所有字段都有默认值
      projectPhases: item.projectPhases || '',
      planStartTime: item.planStartTime || undefined,
      planEndTime: item.planEndTime || undefined,
      paymentStageId: item.paymentStageId != null && item.paymentStageId !== '' ? String(item.paymentStageId) : undefined,
      repaymentRate: item.repaymentRate || undefined,
      repaymentAmount: item.repaymentAmount || undefined,
      repaymentTime: item.repaymentTime || undefined,
      delayDay: item.delayDay || undefined,
      receivableDate: item.receivableDate || undefined,
      reasonsExplanation: item.reasonsExplanation || '',
      scheduleRemark: item.scheduleRemark || '',
      remark: item.remark || '',
      sortOrder: item.sortOrder || planStageList.value.length + 1,
      activeFlag: item.activeFlag || '1'
    }));
    recalculateRepaymentAmounts();
  } catch (error) {
    console.error('查询项目阶段计划失败:', error);
    planStageList.value = [];
  }
};

/** 添加项目阶段计划行 */
const handleAddPlanStage = () => {
  const newStage: ErpProjectPlanStageForm = {
    planStageId: undefined,
    projectId: form.value.projectId,
    projectPlanId: undefined,
    projectPhases: '',
    planStartTime: undefined,
    planEndTime: undefined,
    paymentStageId: undefined,
    repaymentRate: undefined,
    repaymentAmount: undefined,
    repaymentTime: undefined,
    delayDay: undefined,
    receivableDate: undefined,
    reasonsExplanation: '',
    scheduleRemark: '',
    realStartTime: undefined,
    realEndTime: undefined,
    sortOrder: planStageList.value.length + 1,
    remark: '',
    activeFlag: '1'
  };
  planStageList.value.push(newStage);
};

/** 删除项目阶段计划行 */
const handleDeletePlanStage = (index: number) => {
  planStageList.value.splice(index, 1);
  // 重新排序
  planStageList.value.forEach((item, idx) => {
    item.sortOrder = idx + 1;
  });
};
</script>

<style scoped lang="scss">
.card-title {
  font-weight: bold;
  font-size: 16px;
  color: #303133;
}
.empty-tip {
  padding: 16px;
  color: #909399;
  font-size: 14px;
  text-align: center;
}
</style>
