Explorar o código

fix:692【行政审批导出】行政审批的全部记录导出功能:增加“导出”功能,按照列表展示字段全部导出。

mlchen hai 5 días
pai
achega
8b4ff5a54c

+ 856 - 0
src/views/bpm/collaborative/export/recordExport.js

@@ -0,0 +1,856 @@
+import * as XLSX from 'xlsx';
+
+/** 后端 PageParam.pageSize 上限(@Max 100),导出按此分页拉取 */
+export const EXPORT_PAGE_SIZE = 100;
+
+/** 纯装饰控件:不进数据列 */
+const DECORATION_TYPES = ['divider', 'alert', 'button', 'link'];
+/** 容器控件:自身不是数据列,子控件按顺序平铺(结构与 vue-form-making 一致) */
+const CONTAINER_TYPES = [
+  'grid',
+  'col',
+  'td',
+  'tabs',
+  'collapse',
+  'inline',
+  'card',
+  'group',
+  'report',
+  'table'
+];
+/** 明细子表控件:值是一组对象,展开成多行 */
+const SUBTABLE_TYPES = ['blank', 'subform', 'dialog'];
+const FILE_TYPES = ['fileupload', 'imgupload', 'upload'];
+const SELECT_TYPES = ['deptCascader', 'deptAndUserCascader', 'userSelect'];
+const PERSON_FIELD_NAMES = ['发起人', '申请人'];
+
+const SUMMARY_SHEET = '汇总';
+const MIN_COL_WIDTH = 8;
+const MAX_COL_WIDTH = 60;
+const EMPTY_TEXT = '全部';
+const SUMMARY_REMARK_LIMIT = 200;
+
+function pad2(value) {
+  return value < 10 ? '0' + value : '' + value;
+}
+
+function isBlank(value) {
+  return value === null || value === undefined || value === '';
+}
+
+/** yyyyMMddHHmmss */
+export function timestampText(date) {
+  const now = date || new Date();
+  return (
+    now.getFullYear() +
+    pad2(now.getMonth() + 1) +
+    pad2(now.getDate()) +
+    pad2(now.getHours()) +
+    pad2(now.getMinutes()) +
+    pad2(now.getSeconds())
+  );
+}
+
+/** 文件命名:行政审批_{页签}_{yyyyMMddHHmmss}.xlsx */
+export function buildExportFileName(tabLabel, date) {
+  return (
+    ['行政审批', tabLabel || '全部记录', timestampText(date)].join('_') +
+    '.xlsx'
+  );
+}
+
+function dateClockText(date) {
+  const now = date || new Date();
+  return (
+    now.getFullYear() +
+    '-' +
+    pad2(now.getMonth() + 1) +
+    '-' +
+    pad2(now.getDate()) +
+    ' ' +
+    pad2(now.getHours()) +
+    ':' +
+    pad2(now.getMinutes()) +
+    ':' +
+    pad2(now.getSeconds())
+  );
+}
+
+function normalizeDateText(value) {
+  return String(value).trim().replace('T', ' ');
+}
+
+/** yyyy-MM-dd HH:mm(汇总页) */
+export function formatDateTime(value) {
+  if (isBlank(value)) return '';
+  if (typeof value === 'number')
+    return dateClockText(new Date(value)).slice(0, 16);
+  const text = normalizeDateText(value);
+  const matched = text.match(/^(\d{4}-\d{2}-\d{2})[ ](\d{2}:\d{2})/);
+  return matched ? matched[1] + ' ' + matched[2] : text;
+}
+
+/** yyyy-MM-dd HH:mm:ss(单据明细页,与模板一致) */
+export function formatDateTimeFull(value) {
+  if (isBlank(value)) return '';
+  if (typeof value === 'number') return dateClockText(new Date(value));
+  return normalizeDateText(value).replace(/\.\d+$/, '');
+}
+
+/** 与列表 datasource 同口径:补 name -> listName,并展开 valueJson */
+export function mapListRecord(item) {
+  if (!item) return {};
+  return { ...item, listName: item.name, ...(item.valueJson || {}) };
+}
+
+/** 当前页签 + 筛选条件文案 */
+export function buildFilterText(parts) {
+  const text = (parts || [])
+    .map(
+      (part) =>
+        part.label + ' = ' + (isBlank(part.value) ? EMPTY_TEXT : part.value)
+    )
+    .join(' ');
+  return '筛选条件:' + text;
+}
+
+/** report 布局的单元格 → 字段清单(跳过不可见单元格) */
+function reportCells(item) {
+  const cells = [];
+  (item.rows || []).forEach((row) => {
+    (row.columns || []).forEach((cell) => {
+      if (!cell) return;
+      if (cell.options && cell.options.invisible) return;
+      if (Array.isArray(cell.list)) cells.push(...cell.list);
+      else cells.push(cell);
+    });
+  });
+  return cells;
+}
+
+/** 容器控件的子控件;非容器返回 null */
+function containerChildren(item) {
+  switch (item.type) {
+    case 'grid':
+      return (item.columns || []).reduce(
+        (all, column) => all.concat((column && column.list) || []),
+        []
+      );
+    case 'col':
+    case 'td':
+    case 'inline':
+    case 'card':
+    case 'group':
+      return item.list || [];
+    case 'tabs':
+    case 'collapse':
+      return (item.tabs || []).reduce(
+        (all, tab) => all.concat((tab && tab.list) || []),
+        []
+      );
+    case 'report':
+      return reportCells(item);
+    case 'table':
+      return item.tableColumns || [];
+    default:
+      return null;
+  }
+}
+
+/** 明细子表自身的列:取子表模板字段 */
+function subtableFields(item) {
+  return (
+    containerChildren({ type: 'inline', list: item.list || [] }) || []
+  ).reduce((all, child) => {
+    if (!child || !child.type) return all;
+    const model = child.model || child.key || '';
+    if (!model) return all;
+    all.push({ prop: model, label: child.name || child.label || model });
+    return all;
+  }, []);
+}
+
+function walkFields(list, fields, seen, options) {
+  (list || []).forEach((item) => {
+    if (!item || !item.type) return;
+    const type = item.type;
+    const model = item.model || item.key || '';
+    const subtable =
+      SUBTABLE_TYPES.includes(type) || String(model).indexOf('blank_') === 0;
+    if (!model) {
+      if (CONTAINER_TYPES.includes(type)) {
+        walkFields(containerChildren(item), fields, seen, options);
+      }
+      return;
+    }
+    if (seen[model]) return;
+    seen[model] = true;
+    if (subtable) {
+      const mapped = options.subtableColumns
+        ? options.subtableColumns(model)
+        : null;
+      fields.push({
+        name: item.name || item.label || model,
+        model,
+        type,
+        subtable: true,
+        columns: mapped || subtableFields(item)
+      });
+      return;
+    }
+    if (CONTAINER_TYPES.includes(type)) {
+      walkFields(containerChildren(item), fields, seen, options);
+      return;
+    }
+    if (DECORATION_TYPES.includes(type)) return;
+    fields.push({
+      name: item.name || item.label || model,
+      model,
+      type,
+      subtable: false,
+      columns: []
+    });
+  });
+}
+
+/** 解析记录自带的表单模板(递归展开栅格 / 页签 / 卡片 / report / 子表),得到字段清单 */
+export function parseFormFields(formJson, options) {
+  if (!formJson) return [];
+  let making = formJson.makingJson;
+  if (!making) return [];
+  if (typeof making === 'string') {
+    try {
+      making = JSON.parse(making);
+    } catch (e) {
+      return [];
+    }
+  }
+  const fields = [];
+  walkFields((making && making.list) || [], fields, {}, options || {});
+  return fields;
+}
+
+/** 明细子表的列:优先取模板表头字典,其次按数据键推导 */
+function resolveSubtableColumns(field, records, ctx) {
+  const mapped = ctx.subtableColumns ? ctx.subtableColumns(field.model) : null;
+  if (mapped && mapped.length) {
+    return mapped.map((item) => ({
+      prop: item.prop,
+      label: item.label || item.prop
+    }));
+  }
+  const props = [];
+  records.forEach((record) => {
+    const rows = record[field.model];
+    if (!Array.isArray(rows)) return;
+    rows.forEach((row) => {
+      if (!row || typeof row !== 'object') return;
+      Object.keys(row).forEach((key) => {
+        if (props.indexOf(key) === -1) props.push(key);
+      });
+    });
+  });
+  return props.map((prop) => ({ prop, label: prop }));
+}
+
+function plainText(value, ctx) {
+  if (isBlank(value)) return '';
+  if (Array.isArray(value)) return value.length + ' 个';
+  if (typeof value === 'object') {
+    return ctx && ctx.formatValue ? ctx.formatValue(value) : '';
+  }
+  return String(value);
+}
+
+function fileText(value) {
+  if (isBlank(value)) return '';
+  if (Array.isArray(value)) return value.length + ' 个';
+  return '1 个';
+}
+
+function selectText(value, field, ctx) {
+  if (isBlank(value)) return '';
+  // 部门级联:值就是一条部门路径,取末级名称
+  if (field.type === 'deptCascader') {
+    if (ctx.deptName) return plainText(ctx.deptName(value), ctx);
+    return plainText(
+      Array.isArray(value) ? value[value.length - 1] : value,
+      ctx
+    );
+  }
+  const dataSource =
+    (field.options && field.options.remoteDataSource) || field.remoteDataSource;
+  const values = Array.isArray(value) ? value : [value];
+  const names = values.map((item) => {
+    if (item === null || item === undefined || item === '') return '';
+    if (dataSource === 'getGroupUserTree' && ctx.deptUserNames) {
+      return plainText(ctx.deptUserNames(item), ctx);
+    }
+    if (dataSource === 'getUserPage' && ctx.userNames) {
+      return plainText(ctx.userNames(item), ctx);
+    }
+    const path = Array.isArray(item) ? item : [item];
+    if (field.type === 'deptCascader' && ctx.deptNames) {
+      return plainText(ctx.deptNames(path), ctx);
+    }
+    if (ctx.userNames) {
+      const name = plainText(ctx.userNames(item), ctx);
+      if (name) return name;
+    }
+    return plainText(ctx.deptName ? ctx.deptName(path) : item, ctx);
+  });
+  return names.filter(Boolean).join(', ');
+}
+
+/** 单个表单字段的导出文本 */
+function fieldText(row, field, ctx) {
+  const value = row[field.model];
+  if (FILE_TYPES.includes(field.type)) return fileText(value);
+  if (SELECT_TYPES.includes(field.type)) {
+    return selectText(value, field, ctx);
+  }
+  return plainText(value, ctx);
+}
+
+/** 摘要文本:按记录自带模板把字段渲染成「字段名:值」,跳过布局与明细子表 */
+export function remarkText(row, ctx) {
+  const items = ctx && ctx.remarkItems ? ctx.remarkItems(row) : [];
+  const lines = [];
+  (items || []).forEach((item) => {
+    if (!item || !item.model) return;
+    const text = fieldText(row, item, ctx);
+    if (text) lines.push((item.name || item.model) + ':' + text);
+  });
+  return lines.join(';');
+}
+
+function detailRows(record, field) {
+  const rows = record[field.model];
+  if (!Array.isArray(rows)) return [];
+  return rows.filter((row) => row && typeof row === 'object');
+}
+
+/** 按单据分组:一张单据一个 Sheet */
+export function groupRecordsByForm(records, dictLabel) {
+  const groups = [];
+  const index = {};
+  (records || []).forEach((record) => {
+    const key =
+      record.formId !== undefined &&
+      record.formId !== null &&
+      record.formId !== ''
+        ? String(record.formId)
+        : 'form:' + (record.formName || '');
+    let group = index[key];
+    if (!group) {
+      group = {
+        key,
+        formName: record.formName || '(无表单)',
+        categoryLabel: dictLabel
+          ? dictLabel('collaborative_type', record.dictType) || ''
+          : '',
+        records: []
+      };
+      index[key] = group;
+      groups.push(group);
+    }
+    group.records.push(record);
+  });
+  return groups;
+}
+
+/** 单据页的列:序号 / 编号 / 发起人 / 该单据全部字段 / 明细子表 / 结果 / 创建时间 */
+/** 是否为 report 表格布局表单(整表快照,不做字段平铺) */
+function hasReportLayout(records) {
+  return (records || []).some((record) => {
+    const makingJson = record.formJson && record.formJson.makingJson;
+    if (!makingJson) return false;
+    let making = makingJson;
+    if (typeof making === 'string') {
+      try {
+        making = JSON.parse(making);
+      } catch (e) {
+        return false;
+      }
+    }
+    return ((making && making.list) || []).some(
+      (item) => item && (item.type === 'report' || item.type === 'table')
+    );
+  });
+}
+
+function collectGroupFields(group, ctx) {
+  const fields = [];
+  const seen = {};
+  group.records.forEach((record) => {
+    parseFormFields(record.formJson, {
+      subtableColumns: ctx.subtableColumns
+    }).forEach((field) => {
+      if (seen[field.model]) return;
+      seen[field.model] = true;
+      fields.push(field);
+    });
+  });
+  fields.forEach((field) => {
+    if (!field.subtable) return;
+    if (!field.columns || !field.columns.length) {
+      field.columns = resolveSubtableColumns(field, group.records, ctx);
+    }
+  });
+  return fields;
+}
+
+/** 列结构相同的明细子表合并成一组列(多张子表共用 明细行号 + 同一组明细列) */
+function groupSubtableFields(fields) {
+  const groups = [];
+  fields.forEach((field) => {
+    if (!field.subtable || !field.columns.length) return;
+    const key = field.columns
+      .map((item) => item.prop + '|' + item.label)
+      .join(';');
+    let target = null;
+    groups.forEach((group) => {
+      if (group.key === key) target = group;
+    });
+    if (!target) {
+      target = { key, fields: [], columns: field.columns };
+      groups.push(target);
+    }
+    target.fields.push(field);
+  });
+  return groups;
+}
+
+/** 单据页的列:序号 / 编号 / 发起人 / 该单据全部字段 / 明细子表 / 结果 / 创建时间 */
+/** 单据页的列:序号 / 编号 / 发起人 / 该单据全部字段 / 明细子表 / 结果 / 创建时间 */
+function buildGroupColumns(group, ctx) {
+  const fields = collectGroupFields(group, ctx);
+  if (hasReportLayout(group.records)) {
+    // 表格布局表单:按记录做「字段 / 值」纵向快照,不做宽表平铺
+    return {
+      columns: [
+        { label: '序号', kind: 'index' },
+        { label: '编号', kind: 'processInstanceNo' },
+        { label: '字段', kind: 'fieldName' },
+        { label: '值', kind: 'fieldValue' }
+      ],
+      fields,
+      subGroups: [],
+      snapshot: true
+    };
+  }
+  const subGroups = groupSubtableFields(fields);
+  // 模板自己的人选字段(加班人 / 申请人 …)就是模板里的「人」列,不再重复补发起人
+  const hasPersonField = fields.some(
+    (field) =>
+      field.type === 'userSelect' || PERSON_FIELD_NAMES.includes(field.name)
+  );
+  const columns = [
+    { label: '序号', kind: 'index' },
+    { label: '编号', kind: 'processInstanceNo' }
+  ];
+  if (!hasPersonField) {
+    columns.push({ label: '发起人', kind: 'startUserName' });
+  }
+  fields.forEach((field) => {
+    if (field.subtable && field.columns.length) return;
+    columns.push({ label: field.name, kind: 'field', field });
+  });
+  subGroups.forEach((sub) => {
+    columns.push({ label: '明细行号', kind: 'detailIndex', sub });
+    sub.columns.forEach((item) => {
+      columns.push({ label: item.label, kind: 'sub', sub, prop: item.prop });
+    });
+  });
+  columns.push({ label: '结果', kind: 'result' });
+  columns.push({ label: '创建时间', kind: 'createTime' });
+  return { columns, fields, subGroups, snapshot: false };
+}
+
+function cellValue(record, column, ctx, options) {
+  switch (column.kind) {
+    case 'index':
+      return options.index;
+    case 'processInstanceNo':
+      return plainText(record.processInstanceNo, ctx);
+    case 'startUserName':
+      return plainText(record.startUserName, ctx);
+    case 'result':
+      return ctx.dictLabel
+        ? plainText(ctx.dictLabel('流程实例的结果', record.result), ctx)
+        : '';
+    case 'createTime':
+      return formatDateTimeFull(record.createTime);
+    case 'detailIndex':
+      return options.detailIndex;
+    case 'sub': {
+      if (!options.detailRow) return '';
+      const value = options.detailRow[column.prop];
+      if (Array.isArray(value)) return fileText(value);
+      return plainText(value, ctx);
+    }
+    default:
+      return column.field ? fieldText(record, column.field, ctx) : '';
+  }
+}
+
+/** 单据页数据行:明细子表按行展开,多张子表顺序拼接,主表列纵向合并 */
+function buildGroupRows(group, columns, ctx, subGroups) {
+  const rows = [];
+  const merges = [];
+  let serial = 0;
+  group.records.forEach((record) => {
+    const blocks = (subGroups || []).map((sub) => {
+      const list = [];
+      sub.fields.forEach((field) => {
+        detailRows(record, field).forEach((row, index) => {
+          list.push({ row, index: index + 1 });
+        });
+      });
+      return list;
+    });
+    const rowCount = Math.max(
+      blocks.reduce((total, list) => total + list.length, 0),
+      1
+    );
+    serial += 1;
+    const startRow = rows.length;
+    for (let i = 0; i < rowCount; i += 1) {
+      let offset = i;
+      let blockIndex = -1;
+      let rowInBlock = -1;
+      for (let b = 0; b < blocks.length; b += 1) {
+        if (offset < blocks[b].length) {
+          blockIndex = b;
+          rowInBlock = offset;
+          break;
+        }
+        offset -= blocks[b].length;
+      }
+      const detail = blockIndex >= 0 ? blocks[blockIndex][rowInBlock] : null;
+      rows.push(
+        columns.map((column) => {
+          if (
+            column.kind === 'sub' &&
+            (!subGroups[blockIndex] || subGroups[blockIndex] !== column.sub)
+          ) {
+            return '';
+          }
+          return cellValue(record, column, ctx, {
+            index: serial,
+            detailIndex: detail ? detail.index : '',
+            detailRow: detail ? detail.row : undefined
+          });
+        })
+      );
+    }
+    if (rowCount > 1) {
+      columns.forEach((column, columnIndex) => {
+        if (column.kind === 'detailIndex' || column.kind === 'sub') return;
+        merges.push({
+          s: { r: startRow, c: columnIndex },
+          e: { r: startRow + rowCount - 1, c: columnIndex }
+        });
+      });
+    }
+  });
+  return { rows, merges };
+}
+
+/** 表格布局表单的数据行:一条记录一块「字段 / 值」,记录之间空 2 行 */
+function buildSnapshotRows(group, fields, ctx) {
+  const rows = [];
+  const merges = [];
+  const list = (fields || []).filter((field) => !field.subtable);
+  group.records.forEach((record, recordIndex) => {
+    const startRow = rows.length;
+    const block = list.length ? list : [{ name: '', model: '' }];
+    block.forEach((field) => {
+      rows.push([
+        recordIndex + 1,
+        plainText(record.processInstanceNo, ctx),
+        field.name || '',
+        field.model ? fieldText(record, field, ctx) : ''
+      ]);
+    });
+    if (block.length > 1) {
+      merges.push({
+        s: { r: startRow, c: 0 },
+        e: { r: startRow + block.length - 1, c: 0 }
+      });
+      merges.push({
+        s: { r: startRow, c: 1 },
+        e: { r: startRow + block.length - 1, c: 1 }
+      });
+    }
+    if (recordIndex < group.records.length - 1) {
+      rows.push(['', '', '', '']);
+      rows.push(['', '', '', '']);
+    }
+  });
+  return { rows, merges };
+}
+
+function textWidth(text) {
+  let width = 0;
+  String(text || '')
+    .split('\n')
+    .forEach((line) => {
+      let current = 0;
+      for (const char of line) {
+        current += /[\u4e00-\u9fa5]/.test(char) ? 2 : 1;
+      }
+      width = Math.max(width, current);
+    });
+  return width;
+}
+
+function buildColumnWidths(header, body) {
+  return header.map((label, index) => {
+    let width = textWidth(label);
+    body.forEach((row) => {
+      width = Math.max(width, textWidth(row[index]));
+    });
+    return { wch: Math.min(Math.max(width + 2, MIN_COL_WIDTH), MAX_COL_WIDTH) };
+  });
+}
+
+function safeSheetName(name, used) {
+  let base = String(name || '单据').replace(/[\\/:*?[\]]/g, '-');
+  if (base.length > 31) base = base.slice(0, 31);
+  let sheetName = base || '单据';
+  let suffix = 2;
+  while (used[sheetName]) {
+    const tail = '(' + suffix + ')';
+    sheetName = base.slice(0, 31 - tail.length) + tail;
+    suffix += 1;
+  }
+  used[sheetName] = true;
+  return sheetName;
+}
+
+function appendSheet(workbook, spec) {
+  const aoa = [
+    [spec.title],
+    [spec.filterText || ''],
+    [spec.metaText || ''],
+    spec.header
+  ];
+  spec.rows.forEach((row) => aoa.push(row));
+  const totalRowIndex = aoa.length;
+  aoa.push(spec.totalRow || [spec.totalText]);
+  const sheet = XLSX.utils.aoa_to_sheet(aoa);
+  const lastCol = Math.max(spec.header.length - 1, 0);
+  const merges = [0, 1, 2].map((row) => ({
+    s: { r: row, c: 0 },
+    e: { r: row, c: lastCol }
+  }));
+  if (!spec.totalRow) {
+    merges.push({
+      s: { r: totalRowIndex, c: 0 },
+      e: { r: totalRowIndex, c: lastCol }
+    });
+  }
+  (spec.merges || []).forEach((merge) => {
+    merges.push({
+      s: { r: merge.s.r + 4, c: merge.s.c },
+      e: { r: merge.e.r + 4, c: merge.e.c }
+    });
+  });
+  sheet['!merges'] = merges;
+  sheet['!cols'] = buildColumnWidths(spec.header, spec.rows);
+  sheet['!rows'] = aoa.map((item, index) => ({
+    hpt: index === 3 ? 30 : index < 3 ? 30 : 22
+  }));
+  if (spec.rows.length) {
+    // 0 基表头行 + 数据行数,换算成 Excel 行号(1 基),合计行不参与筛选
+    const lastDataRow = 4 + spec.rows.length;
+    sheet['!autofilter'] = {
+      ref: 'A4:' + XLSX.utils.encode_col(lastCol) + lastDataRow
+    };
+  }
+  XLSX.utils.book_append_sheet(workbook, sheet, spec.sheetName);
+}
+
+function subtableSummary(record, fields) {
+  let count = 0;
+  fields.forEach((field) => {
+    if (!field.subtable) return;
+    count = Math.max(count, detailRows(record, field).length);
+  });
+  return count;
+}
+
+function subtableAmount(record, fields) {
+  let total = 0;
+  let found = false;
+  fields.forEach((field) => {
+    if (!field.subtable) return;
+    detailRows(record, field).forEach((row) => {
+      const value = Number(row.price);
+      if (!Number.isNaN(value) && value !== 0) {
+        total += value;
+        found = true;
+      }
+    });
+  });
+  return found ? total : '';
+}
+
+function buildSummarySpec(groups, options) {
+  const header = [
+    '序号',
+    '编号',
+    '分类',
+    '单据',
+    '摘要',
+    '发起人',
+    '结果',
+    '明细条数',
+    '金额合计(元)',
+    '创建时间'
+  ];
+  const rows = [];
+  let serial = 0;
+  let amountTotal = 0;
+  let hasAmount = false;
+  groups.forEach((group) => {
+    const fields = [];
+    group.records.forEach((record) => {
+      parseFormFields(record.formJson, {
+        subtableColumns: options.ctx.subtableColumns
+      }).forEach((field) => {
+        if (!fields.some((item) => item.model === field.model)) {
+          fields.push(field);
+        }
+      });
+    });
+    group.records.forEach((record) => {
+      serial += 1;
+      const detailCount = subtableSummary(record, fields);
+      const amount = subtableAmount(record, fields);
+      if (amount !== '') {
+        amountTotal += amount;
+        hasAmount = true;
+      }
+      const remark = remarkText(record, options.ctx);
+      rows.push([
+        serial,
+        plainText(record.processInstanceNo, options.ctx),
+        group.categoryLabel,
+        group.formName,
+        remark.slice(0, SUMMARY_REMARK_LIMIT),
+        plainText(record.startUserName, options.ctx),
+        options.ctx.dictLabel
+          ? plainText(
+              options.ctx.dictLabel('流程实例的结果', record.result),
+              options.ctx
+            )
+          : '',
+        detailCount,
+        amount,
+        formatDateTime(record.createTime)
+      ]);
+    });
+  });
+  const totalRow = header.map((label, index) => {
+    if (index === 0) return '合计';
+    if (index === 8) return hasAmount ? amountTotal : '';
+    return '';
+  });
+  return {
+    sheetName: SUMMARY_SHEET,
+    title: '行政审批记录·汇总',
+    filterText: options.filterText,
+    metaText: options.metaText,
+    header,
+    rows,
+    totalRow,
+    merges: []
+  };
+}
+
+/** 生成整个 workbook:汇总页 + 每个单据一页(列取该单据自己的模板字段) */
+export function createExportWorkbook(options) {
+  const groups = options.groups || [];
+  const workbook = XLSX.utils.book_new();
+  const used = {};
+  const ctx = options.ctx || {};
+  if (groups.length) {
+    const summary = buildSummarySpec(groups, {
+      ...options,
+      ctx
+    });
+    summary.sheetName = safeSheetName(summary.sheetName, used);
+    appendSheet(workbook, summary);
+  }
+  groups.forEach((group) => {
+    const { columns, fields, subGroups, snapshot } = buildGroupColumns(
+      group,
+      ctx
+    );
+    const body = snapshot
+      ? buildSnapshotRows(group, fields, ctx)
+      : buildGroupRows(group, columns, ctx, subGroups);
+    const title = group.categoryLabel
+      ? group.categoryLabel + ' · ' + group.formName
+      : group.formName;
+    appendSheet(workbook, {
+      sheetName: safeSheetName(
+        group.categoryLabel
+          ? group.categoryLabel + '-' + group.formName
+          : group.formName,
+        used
+      ),
+      title,
+      filterText: options.filterText,
+      metaText: options.formMetaText
+        ? options.formMetaText(group, body.rows.length)
+        : options.metaText,
+      header: columns.map((column) => column.label),
+      rows: body.rows,
+      merges: body.merges,
+      totalText: '合计:' + body.rows.length + ' 行'
+    });
+  });
+  if (!workbook.SheetNames.length) {
+    XLSX.utils.book_append_sheet(
+      workbook,
+      XLSX.utils.aoa_to_sheet([['没有可导出的记录']]),
+      '行政审批记录'
+    );
+  }
+  return workbook;
+}
+
+/** 浏览器触发下载;node 环境写入文件(便于自验证) */
+export function writeWorkbook(workbook, fileName) {
+  XLSX.writeFile(workbook, fileName);
+}
+
+/** 各单据页第 3 行元信息(导出时间 + 记录数 + 明细行数) */
+export function buildGroupMetaText(options) {
+  return (
+    '导出时间:' +
+    dateClockText(options.date) +
+    ' 记录数:' +
+    (options.recordCount || 0) +
+    ' 条' +
+    (options.detailCount ? ' / 明细 ' + options.detailCount + ' 行' : '')
+  );
+}
+
+/** 汇总页第 3 行元信息 */
+export function buildMetaText(options) {
+  return (
+    '页签:' +
+    (options.tabLabel || '全部记录') +
+    ' 导出时间:' +
+    dateClockText(options.date) +
+    ' 导出人:' +
+    (options.exporter || '') +
+    ' 记录数:' +
+    (options.total || 0) +
+    ' 条'
+  );
+}

