yyb
14 小时以前 352f7bbb74f1b6c57b3d3e576849d0565932fbd4
src/views/officeProcessAutomation/AttendManage/leave-apply/index.vue
@@ -10,13 +10,13 @@
          placeholder="姓名或编号"
          clearable
          :prefix-icon="Search"
          @keyup.enter="handleQuery"
          @keyup.enter="onSearch"
        />
        <span class="search_title" style="margin-left: 12px">请假类型:</span>
        <el-select v-model="searchForm.leaveType" placeholder="全部" clearable style="width: 180px">
          <el-option v-for="opt in LEAVE_TYPE_OPTIONS" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
        <el-button type="primary" style="margin-left: 10px" @click="handleQuery">搜索</el-button>
        <el-button type="primary" style="margin-left: 10px" @click="onSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>
      <div>
@@ -31,37 +31,27 @@
        :page="page"
        :isSelection="false"
        :tableLoading="tableLoading"
        @pagination="pagination"
        @pagination="onPagination"
        :total="page.total"
      />
    </div>
    <!-- 新增 / 编辑 -->
    <el-dialog
      v-if="formDialog.visible"
      v-model="formDialog.visible"
      :title="formDialog.title"
      width="960px"
      append-to-body
      destroy-on-close
      class="leave-apply-form-dialog"
      @closed="onFormClosed"
    <ApprovalInstanceSubmitDialog
      v-model="submitDialog.visible"
      :title="submitDialogTitle"
      :form="submitForm"
      :rules="submitFormRules"
      :fields="submitFormFields"
      :active-template="activeTemplate"
      :user-options="flowUserOptions"
      :is-edit="isSubmitEdit"
      :saving="submitSaving"
      :form-ref="submitFormRef"
      flow-attachments-only
      @submit="onSubmit"
    >
      <el-form ref="formRef" :model="form" :rules="formRules" label-width="140px" class="leave-apply-form">
        <el-form-item v-if="form.templateSnapshot" label="审批模板">
          <span class="template-name">{{ form.templateSnapshot.label || form.templateName }}</span>
          <el-button
            v-if="formDialog.mode === 'add'"
            type="primary"
            link
            class="ml12"
            @click="reopenTemplateBind"
          >
            更换模板
          </el-button>
        </el-form-item>
        <FormPayloadFields :fields="templateDisplayFields" :form-payload="form.formPayload" />
      <template #before="{ form, fields }">
        <FormPayloadFields :fields="displayTemplateFields(fields)" :form-payload="form.formPayload" />
        <el-row :gutter="24">
          <el-col :span="12">
            <el-form-item label="假期余额" prop="leaveBalanceDays">
@@ -79,32 +69,14 @@
          </el-col>
          <el-col :span="12">
            <el-form-item label="请假时长">
              <el-input :model-value="leaveDurationDisplay" readonly placeholder="根据模板中请假时间自动计算">
              <el-input :model-value="leaveDurationDisplay(form)" readonly placeholder="根据模板中请假时间自动计算">
                <template #append>天</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <ApprovalTemplateFormSection
          :active-template="form.templateSnapshot"
          :fields="form.formFieldDefs"
          :form-payload="form.formPayload"
          v-model:flow-nodes="form.flowNodes"
          v-model:attachments="form.storageBlobDTOs"
          :template-attachments="form.templateAttachments"
          :user-options="flowUserOptions"
          flow-attachments-only
          hide-template-name
          :allow-change-template="false"
        />
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="formDialog.visible = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    </ApprovalInstanceSubmitDialog>
    <ApprovalTemplateBindDialog
      v-model:visible="templateBindVisible"
