liuxiaolong
2019-05-06 f99bc8c6a1d10610373738edd7d0aa0181c81d99
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
package com.cloud.user.service.impl;
 
import com.alibaba.fastjson.JSONObject;
import com.cloud.common.constants.GlobalDict;
//import com.cloud.common.utils.AppUserUtil;
import com.cloud.common.utils.OrgTypeUtil;
import com.cloud.common.utils.PageUtil;
import com.cloud.model.common.Page;
import com.cloud.model.sys.AppUser;
import com.cloud.model.sys.BbEmployee;
import com.cloud.model.sys.SysOrganization;
import com.cloud.user.constants.ORGConstant;
import com.cloud.user.dao.*;
import com.cloud.user.service.SysOrganizationService;
import com.cloud.user.service.TokenService;
import com.cloud.user.vo.SysOrganizationVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.util.*;
 
@Slf4j
@Service
public class SysOrganizationServiceImpl implements SysOrganizationService {
 
    @Autowired
    private SysOrganizationDao orgDao;
    @Autowired
    private UserCredentialsDao userCredentialsDao;
    @Autowired
    private AppUserDao appUserDao;
    @Autowired
    private BbEmployeeDao bbEmployeeDao;
    /*@Autowired
    private BCryptPasswordEncoder passwordEncoder;*/
    @Autowired
    private UserRoleDao userRoleDao;
    @Autowired
    private TokenService tokenService;
 
    @Transactional
    @Override
    public Map<String,Object> save(SysOrganizationVO org) {
        Integer repeatNum = orgDao.isRepeatOrgName(org.getParentId(),org.getName());
        if (repeatNum>0) {
            throw new IllegalArgumentException("此机构下已有相同组织机构名,请更正!");
        }
        Map<String,Object> result = new HashMap<>();
        JSONObject jsonAddress = null;
        //初始化字段赋值
        org.preInsert(tokenService.currentUser());
 
        //判断orgId是什么
        Long schoolValue = Long.parseLong(OrgTypeUtil.getByKey(GlobalDict.SCHOOL).getValue());
        Long parentValue = Long.parseLong(org.getParentValue());
        Long rootSchoolValue = Long.parseLong(OrgTypeUtil.getByKey(GlobalDict.ROOT_SCHOOL).getValue());
        if(schoolValue < parentValue){
            org.setOrgId(org.getOrgId());
        }else{
            org.setOrgId(org.getParentId());
        }
 
        //总校ID
        /**
         * 2) 判断是否是学校,是学校添加总校id.
         */
        if(schoolValue == Long.parseLong(org.getType())){
            if(rootSchoolValue == parentValue){
                org.setHeadquartersId(org.getParentId());
            }
        }
 
        //经纬度
        if(org.getLat() != null && org.getLng() != null){
            jsonAddress = new JSONObject();
            JSONObject jsonLocation = new JSONObject();
            jsonLocation.put(ORGConstant.PARENT_JSON_LAT,org.getLat());
            jsonLocation.put(ORGConstant.PARENT_JSON_LNG,org.getLng());
            jsonAddress.put("address",jsonLocation);
            org.setRevJson(jsonAddress.toJSONString());
        }
 
        //排序sort
        org.setSort(Integer.parseInt(org.getType().toString().substring(0,1)));
 
        Integer status = orgDao.save(org);
        if(status > 0){
            //更新parentIds 、parentJson
            Map map = getParentsInfo(org);
            if(map!=null){
                String parentIds = map.get("parentIds").toString();
                String parentJson = map.get("parentJson").toString();
                Boolean updataFlag= false;
 
                if(!StringUtils.isBlank(parentIds)){
                    org.setParentIds(parentIds);
                    updataFlag =true;
                }
                if(!StringUtils.isBlank(parentJson)){
                    org.setParentJson(parentJson);
                    updataFlag=true;
                }
                if(updataFlag){
                    orgDao.update(org);
                }
            }
 
            //逻辑处理
            //判断字段  username password 都不为空
            /**
             *  最后一步) 处理添加的管理员
             */
            try{
            if(StringUtils.isNotEmpty(org.getUsername())&&StringUtils.isNotEmpty(org.getPassword())){
                AppUserServiceImpl appUserService = new AppUserServiceImpl();
                Map<String,Object> params = new HashMap<>();
                AppUser appUser = new AppUser();
                appUser.setUsername(org.getUsername());
                appUser.setPassword(org.getPassword());
                appUser.setNickname(org.getName());
                appUser.setOrgId(org.getId());
                appUser.setOfficeId(org.getId().intValue());
 
                params.put("appUser",appUser);
                params.put("appDao",appUserDao);
                params.put("roleDao",userRoleDao);
                params.put("userDao",userCredentialsDao);
                params.put("passCoder",null);
                Long id = appUserService.registerAdmin(params);
 
                JSONObject jsonUser = new JSONObject();
                jsonUser.put("userId",id);
                jsonUser.put("userName",org.getUsername());
                jsonAddress.put("admin",jsonUser);
                SysOrganizationVO orgNew = new SysOrganizationVO();
                orgNew.setId(org.getId());
                orgNew.setRevJson(jsonAddress.toJSONString());
                orgDao.update(orgNew);
 
                //获取CHECK的角色id
                // Integer roleId = 2;
                // params.put("id",id);
                //params.put("roleIds",2+",");
                //appUserService.setRoleToAdmin(params);
            }}catch (Exception e){
                result.put("code",1);
                result.put("message","用户名已存在!");
                orgDao.delete(org.getId(),org.getOrgId());
                return result;
            }
            result.put("code",0);
            result.put("message","保存成功!");
        }else{
            result.put("code",1);
            result.put("message","保存失败!");
        }
 
        return result;
    }
 
