<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="isFormDisabled">
                <template #append>
                  <el-button type="primary" @click="generateProjectCode" :disabled="isCodeGenerated || codeLockedBySubRows">生成项目编号</el-button>
                </template>
              </el-input>
            </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="projectCategory">
              <el-select v-model="form.projectCategory" placeholder="请选择项目类别" :disabled="true">
                <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" v-if="showHasSubProjectSwitch">
            <el-form-item label="含有子项目" prop="subProjectFlag">
              <el-switch
                v-model="form.subProjectFlag"
                active-value="1"
                inactive-value="0"
                :disabled="isFormDisabled"
                @change="onHasSubProjectChange"
              />
            </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="请选择项目经理" clearable filterable :disabled="isFormDisabled">
                <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="请选择部门负责人" clearable filterable :disabled="isFormDisabled">
                <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="form.peopleId" placeholder="请选择抄送人员" clearable filterable multiple :disabled="isFormDisabled">
                <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="24">
            <el-form-item label="附件" prop="ossId">
              <FileUpload
                v-model="ossIdString"
                :limit="5"
                :fileSize="20"
                :fileType="['doc', 'docx', 'pdf', 'xls', 'xlsx']"
                :disabled="isFormDisabled"
                :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 v-if="showSubProjectSection" shadow="never" style="margin-top: 0">
      <template #header>
        <el-row :gutter="10" align="middle">
          <el-col :span="12">
            <span class="sub-project-card-title">子项目</span>
            <span class="sub-project-card-tip">（子项目编号自动生成，子项目名称必填）</span>
          </el-col>
          <el-col :span="12" style="text-align: right">
            <el-button
              type="primary"
              plain
              icon="Plus"
              size="small"
              :disabled="isFormDisabled || !form.projectCode"
              @click="addSubProjectRow"
            >
              添加子项目
            </el-button>
          </el-col>
        </el-row>
      </template>
      <el-table border :data="subProjectRows" empty-text="请点击「添加子项目」">
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column label="子项目编号" prop="projectCode" min-width="140" align="center" />
        <el-table-column label="子项目名称" min-width="200" align="center">
          <template #default="scope">
            <el-input v-model="scope.row.projectName" placeholder="请输入子项目名称" :disabled="isFormDisabled" maxlength="200" show-word-limit />
          </template>
        </el-table-column>
        <el-table-column v-if="!isFormDisabled" label="操作" width="90" align="center" fixed="right">
          <template #default="scope">
            <el-button link type="danger" icon="Delete" @click="removeSubProjectRow(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="ProjectInfoDevEdit" lang="ts">
import {
  getProjectInfo,
  addProjectInfo,
  updateProjectInfo,
  projectSubmitAndFlowStart,
  getErpProjectInfoList,
  listProjectInfo,
  delProjectInfo
} from '@/api/oa/erp/projectInfo';
import { ProjectInfoForm, ProjectInfoVO } from '@/api/oa/erp/projectInfo/types';
import { getRuleGenerateCode } from '@/api/system/codeRule';
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 { getUserList } from '@/api/system/user';
import { CodeRuleEnum, FlowCodeEnum, ProjectCategoryEnum } from '@/enums/OAEnum';
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 { project_category } = toRefs<any>(proxy?.useDict('project_category'));

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

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

// 任务变量
const taskVariables = 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 getUserSelectList = async () => {
  const params = { } as any;
  const res = await getUserList(params);
  userList.value = res.data;
};

type ProjectInfoFormEx = ProjectInfoForm & {
  flowCode?: string;
  variables?: any;
  bizExt?: any;
};