@@ -114,55 +86,12 @@
      @closed="onTemplateBindClosed"
    />
    <!-- 详情 -->
    <el-dialog v-model="detailDialog.visible" title="请假申请详情" width="720px" append-to-body>
      <el-descriptions :column="1" border>
        <el-descriptions-item label="申请人编号">{{ detailRow.applicantNo || "—" }}</el-descriptions-item>
        <el-descriptions-item label="申请人">{{ detailRow.applicantName }}</el-descriptions-item>
        <el-descriptions-item label="请假类型">{{ leaveTypeLabel(detailRow.leaveType) }}</el-descriptions-item>
        <el-descriptions-item label="假期余额">{{ formatBalance(detailRow.leaveBalanceDays) }}</el-descriptions-item>
        <el-descriptions-item label="请假开始时间">{{ detailRow.leaveStartTime || "—" }}</el-descriptions-item>
        <el-descriptions-item label="请假结束时间">{{ detailRow.leaveEndTime || "—" }}</el-descriptions-item>
        <el-descriptions-item label="请假时长">{{ formatDuration(detailRow.leaveDurationDays) }}</el-descriptions-item>
        <el-descriptions-item label="请假事由">{{ detailRow.leaveReason }}</el-descriptions-item>
        <el-descriptions-item label="审批结果">{{ approvalResultLabel(detailRow.approvalResult) }}</el-descriptions-item>
        <el-descriptions-item label="审批方式">{{ approvalModeLabel(detailRow.approvalMode) }}</el-descriptions-item>
        <el-descriptions-item label="审批人">{{ detailRow.approverNames || "—" }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailRow.createTime || "—" }}</el-descriptions-item>
        <el-descriptions-item label="附件">
          <template v-if="rowAttachmentList(detailRow).length">
            <el-tag v-for="(f, i) in rowAttachmentList(detailRow)" :key="i" class="mr6 mb6" type="info">
              {{ f.name }}
            </el-tag>
          </template>
          <span v-else>无</span>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="detailDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 附件列表 -->
    <el-dialog v-model="filesDialog.visible" title="附件" width="520px" append-to-body>
      <el-table v-if="rowAttachmentList(filesDialog.row).length" :data="rowAttachmentList(filesDialog.row)" border>
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="name" label="文件名" min-width="200" show-overflow-tooltip />
        <el-table-column label="操作" width="100" align="center">
          <template #default="{ row }">
            <el-button link type="primary" @click="mockDownload(row)">下载</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-empty v-else description="暂无附件" />
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="filesDialog.visible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
    <ApprovalInstanceDetailDialog
      v-model="detailDialog.visible"
      title="请假申请详情"
      :row="detailRow"
      @edit="openEditFromDetail"
    />
  </div>