+ 206 - 46
src/views/bpm/collaborative/index.vue

@@ -67,30 +67,27 @@
             <div class="filter-container">
               <el-form
                 class="ele-form-search"
+                label-width="100px"
                 @keyup.enter.native="handleSearch"
                 @submit.native.prevent
               >
-                <el-row :gutter="20" style="row-gap: 20px">
-                  <el-col v-bind="{ span: 5 }">
-                    <el-form-item
-                      label="关键字:"
-                      prop="keyword"
-                      label-width="70px"
-                    >
+                <el-row :gutter="16">
+                  <el-col v-bind="queryItemGrid">
+                    <el-form-item label="关键字:" prop="keyword">
                       <el-input
-                        style="width: 100%"
-                        placeholder="请输入"
                         v-model="params.keyword"
+                        placeholder="请输入关键字"
+                        clearable
                       ></el-input>
                     </el-form-item>
                   </el-col>
-                  <el-col v-bind="{ span: 5 }">
-                    <el-form-item label="分类:" label-width="60px">
+                  <el-col v-bind="queryItemGrid">
+                    <el-form-item label="分类:" prop="dictType">
                       <el-select
-                        style="width: 100%"
                         v-model="params.dictType"
-                        @change="changeDictTypeChange"
+                        placeholder="请选择分类"
                         clearable
