ny
22 小时以前 282fbc6488f4e8ceb5fda759f963ee88fbf7b999
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
<script lang="ts" setup>
import type { ScrollActionType, TreeActionType } from '@jnpf/ui';
 
import { computed, h, nextTick, reactive, ref, toRefs, unref, watch } from 'vue';
 
import { useAttrs, useMessage } from '@jnpf/hooks';
import { AButton, BasicTree, ScrollContainer } from '@jnpf/ui';
import { ModalClose, ModalFooter } from '@jnpf/ui/modal';
 
import { $t } from '@vben/locales';
import { useUserStore } from '@vben/stores';
 
import { globalShareState } from '@vben-core/shared/global-state';
 
import { useDebounceFn } from '@vueuse/core';
import { Modal as AModal, Checkbox, Form, Input, Radio, Select, TabPane, Tabs, Tag } from 'ant-design-vue';
import { cloneDeep, pick } from 'lodash-es';
 
import { posSelectProps } from './props';
 
interface State {
  activeKey: string;
  allList: any[];
  finish: boolean;
  innerValue: any[] | string | undefined;
  keyword: string;
  listActiveKey: string;
  loading: boolean;
  options: any[];
  orgLoading: boolean;
  orgTreeData: any[];
  parentId: string;
  query: any;
  selectedData: any[];
  selectedIds: any[];
  subData: any[];
  treeData: any[];
  visible: boolean;
}
 
defineOptions({ inheritAttrs: false, name: 'JnpfPosSelect' });
 
const props = defineProps(posSelectProps);
 
const emit = defineEmits(['update:value', 'change']);
 
defineExpose({ openSelectModal });
 
const attrs: any = useAttrs({ excludeDefaultKeys: false });
const userStore = useUserStore();
const { getOrganizeSelector, getPositionByCondition, getPositionSelectedList, getPositionSelector, getPositionSelectorTree } = globalShareState.getApi();
const orgTreeRef = ref<Nullable<TreeActionType>>(null);
const posTreeRef = ref<Nullable<TreeActionType>>(null);
const infiniteBody = ref<Nullable<ScrollActionType>>(null);
const state = reactive<State>({
  activeKey: '',
  allList: [],
  finish: false,
  innerValue: '',
  keyword: '',
  loading: false,
  options: [],
  orgLoading: false,
  orgTreeData: [],
  parentId: '0',
  query: {
    currentPage: 1,
    hasPage: 0,
    keyword: '',
    pageSize: 20,
  },
  selectedData: [],
  selectedIds: [],
  subData: [],
  treeData: [],
  visible: false,
  listActiveKey: '',
});
const { activeKey, innerValue, loading, options, query, selectedData, selectedIds, subData, treeData, visible, listActiveKey } = toRefs(state);
const formItemContext = Form.useInjectFormItemContext();
const { createMessage } = useMessage();
const systemFieldList = [
  { fullName: '当前用户所属岗位', id: '@positionId', orgNameTree: '当前用户所属岗位' },
  { fullName: '当前用户所属岗位及子岗位', id: '@positionAndSub', orgNameTree: '当前用户所属岗位及子岗位' },
  { fullName: '当前用户所属岗位及子孙岗位', id: '@positionAndProgeny', orgNameTree: '当前用户所属岗位及子孙岗位' },
];
const subList: any = [
  { fullName: '当前岗位', id: '--pos', orgNameTree: '' },
  { fullName: '当前岗位及子岗位', id: '--subPos', orgNameTree: '及子岗位' },
  { fullName: '当前岗位及子孙岗位', id: '--progenyPos', orgNameTree: '及子孙岗位' },
];
const treeExtraInfo: any = {
  render: (node) => {
    return h(props.multiple ? Checkbox : Radio, {
      checked: selectedIds.value.includes(node.id),
    });
  },
};
const debounceHandleSearch = useDebounceFn(handleSearch, 300);
 