const initFormData: ProjectInfoFormEx = {
  projectId: undefined,
  parentProjectId: undefined,
  subProjectFlag: '0',
  contractFlag: '2',
  projectCode: undefined,
  projectName: undefined,
  businessDirection: undefined,
  projectCategory: undefined,
  spareFlag: undefined,
  projectTypeId: undefined,
  paymentMethod: undefined,
  deptId: undefined,
  managerId: undefined,
  chargeId: undefined,
  deputyId: undefined,
  peopleId: undefined,
  amount: undefined,
  projectStatus: '1',
  flowStatus: undefined,
  sortOrder: 0,
  contractId: undefined,
  remark: undefined,
  activeFlag: '1',
  ossId: undefined,
  flowCode: undefined,
  variables: undefined,
  bizExt: undefined
};

const data = reactive<{ form: ProjectInfoFormEx; rules: any }>({
  form: { ...initFormData },
  rules: {
    projectCode: [{ required: true, message: '项目编号不能为空', trigger: 'blur' }],
    projectName: [{ required: true, message: '项目名称不能为空', trigger: 'blur' }],
    projectCategory: [{ required: true, message: '项目类别不能为空', trigger: 'change' }]
  }
});

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

/** 表格行：子项目 */
type SubProjectRow = {
  _key: string;
  projectId?: string | number;
  projectCode: string;
  projectName: string;
};

const subProjectRows = ref<SubProjectRow[]>([]);
const removedSubProjectIds = ref<Array<string | number>>([]);

const isRdCategory = computed(() => form.value.projectCategory === ProjectCategoryEnum.RD);

/** 当前单据为研发主线（非子项目自身编辑页） */
const isRdMainLine = computed(() => !form.value.parentProjectId);

const showHasSubProjectSwitch = computed(() => isRdCategory.value && isRdMainLine.value);

/** 开启「含有子项目」后展示子项目表格与添加按钮 */
const showSubProjectSection = computed(() => showHasSubProjectSwitch.value && form.value.subProjectFlag === '1');

const codeLockedBySubRows = computed(() => subProjectRows.value.length > 0);

const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

/** 根据主项目编号与当前表格行计算下一个子项目编号 */
const nextSubProjectCode = (parentCode: string, rows: SubProjectRow[]): string | null => {
  const pc = parentCode.trim();
  if (!pc) return null;
  const pattern = new RegExp(`^${escapeRegExp(pc)}\\.(\\d{2})$`);
  let max = 0;
  for (const r of rows) {
    const m = pattern.exec(r.projectCode || '');
    if (m) max = Math.max(max, parseInt(m[1], 10));
  }
  if (max >= 99) return null;
  return `${pc}.${String(max + 1).padStart(2, '0')}`;
};

const onHasSubProjectChange = () => {
  if (form.value.subProjectFlag !== '1') {
    if (subProjectRows.value.some((r) => r.projectId)) {
      proxy?.$modal.msgWarning('存在已保存的子项目，请先在表格中删除后再关闭「含有子项目」');
      nextTick(() => {
        form.value.subProjectFlag = '1';
      });
      return;
    }
    subProjectRows.value = [];
    removedSubProjectIds.value = [];
  }
};

const addSubProjectRow = () => {
  const pcode = form.value.projectCode != null ? String(form.value.projectCode).trim() : '';
  if (!pcode) {
    proxy?.$modal.msgWarning('请先生成主项目编号');
    return;
  }
  const next = nextSubProjectCode(pcode, subProjectRows.value);
  if (!next) {
    proxy?.$modal.msgError('子项目序号已达上限 99');
    return;
  }
  subProjectRows.value.push({
    _key: `${Date.now()}_${Math.random()}`,
    projectCode: next,
    projectName: ''
  });
};

const removeSubProjectRow = async (index: number) => {
  const row = subProjectRows.value[index];
  if (row.projectId) {
    await proxy?.$modal.confirm(`是否确认移除子项目「${row.projectCode}」？保存时将删除该子项目数据。`);
    removedSubProjectIds.value.push(row.projectId);
  }
  subProjectRows.value.splice(index, 1);
};

