wlzboy
4 天以前 c098f1e3a3e052aa3d65584aae6dc003a70d75ad
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
<template>
  <view class="staff-selector-component">
    <view class="form-item">
      <view class="form-label" :class="{ required: required }">{{ label }}</view>
      <view class="staff-list">
        <view class="staff-item" v-for="(staff, index) in selectedStaff" :key="staff.userId">
          <view class="staff-info">
            <text class="staff-name">{{ getStaffDisplayName(staff) }}</text>
          </view>
          <uni-icons 
            v-if="canRemove(index)"
            type="closeempty" 
            size="20" 
            color="#ff4d4f"
            @click="removeStaff(index)"
          ></uni-icons>
          <uni-icons 
            v-else
            type="checkmarkempty" 
            size="20" 
            color="#007AFF"
          ></uni-icons>
        </view>
        <view class="add-staff" @click="showStaffSelector">
          <uni-icons type="plusempty" size="20" color="#007AFF"></uni-icons>
          <text>添加人员</text>
        </view>
      </view>
    </view>
    
    <!-- 人员选择弹窗 -->
    <uni-popup ref="staffPopup" type="bottom" :safe-area="true">
      <view class="staff-selector-popup">
        <view class="popup-header">
          <view class="popup-title">选择执行人员</view>
          <view class="popup-close" @click="closeStaffSelector">
            <uni-icons type="closeempty" size="24" color="#333"></uni-icons>
          </view>
        </view>
        
        <view class="search-box">
          <uni-icons type="search" size="18" color="#999"></uni-icons>
          <input 
            class="search-input" 
            placeholder="搜索姓名、手机号" 
            v-model="staffSearchKeyword"
            @input="onStaffSearch"
          />
        </view>
        
        <view class="staff-filter">
          <view 
            class="filter-item" 
            :class="{ active: staffFilterType === 'driver' }"
            @click="filterStaff('driver')"
          >司机</view>
          <view 
            class="filter-item" 
            :class="{ active: staffFilterType === 'doctor' }"
            @click="filterStaff('doctor')"
          >医生</view>
          <view 
            class="filter-item" 
            :class="{ active: staffFilterType === 'nurse' }"
            @click="filterStaff('nurse')"
          >护士</view>
        </view>
        
        <scroll-view class="staff-list-popup" scroll-y="true">
          <view 
            class="staff-item-popup" 
            v-for="staff in filteredStaffList" 
            :key="staff.userId"
            @click="toggleStaffSelection(staff)"
          >
            <view class="staff-info">
              <view class="staff-name-row">
                <text class="staff-name">{{ staff.nickName }}</text>
                <text class="staff-phone">{{ staff.phonenumber }}</text>
              </view>
              <view class="staff-detail-row">
                <text class="staff-dept">{{ staff.deptName }}</text>
              </view>
            </view>
            <uni-icons 
              v-if="isStaffSelected(staff.userId)" 
              type="checkmarkempty" 
              size="24" 
              color="#007AFF"
            ></uni-icons>
            <view v-else class="checkbox-empty"></view>
          </view>
          
          <view class="no-data" v-if="filteredStaffList.length === 0">
            <uni-icons type="info" size="40" color="#ccc"></uni-icons>
            <text>暂无人员数据</text>
          </view>
        </scroll-view>
        
        <view class="popup-footer">
          <button class="cancel-btn" @click="closeStaffSelector">取消</button>
          <button class="confirm-btn" @click="confirmStaffSelection">确定(已选{{ selectedStaff.length }})</button>
        </view>
      </view>
    </uni-popup>
  </view>
</template>
 
<script>
import { mapState } from 'vuex'
import uniPopup from '@/uni_modules/uni-popup/components/uni-popup/uni-popup.vue'
import { listUsersByBranchDepts } from "@/api/system/user"
 