const getCurrPosList: any = computed(() => (userStore.getUserInfo?.positionList || []).map((o) => ({ ...o, orgNameTree: o.treeName })));
const getSelectBindValue: any = computed(() => ({
  ...pick(props, ['placeholder', 'disabled', 'size', 'allowClear']),
  class: unref(attrs).class ? `w-full ${unref(attrs).class}` : 'w-full',
  fieldNames: { label: 'orgNameTree', value: 'id' },
  mode: props.multiple ? 'multiple' : '',
  open: false,
  showArrow: true,
  showSearch: false,
}));
const getOrgTreeBindValue = computed(() => {
  const key = Date.now();
  const data: any = {
    key,
    loadData: onLoadData,
    loading: state.orgLoading,
    onSelect: handleOrgSelect,
    treeData: state.orgTreeData,
  };
  return data;
});
const getPosTreeBindValue = computed(() => {
  const key = Date.now() + 1000;
  const data: any = {
    defaultExpandAll: true,
    key,
    loading: state.loading,
    onSelect: handleSelect,
    treeData: state.treeData,
  };
  if (!props.hasSys || state.activeKey == 'system') data.extraInfo = treeExtraInfo;
  data.onSelect = props.hasSys ? handleSysSelect : handleSelect;
  return data;
});
 
watch(
  () => unref(props.value),
  () => {
    setValue();
  },
  { immediate: true },
);
watch(
  () => state.selectedData,
  (val) => {
    state.selectedIds = val.map((o) => o.id);
  },
  { deep: true },
);
 
