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
<script setup lang="ts">
import { computed, reactive, ref } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getSimpleDictDataList, type DictData } from "../../../../api/crm";
import type { UserSimple } from "../../../../api/purchase";
import { getTemplatePage, getUserListByWorkstationId, getWorkstationPage, type MesWorkstation, type PdTemplate } from "../../../../api/process-design";
import { calculateTaskDuration, createTask, deleteTask, finishWorkOrder, getRouteProcessListByProduct, getTaskPage, getWorkOrder, getWorkOrderProcessListByWorkOrderId, updateTask, type ProTask, type WorkOrder, type WorkOrderProcess } from "../../../../api/production";
import { useAuth } from "../../../../stores/auth";
import { dateText, dayText, dictLabel } from "../../dv/shared";
import { statusToneClass } from "../../../../utils/status";
 
const { hasPermission, state } = useAuth();
const workOrderId = ref<number>();
const mode = ref<"schedule" | "detail">("detail");
const saving = ref(false);
const dicts = ref<DictData[]>([]);
const tasks = ref<ProTask[]>([]);
const processes = ref<WorkOrderProcess[]>([]);
const activeProcessIndex = ref(0);
const currentRouteId = ref(0);
const workstations = ref<MesWorkstation[]>([]);
const templates = ref<PdTemplate[]>([]);
const users = ref<UserSimple[]>([]);
const userLoading = ref(false);
const editIndex = ref(-1);
const dialogOpen = ref(false);
const readonly = computed(() => mode.value === "detail");
const canCreate = computed(() => !readonly.value && hasPermission("mes:pro-task:create"));
const canUpdate = computed(() => !readonly.value && hasPermission("mes:pro-task:update"));
const canDelete = computed(() => !readonly.value && hasPermission("mes:pro-task:delete"));
const canSaveLine = computed(() => (line.id ? canUpdate.value : canCreate.value));
const order = reactive<WorkOrder>({});
const line = reactive<ProTask>({ quantity: undefined, duration: undefined, colorCode: "#00AEF3", assigneeUserIds: [] });
const currentProcess = computed(() => processes.value[activeProcessIndex.value]);
 
