周宾
2025-12-08 4da40604690325917d208e386e3add022f181147
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
<template>
  <div class="app-container labor-issue">
    <div class="config-wrap">
          <div class="left">
            <div class="header">
              <div>部门与岗位</div>
              <div>
                <el-button size="small" type="primary" @click="addDepartment">新增部门</el-button>
                <el-button size="small" @click="addSubDepartment" :disabled="!currentDept">新增子部门</el-button>
                <el-button size="small" @click="addPosition" :disabled="!currentDept">新增岗位</el-button>
              </div>
            </div>
            <el-tree
              :data="deptTree"
              node-key="id"
              :props="{ label: 'label', children: 'children' }"
              @node-click="onNodeClick"
              highlight-current
              v-model:expanded-keys="expandedKeys"
              default-expand-all
              class="tree"
            >
              <template #default="{ data }">
                <span>
                  <el-tag size="small" :type="data.type===1 ? 'success' : 'warning'" effect="plain" style="margin-right:4px;">
                    {{ data.type === 1 ? '部门' : '岗位' }}
                  </el-tag>
                  {{ data.label }}
                </span>
                <span class="ops">
                  <el-button link size="small" type="primary" @click.stop="openRenameDialog(data)">重命名</el-button>
                  <el-button link size="small" type="danger" @click.stop="confirmRemoveNode(data)">删除</el-button>
                </span>
              </template>
            </el-tree>
          </div>
          <div class="right">
            <div v-if="currentDept || currentPosition" class="position-config">
              <div class="title">
                <span v-if="currentPosition">岗位配置:{{ currentPosition.label }}</span>
                <span v-else-if="currentDept">部门配置:{{ currentDept.label }}</span>
              </div>
              <div class="q-toolbar">
                <el-button size="small" type="primary" @click="openAddItemDialog">新增用品</el-button>
              </div>
              <el-table :data="laborConfList" border size="small">
                <el-table-column label="用品名称" prop="dictName" />
                <el-table-column label="数量" prop="num" width="140" align="center" />
                <el-table-column label="季度" width="180" align="center">
                  <template #default="scope">
                    {{ quarterLabelFromNumber(scope.row.quarter) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="160" align="center">
                  <template #default="scope">
                    <el-button link type="primary" size="small" @click="openEditItemDialog(scope.row)">编辑</el-button>
                    <el-button link type="danger" size="small" @click="onDeleteItem(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <!-- 分页组件 -->
              <el-pagination
                v-model:current-page="queryParams.current"
                v-model:page-size="queryParams.size"
                :page-sizes="[10, 20, 50, 100]"
                :total="total"
                background
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                style="margin-top: 16px; justify-content: flex-end;s"
              />
            </div>
            <div v-else class="empty">请选择左侧部门或岗位进行配置</div>
          </div>
        </div>
    <!-- 新增部门/岗位弹窗 -->
    <el-dialog v-model="addDialogVisible" :title="addDialogTitle" width="420px">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="onCancelAdd">取 消</el-button>
        <el-button type="primary" @click="onConfirmAdd" :loading="addLoading">确 认</el-button>
      </template>
    </el-dialog>
    <!-- 重命名弹窗 -->
    <el-dialog v-model="renameDialogVisible" :title="renameDialogTitle" width="420px">
      <el-form :model="renameForm" :rules="addRules" ref="renameFormRef" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="renameForm.name" placeholder="请输入名称" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="onCancelRename">取 消</el-button>
        <el-button type="primary" @click="onConfirmRename" :loading="renameLoading">确 认</el-button>
      </template>
    </el-dialog>
 
    <!-- 新增/编辑用品弹窗(字典选择) -->
    <el-dialog v-model="addItemDialogVisible" :title="addItemDialogTitle" width="520px">
      <el-form :model="addItemForm" label-width="90px">
        <el-form-item label="用品名称">
          <el-select v-model="addItemForm.dictId" filterable placeholder="请选择用品">
            <el-option v-for="opt in sys_lavor_issue" :key="opt.value" :label="opt.label" :value="opt.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="数量">
          <el-input-number v-model="addItemForm.quantity" :min="0" :precision="0" />
        </el-form-item>
        <el-form-item label="季度">
          <el-select v-model="addItemForm.quarter" placeholder="选择季度">
            <el-option :value="1" :label="quarterLabelFromNumber(1)" />
            <el-option :value="2" :label="quarterLabelFromNumber(2)" />
            <el-option :value="3" :label="quarterLabelFromNumber(3)" />
            <el-option :value="4" :label="quarterLabelFromNumber(4)" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="onCancelAddItem">取 消</el-button>
        <el-button type="primary" :loading="addItemSaving" @click="onConfirmAddItem">保 存</el-button>
      </template>
    </el-dialog>
  </div>
</template>
 
<script setup>
import { ref, reactive, computed, watch, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useDict } from '@/utils/dict'
import { getDeptPositionTree, addDeptPosition, updateDeptPosition, deleteDeptPosition, laborConfListPage, addLaborConf, updateLaborConf, deleteLaborConf } from '@/api/lavorissce/issue'
 
// 字典:劳保用品字典
const { sys_lavor_issue } = useDict('sys_lavor_issue')
 
// 结构:部门树 -> 岗位
const departments = reactive([]) // [{id,name,children:[],positions:[{id,label,itemsByQuarter:{Q1:[{name,quantity}],...}}]}]
 
// 加载部门岗位树
async function loadDeptTree() {
  try {
    const res = await getDeptPositionTree()
    const data = res?.data || res || []
    // 覆盖 reactive 数组内容
    departments.splice(0, departments.length, ...data)
  } catch (e) {
    // 静默失败,保留本地示例数据
  }
}
 
// 左侧树(部门/岗位)支持多级
function mapDeptToTree(d) {
  // d: { id, name, type:1, children: [...] }
  const node = {
    id: `dept-${d.id}`,
    label: d.name,
    type: 1,
    raw: d,
    children: [],
  }
  const kids = Array.isArray(d.children) ? d.children : []
  for (const c of kids) {
    if (c.type === 1) {
      node.children.push(mapDeptToTree(c))
    } else if (c.type === 2) {
      // position leaf
      const rawPos = {
        id: c.id,
        label: c.name,
        // ensure items container exists for UI editing
        itemsByQuarter: { Q1: [], Q2: [], Q3: [], Q4: [] },
      }
      node.children.push({
        id: `pos-${d.id}-${c.id}`,
        label: c.name,
        type: 2,
        raw: rawPos,
        parentDeptId: d.id,
      })
    }
  }
  return node
}
const deptTree = computed(() => departments.map(d => mapDeptToTree(d)))
 
const expandedKeys = ref([])
function collectDeptKeys(list, acc) {
  for (const d of list) {
    acc.push(`dept-${d.id}`)
    if (Array.isArray(d.children)) collectDeptKeys(d.children, acc)
  }
}
watch(
  () => departments,
  () => {
    const acc = []
    collectDeptKeys(departments, acc)
    expandedKeys.value = acc
  },
  { deep: true, immediate: true }
)
 
const currentDept = ref(null)
const currentPosition = ref(null)
// 右侧:当前岗位的用品配置可选列表(来自 laborConfListPage)
const laborConfList = ref([])
const laborConfLoading = ref(false)
 
function quarterLabelFromNumber(n) {
  return n === 1 ? '第一季度' : n === 2 ? '第二季度' : n === 3 ? '第三季度' : n === 4 ? '第四季度' : ''
}
 
// 查询参数和分页相关变量
const queryParams = reactive({
  current: 1,
  size: 10
})
const total = ref(0)
 
// 分页大小改变
function handleSizeChange(val) {
  queryParams.size = val
  queryParams.current = 1
  loadLaborConf()
}
 
// 当前页改变
function handleCurrentChange(val) {
  queryParams.current = val
  loadLaborConf()
}
 
// 加载劳保用品配置列表(支持分页)
async function loadLaborConf(deptPositionId) {
  if (!deptPositionId) {
    const currentId = currentPosition.value?.id ?? currentDept.value?.raw?.id
    if (!currentId) return
    deptPositionId = currentId
  }
  
  try {
    laborConfLoading.value = true
    const res = await laborConfListPage({ 
      deptPositionId,
      current: queryParams.current,
      size: queryParams.size
    })
    laborConfList.value = res.data.records.map(it => ({
      ...it,
      id: it.id ?? it.dictId ?? it.value,
      name: it.dictName,
      quantity: it.num,
      quarter: it.quarter,
      quarterLabel: quarterLabelFromNumber(it.quarter),
    }))
    total.value = res.data.total || 0
  } finally {
    laborConfLoading.value = false
  }
}
 
// 新增用品弹窗状态与逻辑(供模板使用)
const addItemDialogVisible = ref(false)
const addItemDialogTitle = ref('新增用品')
const addItemSaving = ref(false)
const addItemForm = reactive({ id: undefined, dictId: undefined, quantity: 0, quarter: 1 })
 
function openAddItemDialog() {
  if (!currentDept.value && !currentPosition.value) return
  addItemDialogTitle.value = '新增用品'
  addItemForm.id = undefined
  addItemForm.dictId = undefined
  addItemForm.quantity = 0
  addItemForm.quarter = 1
  addItemDialogVisible.value = true
}
 
function openEditItemDialog(row) {
  if ((!currentDept.value && !currentPosition.value) || !row) return
  addItemDialogTitle.value = '编辑用品'
  addItemForm.id = row.id
  addItemForm.dictId = row.dictId
  addItemForm.quantity = Number(row.num) || 0
  addItemForm.quarter = Number(row.quarter) || 1
  addItemDialogVisible.value = true
}
 
function onCancelAddItem() {
  addItemDialogVisible.value = false
}
 
async function onConfirmAddItem() {
  if (!currentDept.value && !currentPosition.value) return
  addItemSaving.value = true
  try {
    const qNum = Number(addItemForm.quarter) || 1
    
    if (addItemForm.id) {
      // 编辑用品
      await updateLaborConf({
        id: addItemForm.id,
        dictId: addItemForm.dictId,
        num: Number(addItemForm.quantity) || 0,
        quarter: qNum,
      })
    } else {
      // 新增用品
      const currentId = currentPosition.value?.id ?? currentDept.value?.raw?.id
      await addLaborConf({
        deptPositionId: currentId,
        dictId: addItemForm.dictId,
        num: Number(addItemForm.quantity) || 0,
        quarter: qNum,
      })
    }
    
    // 重新加载用品配置列表
    await loadLaborConf()
    
    addItemDialogVisible.value = false
    ElMessage.success('保存成功')
  } catch (e) {
    ElMessage.error((e && (e.msg || e.message)) || '保存失败')
  } finally {
    addItemSaving.value = false
  }
}
 
async function onDeleteItem(row) {
  if ((!currentDept.value && !currentPosition.value) || !row) return
  try {
    await ElMessageBox.confirm('确定删除该用品配置吗?', '提示', { type: 'warning' })
  } catch {
    return
  }
  try {
    await deleteLaborConf([row.id])
    // 重新加载用品配置列表
    await loadLaborConf()
    ElMessage.success('删除成功')
  } catch (e) {
    ElMessage.error((e && (e.msg || e.message)) || '删除失败')
  }
}
 
// 新增弹窗状态
const addDialogVisible = ref(false)
const addDialogTitle = ref('新增')
const addLoading = ref(false)
const addFormRef = ref()
const addForm = reactive({ name: '', type: 1, parentId: undefined })
const addRules = { name: [{ required: true, message: '请输入名称', trigger: 'blur' }] }
 
// 重命名弹窗状态
const renameDialogVisible = ref(false)
const renameLoading = ref(false)
const renameFormRef = ref()
const renameForm = reactive({ id: undefined, type: 1, name: '' })
const renameDialogTitle = ref('重命名')
 
function newPosition() {
  return {
    id: Date.now(),
    label: '新岗位',
    hrPositionId: undefined,
    itemsByQuarter: {
      Q1: [], Q2: [], Q3: [], Q4: []
    }
  }
}
 
async function addDepartment() {
  openAddDialog({ type: 1 })
}
 
async function addPosition() {
  if (!currentDept.value) return
  openAddDialog({ type: 2, parentId: currentDept.value?.raw?.id })
}
 
async function addSubDepartment() {
  if (!currentDept.value) return
  openAddDialog({ type: 1, parentId: currentDept.value?.raw?.id })
}
 
function openAddDialog({ type, parentId }) {
  addForm.name = ''
  addForm.type = type
  addForm.parentId = parentId
  addDialogTitle.value = type === 1 ? '新增部门' : '新增岗位'
  addDialogVisible.value = true
}
 
function onCancelAdd() {
  addDialogVisible.value = false
}
 
async function onConfirmAdd() {
  addFormRef.value?.validate(async (valid) => {
    if (!valid) return
    try {
      addLoading.value = true
      const payload = { name: addForm.name, type: addForm.type, parentId: addForm.parentId ?? 0 }
      await addDeptPosition(payload)
      addDialogVisible.value = false
      await loadDeptTree()
    } finally {
      addLoading.value = false
    }
  })
}
 
function onNodeClick(node) {
  if (node.type === 1) {
    currentDept.value = node
    currentPosition.value = null
    // 选择部门时,加载部门级别的用品配置
    loadLaborConf()
  } else if (node.type === 2) {
    const dept = findDeptById(departments, node.parentDeptId)
    if (dept) currentDept.value = mapDeptToTree(dept)
    currentPosition.value = node.raw
    // 选择岗位时,查询用品配置列表
    loadLaborConf()
  }
}
 
function openRenameDialog(node) {
  renameForm.id = node.raw.id
  renameForm.type = node.type === 1 ? 1 : 2
  renameForm.name = node.label
  renameDialogTitle.value = node.type === 1 ? '重命名部门' : '重命名岗位'
  renameDialogVisible.value = true
}
 
function onCancelRename() {
  renameDialogVisible.value = false
}
 
async function onConfirmRename() {
  renameFormRef.value?.validate(async (valid) => {
    if (!valid) return
    try {
      renameLoading.value = true
      await updateDeptPosition({ id: renameForm.id, name: renameForm.name, type: renameForm.type })
      renameDialogVisible.value = false
      await loadDeptTree()
    } finally {
      renameLoading.value = false
    }
  })
}
 
async function confirmRemoveNode(node) {
  const type = node.type === 1 ? 1 : 2
  const id = node.type === 1 ? node.raw.id : node.raw.id
  // 简单确认
  try {
    await deleteDeptPosition([id])
    await loadDeptTree()
  } catch (e) {
    // ignore errors
  }
}
 
// 递归查找/删除部门
function findDeptById(list, id) {
  for (const d of list) {
    if (d.id === id) return d
    if (Array.isArray(d.children)) {
      const found = findDeptById(d.children, id)
      if (found) return found
    }
  }
  return null
}
function removeDeptById(list, id) {
  const idx = list.findIndex(d => d.id === id)
  if (idx > -1) {
    list.splice(idx, 1)
    return true
  }
  for (const d of list) {
    if (Array.isArray(d.children) && removeDeptById(d.children, id)) return true
  }
  return false
}
 
// 初始化一个示例结构,便于开箱体验(含子部门)
if (departments.length === 0) {
  const d1 = { id: 1, name: '生产部', positions: [ newPosition(), newPosition() ], children: [] }
  d1.positions[0].label = '一线工'
  d1.positions[1].label = '质检'
  d1.positions[0].itemsByQuarter.Q1.push({ name: '安全手套', quantity: 2 })
  d1.positions[0].itemsByQuarter.Q2.push({ name: '防护眼镜', quantity: 1 })
  const d11 = { id: 11, name: '生产一部', positions: [ newPosition() ], children: [] }
  d11.positions[0].label = '线体A'
  d1.children.push(d11)
  departments.push(d1)
}
 
// 工具:获取指定部门的岗位列表(不含子部门)
function getDeptPositions(deptId) {
  const d = findDeptById(departments, deptId)
  return (d && Array.isArray(d.positions)) ? d.positions : []
}
 
onMounted(() => {
  loadDeptTree()
})
</script>
 
<style scoped>
.labor-issue {
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.config-wrap {
  display: flex;
  gap: 16px;
  align-items: stretch;
}
.left, .right {
  background: #fff;
  border: 1px solid var(--el-border-color, #ebeef5);
  border-radius: 8px;
  box-shadow: var(--el-box-shadow-light, 0 2px 12px 0 rgba(0,0,0,.1));
}
.left { width: 340px; padding: 12px; }
.right { flex: 1; padding: 14px; }
.header {
  display: flex;
    align-items: flex-start;
    margin-bottom: 10px;
    flex-direction: column;
}
.header :deep(.el-button+.el-button) { margin-left: 8px; }
.tree {
  max-height: calc(100vh - 300px);
  overflow: auto;
  padding: 6px;
  border-radius: 6px;
  background: #fafafa;
}
.ops { margin-left: 8px; opacity: 0.6; transition: opacity .2s; }
:deep(.el-tree-node__content):hover .ops { opacity: 1; }
 
.q-toolbar { margin-bottom: 10px; }
.empty { color: #999; padding: 48px; text-align: center; }
 
.summary-wrap { display: flex; flex-direction: column; gap: 16px; }
.people, .summary {
  background: #fff;
  border: 1px solid var(--el-border-color, #ebeef5);
  border-radius: 8px;
  padding: 12px;
  box-shadow: var(--el-box-shadow-light, 0 2px 12px 0 rgba(0,0,0,.06));
}
.summary .header {
  font-weight: 600;
  margin-bottom: 12px;
}
</style>