</template>
@@ -170,21 +99,18 @@
import { Search } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { userListNoPageByTenantId } from "@/api/system/user.js";
import { computed, getCurrentInstance, nextTick, onMounted, reactive, ref, watch } from "vue";
import ApprovalTemplateBindDialog from "../../ApproveManage/approve-shared/components/ApprovalTemplateBindDialog.vue";
import ApprovalTemplateFormSection from "../../ApproveManage/approve-shared/components/ApprovalTemplateFormSection.vue";
import { ElMessage } from "element-plus";
import { computed, onMounted, reactive, ref, watch } from "vue";
import FormPayloadFields from "../../ApproveManage/approve-list/components/FormPayloadFields.vue";
import ApprovalInstanceDetailDialog from "../../ApproveManage/approve-shared/components/ApprovalInstanceDetailDialog.vue";
import ApprovalInstanceSubmitDialog from "../../ApproveManage/approve-shared/components/ApprovalInstanceSubmitDialog.vue";
import ApprovalTemplateBindDialog from "../../ApproveManage/approve-shared/components/ApprovalTemplateBindDialog.vue";
import { buildInstanceTableColumns } from "../../ApproveManage/approve-shared/approvalInstanceFormConfigTable.js";
import { APPROVAL_MODULE_KEYS } from "../../ApproveManage/approve-shared/approvalModuleRegistry.js";
import {
  applyBindingToForm,
  attachmentDisplayName,
  buildFormPayloadRules,
  validateTemplateBinding,
} from "../../ApproveManage/approve-shared/approvalTemplateBindingUtils.js";
import { useApprovalInstanceModule } from "../../ApproveManage/approve-shared/useApprovalInstanceModule.js";
import { useFlowUserOptions } from "../../ApproveManage/approve-shared/useFlowUserOptions.js";
import { SELECT_OPTION_SOURCE } from "../../ApproveManage/approve-template/selectOptionSource.js";
/** 请假类型(value 与后端对齐占位) */
const LEAVE_TYPE_OPTIONS = [
  { label: "年假", value: "annual" },
  { label: "病假", value: "sick" },
@@ -196,70 +122,6 @@
  { label: "调休", value: "compensatory" },
];
function leaveTypeLabel(v) {
  const hit = LEAVE_TYPE_OPTIONS.find((x) => x.value === v);
  return hit?.label || "—";
}
/** 与后端约定字段(占位) */
const createEmptyForm = () => ({
  id: undefined,
  applicantId: "",
  applicantNo: "",
  applicantName: "",
  leaveType: "",
  leaveBalanceDays: undefined,
  leaveStartTime: "",
  leaveEndTime: "",
  leaveDurationDays: null,
  leaveReason: "",
  hasTemplateBinding: false,
  templateId: "",
  templateName: "",
  templateSnapshot: null,
  formFieldDefs: [],
  formPayload: {},
  flowNodes: [],
  templateAttachments: [],
  storageBlobDTOs: [],
});
const { proxy } = getCurrentInstance();
function unwrapArray(payload) {
  if (Array.isArray(payload)) return payload;
  if (payload && Array.isArray(payload.data)) return payload.data;
  if (payload && Array.isArray(payload.rows)) return payload.rows;
  return [];
}
function isActiveUser(u) {
  if (u.delFlag === "2" || u.delFlag === 2) return false;
  if (u.status == null) return true;
  return String(u.status) === "0";
}
function userById(id) {
  if (id == null || id === "") return undefined;
  return allUsersCache.value.find((u) => String(u.userId ?? u.id) === String(id));
}
function applicantNoFromUser(u) {
  if (!u) return "";
  return (
    u.userName ??
    u.userCode ??
    u.jobNumber ??
    u.workNo ??
    (u.userId != null ? String(u.userId) : "")
  );
}
/** 假期余额(对接考勤 API 前不展示假数据) */
function mockLeaveBalance() {
  return undefined;
}
function isLeaveBalanceField(field) {
  const label = String(field?.label || "");
  return label.includes("假期余额") || field?.key === "leaveBalanceDays";
@@ -268,6 +130,10 @@
function isLeaveDurationField(field) {
  const label = String(field?.label || "");
  return label.includes("请假时长") || field?.key === "leaveDurationDays";
}
function displayTemplateFields(fields = []) {
  return (fields || []).filter((f) => !isLeaveBalanceField(f) && !isLeaveDurationField(f));
}
function findLeaveTimeTemplateField(fields = []) {
@@ -287,7 +153,6 @@
  );
}
/** 从模板填报项解析请假起止时间 */
function resolveLeaveTimeRange(payload, leaveTimeField) {
  if (!leaveTimeField?.key) return { start: "", end: "" };
  const val = payload?.[leaveTimeField.key];
@@ -295,7 +160,6 @@
  return { start: val[0] || "", end: val[1] || "" };
}
/** 按起止时间计算请假天数(含时分秒,结果保留两位小数) */
function computeLeaveDays(startStr, endStr) {
  if (!startStr || !endStr) return null;
  const t0 = dayjs(startStr);
@@ -305,61 +169,75 @@
  return Math.round(days * 100) / 100;
}
function formatDuration(v) {
  if (v == null || v === "") return "—";
  return `${v} 天`;
function leaveDurationDisplay(form) {
  const leaveTimeField = findLeaveTimeTemplateField(form.formFieldDefs);
  const { start, end } = resolveLeaveTimeRange(form.formPayload, leaveTimeField);
  const d = computeLeaveDays(start, end);
  return d == null ? "" : String(d);
}
function formatBalance(v) {
  if (v == null || v === "") return "—";
  return `${v} 天`;
}
const searchForm = reactive({
  applicantKeyword: "",
  leaveType: "",
});
function mapStorageBlobsToAttachmentList(blobs) {
  return (blobs || []).map((f) => ({
    name: attachmentDisplayName(f),
    url: f.url || f.downloadURL || f.previewURL || f.previewUrl,
  }));
}
function rowAttachmentList(row) {
  if (!row) return [];
  if (row.attachmentList?.length) return row.attachmentList;
  return mapStorageBlobsToAttachmentList(row.storageBlobDTOs);
}
function approvalModeLabel(mode) {
  if (mode === "countersign") return "会签";
  if (mode === "or_sign") return "或签";
  return "与签";
}
function approvalResultLabel(v) {
  if (v === "approved") return "已通过";
  if (v === "rejected") return "已驳回";
  if (v === "cancelled") return "已撤销";
  return "待审批";
}
function syncApplicantFromUser(uid) {
  const u = userById(uid);
  if (u) {
    form.applicantId = uid != null && uid !== "" ? uid : "";
    form.applicantName = u.nickName || u.userName || "";
    form.applicantNo = applicantNoFromUser(u);
    form.leaveBalanceDays = mockLeaveBalance(u);
  } else {
    form.applicantId = "";
    form.applicantName = "";
    form.applicantNo = "";
    if (uid == null || uid === "") {
      form.leaveBalanceDays = undefined;
    }
function validateLeaveBeforeSave() {
  const leaveTimeField = findLeaveTimeTemplateField(submitForm.formFieldDefs);
  const { start, end } = resolveLeaveTimeRange(submitForm.formPayload, leaveTimeField);
  if (computeLeaveDays(start, end) == null) {
    ElMessage.warning("请检查模板中的请假时间,结束时间须晚于开始时间");
    throw new Error("invalid leave time");
  }
}
/** 系统用户缓存 */
const mod = useApprovalInstanceModule({
  moduleKey: APPROVAL_MODULE_KEYS.LEAVE,
  beforeSave: validateLeaveBeforeSave,
  extraFormRules: {
    leaveBalanceDays: [{ required: true, message: "请填写假期余额", trigger: "blur" }],
  },
});
const {
  tableData,
  tableLoading,
  page,
  detailDialog,
  detailRow,
  submitDialog,
  submitEditRow,
  submitForm,
  submitFormRef,
  submitSaving,
  isSubmitEdit,
  activeTemplate,
  submitFormFields,
  submitFormRules,
  submitDialogTitle,
  templateBindVisible,
  handleQuery,
  initModuleList,
  pagination,
  openAddWithTemplate,
  onTemplateBound,
  onTemplateBindClosed,
  openEditFromDetail,
  submitInstanceForm,
  buildTableActions,
} = mod;
const { flowUserOptions, loadFlowUsers } = useFlowUserOptions();
const allUsersCache = ref([]);
const applicantTemplateField = computed(() =>
  findApplicantTemplateField(submitForm.formFieldDefs)
);
function unwrapArray(payload) {
  if (Array.isArray(payload)) return payload;
  if (payload && Array.isArray(payload.data)) return payload.data;
  return [];
}
async function loadUserPool() {
  try {
@@ -370,412 +248,56 @@
  }
}
const allRows = ref([]);
const searchForm = reactive({
  applicantKeyword: "",
  leaveType: "",
});
const tableLoading = ref(false);
const page = reactive({
  current: 1,
  size: 10,
  total: 0,
});
const filteredList = computed(() => {
  let list = [...allRows.value];
  const kw = (searchForm.applicantKeyword || "").trim().toLowerCase();
  if (kw) {
    list = list.filter((r) => {
      const name = (r.applicantName || "").toLowerCase();
      const no = (r.applicantNo || "").toLowerCase();
      return name.includes(kw) || no.includes(kw);
    });
  }
  if (searchForm.leaveType) {
    list = list.filter((r) => r.leaveType === searchForm.leaveType);
  }
  return list.sort((a, b) => (String(a.createTime) < String(b.createTime) ? 1 : -1));
});
watch(
  filteredList,
  (list) => {
    page.total = list.length;
    const maxPage = Math.max(1, Math.ceil(list.length / page.size) || 1);
    if (page.current > maxPage) {
      page.current = maxPage;
  () => submitDialog.visible,
  (v) => {
    if (!v) return;
    if (submitForm.leaveBalanceDays == null && isSubmitEdit.value) {
      submitForm.leaveBalanceDays =
        submitEditRow.value?.formPayload?.leaveBalanceDays ??
        submitEditRow.value?.leaveBalanceDays;
    }
  },
  { immediate: true }
    if (submitForm.leaveBalanceDays == null && !isSubmitEdit.value) {
      submitForm.leaveBalanceDays = undefined;
    }
  }
);
const tableData = computed(() => {
  const list = filteredList.value;
  const start = (page.current - 1) * page.size;
  return list.slice(start, start + page.size);
});
const tableColumn = ref([
  { label: "申请人编号", prop: "applicantNo", width: 120 },
  { label: "申请人", prop: "applicantName", minWidth: 100 },
  {
    label: "请假类型",
    prop: "leaveType",
    width: 100,
    formatData: (v) => leaveTypeLabel(v),
  },
  {
    label: "请假时长",
    prop: "leaveDurationDays",
    width: 120,
    formatData: (v) => (v == null || v === "" ? "—" : `${v} 天`),
  },
  { label: "请假事由", prop: "leaveReason", minWidth: 180 },
  { label: "创建时间", prop: "createTime", width: 170 },
  {
    label: "审批结果",
    prop: "approvalResult",
    width: 110,
    dataType: "tag",
    formatData: (v) => approvalResultLabel(v),
    formatType: (v) => {
      if (v === "approved") return "success";
      if (v === "rejected") return "danger";
      if (v === "cancelled") return "info";
      return "warning";
    },
  },
  {
    dataType: "action",
    label: "操作",
    align: "center",
    fixed: "right",
    width: 220,
    operation: [
      {
        name: "编辑",
        type: "text",
        clickFun: (row) => openFormDialog("edit", row),
      },
      {
        name: "查看详情",
        type: "text",
        clickFun: (row) => openDetail(row),
      },
      {
        name: "附件",
        type: "text",
        clickFun: (row) => openFiles(row),
      },
    ],
  },
]);
const formDialog = reactive({
  visible: false,
  title: "",
  mode: "add",
});
const formRef = ref();
const form = reactive(createEmptyForm());
const templateBindVisible = ref(false);
const pendingTemplateBinding = ref(null);
const { flowUserOptions, loadFlowUsers } = useFlowUserOptions();
const leaveTimeTemplateField = computed(() => findLeaveTimeTemplateField(form.formFieldDefs));
const applicantTemplateField = computed(() => findApplicantTemplateField(form.formFieldDefs));
const templateDisplayFields = computed(() =>
  (form.formFieldDefs || []).filter((f) => !isLeaveBalanceField(f) && !isLeaveDurationField(f))
);
const leaveDurationDisplay = computed(() => {
  const { start, end } = resolveLeaveTimeRange(form.formPayload, leaveTimeTemplateField.value);
  const d = computeLeaveDays(start, end);
  return d == null ? "" : String(d);
});
const formRules = computed(() => ({
  ...buildFormPayloadRules(templateDisplayFields.value),
  leaveBalanceDays: [
    {
      required: true,
      message: "请填写假期余额",
      trigger: "blur",
    },
  ],
}));
watch(
  () => {
    const key = applicantTemplateField.value?.key;
    return key ? form.formPayload[key] : undefined;
    return key ? submitForm.formPayload[key] : undefined;
  },
  async (uid) => {
    if (!applicantTemplateField.value) return;
    if (!allUsersCache.value.length) {
      await loadUserPool();
    }
    syncApplicantFromUser(uid);
    if (!applicantTemplateField.value || !uid) return;
    if (!allUsersCache.value.length) await loadUserPool();
  }
);
watch(
  () => {
    const key = leaveTimeTemplateField.value?.key;
    return key ? form.formPayload[key] : undefined;
  },
  () => {
    const { start, end } = resolveLeaveTimeRange(form.formPayload, leaveTimeTemplateField.value);
    form.leaveStartTime = start;
    form.leaveEndTime = end;
    form.leaveDurationDays = computeLeaveDays(start, end);
  },
  { deep: true }
);
const tableColumn = buildInstanceTableColumns(tableData, buildTableActions);
const detailDialog = reactive({ visible: false });
const detailRow = ref({});
const filesDialog = reactive({ visible: false, row: null });
function handleQuery() {
  page.current = 1;
  tableLoading.value = true;
  setTimeout(() => {
    tableLoading.value = false;
  }, 150);
function onSearch() {
  handleQuery(searchForm);
}
function resetSearch() {
  searchForm.applicantKeyword = "";
  searchForm.leaveType = "";
  handleQuery();
  onSearch();
}
function pagination(obj) {
  page.current = obj.page;
  page.size = obj.limit;
function onPagination(obj) {
  pagination(obj, searchForm);
}
function openDetail(row) {
  detailRow.value = { ...row };
  detailDialog.visible = true;
async function onSubmit() {
  const ok = await submitInstanceForm({ skipValidate: true });
  if (ok) ElMessage.success(isSubmitEdit.value ? "修改成功" : "提交成功");
}
function openFiles(row) {
  filesDialog.row = row;
  filesDialog.visible = true;
}
function mockDownload(row) {
  const url = row.url || row.downloadURL || row.previewURL || row.previewUrl;
  if (url) {
    window.open(url, "_blank");
    return;
  }
  proxy?.$modal?.msgWarning?.("暂无下载地址");
}
function openAddWithTemplate() {
  formDialog.visible = false;
  pendingTemplateBinding.value = null;
  templateBindVisible.value = true;
}
function onTemplateBound(binding) {
  pendingTemplateBinding.value = binding;
}
async function onTemplateBindClosed() {
  const binding = pendingTemplateBinding.value;
  if (!binding) return;
  pendingTemplateBinding.value = null;
  await openFormWithBinding(binding);
}
async function openFormWithBinding(binding) {
  Object.assign(form, createEmptyForm());
  applyBindingToForm(form, binding);
  form.hasTemplateBinding = true;
  formDialog.mode = "add";
  formDialog.title = "新增请假申请";
  await Promise.all([loadUserPool(), loadFlowUsers()]);
  const applicantKey = applicantTemplateField.value?.key;
  if (applicantKey && form.formPayload[applicantKey]) {
    syncApplicantFromUser(form.formPayload[applicantKey]);
  }
  const { start, end } = resolveLeaveTimeRange(form.formPayload, leaveTimeTemplateField.value);
  form.leaveStartTime = start;
  form.leaveEndTime = end;
  form.leaveDurationDays = computeLeaveDays(start, end);
  formDialog.visible = true;
  nextTick(() => formRef.value?.clearValidate?.());
}
function reopenTemplateBind() {
  formDialog.visible = false;
  pendingTemplateBinding.value = null;
  templateBindVisible.value = true;
}
async function openFormDialog(mode, row) {
  if (mode === "edit" && row && !row.hasTemplateBinding) {
    proxy?.$modal?.msgWarning?.("该记录为旧版数据,请重新通过模板发起申请");
    return;
  }
  formDialog.mode = mode;
  formDialog.title = "编辑请假申请";
  Object.assign(form, createEmptyForm());
  if (mode === "edit" && row) {
    Object.assign(form, {
      id: row.id,
      applicantId: row.applicantId,
      applicantNo: row.applicantNo,
      applicantName: row.applicantName,
      leaveType: row.leaveType,
      leaveBalanceDays: row.leaveBalanceDays,
      leaveStartTime: row.leaveStartTime,
      leaveEndTime: row.leaveEndTime,
      leaveDurationDays: row.leaveDurationDays,
      leaveReason: row.leaveReason,
      hasTemplateBinding: true,
      templateId: row.templateId,
      templateName: row.templateName,
      templateSnapshot: row.templateSnapshot,
      formFieldDefs: row.formFieldDefs || [],
      formPayload: JSON.parse(JSON.stringify(row.formPayload || {})),
      flowNodes: JSON.parse(JSON.stringify(row.flowNodes || [])),
      templateAttachments: JSON.parse(JSON.stringify(row.templateAttachments || [])),
      storageBlobDTOs: JSON.parse(JSON.stringify(row.storageBlobDTOs || [])),
    });
    await loadUserPool();
    const applicantKey = applicantTemplateField.value?.key;
    if (applicantKey) {
      syncApplicantFromUser(form.formPayload[applicantKey]);
    }
onMounted(async () => {
    loadFlowUsers();
  }
  formDialog.visible = true;
  nextTick(() => formRef.value?.clearValidate?.());
}
function onFormClosed() {
  formRef.value?.resetFields?.();
}
/** 从模板填报项同步列表展示字段 */
function syncLeaveFieldsFromPayload() {
  const defs = form.formFieldDefs || [];
  const payload = form.formPayload || {};
  const leaveTimeField = findLeaveTimeTemplateField(defs);
  for (const f of defs) {
    const label = String(f.label || "");
    const val = payload[f.key];
    if (label.includes("申请人") && !label.includes("日期") && !label.includes("时间")) {
      if (val != null && val !== "") {
        form.applicantId = val;
        const u = userById(val);
        if (u) {
          form.applicantName = u.nickName || u.userName || "";
          form.applicantNo = applicantNoFromUser(u);
        }
      }
    }
    if ((label.includes("请假类型") || f.key === "leaveType") && f.type === "select") {
      form.leaveType = val != null && val !== "" ? val : "";
    }
    if (label.includes("事由") || f.key === "summary" || label.includes("请假事由")) {
      form.leaveReason = val != null ? String(val) : "";
    }
  }
  const { start, end } = resolveLeaveTimeRange(payload, leaveTimeField);
  form.leaveStartTime = start;
  form.leaveEndTime = end;
  form.leaveDurationDays = computeLeaveDays(start, end);
}
async function submitForm() {
  try {
    await formRef.value?.validate?.();
  } catch {
    return;
  }
  const flowCheck = validateTemplateBinding({ flowNodes: form.flowNodes });
  if (!flowCheck.ok) {
    proxy?.$modal?.msgWarning?.(flowCheck.message || "请完善审批流程");
    return;
  }
  form.flowNodes = flowCheck.nodes;
  const applicantKey = applicantTemplateField.value?.key;
  if (applicantKey) {
    syncApplicantFromUser(form.formPayload[applicantKey]);
  }
  syncLeaveFieldsFromPayload();
  if (form.leaveDurationDays == null) {
    proxy?.$modal?.msgWarning?.("请检查模板中的请假时间,结束时间须晚于开始时间");
    return;
  }
  const attachmentList = mapStorageBlobsToAttachmentList(form.storageBlobDTOs);
  const payload = {
    applicantId: form.applicantId,
    applicantNo: form.applicantNo,
    applicantName: form.applicantName,
    leaveType: form.leaveType,
    leaveBalanceDays: form.leaveBalanceDays,
    leaveStartTime: form.leaveStartTime,
    leaveEndTime: form.leaveEndTime,
    leaveDurationDays: form.leaveDurationDays,
    leaveReason: form.leaveReason,
    hasTemplateBinding: true,
    templateId: form.templateId,
    templateName: form.templateName,
    templateSnapshot: form.templateSnapshot,
    formFieldDefs: form.formFieldDefs,
    formPayload: JSON.parse(JSON.stringify(form.formPayload || {})),
    flowNodes: JSON.parse(JSON.stringify(form.flowNodes || [])),
    templateAttachments: JSON.parse(JSON.stringify(form.templateAttachments || [])),
    storageBlobDTOs: JSON.parse(JSON.stringify(form.storageBlobDTOs || [])),
    attachmentList,
  };
  if (formDialog.mode === "add") {
    const id = `local_${Date.now()}`;
    allRows.value.unshift({
      id,
      ...payload,
      approvalResult: "pending",
      createTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
    });
    proxy?.$modal?.msgSuccess?.("新增成功");
  } else {
    const idx = allRows.value.findIndex((r) => r.id === form.id);
    if (idx !== -1) {
      const prev = allRows.value[idx];
      allRows.value[idx] = {
        ...prev,
        id: form.id,
        ...payload,
        approvalResult: prev.approvalResult ?? "pending",
        createTime: prev.createTime ?? dayjs().format("YYYY-MM-DD HH:mm:ss"),
      };
    }
    proxy?.$modal?.msgSuccess?.("保存成功");
  }
  formDialog.visible = false;
  handleQuery();
}
onMounted(() => {
  loadFlowUsers();
  await initModuleList(searchForm);
});
</script>
@@ -793,27 +315,5 @@
.search_title {
  font-size: 14px;
  color: var(--el-text-color-regular);
}
.mr6 {
  margin-right: 6px;
}
.mb6 {
  margin-bottom: 6px;
}
.leave-apply-form :deep(.el-row) {
  margin-bottom: 0;
}
.leave-apply-form :deep(.el-form-item) {
  margin-bottom: 18px;
}
.template-name {
  font-weight: 600;
  color: var(--el-text-color-primary);
}
.ml12 {
  margin-left: 12px;
}
.leave-apply-form-dialog :deep(.el-dialog__body) {
  padding-top: 12px;
}
</style>