function setValue() {
  if (!props.value || props.value.length === 0) return setNullValue();
  let ids = props.multiple ? (props.value as any[]) : [props.value];
  const selectSysData: any[] = getSelectSysData(ids);
  ids = ids.filter((o) => !o.includes('@'));
  if (ids.length === 0) return setOptions(selectSysData);
  getPositionSelectedList(ids).then((res) => {
    setOptions([...(res.data.list || []), ...selectSysData]);
  });
}
function setOptions(data) {
  if (!props.value || props.value.length === 0) return setNullValue();
  const selectedList: any[] = data;
  const innerIds = selectedList.map((o) => o.id);
  state.innerValue = props.multiple ? innerIds : innerIds[0];
  state.options = cloneDeep(selectedList);
  state.selectedData = cloneDeep(selectedList);
}
function setNullValue() {
  state.innerValue = props.multiple ? [] : undefined;
  state.options = [];
  state.selectedData = [];
}
function getSelectSysData(ids) {
  const list: any[] = [];
  const sysFieldList = [...systemFieldList];
  for (const element of sysFieldList) {
    inner: for (const id of ids) {
      if (element.id === id) {
        list.push({ ...element });
        break inner;
      }
    }
  }
  return list;
}
function onChange(_val, option) {
  state.selectedData = option || [];
  handleSubmit();
}
function onTagClose(i) {
  removeData(i);
  handleSubmit();
}
function openSelectModal() {
  if (props.disabled) return;
  state.visible = true;
  state.activeKey = '1';
  onTabChange();
  setValue();
  nextTick(() => {
    bindScroll();
  });
}
function handleCancel() {
  state.visible = false;
}
function onTabChange() {
  state.query.hasPage = 0;
  state.query.keyword = '';
  state.listActiveKey = '';
  initData();
}
function handleSearch(e) {
  const value = e.target.value;
  if (state.loading) return;
  if (state.activeKey !== '1') state.activeKey = '1';
  if (props.selectType !== 'all') return getPosTree().setSearchValue(value);
  state.query.keyword = value || '';
  state.query.hasPage = state.query.keyword ? 1 : 0;
  if (state.query.hasPage) {
    nextTick(() => {
      bindScroll();
    });
  }
  initData();
}
function handleSysSelect(keys) {
  if (keys.length === 0) return;
  const data = getPosTree().getSelectedNode(keys[0]);
  getSubData(data);
}
function getSubData(item) {
  const data: any = [];
  for (const element of subList) {
    data.push({ ...item, fullName: element.fullName, icon: '', id: `${item.id}${element.id}`, orgNameTree: item.orgNameTree + element.orgNameTree });
  }
  state.subData = data;
}
function handleOrgSelect(keys) {
  if (keys.length === 0) return;
  getPosTreeData(keys[0]);
}
// 获取岗位树
function getPosTreeData(id) {
  state.loading = true;
  getPositionSelectorTree({ organizeId: id })
    .then((res) => {
      state.treeData = res.data.list || [];
      if (props.hasSys && state.treeData.length > 0) {
        nextTick(() => {
          const keys = [state.treeData[0].id];
          getPosTree().setSelectedKeys(keys);
          handleSysSelect(keys);
        });
      } else {
        state.subData = [];
      }
      state.loading = false;
    })
    .catch(() => {
      state.loading = false;
    });
}
function handleSelect(keys) {
  if (keys.length === 0) return;
  const data = getPosTree().getSelectedNode(keys[0]);
  handleNodeClick(data);
}
function handleListNodeClick(data) {
  if (data?.disabled) return;
  state.listActiveKey = data.id;
  props.hasSys && state.activeKey === '1' ? getSubData(data) : handleNodeClick(data);
}
function handleNodeClick(data) {
  if (data?.disabled) return;
  const index = state.selectedData.findIndex((o) => o.id === data.id);
  if (index !== -1) return state.selectedData.splice(index, 1);
  props.multiple ? state.selectedData.push(data) : (state.selectedData = [data]);
}
function removeAll() {
  state.selectedData = [];
}
function removeData(index: number) {
  state.selectedData.splice(index, 1);
}
function getOrgTree() {
  const tree = unref(orgTreeRef);
  if (!tree) {
    throw new Error('tree is null!');
  }
  return tree;
}
function getPosTree() {
  const tree = unref(posTreeRef);
  if (!tree) {
    throw new Error('tree is null!');
  }
  return tree;
}
function handleSubmit() {
  const ids = state.selectedData.map((o) => o.id);
  if (props.required && !ids.length) {
    createMessage.warning('至少选择一条数据');
    return;
  }
  state.options = state.selectedData;
  state.innerValue = props.multiple ? ids : ids[0];
  if (props.multiple) {
    emit('update:value', ids);
    emit('change', ids, state.options);
  } else {
    emit('update:value', ids[0] || '');
    emit('change', ids[0] || '', state.options[0]);
  }
  formItemContext.onFieldChange();
  handleCancel();
}
function bindScroll() {
  const bodyRef = infiniteBody.value;
  const vBody = bodyRef?.getScrollWrap();
  vBody?.addEventListener('scroll', () => {
    if (state.activeKey != '1') return;
    if (vBody.scrollHeight - vBody.clientHeight - vBody.scrollTop <= 200 && !state.loading && !state.finish) {
      state.query.currentPage += 1;
      getList();
    }
  });
}
function onLoadData(node) {
  state.parentId = node.id;
  return new Promise((resolve: (value?: unknown) => void) => {
    getOrganizeSelector({ parentId: state.parentId }).then((res) => {
      const list = res.data.list;
      getOrgTree().updateNodeByKey(node.eventKey, { isLeaf: list.length === 0, children: list });
      resolve();
    });
  });
}
function getOrgList() {
  state.orgLoading = true;
  getOrganizeSelector({ parentId: state.parentId })
    .then((res) => {
      state.orgTreeData = res.data.list;
      if (state.orgTreeData.length > 0 && state.parentId == '0') {
        nextTick(() => {
          const keys = [state.orgTreeData[0].id];
          getOrgTree().setSelectedKeys(keys);
          handleOrgSelect(keys);
        });
      }
      state.orgLoading = false;
    })
    .catch(() => {
      state.orgLoading = false;
    });
}
function getList() {
  state.loading = true;
  getPositionSelector(state.query)
    .then((res) => {
      if (res.data.list.length < state.query.pageSize) state.finish = true;
      state.treeData = [...state.treeData, ...res.data.list];
      state.loading = false;
      if (props.hasSys && state.query.currentPage === 1 && !state.listActiveKey) {
        state.listActiveKey = state.treeData[0].id;
        getSubData(state.treeData[0]);
      }
    })
    .catch(() => {
      state.loading = false;
    });
}
async function initData() {
  state.parentId = '0';
  state.query.currentPage = 1;
  state.finish = false;
  state.orgTreeData = [];
  state.treeData = [];
  if (props.selectType === 'all') {
    if (state.activeKey === '1') {
      state.query.keyword ? getList() : getOrgList();
    } else {
      state.treeData = props.hasSys ? cloneDeep(systemFieldList) : unref(getCurrPosList);
    }
  } else {
    if (!props.ableIds?.length) return (state.treeData = []);
    state.loading = true;
    getPositionByCondition(props.ableIds).then((res) => {
      state.treeData = res.data.list;
      state.loading = false;
    });
  }
}
</script>
 
