jinlin
2024-01-31 9025b9cf7ec8610003d445a31d93e35e7bd73c2e
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
/**
 * Copyright (c) 2018 人人开源 All rights reserved.
 * <p>
 * https://www.renren.io
 * <p>
 * 版权所有,侵权必究!
 */
 
package com.zt.modules.sys.service;
 
import cn.hutool.core.convert.Convert;
import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.zt.common.constant.Constant;
import com.zt.common.constant.Status;
import com.zt.common.db.query.QueryFilter;
import com.zt.common.entity.MapData;
import com.zt.common.exception.ErrorCode;
import com.zt.common.exception.RenException;
import com.zt.common.service.BaseService;
import com.zt.common.servlet.Result;
import com.zt.common.utils.CacheUtils;
import com.zt.common.utils.TreeUtils;
import com.zt.core.context.User;
import com.zt.core.context.UserContext;
import com.zt.core.sys.model.SysDept;
import com.zt.core.sys.service.ISysDeptService;
import com.zt.modules.sys.dao.SysDeptDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
 
/**
 * 部门管理
 *
 * @author hehz
 */
@Service
public class SysDeptService extends BaseService<SysDeptDao, SysDept> implements ISysDeptService {
 
    @Autowired
    private SysUserService sysUserService;
 
    private List<SysDept> getAll() {
        // 这里手动缓存,不然在当前方法内调用缓存无效
        List<SysDept> all = null;//(List<SysDept>) CacheUtils.get(Constant.Cache.DEPT, "all");
        if (all == null) {
            all = baseDao.getAll();
            //CacheUtils.put(Constant.Cache.DEPT, "all", all);
        }
        return all.stream().map(dept -> {
            try {
                return dept.clone();
            } catch (CloneNotSupportedException e) {
            }
            return null;
        }).collect(Collectors.toList());
    }
 
    public List<SysDept> getTenantAll() {
        return getAll();
//        return getAll().stream().filter(dept -> dept.getTenantId().equals(UserContext.getUser().getTenantId()))
//                .collect(Collectors.toList());
    }
 
    /**
     * 查询当前租户下公司树
     *
     * @return
     */
    public List<SysDept> getCompanyTree() {
        List<SysDept> list = getTenantAll().stream().filter(dept -> dept.isCompany()).collect(Collectors.toList());
        // 查询所属公司及子公司的数据
        List<Long> deptIds = this.getWithDescendantIds(UserContext.getUser().getCompanyId());
        list = list.stream().filter(dept -> deptIds.contains(dept.getId())).collect(Collectors.toList());
        List<SysDept> listOut = TreeUtils.build(list);
        //List<SysDept> listOut2 = TreeUtils.toList(listOut);
        return listOut;
    }
 
    /**
     * 查询当前登录用户公司部门树
     *
     * @return
     */
    public List<SysDept> getDeptTreeRegister() {
        List<SysDept> list = getTenantAll();
 
        List<SysDept> listArea = list.stream().filter(dept -> "sy".equals(dept.getCode())).collect(Collectors.toList());
        if (listArea.size() > 0) {
            Long deptId = listArea.get(0).getId();
            List<Long> deptIds = this.getWithDescendantIds(deptId);
            deptIds.remove(0);
            list = list.stream().filter(dept -> deptIds.contains(dept.getId())).collect(Collectors.toList());
        }
        return TreeUtils.build(list);
    }
 
    public List<SysDept> getDeptTree() {
        User user = UserContext.getUser();
        List<SysDept> list = getTenantAll();
 
        if (1==0 && !user.isSuperAdmin()) {
            // 查询所属部门及子部门的数据
            List<Long> deptIds = this.getWithDescendantIds(user.getDeptId());
            list = list.stream().filter(dept -> deptIds.contains(dept.getId())).collect(Collectors.toList());
        }
 
        return TreeUtils.build(list);
    }
 
    /**
     * 查询公司下部门树
     *
     * @param companyId
     * @return
     */
    public List<SysDept> getDeptList(Long companyId) {
        QueryFilter queryFilter = new QueryFilter();
        // 普通管理员,只能查询所属部门及子部门的数据
        User user = UserContext.getUser();
/*        if (!user.isSuperAdmin()) {
            queryFilter.addParam("deptIds", this.getWithDescendantIds(user.getDeptId()));
        }*/
        // 查询公司下部门列表
        queryFilter.addParam("isCompany", Constant.Bool.NO);
        queryFilter.addParam("companyId", companyId);
 
        // 查询部门列表
        List<SysDept> entityList = baseDao.getList(queryFilter.getParams());
 
        return TreeUtils.build(entityList);
    }
 
