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
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
<script lang="ts" setup>
import type { FormType } from '../data';
import type { MesProRouteApi } from '#/api/mes/pro/route';
import type { MesProRouteProcessApi } from '#/api/mes/pro/route/process';
import type { MesProRouteProductApi } from '#/api/mes/pro/route/product';
import type { MesProRouteProductBomApi } from '#/api/mes/pro/route/productbom';
 
import { computed, ref } from 'vue';
import { useVbenModal } from '@vben/common-ui';
import { IconifyIcon } from '@vben/icons';
import { Alert, Button, Empty, message, Steps, Tag } from 'ant-design-vue';
 
import { useVbenForm } from '#/adapter/form';
import { createRoute, getRoute, updateRoute } from '#/api/mes/pro/route';
import { getRouteProcessListByRoute } from '#/api/mes/pro/route/process';
import { getRouteProductListByRoute } from '#/api/mes/pro/route/product';
import { getRouteProductBomList } from '#/api/mes/pro/route/productbom';
 
import { useFormSchema } from '../data';
import MaterialInputList from './material-input-list.vue';
import ProcessList from './process-list.vue';
import ProductList from './product-list.vue';
 
const emit = defineEmits(['success']);
const formType = ref<FormType>('create');
const formData = ref<MesProRouteApi.Route>();
const activeStep = ref(0);
const productList = ref<MesProRouteProductApi.RouteProduct[]>([]);
const processList = ref<MesProRouteProcessApi.RouteProcess[]>([]);
const bomList = ref<MesProRouteProductBomApi.RouteProductBom[]>([]);
 
const isDetail = computed(() => formType.value === 'detail');
const isNew = computed(() => !formData.value?.id);
const routeId = computed(() => formData.value?.id);
const sortedProcessList = computed(() =>
  [...processList.value].sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0)),
);
const title = computed(() =>
  isDetail.value ? '查看工艺路线' : isNew.value ? '新建工艺路线' : '编辑工艺路线',
);
 
const stepItems = [
  { title: '基本信息', description: '路线名称与说明' },
  { title: '产出与入库', description: '产品及报工仓位' },
  { title: '工序与产出', description: '顺序和半成品/成品' },
  { title: '工序投料', description: '按产品与工序配置' },
  { title: '启用前检查', description: '集中检查缺失项' },
];
 
const productsWithWarehouse = computed(() =>
  productList.value.filter((item) => item.warehouseId && item.locationId && item.areaId).length,
);
const processesWithOutput = computed(() =>
  processList.value.filter((item) => item.outputItemIds?.length).length,
);
const lastProcess = computed(() => sortedProcessList.value.at(-1));
const configuredProductIds = computed(
  () => new Set(bomList.value.map((item) => item.productId).filter(Boolean)),
);
const productsWithBom = computed(() => configuredProductIds.value.size);
const reviewIssues = computed(() => {
  const issues: Array<{ step: number; text: string }> = [];
  if (!productList.value.length) issues.push({ step: 1, text: '还没有配置产出产品' });
  const missingWarehouse = productList.value.filter(
    (item) => !item.warehouseId || !item.locationId || !item.areaId,
  );
  if (missingWarehouse.length) {
    issues.push({
      step: 1,
      text: `${missingWarehouse.length} 个产出产品未配置完整仓库、库区和库位`,
    });
  }
  if (!processList.value.length) issues.push({ step: 2, text: '还没有配置生产工序' });
  if (processList.value.length && !processList.value.some((item) => item.keyFlag)) {
    issues.push({ step: 2, text: '未设置关键工序' });
  }
  if (lastProcess.value && !lastProcess.value.outputItemIds?.length) {
    issues.push({
      step: 2,
      text: `末道工序“${lastProcess.value.processName || lastProcess.value.processCode || lastProcess.value.sort}”必须配置成品产出`,
    });
  }
  const lastOutputs = lastProcess.value?.outputs ?? [];
  if (
    lastOutputs.length &&
    lastOutputs.some(
      (output) => output.productId == null || output.productId !== output.itemId,
    )
  ) {
    issues.push({
      step: 2,
      text: '末道工序的成品产出必须归属到自身产品,不能使用“通用”',
    });
  }
  const productIds = new Set(productList.value.map((item) => item.itemId));
  const invalidOutputCount = processList.value.filter((process) =>
    process.outputItemIds?.some((itemId) => !productIds.has(itemId)),
  ).length;
  if (invalidOutputCount) {
    issues.push({
      step: 2,
      text: `${invalidOutputCount} 道工序的产出未包含在路线产出产品中`,
    });
  }
  const noBomProducts = productList.value.filter(
    (item) => item.itemId && !configuredProductIds.value.has(item.itemId),
  );
  if (noBomProducts.length) {
    issues.push({ step: 3, text: `${noBomProducts.length} 个产品还没有配置任何工序投料` });
  }
  return issues;
});
const primaryText = computed(() => {
  if (activeStep.value === stepItems.length - 1) return isDetail.value ? '关闭' : '完成配置';
  if (activeStep.value === 0 && isNew.value) return '保存并配置产出';
  return '下一步';
});
 