    @Transactional
    @Override
    public int update(SysOrganization org) {
 
        org.preUpdate(tokenService.currentUser());
        return orgDao.update(org);
    }
 
    @Override
    public SysOrganization findById(Long id, Long orgId) {
        //逻辑处理
        SysOrganization sysOrganization = orgDao.findById(id, orgId);
        if(sysOrganization != null) {
            sysOrganization.setCreateTime(null);
            sysOrganization.setUpdateTime(null);
        }
        return sysOrganization;
    }
 
    @Transactional
    @Override
    public int delete(Long id, Long orgId) {
        //1. 删除逻辑判断
 
        //2. 相关数据处理
 
        return orgDao.delete(id, orgId);
    }
 
    @Override
    public Page<SysOrganization> findPageByParams(Map<String, Object> params) {
        int total = orgDao.count(params);
        List<SysOrganization> list = Collections.emptyList();
        if (total > 0) {
            PageUtil.pageParamConver(params, false);
 
            list = orgDao.findData(params);
        }
        return new Page<>(total, list);
    }
 
    /**
     * 查找上级第一个指定的机构类型
     * 例如:查找学校
     *
     * @param type      要查找的机构类型
     * @param currentId 指定的机构id,查它之上的机构
     * @return
     */
    @Override
    public SysOrganization findUpByType(Integer type, Long currentId,Long orgId) {
        //当前组织的父集节点结合
        String parentIds = orgDao.findCurentParentIds(currentId,orgId);
        //String parentStr = getParentIds(parentIds,currentId);
        //orgId分库时,当前机构和上级指定的机构类型不在同一个分库中
        return orgDao.findUpByType(type,null,parentIds);
    }
 
