云
6 天以前 21599300cc73ff7384b74cc5e4ac2cbd82bdc293
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
<script lang="ts" setup>
  import type { VbenFormSchema } from "#/adapter/form";
  import type { MdmItemApi } from "#/api/mdm/item";
  import type { MesProBagCodeApi } from "#/api/mes/pro/bagCode";
 
  import { computed, markRaw, ref } from "vue";
 
  import { useVbenModal } from "@vben/common-ui";
 
  import { Button, message, Progress } from "ant-design-vue";
 
  import { useVbenForm } from "#/adapter/form";
  import { generateBagCodes } from "#/api/mes/pro/bagCode";
  import { getUnit } from "#/api/mdm/unit";
  import { MdmItemSelect } from "#/views/basicData/mdm/components";
 
  import { isFinalTaskStatus, useGenerateTask } from "./use-generate-task";
 
  defineOptions({ name: "MesProBagCodeGenerateForm" });
 
  const emit = defineEmits(["success"]);
 
  // 所选品种主计量单位类型:48袋/100袋 -> 每托 N 袋;吨 -> 无托盘直接输袋码数
  const unitType = ref("");
  const bagsPerPallet = ref<number | null>(null);
  const isTon = ref(false);
  const unitTypeError = ref(false);
  const palletCountVal = ref<number | null>(null);
  const bagCountVal = ref<number | null>(null);
 
  /** 幂等键:打开弹窗时生成,网络重试复用;失败后重新生成 */
  const requestId = ref("");
 
  function newRequestId() {
    return `${Date.now()}-${Math.random().toString(36).slice(2)}-${Math.random()
      .toString(36)
      .slice(2)}`;
  }
 
  /** 换算/配置提示文案 */
  const tipText = computed(() => {
    if (unitTypeError.value) {
      return "该品种主计量单位未配置类型(仅支持 48袋/100袋/吨),请先前往「计量单位」维护后重试";
    }
    if (!unitType.value) {
      return "";
    }
    if (isTon.value) {
      return `计量单位类型为「吨」:不生成托盘,袋码仅绑定生产批次${
        bagCountVal.value ? `,将生成 ${bagCountVal.value} 个袋码` : ""
      }`;
    }
    const per = bagsPerPallet.value ?? 0;
    const count = palletCountVal.value ?? 0;
    return `计量单位类型为「${unitType.value}」:每托 ${per} 袋${
      count > 0
        ? ` × ${count} 托 = ${per * count} 个袋码,将自动生成 ${count} 个托盘并绑定`
        : ",请输入托盘数"
    }`;
  });
 
  function buildSchema(): VbenFormSchema[] {
    const schema: VbenFormSchema[] = [
      {
        fieldName: "itemId",
        label: "品种",
        component: markRaw(MdmItemSelect),
        componentProps: {
          placeholder: "请选择品种(产品品种)",
          onChange: handleItemChange,
        },
        rules: "selectRequired",
      },
    ];
    if (bagsPerPallet.value) {
      schema.push({
        fieldName: "palletCount",
        label: "托盘数",
        component: "InputNumber",
        componentProps: {
          class: "!w-full",
          min: 1,
          placeholder: "请输入托盘数(系统自动生成托盘并均分绑定袋码)",
          precision: 0,
          onChange: (value: number | string) => {
            palletCountVal.value = Number(value) || null;
          },
        },
        rules: "required",
      });
    }
    if (isTon.value) {
      schema.push({
        fieldName: "bagCount",
        label: "袋码数",
        component: "InputNumber",
        componentProps: {
          class: "!w-full",
          min: 1,
          placeholder: "请输入袋码数(吨品种无托盘,袋码仅绑定批次)",
          precision: 0,
          onChange: (value: number | string) => {
            bagCountVal.value = Number(value) || null;
          },
        },
        rules: "required",
      });
    }
    schema.push({
      fieldName: "remark",
      label: "备注",
      component: "Textarea",
      componentProps: {
        placeholder: "请输入备注",
        rows: 2,
      },
    });
    return schema;
  }
 
  /** 选择品种后读取主计量单位类型,动态切换托盘数/袋码数输入 */
  async function handleItemChange(item?: MdmItemApi.Item) {
    unitType.value = "";
    bagsPerPallet.value = null;
    isTon.value = false;
    unitTypeError.value = false;
    palletCountVal.value = null;
    bagCountVal.value = null;
    if (item?.unitMeasureId) {
      try {
        const unit = await getUnit(item.unitMeasureId);
        const type = (unit?.type ?? "").trim();
        unitType.value = type;
        if (type === "吨") {
          isTon.value = true;
        } else {
          const matcher = /^(\d{1,5})袋$/.exec(type);
          if (matcher) {
            bagsPerPallet.value = Number(matcher[1]);
          } else {
            unitTypeError.value = true;
          }
        }
      } catch {
        unitTypeError.value = true;
      }
    } else if (item) {
      unitTypeError.value = true;
    }
    await formApi.setState({ schema: buildSchema() });
  }
 
  const [Form, formApi] = useVbenForm({
    commonConfig: {
      componentProps: {
        class: "w-full",
      },
      labelWidth: 100,
    },
    layout: "horizontal",
    schema: [],
    showDefaultActions: false,
  });
 
  const [Modal, modalApi] = useVbenModal({
    async onConfirm() {
      const { valid } = await formApi.validate();
      if (!valid) return;
      if (task.value && !isFinalTaskStatus(task.value.status)) return;
      if (unitTypeError.value) {
        message.warning(tipText.value);
        return;
      }
      modalApi.lock();
      let asyncStarted = false;
      try {
        const values =
          (await formApi.getValues()) as MesProBagCodeApi.GenerateParams;
        const data: MesProBagCodeApi.GenerateParams = {
          itemId: values.itemId,
          remark: values.remark,
          requestId: requestId.value,
        };
        if (isTon.value) {
          data.bagCount = values.bagCount;
        } else {
          data.palletCount = values.palletCount;
        }
        const result = await generateBagCodes(data);
        if (result.async && result.taskId) {
          asyncStarted = true;
          modalApi.unlock();
          // 大批量已转后台:保持弹窗打开,展示进度并轮询
          startGenerateTask({
            id: result.taskId,
            status: 10,
            statusName: "排队中",
            progress: 0,
            totalCount: result.totalCount,
            finishedCount: 0,
            palletCount: result.palletCount,
            uuid: result.uuid,
          });
          return;
        }
        message.success(
          `已成功生成 ${result.totalCount} 条袋码` +
            (result.palletCount
              ? `,并自动生成 ${result.palletCount} 个托盘`
              : ""),
        );
        emit("success");
        await modalApi.close();
      } finally {
        if (!asyncStarted) modalApi.unlock();
      }
    },
    async onOpenChange(isOpen: boolean) {
      if (!isOpen) {
        stopGenerateTaskPolling();
        return;
      }
      modalApi.lock();
      try {
        resetGenerateTask();
        requestId.value = newRequestId();
        unitType.value = "";
        bagsPerPallet.value = null;
        isTon.value = false;
        unitTypeError.value = false;
        palletCountVal.value = null;
        bagCountVal.value = null;
        await formApi.setValues({
          itemId: undefined,
          palletCount: undefined,
          bagCount: undefined,
          remark: undefined,
        });
        await formApi.setState({ schema: buildSchema() });
      } finally {
        modalApi.unlock();
      }
    },
  });
 
  const {
    task,
    canceling: generateTaskCanceling,
    cancel: cancelGenerateTask,
    reset: resetGenerateTask,
    stopPolling: stopGenerateTaskPolling,
    start: startGenerateTask,
  } = useGenerateTask(modalApi, {
    onSuccess: () => emit("success"),
    onFailed: () => {
      // 失败后换新的幂等键,允许用户直接重新提交
      requestId.value = newRequestId();
    },
  });