+                        @change="changeDictTypeChange"
                       >
                         <el-option
                           v-for="(item, index) in dictList[
@@ -103,13 +100,13 @@
                       </el-select>
                     </el-form-item>
                   </el-col>
-                  <el-col v-bind="{ span: 5 }">
-                    <el-form-item label="单据:" label-width="60px">
+                  <el-col v-bind="queryItemGrid">
+                    <el-form-item label="单据:" prop="formId">
                       <el-select
-                        style="width: 100%"
                         v-model="params.formId"
-                        @change="changeFormIdChange"
+                        placeholder="请选择单据"
                         clearable
+                        @change="changeFormIdChange"
                       >
                         <el-option
                           v-for="(item, index) in templateList[params.dictType]"
@@ -120,40 +117,29 @@
                       </el-select>
                     </el-form-item>
                   </el-col>
-                  <el-col v-bind="{ span: 4 }">
-                    <el-form-item
-                      label="结果:"
-                      prop="result"
-                      label-width="60px"
-                    >
+                  <el-col v-bind="queryItemGrid">
+                    <el-form-item label="结果:" prop="result">
                       <DictSelection
                         style="width: 100%; display: block"
                         dictName="流程实例的结果"
+                        placeholder="请选择结果"
                         clearable
                         v-model="params.result"
                       >
                       </DictSelection>
                     </el-form-item>
                   </el-col>