const [Form, formApi] = useVbenForm({
  commonConfig: {
    componentProps: { class: 'w-full' },
    formItemClass: 'col-span-1',
    labelWidth: 100,
  },
  layout: 'horizontal',
  schema: [],
  showDefaultActions: false,
  wrapperClass: 'grid-cols-2',
});
 
async function loadConfiguration() {
  if (!routeId.value) return;
  const [products, processes, boms] = await Promise.all([
    getRouteProductListByRoute(routeId.value),
    getRouteProcessListByRoute(routeId.value),
    getRouteProductBomList({ routeId: routeId.value }),
  ]);
  productList.value = products || [];
  processList.value = processes || [];
  bomList.value = boms || [];
}
 
async function saveBaseInformation() {
  const { valid } = await formApi.validate();
  if (!valid) return false;
  modalApi.lock();
  try {
    const data = (await formApi.getValues()) as MesProRouteApi.Route;
    if (!routeId.value) {
      const id = await createRoute(data);
      formData.value = { ...data, id };
      await formApi.setFieldValue('id', id);
      formType.value = 'update';
      message.success('基本信息已保存,请继续配置产出产品和入库位置');
    } else {
      await updateRoute({ ...data, id: routeId.value });
      formData.value = { ...formData.value, ...data, id: routeId.value };
    }
    emit('success');
    return true;
  } finally {
    modalApi.unlock();
  }
}
 
function validateProducts() {
  if (!productList.value.length) {
    message.warning('请至少添加一个产出产品,再配置工序');
    return false;
  }
  if (productsWithWarehouse.value !== productList.value.length) {
    message.warning('请为每个产出产品配置完整的仓库、库区和库位');
    return false;
  }
  return true;
}
 
function validateProcesses() {
  if (!processList.value.length) {
    message.warning('请至少添加一道生产工序');
    return false;
  }
  return true;
}
 
function validateBom() {
  if (productsWithBom.value !== productList.value.length) {
    message.warning('每个产出产品至少要配置一条工序投料');
    return false;
  }
  return true;
}
 
async function goToStep(target: number) {
  if (target < 0 || target >= stepItems.length) return;
  if (target <= activeStep.value || isDetail.value) {
    activeStep.value = target;
    return;
  }
  if (!(await saveBaseInformation())) return;
  await loadConfiguration();
  if (target >= 2 && !validateProducts()) return void (activeStep.value = 1);
  if (target >= 3 && !validateProcesses()) return void (activeStep.value = 2);
  if (target >= 4 && !validateBom()) return void (activeStep.value = 3);
  activeStep.value = target;
}
 
async function handlePrimaryAction() {
  if (activeStep.value === stepItems.length - 1) {
    if (!isDetail.value && reviewIssues.value.length) {
      message.warning('仍有缺失配置,请根据检查结果补充后再完成');
      return;
    }
    await modalApi.close();
    return;
  }
  await goToStep(activeStep.value + 1);
}
 
const [Modal, modalApi] = useVbenModal({
  showConfirmButton: false,
  cancelText: '关闭',
  async onOpenChange(isOpen: boolean) {
    if (!isOpen) {
      formData.value = undefined;
      productList.value = [];
      processList.value = [];
      bomList.value = [];
      activeStep.value = 0;
      return;
    }
    formApi.setState({ schema: useFormSchema(formApi) });
    const data = modalApi.getData<{ formType: FormType; id?: number }>();
    formType.value = data.formType;
    formApi.setDisabled(isDetail.value);
    if (!data.id) return;
    modalApi.lock();
    try {
      formData.value = await getRoute(data.id);
      await formApi.setValues(formData.value);
      await loadConfiguration();
    } finally {
      modalApi.unlock();
    }
  },
});
</script>
 