export default {
  name: 'StaffSelector',
  components: {
    uniPopup
  },
  props: {
    // 已选择的人员列表
    value: {
      type: Array,
      default: () => []
    },
    // 标签文本
    label: {
      type: String,
      default: '执行任务人员'
    },
    // 是否必填
    required: {
      type: Boolean,
      default: false
    },
    // 是否自动添加当前用户
    autoAddCurrentUser: {
      type: Boolean,
      default: true
    },
    // 当前用户是否可移除
    currentUserRemovable: {
      type: Boolean,
      default: false
    },
    // 分公司ID列表(外部传入,用于指定加载哪些分公司的用户)
    branchDeptIds: {
      type: Array,
      default: null
    },
    // 单个分公司ID(仅传一个时更便捷)
    branchDeptId: {
      type: [Number, String],
      default: null
    }
  },
  data() {
    return {
      selectedStaff: [],
      allStaffList: [],
      filteredStaffList: [],
      staffSearchKeyword: '',
      staffFilterType: 'driver', // 默认选中司机
      staffListCache: {}, // 缓存: { key: { data: [], timestamp: 0 } }
      cacheExpireTime: 5 * 60 * 1000 // 缓存过期时间:5分钟
    }
  },
  computed: {
    ...mapState({
      currentUser: state => ({
        userId: state.user.userId,
        nickName: state.user.nickName || '张三',
        phonenumber: state.user.phonenumber || '',
        deptId: state.user.deptId || 100,
        posts: state.user.posts || [],
        roles: state.user.roles || [],
        dept: state.user.dept || null
      })
    })
  },
  watch: {
    value: {
      handler(newVal) {
        if (newVal && Array.isArray(newVal)) {
          this.selectedStaff = [...newVal]
        }
      },
      immediate: true,
      deep: true
    },
    // 监听分公司ID数组变化,重新加载用户列表
    branchDeptIds: {
      handler(newVal, oldVal) {
        if (JSON.stringify(newVal) !== JSON.stringify(oldVal)) {
          console.log('分公司ID变化,重新加载用户:', newVal)
          this.loadStaffList()
        }
      },
      deep: true
    },
    // 监听单个分公司ID变化
    branchDeptId(newVal, oldVal) {
      if (newVal !== oldVal) {
        console.log('分公司ID变化,重新加载用户:', newVal)
        this.loadStaffList()
      }
    }
  },
  mounted() {
    this.loadStaffList()
    
    // 如果需要自动添加当前用户且选中人员为空
    if (this.autoAddCurrentUser && this.selectedStaff.length === 0) {
      this.initWithCurrentUser()
    }
  },
  methods: {
    // 初始化选中的人员(默认包含当前用户)
    initWithCurrentUser() {
      const currentUserStaff = {
        userId: this.currentUser.userId,
        nickName: this.currentUser.nickName,
        phonenumber: this.currentUser.phonenumber,
        deptId: this.currentUser.deptId,
        posts: this.currentUser.posts || [],
        roles: this.currentUser.roles || [],
        dept: this.currentUser.dept || null
      }
      
      // 获取当前用户的所有角色类型(可能有多个)
      currentUserStaff.types = this.getUserTypes(currentUserStaff)
      currentUserStaff.type = currentUserStaff.types[0] || 'driver' // 主要类型
      
      this.selectedStaff = [currentUserStaff]
      this.emitChange()
    },
    
    // 加载人员列表
    loadStaffList() {
      // 获取所有部门ID
      let deptIds = []
      if (this.branchDeptIds && this.branchDeptIds.length > 0) {
        deptIds = this.branchDeptIds
      } else if (this.branchDeptId) {
        deptIds = [this.branchDeptId]
      }
          
      if (deptIds.length > 0) {
        console.log('根据分公司ID加载用户:', deptIds)
        this.loadStaffByBranchDepts(deptIds)
      } else {
        console.log('未传入分公司ID,组件不加载人员列表')
        this.$modal && this.$modal.showToast && this.$modal.showToast('请传入分公司ID')
      }
    },
    
    // 根据分公司ID数组加载用户(支持缓存)
    loadStaffByBranchDepts(deptIds) {
      // 生成缓存key(按排序后id拼接)
      const cacheKey = [...deptIds].sort((a, b) => a - b).join(',')
      const cached = this.staffListCache[cacheKey]
      const now = Date.now()
      
      // 检查缓存是否有效
      if (cached && (now - cached.timestamp) < this.cacheExpireTime) {
        console.log('使用缓存的人员列表:', cacheKey)
        this.processUserList(cached.data)
        return
      }
      
      // 缓存失效或不存在,调用接口
      console.log('加载人员列表:', deptIds)
      listUsersByBranchDepts(deptIds).then(response => {
        const userList = response.data || []
        // 更新缓存
        this.staffListCache[cacheKey] = {
          data: userList,
          timestamp: now
        }
        this.processUserList(userList)
      }).catch(error => {
        console.error('加载人员列表失败:', error)
        this.$modal.showToast('加载人员列表失败')
      })
    },
 
    
    
    // 处理用户列表数据
    processUserList(userList) {
      this.allStaffList = userList.map(user => ({
        userId: user.userId,
        nickName: user.nickName,
        phonenumber: user.phonenumber,
        deptName: user.dept?.deptName || '',
        postName: user.posts && user.posts.length > 0 ? user.posts[0].postName : '',
        roleName: user.roles && user.roles.length > 0 ? user.roles[0].roleName : '',
        posts: user.posts || [],
        roles: user.roles || [],
        dept: user.dept || null,
        // 支持多种类型
        types: this.getUserTypes(user),
        type: this.getUserTypes(user)[0] || 'driver' // 主要类型(用于向后兼容)
      }))
      
      this.filterStaffList()
    },
    
    // 根据用户的岗位或角色判断所有类型(支持多种身份)
    getUserTypes(user) {
      const types = []
      const postNames = user.posts ? user.posts.map(p => p.postName).join('') : ''
      const roleNames = user.roles ? user.roles.map(r => r.roleName).join('') : ''
      const deptName = user.dept?.deptName || ''
      
      // 判断是否为司机
      if (postNames.includes('司机') || roleNames.includes('司机') || 
          deptName.includes('车队') || deptName.includes('司机')) {
        types.push('driver')
      }
      
      // 判断是否为医生
      if (postNames.includes('医生') || roleNames.includes('医生') || 
          deptName.includes('医生') || deptName.includes('医护')) {
        types.push('doctor')
      }
      
      // 判断是否为护士
      if (postNames.includes('护士') || roleNames.includes('护士') || deptName.includes('护士')) {
        types.push('nurse')
      }
      
      // 如果没有匹配到任何类型,默认为司机
      if (types.length === 0) {
        types.push('driver')
      }
      
      return types
    },
    
    // 获取类型名称
    getUserTypeName(staffType) {
      const typeMap = {
        'driver': '司机',
        'doctor': '医生',
        'nurse': '护士'
      }
      return typeMap[staffType] || staffType || '司机'
    },
    
    // 显示人员选择弹窗
    showStaffSelector() {
      this.$refs.staffPopup.open()
      this.filterStaffList()
    },
    
    // 关闭人员选择弹窗
    closeStaffSelector() {
      this.$refs.staffPopup.close()
      this.staffSearchKeyword = ''
      this.staffFilterType = 'driver' // 重置为默认司机
    },
    
    // 人员搜索
    onStaffSearch(e) {
      this.staffSearchKeyword = e.detail.value
      this.filterStaffList()
    },
    
    // 筛选人员类型
    filterStaff(type) {
      this.staffFilterType = type
      this.filterStaffList()
    },
    
    // 过滤人员列表
    filterStaffList() {
      let list = [...this.allStaffList]
      
      // 按关键词搜索
      if (this.staffSearchKeyword && this.staffSearchKeyword.trim() !== '') {
        const keyword = this.staffSearchKeyword.trim().toLowerCase()
        list = list.filter(staff => {
          return staff.nickName.toLowerCase().includes(keyword) || 
                 (staff.phonenumber && staff.phonenumber.includes(keyword))
        })
      }
      
      // 根据选中的类型,将有该身份的人排在前面
      list.sort((a, b) => {
        const aHasType = a.types.includes(this.staffFilterType)
        const bHasType = b.types.includes(this.staffFilterType)
        
        if (aHasType && !bHasType) return -1  // a有该身份,排前面
        if (!aHasType && bHasType) return 1   // b有该身份,排前面
        return 0  // 都有或都没有,保持原顺序
      })
      
      this.filteredStaffList = list
    },
    
    // 切换人员选中状态
    toggleStaffSelection(staff) {
      const index = this.selectedStaff.findIndex(s => s.userId === staff.userId)
      
      if (index > -1) {
        // 如果是第一个且不可移除(当前用户),不允许移除
        if (!this.canRemove(index)) {
          this.$modal.showToast('当前用户不能移除')
          return
        }
        // 已选中,移除
        this.selectedStaff.splice(index, 1)
      } else {
        // 未选中,添加
        this.selectedStaff.push({ ...staff })
      }
    },
    
    // 判断人员是否已选中
    isStaffSelected(userId) {
      return this.selectedStaff.some(staff => staff.userId === userId)
    },
    
    // 判断是否可以移除
    canRemove(index) {
      // 如果是第一个且当前用户不可移除
      if (index === 0 && !this.currentUserRemovable) {
        return false
      }
      return true
    },
    
    // 确认人员选择
    confirmStaffSelection() {
      if (this.selectedStaff.length === 0) {
        this.$modal.showToast('请至少选择一名人员')
        return
      }
      this.emitChange()
      this.closeStaffSelector()
    },
    
    // 移除人员
    removeStaff(index) {
      if (!this.canRemove(index)) {
        this.$modal.showToast('当前用户不能移除')
        return
      }
      this.selectedStaff.splice(index, 1)
      this.emitChange()
    },
    
    // 触发change事件
    emitChange() {
      this.$emit('input', this.selectedStaff)
      this.$emit('change', this.selectedStaff)
    },
    
    // 获取人员显示名称(优先显示姓名,如果姓名为空则显示手机号)
    getStaffDisplayName(staff) {
      if (!staff) {
        return '未知人员'
      }
      // 优先显示 nickName,如果为空则显示手机号,都为空则显示 userId
      if (staff.nickName && staff.nickName.trim()) {
        return staff.nickName
      }
      if (staff.phonenumber && staff.phonenumber.trim()) {
        return staff.phonenumber
      }
      return `用户${staff.userId || ''}`
    }
  }
}
</script>
 