function workstationText(value?: number) {
  const row = workstations.value.find(item => item.id === value);
  return row ? [row.code, row.name].filter(Boolean).join(" / ") : "请选择工作站";
}
function templateText(value?: number) {
  return templates.value.find(item => item.id === value)?.templateName || "请选择工艺参数模板";
}
function userNames(ids?: number[]) {
  return (ids || []).map(id => users.value.find(user => user.id === id)?.nickname).filter(Boolean).join("、") || "请选择报工人";
}
function validColor(value?: string) {
  return /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(String(value || ""));
}
function taskStatusFallback(value?: number) {
  return ({ 0: "未开始", 1: "进行中", 2: "已完成", 3: "已取消", 4: "暂停中" } as Record<number, string>)[Number(value)] || "--";
}
function taskStatusText(row: ProTask) {
  return dictLabel(dicts.value, "mes_pro_task_status", row.status, taskStatusFallback(row.status));
}
function taskStatusClass(row: ProTask) {
  return statusToneClass(row.status, taskStatusText(row));
}
function taskProgress(row: ProTask) {
  const backendProgress = Number(row.progressPercent ?? row.progress);
  if (Number.isFinite(backendProgress) && backendProgress > 0) return Math.min(100, Math.round(backendProgress));
  const quantity = Number(row.quantity || 0);
  if (!quantity) return 0;
  return Math.min(100, Math.round((Number(row.producedQuantity || 0) / quantity) * 100));
}
async function loadTasks() {
  if (!state.accessToken || !workOrderId.value) return;
  const process = currentProcess.value;
  const page = await getTaskPage(state.accessToken, {
    pageNo: 1,
    pageSize: 100,
    workOrderId: workOrderId.value,
    routeId: currentRouteId.value || undefined,
    processId: process?.processId,
  });
  tasks.value = page.list || [];
}
async function loadProcesses() {
  if (!state.accessToken || !workOrderId.value || !order.productId) return;
  const list = await getWorkOrderProcessListByWorkOrderId(state.accessToken, workOrderId.value);
  processes.value = [...list].sort((a, b) => Number(a.sort || 0) - Number(b.sort || 0));
  if (order.routeId) currentRouteId.value = order.routeId;
  else {
    const routeProcesses = await getRouteProcessListByProduct(state.accessToken, order.productId);
    currentRouteId.value = routeProcesses?.[0]?.routeId || 0;
  }
  activeProcessIndex.value = 0;
}
async function recalcDuration() {
  if (!state.accessToken || !line.workstationId || !Number(line.quantity)) return;
  try {
    const data = await calculateTaskDuration(state.accessToken, line.workstationId, Number(line.quantity));
    line.duration = data.duration || line.duration;
    if (data.duration === 0) uni.showToast({ title: "该工作站未绑定设备,或绑定设备未配置生产效率", icon: "none" });
  } catch {
    // 计算失败不影响手工录入
  }
}
async function loadWorkstationUsers(workstationId?: number, keepSelected = false) {
  users.value = [];
  if (!keepSelected) line.assigneeUserIds = [];
  if (!state.accessToken || !workstationId) return;
  userLoading.value = true;
  try {
    users.value = await getUserListByWorkstationId(state.accessToken, workstationId);
    if (!users.value.length) uni.showToast({ title: "当前工作站没有配置人力资源", icon: "none" });
    if (keepSelected && line.assigneeUserIds?.length) {
      const validIds = new Set(users.value.map(user => user.id).filter(Boolean));
      line.assigneeUserIds = line.assigneeUserIds.filter(id => validIds.has(id));
    }
  } catch (error) {
    uni.showToast({ title: error instanceof Error ? error.message : "报工人加载失败", icon: "none" });
  } finally {
    userLoading.value = false;
  }
}
async function openLine(row?: ProTask, index = -1) {
  const process = currentProcess.value;
  if (!row && !process?.processId) return uni.showToast({ title: "当前订单未配置工序", icon: "none" });
  editIndex.value = index;
  Object.keys(line).forEach(key => delete (line as Record<string, unknown>)[key]);
  Object.assign(line, row ? JSON.parse(JSON.stringify(row)) : {
    workOrderId: workOrderId.value,
    workOrderCode: order.code,
    workOrderName: order.name,
    routeId: currentRouteId.value,
    processId: process?.processId,
    processName: process?.processName,
    paramTemplateId: process?.paramTemplateId,
    itemId: process?.outputItemId || order.productId,
    itemCode: order.productCode,
    itemName: order.productName,
    itemSpecification: order.productSpecification,
    unitMeasureName: order.unitMeasureName,
    quantity: order.quantity,
    colorCode: process?.colorCode || "#00AEF3",
    assigneeUserIds: [],
  });
  await loadWorkstationUsers(line.workstationId, !!row);
  dialogOpen.value = true;
}
async function switchProcess(index: number) {
  activeProcessIndex.value = index;
  await loadTasks();
}
async function selectWorkstation(index: number) {
  const row = workstations.value[index];
  line.workstationId = row.id;
  line.workstationCode = row.code;
  line.workstationName = row.name;
  line.startTime = "";
  line.endTime = "";
  await loadWorkstationUsers(row.id);
  await recalcDuration();
}
function selectTemplate(index: number) {
  line.paramTemplateId = templates.value[index]?.id;
}
function toggleUser(user: UserSimple) {
  if (!line.workstationId) return uni.showToast({ title: "请先选择工作站", icon: "none" });
  if (!user.id) return;
  const list = line.assigneeUserIds || [];
  line.assigneeUserIds = list.includes(user.id) ? list.filter(id => id !== user.id) : [...list, user.id];
}
async function saveLine() {
  if (!line.workstationId) return uni.showToast({ title: "请选择工作站", icon: "none" });
  if (!Number(line.quantity)) return uni.showToast({ title: "请填写排产数量", icon: "none" });
  if (!validColor(line.colorCode)) return uni.showToast({ title: "甘特颜色格式应为 #00AEF3", icon: "none" });
  if (!line.startTime) return uni.showToast({ title: "请选择开始时间", icon: "none" });
  if (!Number(line.duration)) return uni.showToast({ title: "请填写生产时长", icon: "none" });
  if (!line.assigneeUserIds?.length) return uni.showToast({ title: "请选择报工人", icon: "none" });
  if (!state.accessToken || saving.value || !canSaveLine.value) return;
  saving.value = true;
  try {
    const data = { ...line, workOrderId: workOrderId.value };
    if (line.id) await updateTask(state.accessToken, data);
    else await createTask(state.accessToken, data);
    uni.showToast({ title: "保存成功", icon: "success" });
    dialogOpen.value = false;
    await loadTasks();
  } catch (error) {
    uni.showToast({ title: error instanceof Error ? error.message : "保存失败", icon: "none" });
  } finally {
    saving.value = false;
  }
}
async function removeTask(row: ProTask) {
  if (!state.accessToken || !row.id) return;
  const ok = await new Promise<boolean>(resolve => uni.showModal({ title: "确认删除", content: `确定删除任务“${row.code || row.name}”吗?`, success: res => resolve(res.confirm) }));
  if (!ok) return;
  try {
    await deleteTask(state.accessToken, row.id);
    uni.showToast({ title: "删除成功", icon: "success" });
    await loadTasks();
  } catch (error) {
    uni.showToast({ title: error instanceof Error ? error.message : "删除失败", icon: "none" });
  }
}
async function finishOrder() {
  if (!state.accessToken || !workOrderId.value) return;
  if (!processes.value.length) return uni.showToast({ title: "当前订单未配置工序", icon: "none" });
  const ok = await new Promise<boolean>(resolve => uni.showModal({ title: "确认完成", content: "确认要完成该订单吗?完成后订单下所有任务将标记为已完成。", success: res => resolve(res.confirm) }));
  if (!ok) return;
  try {
    await finishWorkOrder(state.accessToken, workOrderId.value);
    uni.showToast({ title: "订单已完成", icon: "success" });
    setTimeout(() => uni.navigateBack(), 500);
  } catch (error) {
    uni.showToast({ title: error instanceof Error ? error.message : "完成失败", icon: "none" });
  }
}
onLoad(async query => {
  workOrderId.value = Number(query.workOrderId);
  mode.value = query.mode === "schedule" ? "schedule" : "detail";
    if (!state.accessToken || !workOrderId.value) return;
  try {
    const [ds, wo, ws, tp] = await Promise.all([
      getSimpleDictDataList(state.accessToken),
      getWorkOrder(state.accessToken, workOrderId.value),
      getWorkstationPage(state.accessToken, { pageNo: 1, pageSize: 200 }),
      getTemplatePage(state.accessToken, { pageNo: 1, pageSize: 200 }),
    ]);
    dicts.value = ds;
    Object.assign(order, wo);
    workstations.value = ws.list;
    templates.value = tp.list;
    await loadProcesses();
    await loadTasks();
  } catch (error) {
    uni.showToast({ title: error instanceof Error ? error.message : "数据加载失败", icon: "none" });
  }
});
</script>
 