    /**
     * 查找上级第一个机构(类型为机构)
     * 例如:查找学校
     *
     * @param currentId 指定的机构id,查它之上的机构
     * @return
     */
    @Override
    public SysOrganization findUpById(Long currentId,Long orgId) {
        //当前组织的父集节点结合
        String parentIds = orgDao.findCurentParentIds(currentId,orgId);
        //String parentStr = getParentIds(parentIds,currentId);
        //orgId分库时,当前机构和上级指定的机构类型不在同一个分库中,如果currentId是机构排除本身
        return orgDao.findUpById(currentId,parentIds,OrgTypeUtil.BUSINESS_TYPE);
    }
 
    /**
     * 查找下级的指定类型的所有机构
     * 例如;查找查找学校所有年级,年级所有的班级
     *
     * @param type      要查找的机构类型
     * @param currentId 指定的机构id,查它之下的机构
     * @return
     */
    @Override
    public List<SysOrganization> findDownByType(Integer type, Long currentId,Long orgId) {
 
        //当前组织的父集节点结合
        String parentIds = orgDao.findCurentParentIds(currentId,orgId);
        return orgDao.findDownByType(type,orgId,parentIds);
    }
 
    @Override
    public Map<String,Object> findCheckSchool(Map<String,Object> params) {
        Map<String,Object> map = new HashMap<>();
        //当前组织的父集节点结合
        String parentIds = orgDao.findCurentParentIds(Long.parseLong(params.get("currentId").toString()),null);
        //从字典查出学校value
        List<Integer> list = new ArrayList<>();
        Integer school = Integer.parseInt(OrgTypeUtil.getByKey(GlobalDict.SCHOOL).getValue());
        Integer xuequ = Integer.parseInt(OrgTypeUtil.getByKey(GlobalDict.ROOT_SCHOOL).getValue());
        list.add(school);
        list.add(xuequ);
        params.put("type",list);
        params.put("parentIds",parentIds);
        List<Map<String,Object>> data = orgDao.findCheckSchool(params);
        if(data != null){
            for(Map<String,Object> org:data){
               JSONObject jsonObject = new JSONObject();
               if(org.containsKey("revJson")){
                   jsonObject = JSONObject.parseObject(org.get("revJson").toString());
                   JSONObject location = JSONObject.parseObject(jsonObject.get("address").toString());
                   org.put("lat",location.get("lat"));
                   org.put("lng",location.get("lng"));
               }else {
                   org.put("lat","");
                   org.put("lng","");
               }
               if(!org.containsKey("address")){
                   org.put("address","");
               }
               org.remove("revJson");
            }
        }
        if(data.size()>0){
            map.put("data",data);
            map.put("code",0);
            map.put("message","查询成功");
        }else {
            map.put("data","");
            map.put("code",1);
            map.put("message","暂无数据");
        }
        return map;
    }
 
    @Override
    public List<Integer> findDownByOffIds(Map<String, Object> param) {
        return orgDao.findDownByOffIds(param);
    }
 
    @Override
    public boolean isImportStudentClass(Map<String, Object> param) {
        return orgDao.isImportStudentClass(param);
    }
 
    @Override
    public Map<String, Object> isisImportTeacherOffice(Map<String, Object> param) {
        return orgDao.isisImportTeacherOffice(param);
    }
 
    @Override
    public String findCompactName(Integer officeId) {
        return orgDao.findCompactName(officeId);
    }
 
    @Override
    public List<Integer> findOrgIds(Integer id) {
 
        String parentIds = orgDao.findCurentParentIds(id.longValue(),null);
 
        List<Integer> types = new ArrayList<>();
        int destrictType = Integer.parseInt(OrgTypeUtil.getByKey(GlobalDict.SCHOOL_DISTRICT).getValue());
        int rootSchoolType = Integer.parseInt(OrgTypeUtil.getByKey(GlobalDict.ROOT_SCHOOL).getValue());
        int schoolType = Integer.parseInt(OrgTypeUtil.getByKey(GlobalDict.SCHOOL).getValue());
        types.add(destrictType);
        types.add(rootSchoolType);
        types.add(schoolType);
        Map<String,Object> params = new HashMap<>();
        params.put("types",types);
        params.put("parentIds",parentIds);
        List<Integer> list = orgDao.findOrgIds(params);
        return list;
    }
 