<template>
  <div v-if="buttonType === 'button'" :class="[$attrs.class]" class="select-tag-list">
    <AButton pre-icon="icon-ym icon-ym-btn-add" :type="buttonShowType" @click="openSelectModal">{{ modalTitle }}</AButton>
    <div class="tags" v-if="showSelectedList">
      <Tag v-for="(item, i) in options" :key="item.id" :closable="!disabled" class="!mt-[10px]" @close="onTagClose(i)">{{ item.orgNameTree }}</Tag>
    </div>
  </div>
  <Select v-bind="getSelectBindValue" v-else v-model:value="innerValue" :options="options" @change="onChange" @click="openSelectModal" />
  <AModal v-model:open="visible" :keyboard="false" :mask-closable="false" title="选择岗位" :width="800" centered class="common-select-modal">
    <template #closeIcon>
      <ModalClose :can-fullscreen="false" @cancel="handleCancel" />
    </template>
    <template #footer>
      <ModalFooter @cancel="handleCancel" @ok="handleSubmit">
        <template #insertFooter v-if="multiple">
          <div class="float-left">
            <span class="mr-[10px]">{{ $t('component.jnpf.common.selected') }}({{ selectedData.length }})</span>
            <span class="remove-all-btn" @click="removeAll">{{ $t('component.jnpf.common.clearAll') }}</span>
          </div>
        </template>
      </ModalFooter>
    </template>
    <div class="common-select-modal-main">
      <div class="selected-pane">
        <Tag v-for="(item, i) in selectedData" :key="item.id" :closable="true" class="selected-pane-tag" @close="removeData(i)">
          {{ item.orgNameTree }}
        </Tag>
      </div>
      <div class="select-pane">
        <div class="select-pane-tool">
          <Tabs v-model:active-key="activeKey" :tab-bar-gutter="20" class="select-pane-tool-tabs" @change="onTabChange">
            <TabPane key="1" tab="岗位" />
            <TabPane key="system" tab="动态参数" v-if="hasSys && selectType === 'all'" />
            <TabPane key="current" tab="当前岗位" v-if="!hasSys && selectType === 'all'" />
            <template #rightExtra>
              <Input v-model:value="query.keyword" :placeholder="$t('common.enterKeyword')" allow-clear @change="debounceHandleSearch" />
            </template>
          </Tabs>
          <div class="select-pane-main">
            <template v-if="activeKey === '1' && !query.hasPage">
              <BasicTree ref="orgTreeRef" class="tree-main select-pane-item" v-bind="getOrgTreeBindValue" v-if="selectType === 'all'" />
              <BasicTree ref="posTreeRef" class="tree-main select-pane-item" v-bind="getPosTreeBindValue" />
            </template>
            <ScrollContainer v-else class="select-pane-list select-pane-item" ref="infiniteBody" v-loading="loading && query.currentPage === 1">
              <div
                v-for="(item, i) in treeData"
                :key="i"
                class="select-pane-list__item"
                :class="{ 'select-pane-list__item-active': listActiveKey === item.id }"
                @click="handleListNodeClick(item)">
                <div class="select-pane-list__item-title">
                  <i :class="item.icon" v-if="item.icon" class="mr-[6px]"></i>
                  <span :title="item.orgNameTree">{{ item.orgNameTree }}</span>
                </div>
                <div class="select-pane-list__item-action" v-if="!hasSys || activeKey !== '1'">
                  <Checkbox :checked="selectedIds.includes(item.id)" v-if="multiple" />
                  <Radio :checked="selectedIds.includes(item.id)" v-else />
                </div>
              </div>
              <jnpf-empty v-if="treeData.length === 0" />
            </ScrollContainer>
            <ScrollContainer class="select-pane-list select-pane-item" ref="infiniteBody" v-if="hasSys && activeKey === '1'">
              <div v-for="(item, i) in subData" :key="i" class="select-pane-list__item" @click="handleNodeClick(item)">
                <div class="select-pane-list__item-title">
                  <i :class="item.icon" v-if="item.icon" class="mr-[6px]"></i>
                  <span :title="item.fullName">{{ item.fullName }}</span>
                </div>
                <div class="select-pane-list__item-action">
                  <Checkbox :checked="selectedIds.includes(item.id)" v-if="multiple" />
                  <Radio :checked="selectedIds.includes(item.id)" v-else />
                </div>
              </div>
              <jnpf-empty v-if="subData.length === 0" />
            </ScrollContainer>
          </div>
        </div>
      </div>
    </div>
  </AModal>
</template>