    @Override
    @Cacheable(value = Constant.Cache.DEPT, key = "'id:' + #id")
    public SysDept get(Long id) {
        return baseDao.getById(id);
    }
 
    /**
     * 通过deptId查找所有祖先,按照祖先的层级排序
     *
     * @param id
     * @return
     */
    @Override
    public List<SysDept> getAncestor(Long id) {
        return TreeUtils.getAncestor(getTenantAll(), id);
    }
 
    /**
     * 获取自己和所有下级
     *
     * @param id
     * @return
     */
    public List<SysDept> getWithDescendant(Long id) {
        return TreeUtils.getWithDescendant(getTenantAll(), id);
    }
 
    @Override
    @Cacheable(value = Constant.Cache.DEPT, key = "'withdescendant:' + #id")
    public List<Long> getWithDescendantIds(Long id) {
        return this.getWithDescendant(id).stream().map(dept -> dept.getId()).collect(Collectors.toList());
    }
 
 
    /**
     * 获取下级
     *
     * @param id
     * @return
     */
    @Override
    public List<SysDept> getDescendant(Long id) {
        return TreeUtils.getDescendant(getTenantAll(), id);
    }
 
    /**
     * 获取某部门的子节点
     *
     * @param id
     * @return
     */
    @Override
    public List<SysDept> getChildren(Long id) {
        return getTenantAll().stream().filter(dept -> dept.getPid().equals(id)).collect(Collectors.toList());
    }
 
    public List<SysDept> getByTypes(List<String> types) {
        return getTenantAll().stream().filter(dept -> types.contains(dept.getNature())).collect(Collectors.toList());
    }
 
    /**
     * 增加部门
     *
     * @param dept
     */
    @Override
    @CacheEvict(value = Constant.Cache.DEPT, allEntries = true)
    public void insert(SysDept dept) {
        if (dept.getId() == null || dept.getId() == 0) {
            dept.setId(IdWorker.getId());
        }
        dept.setStatus(Status.ENABLE.getValue());
        resetFullNameAndInnerId(dept, null);
 
        // 部门类型为公司时,生成id
        if (dept.isCompany()) {
            dept.setCompanyId(dept.getId());
        }
        dept.setTenantId(1L);
        super.insert(dept);
 
        // 更新数据范围表
        // dataScopeService.updateByDeptAdd(dept.getId(), dept.getParentId());
    }
 
    /**
     * 更新部门
     *
     * @param dept
     */
    @Override
    @CacheEvict(value = Constant.Cache.DEPT, allEntries = true)
    public void update(SysDept dept) {
        Long id = dept.getId();
        if (id == 0) {
            throw new RenException("获取主键失败");
        }
 
        SysDept tmp = get(id);
        TreeUtils.updateValidate(getTenantAll(), dept, tmp);
 
        if (!tmp.getPid().equals(dept.getPid())) {// 部门层级改变了
            resetFullNameAndInnerId(dept, null);
        }
 
        super.update(dept);
 
        // if (!tmp.getPid().equals(pid)) {// 部门层级改变了
        // // 更新数据范围表
        // dataScopeService.updateByDeptUpdate(dept.getId(),
        // dept.getParentId());
        // }
    }
 
    /**
     * 删除部门
     *
     * @param id
     */
    @Override
    @CacheEvict(value = Constant.Cache.DEPT, allEntries = true)
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        // 判断是否有子部门
        List<Long> subList = this.getWithDescendantIds(id);
        if (subList.size() > 1) {
            throw new RenException(ErrorCode.DEPT_SUB_DELETE_ERROR);
        }
 
        // 判断部门下面是否有用户
        int count = sysUserService.getByDeptId(id).size();
        if (count > 0) {
            throw new RenException(ErrorCode.DEPT_USER_DELETE_ERROR);
        }
 