/** 从服务端加载子项目列表（仅主项目编辑） */
const loadSubProjectsFromServer = async () => {
  subProjectRows.value = [];
  removedSubProjectIds.value = [];
  if (!form.value.projectId || form.value.parentProjectId) return;
  const res = await getErpProjectInfoList({ parentProjectId: form.value.projectId } as any);
  const list: ProjectInfoVO[] = res.data || [];
  subProjectRows.value = list.map((c) => ({
    _key: String(c.projectId),
    projectId: c.projectId,
    projectCode: c.projectCode != null ? String(c.projectCode) : '',
    projectName: c.projectName != null ? String(c.projectName) : ''
  }));
  if (list.length > 0) {
    form.value.subProjectFlag = '1';
  }
};

const resolveParentIdByCode = async (projectCode: string): Promise<string | number | undefined> => {
  const res = await listProjectInfo({ projectCode, pageNum: 1, pageSize: 30 } as any);
  const rows = (res as any).rows || [];
  const exact = rows.find((r: ProjectInfoVO) => String(r.projectCode) === String(projectCode));
  return exact?.projectId;
};

const buildChildPayload = (
  parentId: string | number,
  row: SubProjectRow,
  peopleJoined: string,
  statusSnap: { projectStatus?: string; flowStatus?: string }
): ProjectInfoForm => {
  const m = form.value;
  return {
    contractFlag: m.contractFlag,
    businessDirection: m.businessDirection,
    projectCategory: m.projectCategory,
    spareFlag: m.spareFlag,
    singleContractFlag: m.singleContractFlag,
    projectTypeId: m.projectTypeId,
    paymentMethod: m.paymentMethod,
    deptId: m.deptId,
    managerId: m.managerId,
    chargeId: m.chargeId,
    deputyId: m.deputyId,
    peopleId: peopleJoined as any,
    amount: m.amount,
    remark: m.remark,
    ossId: m.ossId,
    activeFlag: m.activeFlag ?? '1',
    sortOrder: m.sortOrder ?? 0,
    contractId: m.contractId,
    parentProjectId: parentId,
    subProjectFlag: '0',
    projectCode: row.projectCode,
    projectName: row.projectName.trim(),
    projectStatus: '3',
    flowStatus: statusSnap.flowStatus ?? m.flowStatus
  };
};

const persistSubProjects = async (
  parentId: string | number,
  statusSnap: { projectStatus?: string; flowStatus?: string }
) => {
  if (subProjectRows.value.length === 0 && removedSubProjectIds.value.length === 0) {
    return;
  }
  const peopleJoined = Array.isArray(form.value.peopleId)
    ? form.value.peopleId.join(',')
    : ((form.value.peopleId as string) ?? '');
  for (const id of removedSubProjectIds.value) {
    await delProjectInfo(id);
  }
  removedSubProjectIds.value = [];
  for (const row of subProjectRows.value) {
    const payload = buildChildPayload(parentId, row, peopleJoined, statusSnap);
    if (row.projectId) {
      await updateProjectInfo({ ...payload, projectId: row.projectId });
    } else {
      await addProjectInfo(payload);
    }
  }
};

// 附件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 isFormDisabled = computed(() => {
  return routeParams.value.type === 'view' || routeParams.value.type === 'approval';
});

