ny
昨天 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
<script lang="ts" setup>
import type { ScrollActionType, TreeActionType } from '@jnpf/ui';
 
import { computed, nextTick, reactive, ref, toRefs, unref, watch } from 'vue';
 
import { useGlobSetting, useMessage } from '@jnpf/hooks';
import { BasicTree, ScrollContainer } from '@jnpf/ui';
import { BasicModal, useModalInner } from '@jnpf/ui/modal';
 
import { useUserStore } from '@vben/stores';
 
import { useDebounceFn } from '@vueuse/core';
import { Avatar, Checkbox, Input, TabPane, Tabs, Tag } from 'ant-design-vue';
 
import { getOrganizeSelector } from '#/api/permission/organize';
import { getPositionSelectorTree } from '#/api/permission/position';
import { getUserInfoList, getUserList } from '#/api/permission/user';
import { getInfo, saveUserList } from '#/api/systemData/interfaceOauth';
import { $t } from '#/locales';
import { useOrganizeStore } from '#/store';
 
defineEmits(['register']);
 
interface State {
  activeKey: string;
  finish: boolean;
  innerValue: any[] | string | undefined;
  lastList: any[];
  lastLoading: boolean;
  listActiveKey: string;
  loading: boolean;
  options: any[];
  orgLoading: boolean;
  orgTreeData: any[];
  parentId: string;
  query: any;
  selectedData: any[];
  selectedIds: any[];
  treeData: any[];
  userQuery: any;
  interfaceIdentId: string;
}
 
const userStore = useUserStore();
const organizeStore = useOrganizeStore();
const globSetting = useGlobSetting();
const apiUrl = ref(globSetting.apiURL);
const orgTreeRef = ref<Nullable<TreeActionType>>(null);
const posTreeRef = ref<Nullable<TreeActionType>>(null);
const infiniteBody = ref<Nullable<ScrollActionType>>(null);
const state = reactive<State>({
  activeKey: '',
  finish: false,
  innerValue: '',
  lastList: [],
  lastLoading: false,
  loading: false,
  options: [],
  orgLoading: false,
  orgTreeData: [],
  parentId: '0',
  query: {
    currentPage: 1,
    hasPage: 0,
    keyword: '',
    pageSize: 20,
  },
  selectedData: [],
  selectedIds: [],
  treeData: [],
  userQuery: {},
  listActiveKey: '',
  interfaceIdentId: '',
});
const { activeKey, lastList, lastLoading, query, selectedData, selectedIds, treeData, listActiveKey } = toRefs(state);
const [registerModal, { changeLoading, changeOkLoading, closeModal }] = useModalInner(init);
const { createMessage } = useMessage();
const defaultUserQuery = {
  enabledMark: 1,
  groupId: '',
  organizeId: '',
  positionId: '',
  roleId: '',
};
const debounceHandleSearch = useDebounceFn(handleSearch, 300);
 
const getCurrList: any = computed(() => {
  const userInfo: any = userStore.getUserInfo || {};
  const current = {
    fullName: `${userInfo.userName}/${userInfo.userAccount}`,
    headIcon: userInfo.headIcon,
    id: userInfo.userId,
    realName: userInfo.userName,
  };
  return [current];
});
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,
  };
  return data;
});
 
watch(
  () => state.selectedData,
  (val) => {
    state.selectedIds = val.map((o) => o.id);
  },
  { deep: true },
);
 
