gaoluyang
2026-11-03 2d8b1a28fa5c8b852f0d0078bac4894bfb4abed5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
<script setup lang="ts">
  import { computed, ref } from "vue";
  import { onShow, onPullDownRefresh } from "@dcloudio/uni-app";
  import { getSimpleDictDataList, type DictData } from "../../../../api/crm";
  import {
    cancelProcessInstanceByStartUser,
    getCategorySimpleList,
    getProcessDefinition,
    getProcessInstanceMyPage,
    getSimpleProcessDefinitionList,
    type BpmCategory,
    type BpmProcessDefinition,
    type BpmProcessInstance,
  } from "../../../../api/bpm";
  import { useAuth } from "../../../../stores/auth";
  import { DICT, MODEL_FORM_TYPE, PROCESS_INSTANCE_STATUS, dateTimeText, dictLabel, summaryInline, toast } from "../../shared";
  import { confirmModal } from "../../shared";
  import PickerSheet from "../../../mes/process-design/components/PickerSheet.vue";
  import type { SheetOption } from "../../../mes/process-design/shared";
  import { statusToneClass } from "../../../../utils/status";
 
  const { hasPermission, isLoggedIn, state } = useAuth();
 
  const keyword = ref("");
  const rows = ref<BpmProcessInstance[]>([]);
  const dicts = ref<DictData[]>([]);
  const categories = ref<BpmCategory[]>([]);
  const definitions = ref<BpmProcessDefinition[]>([]);
  const pageNo = ref(1);
  const total = ref(0);
  const loading = ref(false);
  const loadError = ref("");
 
  /** 与 web 端 processInstance/index.vue 一致(该模块无 :query 码,不做加载守卫) */
  const canDetail = computed(() => hasPermission("bpm:process-instance:query"));
  const canCancel = computed(() => hasPermission("bpm:process-instance:cancel"));
  const canCreate = computed(() => hasPermission("bpm:process-instance:create"));
  const hasMore = computed(() => rows.value.length < total.value);
 
  /* ---------- 筛选 ---------- */
 
  const filter = ref<{
    processDefinitionId?: string;
    category?: string;
    status?: number;
  }>({});
 
  const statusFilterText = computed(() =>
    filter.value.status === undefined
      ? "全部状态"
      : dictLabel(dicts.value, DICT.BPM_PROCESS_INSTANCE_STATUS, filter.value.status, "全部状态"),
  );
 
  const definitionFilterText = computed(() => {
    if (!filter.value.processDefinitionId) return "全部流程";
    return (
      definitions.value.find(item => String(item.id) === String(filter.value.processDefinitionId))
        ?.name ?? "全部流程"
    );
  });
 
  const categoryFilterText = computed(() => {
    if (!filter.value.category) return "全部分类";
    return (
      categories.value.find(item => item.code === filter.value.category)?.name ?? "全部分类"
    );
  });
 
  const statusOptions = ref<SheetOption[]>([]);
  const definitionOptions = ref<SheetOption[]>([]);
  const categoryOptions = ref<SheetOption[]>([]);
 
  const showStatus = ref(false);
  const showDefinition = ref(false);
  const showCategory = ref(false);
 
  function openStatus() {
    statusOptions.value = [
      { key: "", label: "全部状态" },
      ...dictOptionsFor(DICT.BPM_PROCESS_INSTANCE_STATUS),
    ];
    showStatus.value = true;
  }
 
  function openDefinition() {
    definitionOptions.value = [
      { key: "", label: "全部流程" },
      ...definitions.value.map(item => ({ key: item.id as string, label: item.name || "--" })),
    ];
    showDefinition.value = true;
  }
 
  function openCategory() {
    categoryOptions.value = [
      { key: "", label: "全部分类" },
      ...categories.value.map(item => ({ key: item.code as string, label: item.name || "--" })),
    ];
    showCategory.value = true;
  }
 
  function dictOptionsFor(type: string): SheetOption[] {
    return dicts.value
      .filter(item => item.dictType === type)
      .map(item => ({ key: item.value, label: item.label }));
  }
 
  function onStatusPicked(keys: Array<number | string>) {
    const key = keys[0];
    filter.value.status =
      key === undefined || key === "" ? undefined : Number(key);
    load(true);
  }
 
  function onDefinitionPicked(keys: Array<number | string>) {
    const key = keys[0];
    filter.value.processDefinitionId =
      key === undefined || key === "" ? undefined : String(key);
    load(true);
  }
 
  function onCategoryPicked(keys: Array<number | string>) {
    const key = keys[0];
    filter.value.category = key === undefined || key === "" ? undefined : String(key);
    load(true);
  }
 
  function resetFilter() {
    filter.value = {};
    keyword.value = "";
    load(true);
  }
 
  /* ---------- 数据加载 ---------- */
 
  function statusText(row: BpmProcessInstance) {
    // web 端:审批中且有在办任务时展示“昵称(节点名) 审批中”,这里简化为状态文案 + 当前节点
    if (row.status === PROCESS_INSTANCE_STATUS.RUNNING && row.tasks?.length) {
      const task = row.tasks[0];
      const nickname = task.assigneeUser?.nickname || "待审批";
      const nodeName = task.name || "审批";
      if (row.tasks.length > 1) return `${nickname}等 ${row.tasks.length} 人 (${nodeName})审批中`;
      return `${nickname} (${nodeName}) 审批中`;
    }
    return dictLabel(dicts.value, DICT.BPM_PROCESS_INSTANCE_STATUS, row.status, "--");
  }
  function statusClass(row: BpmProcessInstance) {
    return statusToneClass(row.status, statusText(row));
  }
 
  async function load(reset = false) {
    if (!state.accessToken || loading.value) return;
    if (reset) {
      pageNo.value = 1;
      rows.value = [];
    }
    loading.value = true;
    loadError.value = "";
    try {
      if (!dicts.value.length) dicts.value = await getSimpleDictDataList(state.accessToken);
      if (!categories.value.length) {
        categories.value = (await getCategorySimpleList(state.accessToken)) || [];
      }
      if (!definitions.value.length) {
        definitions.value = (await getSimpleProcessDefinitionList(state.accessToken))?.list || [];
      }
      const data = await getProcessInstanceMyPage(state.accessToken, {
        pageNo: pageNo.value,
        pageSize: 15,
        name: keyword.value.trim() || undefined,
        processDefinitionId: filter.value.processDefinitionId,
        category: filter.value.category,
        status: filter.value.status,
      });
      total.value = data.total;
      rows.value = reset ? data.list : [...rows.value, ...data.list];
      pageNo.value += 1;
    } catch (error) {
      loadError.value = error instanceof Error ? error.message : "我的流程加载失败";
    } finally {
      loading.value = false;
    }
  }
 
  /* ---------- 操作 ---------- */
 
  function goDetail(row: BpmProcessInstance) {
    if (!row.id) return;
    uni.navigateTo({
      url: `/pages/bpm/process-instance/detail?id=${encodeURIComponent(row.id)}`,
    });
  }
 
  /** 取消流程:与 web 端 prompt 取消原因一致 */
  function cancelInstance(row: BpmProcessInstance) {
    if (!row.id) return;
    uni.showModal({
      title: "取消流程",
      editable: true,
      placeholderText: "请输入取消原因",
      success: async res => {
        if (!res.confirm) return;
        const reason = String(res.content || "").trim();
        if (!reason) {
          toast("请输入取消原因");
          return;
        }
        try {
          await cancelProcessInstanceByStartUser(state.accessToken as string, {
            id: row.id as string,
            reason,
          });
          toast("已取消");
          load(true);
        } catch (error) {
          toast(error instanceof Error ? error.message : "取消失败");
        }
      },
    });
  }
 
  /**
   * 重新发起:**直接进入该流程的表单页**,不经过「发起流程」列表页。
   *
   * 对齐 web 端 processInstance/index.vue 的 handleCreate 语义:
   *  - 业务表单(CUSTOM,formType=20):web 跳到该业务的创建页(formCustomCreatePath?id=businessKey);
   *    App 端没有这些业务页面,只能提示回 Web 端发起。
   *  - 流程表单(NORMAL,formType=10):打开表单页并带 processInstanceId,由表单页回填历史表单值。
   *
   * 定义取「该 key 的最新版本」(web 端也是在启用中的定义列表里按 key 匹配),
   * 拿不到就回退到流程实例自己绑定的定义 id。
   */
  async function reCreate(row: BpmProcessInstance) {
    if (!row.id || !state.accessToken) return;
    const boundDefinitionId = row.processDefinitionId || row.processDefinition?.id;
    let targetDefinitionId = boundDefinitionId ? String(boundDefinitionId) : "";
    try {
      if (targetDefinitionId) {
        const def = await getProcessDefinition(state.accessToken, { id: targetDefinitionId });
        if (Number(def?.formType) === MODEL_FORM_TYPE.CUSTOM) {
          toast("该流程为业务表单,请在 Web 端重新发起");
          return;
        }
        // 重新发起使用该 key 的最新版本定义
        if (def?.key) {
          const latest = await getProcessDefinition(state.accessToken, { key: def.key });
          if (latest?.id) targetDefinitionId = String(latest.id);
        }
      }
    } catch {
      // 拿不到流程定义时不拦截,交给表单页兜底解析
    }
    const params = [`processInstanceId=${encodeURIComponent(row.id)}`];
    if (targetDefinitionId) params.unshift(`id=${encodeURIComponent(targetDefinitionId)}`);
    uni.navigateTo({ url: `/pages/bpm/process-instance/create/form?${params.join("&")}` });
  }
 
  async function handleDelete() {
    const ok = await confirmModal("确认删除?");
    if (ok) return;
  }
 
  onShow(() => {
    load(true);
  });
 
  onPullDownRefresh(async () => {
    await load(true);
    uni.stopPullDownRefresh();
  });