        // 删除
        this.deleteLogic(id);
    }
 
    /**
     * 修改全称和内部编码
     *
     * @param dept
     * @param parent
     */
    private void resetFullNameAndInnerId(SysDept dept, SysDept parent) {
        if (parent == null) {
            parent = get(dept.getPid());
        }
        if (parent != null) {// 存在上级
            dept.setPids(parent.getPids() + "," + String.valueOf(dept.getId()));
        } else {// 没有上级
            dept.setPids(String.valueOf(dept.getId()));
        }
        resetChildFullNameAndInnerId(dept);
    }
 
    /**
     * 修改子类全称和内部编码
     *
     * @param parent
     */
    private void resetChildFullNameAndInnerId(SysDept parent) {
        List<SysDept> list = getChildren(parent.getId());
        for (SysDept dept : list) {
            resetFullNameAndInnerId(dept, parent);
            this.update(dept);
            resetChildFullNameAndInnerId(dept);
        }
    }
 
    public List<SysDept> fetchRepairer() {
        List<SysDept> list = this.getTenantAll();
 
        String factoryId = "cj".equals(UserContext.getUser().getUnitType()) ? UserContext.getUser().getCompanyId().toString() : "";
        String regionFlag = UserContext.getUser().getArea();//getSessionValue(UserContext.REGION_FLAG);
 
        /*
        如果属于某厂家,就返回此厂家
         */
        if (!StringUtils.isEmpty(factoryId)) {
            List<SysDept> collect = list
                    .stream()
                    .filter(dept -> {
                        return dept.getId().equals(new Long(factoryId));
                    })
                    .collect(Collectors.toList());
            return collect;
        }
 
        if (!StringUtils.isEmpty(regionFlag)) {
            List<SysDept> collectRegion = list
                    .stream()
                    .filter(dept -> {
                        return dept.getCode().equals(regionFlag);
                    })
                    .collect(Collectors.toList());
 
            if (!collectRegion.isEmpty()) {
                final SysDept regionSysDept = collectRegion.get(0);
 
                List<SysDept> collect = list
                        .stream()
                        .filter(dept -> {
                            String pids = dept.getPids();
                            String[] pidsArray = pids.split(",");
                            for (String pid : pidsArray) {
                                if (pid.equals(regionSysDept.getId().toString()) && new Integer(2).equals(dept.getNature())) {
                                    return true;
                                }
                            }
 
                            return false;
                        })
                        .collect(Collectors.toList());
                return collect;
            }
        }
 
        List<SysDept> collect = list
                .stream()
//                .filter(dept -> (new Integer(1).equals(dept.getNature()) && dept.isCompany())
//                        || (new Integer(2).equals(dept.getNature()) && dept.isCompany() /*&& dept.getPid().toString().equals("1271368584383188993") */)
//                        || "HBDD".equals(dept.getCode()))
                 .filter(dept -> "cj".equals(dept.getNature()))
                .collect(Collectors.toList());
        return collect;
    }
 
    public Long fetchRepairerId(String factoryName) {
        List<SysDept> list = this.fetchRepairer();
        if (list != null && !list.isEmpty()) {
            for (SysDept sysDept : list) {
                if (sysDept.getName() != null && sysDept.getName().equals(factoryName)) {
                    return sysDept.getId();
                }
            }
        }
        return null;
    }
 
    public List<SysDept> getListByParent(String pid, String pCode, String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("pCode", pCode);
        map.put("code", code);
        map.put("pId", pid);
        List<SysDept> list = baseDao.getListByParent(map);
        return list;
    }
 
    public Long getCompanyIdByDeptId(Long deptId) {
        SysDept sysDept = baseDao.getById(deptId);
        if (sysDept != null)
            return sysDept.getCompanyId();
        else
            return deptId;
    }
 
    public Map<String, String> getMapFactory(Boolean idToName) {
        List<SysDept> list = this.getTenantAll();
 
        List<SysDept> collect = list
                .stream()
                .filter(dept -> ("cj".equals(dept.getNature()) ))
                .collect(Collectors.toList());
 
        Map<String, String> result = new HashMap<>();
        for (SysDept item : collect) {
            if (idToName)
                result.put(item.getId().toString(), item.getName());
            else
                result.put(item.getName(), item.getId().toString());
        }
        return result;
    }
 
    public Map<String, String> getMapTeamFactory(Boolean idToName) {
        List<SysDept> list = this.getTenantAll();
 
        List<SysDept> collect = list
                .stream()
                .filter(dept -> ("cj".equals(dept.getNature()) ||"td".equals(dept.getNature())))
                .collect(Collectors.toList());
 
        Map<String, String> result = new HashMap<>();
        for (SysDept item : collect) {
            if (idToName)
                result.put(item.getId().toString(), item.getName());
            else
                result.put(item.getName(), item.getId().toString());
        }
        return result;
    }
 
    public List<SysDept> getDeptList3() {
        return baseDao.getDeptList3();
    }
}