-                  <el-col v-bind="{ span: 5 }">
-                    <el-form-item
-                      label="发起人:"
-                      prop="startUserName"
-                      label-width="70px"
-                    >
+                  <el-col v-bind="queryItemGrid">
+                    <el-form-item label="发起人:" prop="startUserName">
                       <el-input
-                        style="width: 100%"
                         v-model="params.startUserName"
+                        placeholder="请输入发起人"
                         clearable
                       ></el-input>
                     </el-form-item>
                   </el-col>
-                  <el-col v-bind="{ span: 7 }">
-                    <el-form-item
-                      label="创建时间:"
-                      prop="createTime1"
-                      label-width="90px"
-                    >
+                  <el-col v-bind="queryDateGrid">
+                    <el-form-item label="创建时间:" prop="createTime1">
                       <el-date-picker
                         v-model="createTime1"
                         style="width: 100%"
@@ -167,12 +153,8 @@
                       />
                     </el-form-item>
                   </el-col>
-                  <el-col v-bind="{ span: 4 }">
-                    <el-form-item
-                      label=""
-                      prop="createTime1"
-                      label-width="90px"
-                    >
+                  <el-col v-bind="queryActionGrid">
+                    <el-form-item label-width="0">
                       <div class="ele-form-actions">
                         <el-button
                           type="primary"