</script>
 
<template>
  <view class="page">
    <template v-if="isLoggedIn">
      <view class="search">
        <input
          v-model="keyword"
          placeholder="搜索流程名称"
          confirm-type="search"
          @confirm="load(true)"
        />
        <text v-if="keyword" @click="keyword = ''; load(true)">清除</text>
      </view>
 
      <view class="filters">
        <text class="filter" @click="openStatus">{{ statusFilterText }}</text>
        <text class="filter" @click="openDefinition">{{ definitionFilterText }}</text>
        <text class="filter" @click="openCategory">{{ categoryFilterText }}</text>
        <text class="reset" @click="resetFilter">重置</text>
      </view>
 
      <scroll-view class="content" scroll-y lower-threshold="80" @scrolltolower="hasMore && load()">
        <view v-if="loadError" class="state error" @click="load(true)">{{ loadError }},点击重试</view>
        <view v-else-if="rows.length">
          <view v-for="row in rows" :key="row.id" class="row">
            <view class="head" @click="canDetail && goDetail(row)">
              <view class="head-main">
                <text class="name">{{ row.name || '未命名流程' }}</text>
                <text class="code">{{ row.categoryName || '未分类' }}</text>
              </view>
              <text :class="['status', statusClass(row)]">{{ statusText(row) }}</text>
            </view>
            <view class="grid">
              <text class="summary">{{ summaryInline(row.summary) }}</text>
              <text>发起时间:{{ dateTimeText(row.startTime) }}</text>
              <text>结束时间:{{ dateTimeText(row.endTime) }}</text>
            </view>
            <view class="actions">
              <text v-if="canDetail" class="action" @click="goDetail(row)">详情</text>
              <text
                v-if="canCancel && row.status === 1"
                class="action danger"
                @click="cancelInstance(row)"
              >
                取消
              </text>
              <text
                v-if="canCreate && row.status !== 1"
                class="action"
                @click="reCreate(row)"
              >
                重新发起
              </text>
            </view>
          </view>
          <text class="more">{{ loading ? '加载中...' : hasMore ? '上拉加载更多' : '没有更多了' }}</text>
        </view>
        <view v-else class="state">{{ loading ? '加载中...' : '暂无流程记录' }}</view>
      </scroll-view>
    </template>
    <view v-else class="state">登录后查看我的流程</view>
 
    <PickerSheet
      v-model:show="showStatus"
      title="流程状态"
      :items="statusOptions"
      :selected-keys="filter.status === undefined ? [] : [filter.status]"
      @confirm="onStatusPicked"
    />
    <PickerSheet
      v-model:show="showDefinition"
      title="所属流程"
      :items="definitionOptions"
      :selected-keys="filter.processDefinitionId ? [filter.processDefinitionId] : []"
      @confirm="onDefinitionPicked"
    />
    <PickerSheet
      v-model:show="showCategory"
      title="流程分类"
      :items="categoryOptions"
      :selected-keys="filter.category ? [filter.category] : []"
      @confirm="onCategoryPicked"
    />
  </view>
