<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>

    <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>

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

<script setup name="ProjectInfoEdit" lang="ts">
import { getErpProjectInfoList, getProjectInfo, listProjectInfo } from '@/api/oa/erp/projectInfo';
import { saveContractOrder, updateContractOrder, submitContractOrderAndFlowStart } from '@/api/oa/erp/contractOrder';
import { ProjectInfoForm } from '@/api/oa/erp/projectInfo/types';
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 { 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';

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 } = toRefs<any>(
  proxy?.useDict('business_direction', 'project_status', 'contract_flag', 'project_category', 'spare_flag', 'contract_status', 'project_phases')
);

const buttonLoading = ref(false);
const projectInfoFormRef = ref<ElFormInstance>();

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

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

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

// 项目编号生成状态
const isCodeGenerated = ref(false);

/** 查询部门信息下拉框结构 */
const deptInfoList = ref([]);
const getDeptInfoListSelect = async () => {
  const params = { deptCategory: '03' } as any;
  let 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[]>([]);
// 保存原始的项目类型列表（扁平结构），用于查找 parentId
const projectTypeList = ref<ProjectTypeVO[]>([]);
/** 查询项目类型列表 */
const getProjectTypeList = async () => {
  const params = { spareFlag: form.value.spareFlag } as any;
  const res = await listProjectType(params);
  // 保存原始数据用于查找
  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[];
};

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' }],
    ossId: [{ required: true, message: '请上传终版合同', trigger: 'change' }]
  }
});

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

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

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

//返回
const goBack = () => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};

/** 提交按钮 */
const submitForm = (status: string, mode: boolean) => {
  try {
    projectInfoFormRef.value?.validate(async (valid: boolean) => {
      if (valid) {
        buttonLoading.value = true;

        // 准备提交数据，将 peopleId 数组转换为字符串
        const submitData = { ...form.value };
        if (Array.isArray(submitData.peopleId)) {
          submitData.peopleId = submitData.peopleId.join(',') as any;
        }
        // 添加项目阶段计划列表
        submitData.planStageList = planStageList.value.map((item) => ({
          ...item,
          projectId: form.value.projectId
        }));

        // 设置后端发起和不等于草稿状态 直接走流程发起
        if (status != 'draft') {
          // 后端发起流程模式
          submitData.flowCode = FlowCodeEnum.CONTRACT_ORDER_KEY;

          // 根据 projectTypeId 查找对应的 parentId
          let projectTypeParentId = undefined;
          if (submitData.projectTypeId) {
            const projectType = projectTypeList.value.find((item) => item.projectTypeId === submitData.projectTypeId);
            if (projectType) {
              projectTypeParentId = projectType.parentId;
            }
          }
          // 流程变量
          submitData.variables = {
            projectId: submitData.projectId,
            projectCode: submitData.projectCode,
            projectName: submitData.projectName,
            contractManagerId: submitData.peopleId
          };
          // 流程实例业务扩展字段
          submitData.bizExt = {
            businessTitle: '合同订单激活'
          };
          submitData.projectStatus = '3';
          submitData.flowStatus = 'finish';
          const res = await submitContractOrderAndFlowStart(submitData).finally(() => (buttonLoading.value = false));
          form.value = res.data;
          buttonLoading.value = false;
          proxy?.$modal.msgSuccess('操作成功');
          proxy?.$tab.closePage();
          router.go(-1);
        } else {
          if (status === 'draft') {
            submitData.projectStatus = '1';
            submitData.flowStatus = 'draft';
          }
          if (submitData.projectId) {
            await updateContractOrder(submitData).finally(() => (buttonLoading.value = false));
          } else {
            await saveContractOrder(submitData).finally(() => (buttonLoading.value = false));
          }
          buttonLoading.value = false;
          proxy?.$modal.msgSuccess('暂存成功');
          proxy?.$tab.closePage();
          router.go(-1);
        }
      }
    });
  } finally {
    buttonLoading.value = false;
  }
};

//初始化调用
const loadSelectOptions = async () => {
  await getUserList();
  await getDeptInfoListSelect();
  await getPaymentStageList();
};

/** 查询合同信息并赋值相关字段 */
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[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) => {
            return 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;
            });
          }
        }
      }
    } 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;
    if (id && (routeParams.value.type === 'update' || routeParams.value.type === 'view' || routeParams.value.type === 'approval')) {
      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) => {
          return String(id.trim());
        }) as any;
      }
      // 加载项目阶段计划列表
      await getPlanStageList();
    } 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;
}
</style>