@@ -211,6 +193,15 @@
                 >
                   打印
                 </el-button>
+                <el-button
+                  type="primary"
+                  class="el-icon-download"
+                  size="small"
+                  :loading="exportLoading"
+                  @click="handleExport"
+                >
+                  导出
+                </el-button>
               </template>
               <template v-slot:formName="{ row }">
                 <el-link
@@ -358,6 +349,18 @@
   import tabMixins from '@/mixins/tableColumnsMixin';
   import { getGroupUserTree } from '@/api/main';
   import { getToken, getCurrentUser } from '@/utils/token-util';
+  import {
+    buildExportFileName,
+    buildFilterText,
+    buildGroupMetaText,
+    buildMetaText,
+    createExportWorkbook,
+    EXPORT_PAGE_SIZE,
+    groupRecordsByForm,
+    mapListRecord,
+    writeWorkbook
+  } from './export/recordExport';
+  import BLANK_TABLE_HEADERS from '@/BIZComponents/processSubmitDialog/components/blank_table_headers.json';
 
   // 默认表单数据
   const defaultParams = {
@@ -393,6 +396,7 @@
         formColumnList: [],
         createTime1: [],
         selection: [],
+        exportLoading: false,
         // 个人 / 部门 / 通知我的
         activeName: 'user',
         columnsVersion: 1,
@@ -519,6 +523,60 @@
         ];
       },
 