</template>
 
<style lang="scss" scoped>
  .page{height:100vh;display:flex;flex-direction:column;padding:0 30rpx;box-sizing:border-box;overflow:hidden;background:#f3f6fb}
  .search{display:flex;align-items:center;height:80rpx;margin:20rpx 0 12rpx;padding:0 20rpx;background:#fff;border-radius:16rpx;box-shadow:0 8rpx 20rpx rgba(43,69,107,.06)}
  .search input{flex:1;font-size:27rpx}
  .search text{color:var(--color-primary, #1769d8);font-size:24rpx}
  .filters{display:flex;align-items:center;gap:12rpx;margin-bottom:16rpx;overflow:hidden}
  .filter{flex:none;max-width:210rpx;overflow:hidden;padding:10rpx 20rpx;color:#3d5069;font-size:24rpx;text-overflow:ellipsis;white-space:nowrap;background:#fff;border:1rpx solid #dbe4ef;border-radius:999rpx}
  .reset{flex:none;margin-left:auto;color:var(--color-primary, #1769d8);font-size:24rpx}
  .content{height:0;flex:1;padding-bottom:60rpx;box-sizing:border-box}
  .row{padding:24rpx 22rpx 18rpx;margin-bottom:18rpx;background:#fff;border-radius:16rpx;box-shadow:0 10rpx 24rpx rgba(43,69,107,.08)}
  .head{display:flex;align-items:flex-start;justify-content:space-between;gap:16rpx}
  .head-main{display:flex;min-width:0;flex:1;flex-direction:column;gap:8rpx}
  .head-main .code{color:#78879b;font-size:23rpx}
  .name{overflow:hidden;color:#20334c;font-size:30rpx;font-weight:600;text-overflow:ellipsis;white-space:nowrap}
  .status{flex:none;max-width:300rpx;padding:8rpx 16rpx;color:#3d5069;font-size:22rpx;background:#eef2f7;border:1rpx solid #cfdae7;border-radius:999rpx}
  .grid{display:grid;gap:10rpx;padding:16rpx 0;margin-top:16rpx;color:#66778c;font-size:23rpx;border-top:1rpx solid #edf1f6}
  .grid text{overflow:hidden;text-overflow:ellipsis}
  .grid .summary{white-space:normal;word-break:break-all}
  .actions{display:flex;justify-content:flex-end;gap:14rpx;padding-top:14rpx;border-top:1rpx solid #edf1f6}
  .action{padding:8rpx 22rpx;color:var(--color-primary, #1769d8);font-size:24rpx;background:#eef4fd;border-radius:999rpx}
  .action.danger{color:#d9534f;background:#fdeeee}
  .more{display:block;padding:16rpx 0 6rpx;color:#93a1b3;font-size:22rpx;text-align:center}
  .state{padding:60rpx 20rpx;color:#8795a8;font-size:25rpx;text-align:center}
  .state.error{color:#c65050}
</style>