    @Override
    public String findOrgName(Integer id) {
        return orgDao.findOrgName(id);
    }
 
 
    /**
     * 查找所有的组织树
     * @param params  组织机构ID
     * @return
     */
    @Override
    public List<SysOrganization> findAll(Map<String,Object> params) {
        return orgDao.findAll(params);
    }
 
    @Override
    public List<SysOrganization> findHeadquarters(Long currentId, String type) {
        return orgDao.findHeadquarters(currentId,type);
    }
 
    @Override
    public List<SysOrganization> findSubOrg(Long headId, boolean isSelf, String type) {
        return orgDao.findSubOrg(headId,isSelf,type);
    }
 
    @Override
    @Transactional
    public Map<String, Object> deleteOrg(Map<String, Object> params) {
        //查询该机构下是否存在人员,如果存在人员就不允许删除
        Map<String,Object> map = new HashMap<>();
        params.put("delFlag", GlobalDict.IS_NOT_DEL);
        List<BbEmployee> employeeList = bbEmployeeDao.findDataByOfficeId(params);
        List<AppUser> appUserList = appUserDao.findDataByOfficeId(params);
        if((employeeList != null && employeeList.size()>0)||(appUserList != null && appUserList.size()>0)){
            map.put("code",1);
            map.put("message","删除失败,该机构(包含下级机构)有人员存在");
        }else{
            Integer status = orgDao.deleteOrg(params);
            //删除组织下的所有登录用户
//            appUserDao.deleteAppUserByOrgId(params.get("id").toString());
            if(status > 0){
                map.put("code",0);
                map.put("message","删除成功!!!");
            }else {
                map.put("code",1);
                map.put("message","删除失败!!!");
            }
        }
        return map;
    }
 
    /**
     * 递归遍历上级得到信息
     */
    public Map<String,String> getParentsInfo(SysOrganization org){
        Map result = new  HashMap<String,String>();
        if(org.getParentId() != null && org.getParentId() != 0){
            result = getParentInfoByData(org);
        }else{
            result = getParentInfoByRecursion(org);
        }
        return result;
    }
 
    /**
     * 得到父节点所有信息,根据parent进行组装
     * @param org
     * @return
     */
    private Map<String,String> getParentInfoByData(SysOrganization org){
        Map result = new  HashMap<String,String>();
        String parentIds = "";
        String parentJson = "";
        SysOrganization parent = this.findById(org.getParentId(),null);
        if(parent != null) {
            parentIds = parent.getParentIds() + org.getId() + ",";
            JSONObject jsonObject = new JSONObject();
 
            JSONObject value = new JSONObject();
            value.put(ORGConstant.PARENT_JSON_NAME, parent.getName());
            value.put(ORGConstant.PARENT_JSON_TYPE, parent.getType());
 
            //parentjson不为空,则拼接
            if (!StringUtils.isBlank(parent.getParentJson())) {
                jsonObject = JSONObject.parseObject(parent.getParentJson());
            }
            jsonObject.put(org.getId().toString(), value);
 
            parentJson = JSONObject.toJSONString(jsonObject==null ? value : jsonObject);
        }
        result.put("parentIds",parentIds);
        result.put("parentJson",parentJson);
        return result;
 
    }
 
    /**
     * 得到父节点所有信息(根据递归,无parent时)
     * @param org
     * @return
     */
    private Map<String,String> getParentInfoByRecursion(SysOrganization org){
        Map result = new  HashMap<String,String>();
        String parentIds = ","+org.getId()+",";
        String parentJson = "";
 
        OrgTypeUtil.getByKey(GlobalDict.SCHOOL).getValue();
 
 
 
        result.put("parentIds",parentIds);
        result.put("parentJson",parentJson);
        return result;
    }
 
}