<style lang="scss" scoped>
.staff-selector-component {
  .form-item {
    margin-bottom: 40rpx;
    
    .form-label {
      font-size: 28rpx;
      margin-bottom: 15rpx;
      color: #333;
      
      &.required::before {
        content: '*';
        color: #ff4d4f;
        margin-right: 4rpx;
        font-weight: bold;
      }
    }
    
    .staff-list {
      .staff-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 20rpx;
        background-color: #f9f9f9;
        border-radius: 10rpx;
        margin-bottom: 20rpx;
        
        .staff-info {
          flex: 1;
          
          .staff-name {
            font-size: 28rpx;
            color: #333;
            margin-right: 10rpx;
            display: block;
            margin-bottom: 8rpx;
          }
          
          .staff-roles {
            display: flex;
            flex-wrap: wrap;
            gap: 8rpx;
            
            .staff-role {
              font-size: 22rpx;
              color: white;
              background-color: #007AFF;
              padding: 4rpx 12rpx;
              border-radius: 6rpx;
            }
          }
        }
      }
      
      .add-staff {
        display: flex;
        align-items: center;
        justify-content: center;
        padding: 20rpx;
        border: 1rpx dashed #007AFF;
        border-radius: 10rpx;
        color: #007AFF;
        
        text {
          margin-left: 10rpx;
        }
      }
    }
  }
}
 
