<template>
  <div class="p-2">
    <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="80" align="center" fixed="right" v-if="!isFormDisabled">
          <template #default="scope">
            <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">
      <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="projectTypeId">
              <el-cascader
                v-model="form.projectTypeId"
                :options="projectTypeOptions"
                :props="{ value: 'projectTypeId', label: 'typeName', children: 'children', emitPath: false }"
                placeholder="请选择订单类型"
                style="width: 100%"
                :disabled="isFormDisabled"
              />
            </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="deptId">
              <el-select v-model="form.deptId" placeholder="请选择部门" :disabled="isFormDisabled">
                <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="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="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="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="projectStatus">-->
          <!--              <el-radio-group v-model="form.projectStatus" disabled>-->
          <!--                <el-radio v-for="dict in project_status" :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="ossId">
              <FileUpload
                v-model="ossIdString"
                :limit="1"
                :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-col :span="1.5" v-if="!isFormDisabled">-->
<!--            <el-button type="primary" icon="Plus" @click="handleAddPlanStage">添加阶段</el-button>-->
<!--          </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="150" align="center">-->
<!--          <template #default="scope">-->
<!--            <el-select v-model="scope.row.projectPhases" placeholder="请选择项目阶段" style="width: 100%" :disabled="isFormDisabled">-->
<!--              <el-option v-for="dict in project_phases" :key="dict.value" :label="dict.label" :value="dict.value" />-->
<!--            </el-select>-->
<!--          </template>-->
<!--        </el-table-column>-->
<!--        <el-table-column label="计划开始时间" width="160" align="center">-->
<!--          <template #default="scope">-->
<!--            <el-date-picker-->
<!--              v-model="scope.row.planStartTime"-->
<!--              type="date"-->
<!--              value-format="YYYY-MM-DD"-->
<!--              placeholder="选择日期"-->
<!--              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.planEndTime"-->
<!--              type="date"-->
<!--              value-format="YYYY-MM-DD"-->
<!--              placeholder="选择日期"-->
<!--              style="width: 100%"-->
<!--              :disabled="isFormDisabled"-->
<!--            />-->
<!--          </template>-->
<!--        </el-table-column>-->
        <el-table-column label="回款阶段" width="220" align="center">
          <template #default="scope">
            <el-select v-model="scope.row.collectionStage" placeholder="请选择回款阶段" clearable style="width: 100%" :disabled="isFormDisabled">
              <el-option v-for="stage in paymentStageList" :key="stage.paymentStageId" :label="stage.paymentMethod" :value="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="150" align="center">-->
        <!--          <template #default="scope">-->
        <!--            <el-input-number-->
        <!--              v-model="scope.row.repaymentAmount"-->
        <!--              :min="0"-->
        <!--              :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-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="新增项目" 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 project_category"
                  :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="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"
    />

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

<script setup name="ProjectInfoEdit" lang="ts">
import { getErpProjectInfoList, getProjectInfo } from '@/api/oa/erp/projectInfo';
import { saveContractOrder, updateContractOrder, submitContractOrderAndFlowStart } from '@/api/oa/erp/contractOrder';
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 { 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 } = toRefs<any>(
  proxy?.useDict('business_direction', 'project_status', 'contract_flag', 'project_category', 'spare_flag', 'contract_status', 'project_phases', 'project_source')
);

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 & { _projectForm?: any };

const projectList = ref<ProjectRow[]>([]);
const projectListLoading = ref(false);