</script>
 
<template>
  <Modal title="生成袋码数据包" class="w-2/5">
    <template v-if="task">
      <div class="mx-4 mb-2">
        <p class="mb-1 text-sm">
          任务 #{{ task.id }} · {{ task.statusName }}
        </p>
        <p class="mb-2 text-sm text-gray-500">
          已生成 {{ task.finishedCount ?? 0 }} / {{ task.totalCount ?? 0 }} 条
        </p>
        <Progress
          :percent="task.progress ?? 0"
          :status="
            task.status === 50
              ? 'exception'
              : task.status === 30
                ? 'success'
                : 'active'
          "
        />
        <p v-if="task.errorMsg" class="mt-2 text-sm text-red-500">
          {{ task.errorMsg }}
        </p>
        <div class="mt-4 flex justify-end">
          <Button
            danger
            size="small"
            :loading="generateTaskCanceling"
            @click="cancelGenerateTask"
          >
            取消生成
          </Button>
        </div>
      </div>
    </template>
    <template v-else>
      <Form class="mx-4" />
      <div
        v-if="tipText"
        class="mx-4 mb-2 rounded bg-gray-50 px-3 py-2 text-sm"
        :class="unitTypeError ? 'text-red-500' : 'text-gray-500'"
      >
        {{ tipText }}
      </div>
    </template>
  </Modal>
</template>