// 生成主项目编号（存在子项目行时禁止改主编号）
const generateProjectCode = async () => {
  if (isCodeGenerated.value || codeLockedBySubRows.value) return;

  try {
    const codeRuleCode = form.value.projectCategory === ProjectCategoryEnum.RD ? CodeRuleEnum.PROJECT_RD : CodeRuleEnum.PROJECT;
    const params = { codeRuleCode: codeRuleCode } as any;
    const res = await getRuleGenerateCode(params);
    form.value.projectCode = res.msg;
    isCodeGenerated.value = true;
    proxy?.$modal.msgSuccess('项目编号生成成功');
  } catch (error) {
    console.error('生成项目编号失败:', error);
    proxy?.$modal.msgError('生成项目编号失败');
  }
};

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

    if (form.value.subProjectFlag === '1' && subProjectRows.value.length > 0) {
      for (const row of subProjectRows.value) {
        if (!row.projectName || !String(row.projectName).trim()) {
          proxy?.$modal.msgError('请填写所有子项目名称');
          return;
        }
      }
    }

    buttonLoading.value = true;

    const submitData = { ...form.value };
    submitData.subProjectFlag = subProjectRows.value.length > 0 ? '1' : '0';
    if (Array.isArray(submitData.peopleId)) {
      submitData.peopleId = submitData.peopleId.join(',') as any;
    }

    const runAfterClose = () => {
      proxy?.$modal.msgSuccess(status === 'draft' ? '暂存成功' : '操作成功');
      proxy?.$tab.closePage();
      router.go(-1);
    };

    try {
      if (status != 'draft') {
        submitData.flowCode = FlowCodeEnum.PROJECT_RD_KEY;
        const res = await projectSubmitAndFlowStart(submitData);
        const flowVo = (res as any).data;
        let parentId: string | number | undefined = flowVo?.projectId ?? submitData.projectId;
        if (!parentId && submitData.projectCode) {
          parentId = await resolveParentIdByCode(String(submitData.projectCode));
        }
        const snap = {
          projectStatus: flowVo?.projectStatus,
          flowStatus: flowVo?.flowStatus
        };
        if (parentId && (subProjectRows.value.length > 0 || removedSubProjectIds.value.length > 0)) {
          await persistSubProjects(parentId, snap);
        }
        if (flowVo) {
          Object.assign(form.value, flowVo);
        }
        runAfterClose();
      } else {
        if (status === 'draft') {
          submitData.projectStatus = '1';
          submitData.flowStatus = 'draft';
        }
        const snap = {
          projectStatus: submitData.projectStatus,
          flowStatus: submitData.flowStatus
        };
        if (submitData.projectId) {
          await updateProjectInfo(submitData);
          await persistSubProjects(submitData.projectId as string | number, snap);
        } else {
          await addProjectInfo(submitData);
          const parentId = await resolveParentIdByCode(String(submitData.projectCode));
          if (parentId && (subProjectRows.value.length > 0 || removedSubProjectIds.value.length > 0)) {
            await persistSubProjects(parentId, snap);
          }
        }
        runAfterClose();
      }
    } catch (e) {
      console.error(e);
    } finally {
      buttonLoading.value = false;
    }
  });
};

//初始化调用
const loadSelectOptions = () => {
  getDeptInfoListSelect();
  getUserSelectList();
};

onMounted(async () => {
  nextTick(async () => {
    // 获取路由参数
    routeParams.value = route.query;
    proxy?.$modal.loading('正在加载数据，请稍后...');
    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.subProjectFlag) {
        form.value.subProjectFlag = '0';
      }
      // 将抄送人员字符串转换为数组，用于多选下拉框显示
      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;
      }
      if (form.value.projectCode) {
        isCodeGenerated.value = true;
      }
      if (isRdMainLine.value) {
        await loadSubProjectsFromServer();
      }
    } else {
      // 新增模式：获取登录用户信息并自动赋值
      try {
        const userInfoRes = await getInfo();
        const userVO = userInfoRes.data.user;
        if (userInfoRes.data?.user) {
          form.value.deptId = userVO.deptId;
          form.value.managerId = userVO.userId;
          form.value.chargeId = userVO.chargeId;
          form.value.deputyId = userVO.deputyId;
        }
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }

      // 新增模式：如果已有项目编号，禁用生成按钮
      if (form.value.projectCode) {
        isCodeGenerated.value = true;
      }
      // 新增模式：设置项目类别
      if (routeParams.value.projectCategory) {
        form.value.projectCategory = routeParams.value.projectCategory as string;
      }
    }
    form.value.spareFlag = form.value.projectCategory === ProjectCategoryEnum.SALE_SPARE ? '1' : '0';
    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);
};
</script>

<style scoped lang="scss">
.sub-project-card-title {
  font-weight: 600;
  margin-right: 8px;
}
.sub-project-card-tip {
  font-size: 12px;
  color: var(--el-text-color-secondary);
}
</style>