<template>
  <Modal :title="title" class="w-[94vw] max-w-[1560px]">
    <div class="route-config-shell">
      <header class="route-config-header">
        <div class="min-w-0">
          <div class="flex flex-wrap items-center gap-2">
            <h2 class="m-0 text-lg font-semibold text-gray-900 dark:text-gray-100">
              {{ formData?.name || '新工艺路线' }}
            </h2>
            <Tag :color="isDetail ? 'default' : 'processing'">
              {{ isDetail ? '只读查看' : '配置中' }}
            </Tag>
          </div>
          <p class="mb-0 mt-1 text-sm text-gray-600 dark:text-gray-300">
            工序投料依赖产出产品和工序,因此在工序编排完成后集中配置。
          </p>
        </div>
        <div class="route-config-summary" aria-label="当前配置概览">
          <span>产出 {{ productList.length }}</span>
          <span>工序 {{ processList.length }}</span>
          <span>投料 {{ bomList.length }}</span>
        </div>
      </header>
 
      <Steps
        :current="activeStep"
        :items="stepItems"
        class="route-config-steps"
        responsive
        size="small"
        type="navigation"
        @change="goToStep"
      />
 
      <main class="route-config-content">
        <section v-show="activeStep === 0" class="route-step-panel">
          <div class="route-step-copy">
            <IconifyIcon icon="lucide:route" />
            <div>
              <h3>先定义这条路线是什么</h3>
              <p>编码用于系统识别,名称和说明帮助现场人员快速选择。</p>
            </div>
          </div>
          <Form class="route-base-form" />
        </section>
 
        <section v-if="routeId" v-show="activeStep === 1" class="route-step-panel">
          <Alert
            class="mb-4"
            message="先维护所有可能的工序产出"
            description="实际形成的中间半成品和末道工序的成品都要加入,并分别指定报工后进入的仓库、库区和库位。"
            show-icon
            type="info"
          />
          <ProductList
            :form-type="formType"
            :route-id="routeId"
            @change="productList = $event"
          />
        </section>
 
        <section v-if="routeId" v-show="activeStep === 2" class="route-step-panel">
          <Alert
            class="mb-4"
            message="按实际生产顺序编排工序"
            description="中间工序没有独立产出时可留空;形成半成品时选择对应半成品,最后一道工序必须选择路线绑定的全部成品。多产品共用的半成品归属选“通用”,成品必须归属到自身产品。"
            show-icon
            type="info"
          />
          <ProcessList
            :form-type="formType"
            :route-id="routeId"
            @change="processList = $event"
          />
        </section>
 
        <section v-if="routeId" v-show="activeStep === 3" class="route-step-panel">
          <MaterialInputList
            :form-type="formType"
            :processes="sortedProcessList"
            :products="productList"
            :route-id="routeId"
            @change="bomList = $event"
          />
        </section>
 
        <section v-show="activeStep === 4" class="route-step-panel">
          <div class="review-heading">
            <div>
              <h3>启用前检查</h3>
              <p>确认产出、仓位、工序和投料形成闭环后,再回到列表启用路线。</p>
            </div>
            <Tag :color="reviewIssues.length ? 'warning' : 'success'">
              {{ reviewIssues.length ? `${reviewIssues.length} 项待处理` : '配置完整' }}
            </Tag>
          </div>
 
          <div class="review-metrics">
            <div><strong>{{ productsWithWarehouse }}/{{ productList.length }}</strong><span>产品仓位完整</span></div>
            <div><strong>{{ processesWithOutput }}</strong><span>配置产出的工序</span></div>
            <div><strong>{{ productsWithBom }}/{{ productList.length }}</strong><span>产品已配置投料</span></div>
          </div>
 
          <div v-if="reviewIssues.length" class="issue-list" role="status">
            <button
              v-for="issue in reviewIssues"
              :key="issue.text"
              class="issue-item"
              type="button"
              @click="activeStep = issue.step"
            >
              <IconifyIcon icon="lucide:circle-alert" />
              <span>{{ issue.text }}</span>
              <IconifyIcon class="ml-auto" icon="lucide:chevron-right" />
            </button>
          </div>
          <Empty v-else description="所有必需配置均已完成">
            <template #image>
              <div class="review-success-icon"><IconifyIcon icon="lucide:badge-check" /></div>
            </template>
          </Empty>
        </section>
      </main>
    </div>
 
    <template #prepend-footer>
      <div class="flex flex-auto items-center justify-between gap-3">
        <Button v-if="activeStep > 0" @click="activeStep--">
          <IconifyIcon class="mr-1" icon="lucide:arrow-left" />上一步
        </Button>
        <span v-else class="text-sm text-gray-500">新建路线默认停用,配置完整后再启用</span>
        <Button type="primary" @click="handlePrimaryAction">
          {{ primaryText }}
          <IconifyIcon
            v-if="activeStep < stepItems.length - 1"
            class="ml-1"
            icon="lucide:arrow-right"
          />
        </Button>
      </div>
    </template>
  </Modal>