// 人员选择弹窗样式
.staff-selector-popup {
  background-color: white;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    flex-shrink: 0;
    
    .popup-title {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
    }
    
    .popup-close {
      padding: 10rpx;
    }
  }
  
  .search-box {
    display: flex;
    align-items: center;
    margin: 20rpx 30rpx;
    padding: 15rpx 20rpx;
    background-color: #f5f5f5;
    border-radius: 10rpx;
    flex-shrink: 0;
    
    .search-input {
      flex: 1;
      margin-left: 10rpx;
      font-size: 28rpx;
    }
  }
  
  .staff-filter {
    display: flex;
    padding: 0 30rpx 20rpx;
    gap: 15rpx;
    flex-shrink: 0;
    
    .filter-item {
      flex: 1;
      text-align: center;
      padding: 15rpx 0;
      background-color: #f5f5f5;
      border-radius: 10rpx;
      font-size: 26rpx;
      color: #666;
      
      &.active {
        background-color: #007AFF;
        color: white;
      }
    }
  }
  
  .staff-list-popup {
    flex: 1;
    overflow-y: auto;
    padding: 0 30rpx;
    
    .staff-item-popup {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 25rpx 20rpx;
      border-bottom: 1rpx solid #f0f0f0;
      
      &:active {
        background-color: #f5f5f5;
      }
      
      .staff-info {
        flex: 1;
        
        .staff-name-row {
          display: flex;
          align-items: center;
          margin-bottom: 10rpx;
          
          .staff-name {
            font-size: 30rpx;
            font-weight: bold;
            color: #333;
            margin-right: 20rpx;
          }
          
          .staff-phone {
            font-size: 24rpx;
            color: #999;
          }
        }
        
        .staff-detail-row {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          
          .staff-dept {
            font-size: 24rpx;
            color: #666;
            margin-right: 15rpx;
          }
          
          .staff-types {
            display: flex;
            gap: 8rpx;
            
            .type-tag {
              font-size: 20rpx;
              color: white;
              padding: 4rpx 10rpx;
              border-radius: 6rpx;
              
              &.type-driver {
                background-color: #007AFF;
              }
              
              &.type-doctor {
                background-color: #34C759;
              }
              
              &.type-nurse {
                background-color: #AF52DE;
              }
            }
          }
        }
      }
      
      .checkbox-empty {
        width: 40rpx;
        height: 40rpx;
        border: 2rpx solid #ddd;
        border-radius: 50%;
      }
    }
    
    .no-data {
      text-align: center;
      padding: 100rpx 0;
      color: #999;
      
      text {
        display: block;
        margin-top: 20rpx;
        font-size: 28rpx;
      }
    }
  }
  
  .popup-footer {
    display: flex;
    padding: 20rpx 30rpx;
    border-top: 1rpx solid #f0f0f0;
    gap: 20rpx;
    flex-shrink: 0;
    
    button {
      flex: 1;
      height: 80rpx;
      border-radius: 10rpx;
      font-size: 30rpx;
    }
    
    .cancel-btn {
      background-color: #f5f5f5;
      color: #666;
    }
    
    .confirm-btn {
      background-color: #007AFF;
      color: white;
    }
  }
}
</style>