<template>
  <view class="page">
    <view class="form-card">
      <view class="field"><text>订单编码</text><text class="value">{{ order.code || '--' }}</text></view>
      <view class="field"><text>订单名称</text><text class="value">{{ order.name || '--' }}</text></view>
      <view class="field"><text>订单来源</text><text class="value">{{ dictLabel(dicts,'mes_pro_work_order_source_type',order.orderSourceType) }}</text></view>
      <view class="field"><text>来源单据编号</text><text class="value">{{ order.orderSourceCode || '--' }}</text></view>
      <view class="field"><text>产品</text><text class="value">{{ [order.productCode,order.productName,order.productSpecification,order.unitMeasureName].filter(Boolean).join(' / ') || '--' }}</text></view>
      <view class="field"><text>订单数量</text><text class="value">{{ order.quantity ?? '--' }}</text></view>
      <view class="field"><text>客户</text><text class="value">{{ order.clientName || '--' }}</text></view>
      <view class="field"><text>批次号</text><text class="value">{{ order.batchCode || '--' }}</text></view>
      <view class="field"><text>需求日期</text><text class="value">{{ dayText(order.requestDate) }}</text></view>
      <view class="field column"><text>备注</text><textarea v-model="order.remark" disabled /></view>
    </view>
    <view class="tab-card">
      <view class="section"><text>生产任务</text><button v-if="canCreate && processes.length" @click="openLine()">新增任务</button></view>
      <view v-if="processes.length" class="process-tabs">
        <text v-for="(process,index) in processes" :key="process.processId || index" :class="{active:activeProcessIndex===index}" @click="switchProcess(index)">{{ process.processName || `工序${index+1}` }}</text>
      </view>
      <view v-else class="empty">当前订单未配置工序,请先在生产订单中维护工序信息</view>
      <view v-for="(item,index) in tasks" :key="item.id || index" class="sub-row">
        <view class="sub-head"><text class="sub-title">{{ item.name || item.code || `任务 ${index+1}` }}</text><view class="status-wrap"><text :class="['status', 'task-tag', taskStatusClass(item)]">{{ taskStatusText(item) }}</text></view></view>
        <view class="sub-grid">
          <text>任务编码:{{ item.code || '--' }}</text>
          <text>工作站:{{ [item.workstationCode,item.workstationName].filter(Boolean).join(' / ') || '--' }}</text>
          <text>工序:{{ item.processName || '--' }}</text>
          <text>工艺参数模板:{{ item.paramTemplateId ? `模板 #${item.paramTemplateId}` : '未配置' }}</text>
          <text>排产数量:{{ item.quantity ?? '--' }}</text>
          <text>已生产数量:{{ item.producedQuantity ?? '--' }}</text>
          <text>开始生产时间:{{ dateText(item.startTime) }}</text>
          <text>生产时长(h):{{ item.duration ?? '--' }}</text>
          <text>预计完成时间:{{ dateText(item.endTime) }}</text>
          <text>报工人:{{ userNames(item.assigneeUserIds) }}</text>
          <text>备注:{{ item.remark || '--' }}</text>
        </view>
        <view class="progress"><view><view :style="{width:taskProgress(item)+'%'}" /></view><text>{{ taskProgress(item) }}%</text></view>
        <view class="actions"><button v-if="canUpdate" @click="openLine(item,index)">编辑</button><button v-if="canDelete" class="danger" @click="removeTask(item)">删除</button></view>
      </view>
      <view v-if="processes.length && !tasks.length" class="empty">暂无生产任务</view>
    </view>
    <button v-if="mode==='schedule' && processes.length" class="save" @click="finishOrder">完成订单</button>
    <view v-if="dialogOpen" class="mask">
      <view class="dialog">
        <view class="dialog-title">{{ line.id ? '编辑生产任务' : '新增生产任务' }}</view>
        <view class="field"><text>任务名称</text><input v-model="line.name" placeholder="请输入任务名称" /></view>
        <view class="field"><text>工艺参数模板</text><picker :range="templates" range-key="templateName" @change="selectTemplate(Number($event.detail.value))"><view class="picker"><text>{{ templateText(line.paramTemplateId) }}</text><text>›</text></view></picker></view>
        <view class="field"><text>工作站 <text class="required">*</text></text><picker :range="workstations" range-key="name" @change="selectWorkstation(Number($event.detail.value))"><view class="picker"><text>{{ workstationText(line.workstationId) }}</text><text>›</text></view></picker></view>
        <view class="field"><text>排产数量 <text class="required">*</text></text><input :value="String(line.quantity ?? '')" type="digit" placeholder="请输入排产数量" @input="line.quantity=Number($event.detail.value||0);recalcDuration()" /></view>
        <view class="field"><text>甘特颜色</text><input v-model="line.colorCode" placeholder="请输入颜色值" /></view>
        <view class="field"><text>开始时间 <text class="required">*</text></text><picker mode="date" :disabled="!line.workstationId" :value="String(line.startTime||'').slice(0,10)" @change="line.startTime=$event.detail.value+' 00:00:00'"><view :class="['picker', !line.workstationId ? 'disabled' : '']"><text>{{ line.workstationId ? dateText(line.startTime).replace('--','请选择开始时间') : '请先选择工作站' }}</text><text>›</text></view></picker></view>
        <view class="field"><text>生产时长(h) <text class="required">*</text></text><input :value="String(line.duration ?? '')" type="number" placeholder="请输入生产时长" @input="line.duration=Number($event.detail.value||0)" /></view>
        <view class="field column"><text>报工人 <text class="required">*</text></text><view class="checks"><text v-if="!line.workstationId" class="hint">请先选择工作站</text><text v-else-if="userLoading" class="hint">加载中...</text><text v-else-if="!users.length" class="hint">当前工作站暂无报工人</text><text v-for="user in users" v-else :key="user.id" :class="{active:line.assigneeUserIds?.includes(user.id!)}" @click="toggleUser(user)">{{ user.nickname }}</text></view></view>
        <view class="field column"><text>备注</text><textarea v-model="line.remark" placeholder="请输入备注" /></view>
        <view class="dialog-actions"><button @click="dialogOpen=false">取消</button><button class="primary" :loading="saving" :disabled="saving" @click="saveLine">确认</button></view>
      </view>
    </view>
  </view>