// ----- 新增项目弹窗 -----
const addProjectDialog = reactive({ visible: false });
const addProjectFormRef = ref<FormInstance>();
const addProjectCodeGenerated = ref(false);
const addProjectSubmitLoading = ref(false);
const addProjectForm = reactive<Record<string, any>>({
  projectCode: undefined,
  projectName: undefined,
  projectCategory: 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' }],
  projectCategory: [{ required: true, message: '项目类别不能为空', trigger: 'change' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'change' }],
  managerId: [{ 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.deptId = undefined;
  addProjectForm.managerId = undefined;
  addProjectForm.chargeId = undefined;
  addProjectForm.deputyId = undefined;
  addProjectForm.peopleId = undefined;
  addProjectForm.amount = undefined;
  addProjectForm.remark = undefined;
  addProjectCodeGenerated.value = false;
};

/** 新增项目确定：校验后加入 projectList（projectSource=新增），提交时由 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);
    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,
      projectSource: PROJECT_SOURCE_NEW,
      _projectForm: { ...addProjectForm }
    };
    projectList.value.push(row);
    addProjectDialog.visible = false;
    proxy?.$modal.msgSuccess('已添加到待保存列表，请在提交时一并保存');
  });
};

const handleAddProject = () => {
  resetAddProjectForm();
  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) => ({ ...(item as any) }));
  } 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;
};

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

const paymentStageList = ref<PaymentStageVO[]>([]);
const getPaymentStageList = async () => {
  try {
    const res = await getBasePaymentStageList({ pageNum: 1, pageSize: 9999 });
    paymentStageList.value = (res.data || []).map((item: any) => ({
      ...item,
      paymentStageId: item.paymentStageId != null ? String(item.paymentStageId) : item.paymentStageId
    }));
  } 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') || [];
};

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

const initFormData: ProjectInfoFormEx = {
  projectId: undefined,
  contractFlag: '1',
  projectCode: undefined,
  projectName: undefined,
  businessDirection: undefined,
  projectCategory: '9',
  spareFlag: '1',
  projectTypeId: 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,
  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' }],
    projectTypeId: [{ required: true, message: '订单类型不能为空', trigger: 'change' }],
    deptId: [{ required: true, message: '部门不能为空', trigger: 'change' }],
    managerId: [{ required: true, message: '项目经理不能为空', trigger: 'change' }],
    peopleId:  [{ required: true, message: '抄送人员不能为空', trigger: 'change' }],
    ossId: [{ required: true, message: '请上传终版合同', trigger: 'change' }]
  }
});

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

/** 是否禁用表单（查看/审批模式） */
const isFormDisabled = computed(() => 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 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.deptId = pf.deptId;
    base.managerId = pf.managerId;
    base.chargeId = pf.chargeId;
    base.deputyId = pf.deputyId;
    base.peopleId = Array.isArray(pf.peopleId) && pf.peopleId.length > 0 ? pf.peopleId.join(',') : 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;
}

/** 提交按钮：暂存走 save/update，正式提交走 submitContractOrderAndFlowStart，关联项目一并提交 */
const submitForm = (status: string, mode: boolean) => {
  projectInfoFormRef.value?.validate(async (valid: boolean) => {
    if (!valid) 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,
          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()]);
};

/** 根据路由 contractId 加载合同信息并回填表单；有项目则加载主项目+阶段+关联项目，无则从合同带出 */
const loadContractInfo = async () => {
  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;
        }
        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.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) => {
              const stage = paymentStageList.value.find((s: PaymentStageVO) => String(s.paymentStageId) === String(pm.paymentStageId));
              return {
                planStageId: undefined,
                projectId: form.value.projectId,
                projectPlanId: undefined,
                projectPhases: '',
                planStartTime: undefined,
                planEndTime: undefined,
                collectionStage: stage.paymentStageId,
                repaymentRate: pm.paymentPercentage ?? undefined,
                repaymentAmount: undefined,
                repaymentTime: undefined,
                delayDay: undefined,
                receivableDate: undefined,
                reasonsExplanation: '',
                scheduleRemark: '',
                sortOrder: pm.sortOrder ?? index + 1,
                remark: pm.remark ?? '',
                activeFlag: '1'
              } as ErpProjectPlanStageForm;
            });
          }
        }
      }
      // 关联项目列表从 erp_project_contracts 加载（form.contractId 已在上面分支中设置）
      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.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 getProjectTypeList();
    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[]>([]);

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,
      collectionStage: item.collectionStage || '',
      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'
    }));
  } 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,
    collectionStage: '',
    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>