+      // 查询条件栅格:大屏一行 4 项(6×4=24),中屏一行 2 项
+      queryItemGrid() {
+        return this.styleResponsive ? { lg: 6, md: 12 } : { span: 6 };
+      },
+      // 创建时间占两格,日期区间输入不挤压
+      queryDateGrid() {
+        return this.styleResponsive ? { lg: 12, md: 24 } : { span: 12 };
+      },
+      // 操作按钮占最后一格并靠右,正好贴住栅格右边缘
+      queryActionGrid() {
+        return this.styleResponsive ? { lg: 6, md: 24 } : { span: 6 };
+      },
+      // 当前页签名称,用于文件名与导出元信息
+      currentTabLabel() {
+        const tab = this.tabOptions.find(
+          (item) => item.name === this.activeName
+        );
+        return tab ? tab.label : '';
+      },
+      // 导出 Excel 第 2 行的筛选条件文案(空条件写「全部」)
+      exportFilterText() {
+        let [createTimeBegin, createTimeEnd] = this.createTime1 || [];
+        const form =
+          this.defaultTemplateList.find(
+            (item) => item.id == this.params.formId
+          ) || {};
+        return buildFilterText([
+          { label: '页签', value: this.currentTabLabel },
+          {
+            label: '分类',
+            value: this.params.dictType
+              ? this.getDictV('collaborative_type', this.params.dictType)
+              : ''
+          },
+          { label: '单据', value: this.params.formId ? form.name : '' },
+          {
+            label: '结果',
+            value: this.params.result
+              ? this.getDictValue('流程实例的结果', this.params.result)
+              : ''
+          },
+          { label: '发起人', value: this.params.startUserName },
+          { label: '关键字', value: this.params.keyword },
+          {
+            label: '创建时间',
+            value:
+              createTimeBegin && createTimeEnd
+                ? createTimeBegin.slice(0, 10) +
+                  ' ~ ' +
+                  createTimeEnd.slice(0, 10)
+                : ''
+          }
+        ]);
+      },
       getUserName() {
         return (id) => {
           if (!id) return '';
@@ -776,6 +834,91 @@
         }
         this.$refs.printService.printRows(this.selection);
       },