</template>
 
<style lang="scss" scoped>
.page{min-height:100vh;padding:24rpx 30rpx 70rpx;box-sizing:border-box;background:#f6f7f9}.form-card,.tab-card{overflow:hidden;background:#fff;border-radius:16rpx}.tab-card{margin-top:22rpx;padding-bottom:20rpx}.field{display:flex;align-items:center;min-height:96rpx;padding:0 24rpx;gap:20rpx;border-bottom:1rpx solid #eef1f5}.field>text:first-child{width:210rpx;flex:none;color:#33455d;font-size:27rpx}.field input,.field picker,.picker,.value{min-width:0;flex:1;color:#1e3049;font-size:27rpx}.field input,.value{text-align:right}.picker{display:flex;align-items:center;justify-content:space-between;color:#65758a}.picker.disabled{color:#9aa8b8}.picker text:first-child,.value{overflow:hidden;text-align:right;text-overflow:ellipsis;white-space:nowrap}.picker text:last-child{margin-left:16rpx;color:#8092a7;font-size:36rpx}.required{color:#e23b3b}.column{align-items:flex-start;flex-direction:column;padding:20rpx 24rpx}.column>text:first-child{width:auto}.column textarea{width:100%;height:150rpx;font-size:27rpx;box-sizing:border-box}.section{display:flex;align-items:center;justify-content:space-between;padding:20rpx 24rpx;border-bottom:1rpx solid #eef1f5}.section>text{color:#172b45;font-size:31rpx;font-weight:600}.section button,.actions button{min-height:50rpx;padding:0 16rpx;margin:0;color:var(--color-primary, #1769d8);font-size:23rpx;line-height:48rpx;background:#fff;border:1rpx solid var(--color-primary, #1769d8);border-radius:8rpx}.section button::after,.actions button::after,.dialog-actions button::after,.save::after{border:0}.process-tabs{display:flex;gap:12rpx;overflow-x:auto;padding:18rpx 24rpx;border-bottom:1rpx solid #eef1f5}.process-tabs text{flex:none;height:52rpx;padding:0 22rpx;color:#66778c;font-size:24rpx;line-height:52rpx;background:#f3f6fb;border-radius:999rpx}.process-tabs .active{color:var(--color-primary, #1769d8);font-weight:600;background:#eaf3ff}.sub-row{display:grid;gap:14rpx;padding:22rpx 22rpx;margin:18rpx 10rpx;color:#51657e;font-size:24rpx;background:#fff;border:1rpx solid #e2eaf5;border-radius:16rpx;box-shadow:0 12rpx 28rpx rgba(43,69,107,.08)}.sub-head{display:flex;align-items:flex-start;justify-content:space-between;gap:12rpx}.sub-title{min-width:0;color:#102846;font-size:29rpx;font-weight:700}.status-wrap{display:flex;align-items:center;flex:none;height:40rpx}.task-tag{display:inline-flex;align-items:center;min-width:70rpx;height:34rpx;justify-content:center;padding:0 14rpx;color:#17865a;font-size:22rpx;background:#eafaf2;border:1rpx solid #b8efd5;border-radius:999rpx;white-space:nowrap}.sub-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));column-gap:18rpx;row-gap:10rpx;padding-top:12rpx;border-top:1rpx solid #edf1f6}.sub-grid text{min-width:0;line-height:1.5;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.progress{display:flex;align-items:center;gap:12rpx;color:#66778c;font-size:22rpx}.progress>view{height:12rpx;flex:1;overflow:hidden;background:#eef3f8;border-radius:999rpx}.progress>view>view{height:100%;background:var(--color-primary, #1769d8);border-radius:999rpx}.actions{display:flex;justify-content:flex-end;gap:10rpx}.actions .danger{color:#c65050;border-color:#e3a0a0}.empty{padding:36rpx;color:#8795a8;font-size:26rpx;text-align:center}.save{margin-top:30rpx;color:#fff;font-size:30rpx;background:var(--color-primary, #1769d8);border-radius:12rpx}.mask{position:fixed;inset:0;z-index:50;display:flex;align-items:flex-end;background:rgba(0,0,0,.42)}.dialog{width:100%;max-height:88vh;overflow:auto;background:#fff;border-radius:24rpx 24rpx 0 0}.dialog-title{padding:26rpx 30rpx;color:#172b45;font-size:31rpx;font-weight:600;text-align:center;border-bottom:1rpx solid #eef1f5}.checks{display:flex;flex-wrap:wrap;gap:12rpx;width:100%}.checks text{padding:8rpx 16rpx;color:#66778c;font-size:24rpx;background:#f4f7fb;border:1rpx solid #dce4ee;border-radius:999rpx}.checks .active{color:var(--color-primary, #1769d8);background:var(--color-primary-soft, #edf5ff);border-color:var(--color-primary-border, #8ab3ee)}.checks .hint{width:100%;box-sizing:border-box;color:#8795a8;text-align:center;background:#f7f9fc;border-color:#e6edf5}.dialog-actions{display:flex;gap:18rpx;padding:22rpx 30rpx calc(22rpx + env(safe-area-inset-bottom))}.dialog-actions button{flex:1;margin:0;color:#33455d;background:#f3f6fb;border-radius:12rpx}.dialog-actions .primary{color:#fff;background:var(--color-primary, #1769d8)}
</style>