</template>
 
<style scoped>
.route-config-shell { min-height: min(720px, 72vh); background: rgb(248 250 252); color: rgb(15 23 42); }
.route-config-header { display: flex; align-items: center; justify-content: space-between; gap: 24px; padding: 18px 24px 14px; background: white; border-bottom: 1px solid rgb(226 232 240); }
.route-config-summary { display: flex; flex-shrink: 0; gap: 8px; }
.route-config-summary span { padding: 5px 10px; border-radius: 8px; background: rgb(239 246 255); color: rgb(29 78 216); font-size: 12px; font-weight: 600; }
.route-config-steps { padding: 12px 20px 0; background: white; }
.route-config-content { padding: 20px 24px 28px; }
.route-step-panel { min-height: 460px; padding: 22px; border-radius: 14px; background: white; box-shadow: 0 10px 28px rgb(15 23 42 / 6%); }
.route-step-copy, .review-heading { display: flex; align-items: flex-start; justify-content: space-between; gap: 14px; margin-bottom: 22px; }
.route-step-copy { justify-content: flex-start; }
.route-step-copy > svg { width: 38px; height: 38px; padding: 9px; border-radius: 10px; background: rgb(219 234 254); color: rgb(29 78 216); }
.route-step-copy h3, .review-heading h3 { margin: 0; color: rgb(15 23 42); font-size: 17px; font-weight: 650; }
.route-step-copy p, .review-heading p { margin: 4px 0 0; color: rgb(71 85 105); font-size: 14px; }
.route-base-form { max-width: 1040px; margin: 34px auto 0; }
.review-metrics { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 14px; margin: 24px 0; }
.review-metrics > div { display: flex; align-items: baseline; gap: 10px; padding: 18px; border-radius: 12px; background: rgb(248 250 252); }
.review-metrics strong { color: rgb(29 78 216); font-size: 24px; }
.review-metrics span { color: rgb(71 85 105); font-size: 13px; }
.issue-list { display: grid; gap: 10px; }
.issue-item { display: flex; width: 100%; min-height: 48px; align-items: center; gap: 10px; padding: 10px 14px; border: 1px solid rgb(253 230 138); border-radius: 10px; background: rgb(255 251 235); color: rgb(146 64 14); cursor: pointer; text-align: left; transition: background-color 180ms ease, border-color 180ms ease; }
.issue-item:hover, .issue-item:focus-visible { border-color: rgb(245 158 11); background: rgb(254 243 199); outline: none; }
.review-success-icon { display: grid; width: 72px; height: 72px; place-items: center; margin: 0 auto; border-radius: 50%; background: rgb(220 252 231); color: rgb(22 163 74); font-size: 38px; }
:global(.dark) .route-config-shell { background: rgb(15 23 42); color: rgb(226 232 240); }
:global(.dark) .route-config-header, :global(.dark) .route-config-steps, :global(.dark) .route-step-panel { background: rgb(30 41 59); border-color: rgb(51 65 85); }
:global(.dark) .route-step-copy h3, :global(.dark) .review-heading h3 { color: rgb(241 245 249); }
:global(.dark) .route-step-copy p, :global(.dark) .review-heading p, :global(.dark) .review-metrics span { color: rgb(203 213 225); }
:global(.dark) .review-metrics > div { background: rgb(15 23 42); }
@media (max-width: 900px) {
  .route-config-header { align-items: flex-start; flex-direction: column; }
  .review-metrics { grid-template-columns: 1fr; }
  .route-step-panel { padding: 16px; }
}
</style>