+      /* 导出取数:复用当前页签的列表接口与筛选条件 */
+      requestPage(pageNo, pageSize) {
+        let [createTimeBegin, createTimeEnd] = this.createTime1 || [];
+        const apiName =
+          this.apiMap[this.activeName] || 'getProcessInstancePage';
+        return this.callApi(
+          apiName,
+          pageNo,
+          pageSize,
+          createTimeBegin,
+          createTimeEnd
+        );
+      },
+      /* 导出取值口径:字典、用户/部门翻译、摘要字段、明细子表表头 */
+      exportContext() {
+        return {
+          dictLabel: (code, value) => this.getDictV(code, value),
+          formatValue: (value) => this.formatValue(value),
+          remarkItems: (row) => this.getRowRemarkList(row),
+          userNames: (id) => this.getUserName(id),
+          deptNames: (value) => this.getDeptName(value),
+          deptName: (value) => this.getDeptName(value),
+          deptUserNames: (value) => this.getDeptUserName(value),
+          subtableColumns: (model) => BLANK_TABLE_HEADERS[model] || null
+        };
+      },
+      /* 点击导出:按当前页签 + 当前筛选条件直接导出全部记录 */
+      async handleExport() {
+        if (this.exportLoading) return;
+        this.exportLoading = true;
+        try {
+          const records = await this.fetchAllRecords();
+          if (!records.length) {
+            this.$message.warning('当前条件下没有可导出的记录');
+            return;
+          }
+          // 按单据分组:每个单据一张 Sheet,列取该单据自己的模板字段
+          const groups = groupRecordsByForm(records, (code, value) =>
+            this.getDictV(code, value)
+          );
+          const fileName = buildExportFileName(this.currentTabLabel);
+          const workbook = createExportWorkbook({
+            groups,
+            ctx: this.exportContext(),
+            filterText: this.exportFilterText,
+            metaText: buildMetaText({
+              tabLabel: this.currentTabLabel,
+              exporter: (this.$store.state.user.info || {}).name,
+              total: records.length
+            }),
+            formMetaText: (group, rowCount) =>
+              buildGroupMetaText({
+                recordCount: group.records.length,
+                detailCount: Math.max(rowCount - group.records.length, 0)
+              })
+          });
+          writeWorkbook(workbook, fileName);
+          this.$message.success(
+            '导出成功,正在下载:' +
+              fileName +
+              '(' +
+              workbook.SheetNames.length +
+              ' 个 Sheet)'
+          );
+        } catch (e) {
+          this.$message.error(e.message || '导出失败,请稍后重试');
+        } finally {
+          this.exportLoading = false;
+        }
+      },
+      /* 顺序分批拉取当前条件下的全部记录(后端 pageSize 上限 100) */
+      async fetchAllRecords() {
+        const records = [];
+        let pageNo = 1;
+        let count = 0;
+        do {
+          const data = await this.requestPage(pageNo, EXPORT_PAGE_SIZE);
+          const list = data.list || [];
+          count = data.count || 0;
+          list.forEach((item) => records.push(mapListRecord(item)));
+          if (!list.length) break;
+          pageNo += 1;
+        } while (records.length < count);
+        return records;
+      },
       /**  */
       handleAudit(row) {
         this.$refs.detailRef.open(row.id);
@@ -834,11 +977,19 @@
   }
 
   .filter-container {
-    margin-bottom: 10px;
-    margin-top: 10px;
+    margin-bottom: 12px;
+    margin-top: 20px;
+    padding: 4px 0 0;
 
-    ::v-deep .el-form-item {
-      margin-bottom: 15px;
+    /* el-row 是浮动布局,row-gap 无效,行间距只能靠 form-item 的下外边距;
+       styles/transition/common.scss 的 .el-form-box .ele-form-search .el-form-item
+       用 !important 把外边距压成 0,这里必须同权重更高 + !important 才能生效 */
+    ::v-deep .ele-form-search .el-form-item {
+      margin-bottom: 24px !important;
+    }
+
+    ::v-deep .el-form-item__content {
+      line-height: 32px;
     }
 
     ::v-deep .el-form-item .el-input,
@@ -847,6 +998,15 @@
     ::v-deep .el-form-item .ele-select {
       width: 100%;
     }
+
+    ::v-deep .el-form-item__label {
+      padding-right: 12px;
+      white-space: nowrap;
+    }
+
+    ::v-deep .ele-form-actions {
+      text-align: right;
+    }
   }
 
   .content-box {