function init(data) {
  changeLoading(true);
  state.interfaceIdentId = data.id;
  state.activeKey = '1';
  state.selectedData = [];
  onTabChange();
  getInfo(data.id).then((res) => {
    const ids = res.data.userList.map((o) => o.userId) || [];
    if (!ids.length) return changeLoading(false);
    getUserInfoList(ids).then((res) => {
      state.selectedData = res.data.list;
      changeLoading(false);
    });
  });
  changeLoading(false);
}
function onTabChange() {
  state.query.hasPage = 0;
  state.query.keyword = '';
  initData();
  nextTick(() => {
    bindScroll();
  });
}
function handleSearch(e) {
  const value = e.target.value;
  if (state.lastLoading) return;
  if (state.activeKey !== '1') state.activeKey = '1';
  state.query.keyword = value || '';
  state.query.hasPage = state.query.keyword ? 1 : 0;
  if (state.query.hasPage) {
    state.userQuery = { ...defaultUserQuery };
    nextTick(() => {
      bindScroll();
    });
  }
  initData();
}
function handleOrgSelect(keys) {
  if (keys.length === 0) return;
  const data = getOrgTree().getSelectedNode(keys[0]);
  state.activeKey == 'organize' ? handleListNodeClick(data) : getPosTreeData(keys[0]);
}
// 获取岗位树
function getPosTreeData(id) {
  state.loading = true;
  getPositionSelectorTree({ organizeId: id })
    .then((res) => {
      state.treeData = res.data.list || [];
      if (state.treeData.length > 0) {
        nextTick(() => {
          if (state.activeKey !== 'position') return;
          const keys = [state.treeData[0].id];
          getPosTree().setSelectedKeys(keys);
          handleSelect(keys);
        });
      } else {
        state.lastList = [];
      }
      state.loading = false;
    })
    .catch(() => {
      state.loading = false;
    });
}
function handleSelect(keys) {
  if (keys.length === 0) return;
  const data = getPosTree().getSelectedNode(keys[0]);
  handleListNodeClick(data);
}
function handleListNodeClick(data) {
  state.listActiveKey = data.id;
  const key = `${state.activeKey === '1' ? 'group' : state.activeKey}Id`;
  state.userQuery = { ...defaultUserQuery, [key]: state.listActiveKey };
  state.lastList = [];
  state.finish = false;
  state.query.currentPage = 1;
  getLastList();
}
function handleNodeClick(data) {
  const index = state.selectedData.findIndex((o) => o.id === data.id);
  if (index !== -1) return state.selectedData.splice(index, 1);
  state.selectedData.push(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 bindScroll() {
  const bodyRef = infiniteBody.value;
  const vBody = bodyRef?.getScrollWrap();
  vBody?.addEventListener('scroll', () => {
    if (vBody.scrollTop > 0 && vBody.scrollHeight - vBody.clientHeight - vBody.scrollTop <= 200 && !state.lastLoading && !state.finish) {
      state.query.currentPage += 1;
      getLastList();
    }
  });
}
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 getLastList() {
  const oldActiveKey = state.activeKey;
  state.lastLoading = true;
  const query = { ...state.query, ...state.userQuery };
  getUserList(query)
    .then((res) => {
      state.lastLoading = false;
      if (state.activeKey !== oldActiveKey) return;
      state.finish = res.data.list.length < state.query.pageSize;
      state.lastList = [...state.lastList, ...res.data.list];
    })
    .catch(() => {
      state.lastLoading = false;
    });
}
async function initData() {
  state.parentId = '0';
  state.query.currentPage = 1;
  state.finish = false;
  state.orgTreeData = [];
  state.treeData = [];
  state.lastList = [];
  state.listActiveKey = '';
  switch (state.activeKey) {
    case '1': {
      if (state.query.keyword) return getLastList();
      const res = await organizeStore.getGroupList();
      state.treeData = [{ fullName: '全部用户', icon: 'icon-ym icon-ym-generator-group1', id: '' }, ...res];
      handleListNodeClick(state.treeData[0]);
      break;
    }
    case 'current': {
      state.lastList = unref(getCurrList);
      break;
    }
    case 'organize':
    case 'position': {
      getOrgList();
      break;
    }
    case 'role': {
      state.treeData = await organizeStore.getRoleList();
      state.treeData[0] && handleListNodeClick(state.treeData[0]);
      break;
    }
    default: {
      state.treeData = [];
    }
  }
}
function handleSubmit() {
  changeOkLoading(true);
  const userIds = state.selectedData.map((o) => o.id);
  const query = {
    interfaceIdentId: state.interfaceIdentId,
    userIds,
  };
  saveUserList(query)
    .then((res) => {
      createMessage.success(res.msg);
      changeOkLoading(false);
      closeModal();
    })
    .catch(() => {
      changeOkLoading(false);
    });
}
</script>
<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="授权用户" :width="800" @ok="handleSubmit" destroy-on-close class="common-select-modal">
    <template #insertFooter>
      <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>
    <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.fullName }}
        </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="organize" tab="组织架构" />
            <TabPane key="position" tab="岗位" />
            <TabPane key="role" tab="角色" />
            <TabPane key="current" tab="当前用户" />
            <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="!query.hasPage">
              <ScrollContainer class="select-pane-list select-pane-item" v-if="activeKey === '1' || activeKey === 'role'">
                <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.fullName">{{ item.fullName }}</span>
                  </div>
                </div>
                <jnpf-empty v-if="treeData.length === 0" />
              </ScrollContainer>
              <BasicTree
                ref="orgTreeRef"
                class="tree-main select-pane-item"
                v-bind="getOrgTreeBindValue"
                v-if="activeKey === 'organize' || activeKey === 'position'" />
              <BasicTree ref="posTreeRef" class="tree-main select-pane-item" v-bind="getPosTreeBindValue" v-if="activeKey === 'position'" />
            </template>
            <ScrollContainer class="select-pane-list select-pane-item" ref="infiniteBody" v-loading="lastLoading && query.currentPage === 1">
              <div v-for="(item, i) in lastList" :key="i" class="select-pane-list__item" @click="handleNodeClick(item)">
                <div class="select-pane-list__item-title">
                  <Avatar :size="26" :src="apiUrl + item.headIcon" class="select-pane-list__item--headIcon" v-if="item.headIcon" />
                  <i :class="item.icon" class="mr-[6px]" v-if="item.icon && !item.headIcon"></i>
                  <span :title="item.fullName">{{ item.fullName }}</span>
                </div>
                <div class="select-pane-list__item-action">
                  <Checkbox :checked="selectedIds.includes(item.id)" />
                </div>
              </div>
              <jnpf-empty v-if="lastList.length === 0" />
            </ScrollContainer>
          </div>
        </div>
      </div>
    </div>
  </BasicModal>
</template>