智慧保安后台管理-外网
Administrator
2021-11-09 0e5b425783f87d734d07e83779988c8d18bb2dc7
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
/*
 *      Copyright (c) 2018-2028, Chill Zhuang All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *  Redistributions of source code must retain the above copyright notice,
 *  this list of conditions and the following disclaimer.
 *  Redistributions in binary form must reproduce the above copyright
 *  notice, this list of conditions and the following disclaimer in the
 *  documentation and/or other materials provided with the distribution.
 *  Neither the name of the dreamlu.net developer nor the names of its
 *  contributors may be used to endorse or promote products derived from
 *  this software without specific prior written permission.
 *  Author: Chill 庄骞 (smallchill@163.com)
 */
package org.springblade.modules.system.service.impl;
 
 
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.zxing.WriterException;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springblade.common.cache.SysCache;
import org.springblade.common.constant.AgeUtil;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.constant.TenantConstant;
import org.springblade.common.utils.QRCodeUtil;
import org.springblade.core.log.exception.ServiceException;
import org.springblade.core.mp.base.BaseServiceImpl;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tenant.BladeTenantProperties;
import org.springblade.core.tool.constant.BladeConstant;
import org.springblade.core.tool.jackson.JsonUtil;
import org.springblade.core.tool.support.Kv;
import org.springblade.core.tool.utils.*;
import org.springblade.modules.FTP.FtpUtil;
import org.springblade.modules.auth.enums.UserEnum;
import org.springblade.modules.dispatcher.vo.DispatcherVO;
import org.springblade.modules.information.entity.Information;
import org.springblade.modules.information.service.IInformationService;
import org.springblade.modules.system.entity.*;
import org.springblade.modules.system.excel.QrCodeExcel;
import org.springblade.modules.system.excel.SecurityExcel;
import org.springblade.modules.system.excel.UserExcel;
import org.springblade.modules.system.mapper.UserMapper;
import org.springblade.modules.system.node.TreeNode;
import org.springblade.modules.system.service.*;
import org.springblade.modules.system.vo.UserVO;
import org.springblade.modules.system.wrapper.UserWrapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
 
/**
 * 服务实现类
 *
 * @author Chill
 */
@Service
@AllArgsConstructor
public class UserServiceImpl extends BaseServiceImpl<UserMapper, User> implements IUserService {
    private static final String GUEST_NAME = "guest";
 
    private final IUserDeptService userDeptService;
    private final IUserOauthService userOauthService;
    private final IRoleService roleService;
    private final BladeTenantProperties tenantProperties;
    private final IInformationService iInformationService;
    private final IDeptService deptService;
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean submit(User user) {
        if (StringUtil.isBlank(user.getTenantId())) {
            user.setTenantId(BladeConstant.ADMIN_TENANT_ID);
        }
        String tenantId = user.getTenantId();
        Tenant tenant = SysCache.getTenant(tenantId);
        if (Func.isNotEmpty(tenant)) {
            Integer accountNumber = tenant.getAccountNumber();
            if (tenantProperties.getLicense()) {
                String licenseKey = tenant.getLicenseKey();
                String decrypt = DesUtil.decryptFormHex(licenseKey, TenantConstant.DES_KEY);
                accountNumber = JsonUtil.parse(decrypt, Tenant.class).getAccountNumber();
            }
            Integer tenantCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId));
            if (accountNumber != null && accountNumber > 0 && accountNumber <= tenantCount) {
                throw new ServiceException("当前租户已到最大账号额度!");
            }
        }
        if (Func.isNotEmpty(user.getPassword())) {
            user.setPassword(DigestUtil.encrypt(user.getPassword()));
        }
//        Integer userCount = baseMapper.selectCount(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, user.getAccount()));
        Integer userCount = baseMapper.selectCountAccount(user.getAccount());
        if (userCount > 0 && Func.isEmpty(user.getId())) {
            throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
        }
        boolean b = save(user) && submitUserDept(user);
        String rtime = null;
        if (null != user.getRtime()) {
            rtime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(user.getRtime());
        }
        user.setIsDeleted(0);
        String s = "insert into blade_user(id,tenant_id,account,password,real_name,email,phone,sex,role_id,dept_id,cardid,nativePlace,nation," +
            "politicaloutlook,healstats,height,address,registered,securitynumber,hold,status,dispatch,jurisdiction,is_deleted) " +
            "values(" + "'" + user.getId() + "'" + "," + "'" + user.getTenantId() + "'" + "," + "'" + user.getAccount() + "'" + "," +
            "'" + user.getPassword() + "'" + "," + "'" + user.getRealName() + "'" + "," +
            "'" + user.getEmail() + "'" + "," + "'" + user.getPhone() + "'" + "," + "'" + user.getSex() + "'" + "," + "'" + user.getRoleId() + "'" +
            "," + "'" + user.getDeptId() + "'" +
            "," + "'" + user.getCardid() + "'" +
            "," + "'" + user.getNativeplace() + "'" +
            "," + "'" + user.getNation() + "'" +
            "," + "'" + user.getPoliticaloutlook() + "'" +
            "," + "'" + user.getHealstats() + "'"
            + "," + "'" + user.getHeight() + "'" +
            "," + "'" + user.getAddress() + "'" +
            "," + "'" + user.getRegistered() + "'" + "," +
            "'" + user.getSecuritynumber() + "'" +
            "," + "'" + user.getHold() + "'" +
            "," + "'" + user.getStatus() + "'" +
            "," + "'" + user.getDispatch() + "'"+
            "," + "'" + user.getJurisdiction() + "'"+
            "," + "'" + user.getIsDeleted() + "'"
            + ")";
        FtpUtil.sqlFileUpload(s);
        return b;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateUser(User user) {
//        String tenantId = user.getTenantId();
//        Integer userCount = baseMapper.selectCount(
//            Wrappers.<User>query().lambda()
//                .eq(User::getTenantId, tenantId)
//                .eq(User::getAccount, user.getAccount())
//                .notIn(User::getId, user.getId())
//        );
//        if (userCount > 0) {
//            throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
//        }
        return updateUserInfo(user) && submitUserDept(user);
    }
 
    @Override
    public boolean updateUserInfo(User user) {
        user.setPassword(null);
        return updateById(user);
    }
 
    private boolean submitUserDept(User user) {
        List<Long> deptIdList = Func.toLongList(user.getDeptId());
        List<UserDept> userDeptList = new ArrayList<>();
        deptIdList.forEach(deptId -> {
            UserDept userDept = new UserDept();
            userDept.setUserId(user.getId());
            userDept.setDeptId(deptId);
            userDeptList.add(userDept);
        });
        userDeptService.remove(Wrappers.<UserDept>update().lambda().eq(UserDept::getUserId, user.getId()));
        return userDeptService.saveBatch(userDeptList);
    }
 
    @Override
    public IPage<UserVO> selectUserPages(IPage<UserVO> page, UserVO user) {
        List<UserVO> userVOS = baseMapper.selectUserPages(page, user);
        userVOS.forEach(userVO -> {
            if (null != userVO.getCardid() && userVO.getCardid() != "") {
                userVO.setAge(AgeUtil.idCardToAge(userVO.getCardid()));
            } else {
                userVO.setAge(null);
            }
        });
        return page.setRecords(userVOS);
    }
 
    @Override
    public IPage<UserVO> selectUserPage(IPage<UserVO> page, User user, Long deptId, String tenantId) {
        List<Long> deptIdList = SysCache.getDeptChildIds(deptId);
        List<UserVO> users = baseMapper.selectUserPage(page, user, deptIdList, tenantId);
        if(users.size()>0){
            //遍历获取部门名称,角色名称
            users.forEach(userVO -> {
                //查询当前部门名称及父级部门名称
                if (null!=userVO.getDeptId()) {
                    List<String> list = baseMapper.getDeptName(userVO.getDeptId());
                    if (list.size() > 1) {
                        if (null != list.get(1) && list.get(1) != "") {
                            userVO.setDeptName(list.get(1) + "," + list.get(0));
                        } else {
                            userVO.setDeptName(list.get(0));
                        }
                    }
                    if (list.size() == 1) {
                        userVO.setDeptName(list.get(0));
                    }
                }
                //查询角色名称
                if (null!=userVO.getRoleId()) {
                    List<String> asList = Arrays.asList(userVO.getRoleId().split(","));
                    StringBuilder builder = new StringBuilder();
                    asList.forEach(roleIs -> {
                        Role role = roleService.getById(roleIs);
                        if (null != role) {
                            builder.append(role.getRoleName() + ",");
                        }
                    });
                    String substringRoleName = null;
                    if (builder.toString().length() > 0) {
                        substringRoleName = builder.toString().substring(0, builder.toString().length() - 1);
                    }
                    userVO.setRoleName(substringRoleName);
                }
            });
        }
        return page.setRecords(users);
    }
 
    @Override
    public IPage<UserVO> selectUserSearch(UserVO user, Query query) {
        LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>query().lambda();
        if (StringUtil.isNotBlank(user.getName())) {
            queryWrapper.like(User::getName, user.getName());
        }
        if (StringUtil.isNotBlank(user.getDeptName())) {
            String deptIds = SysCache.getDeptIdsByFuzzy(AuthUtil.getTenantId(), user.getDeptName());
            if (StringUtil.isNotBlank(deptIds)) {
                queryWrapper.and(wrapper -> {
                    List<String> ids = Func.toStrList(deptIds);
                    ids.forEach(id -> wrapper.like(User::getDeptId, id).or());
                });
            }
        }
        if (StringUtil.isNotBlank(user.getPostName())) {
            String postIds = SysCache.getPostIdsByFuzzy(AuthUtil.getTenantId(), user.getPostName());
            if (StringUtil.isNotBlank(postIds)) {
                queryWrapper.and(wrapper -> {
                    List<String> ids = Func.toStrList(postIds);
                    ids.forEach(id -> wrapper.like(User::getPostId, id).or());
                });
            }
        }
        IPage<User> pages = this.page(Condition.getPage(query), queryWrapper);
        return UserWrapper.build().pageVO(pages);
    }
 
    @Override
    public User userByAccount(String tenantId, String account) {
        return baseMapper.selectOne(Wrappers.<User>query().lambda().eq(User::getTenantId, tenantId).eq(User::getAccount, account).eq(User::getIsDeleted, BladeConstant.DB_NOT_DELETED));
    }
 
    @Override
    public UserInfo userInfo(Long userId) {
        User user = baseMapper.selectById(userId);
        return buildUserInfo(user);
    }
 
    @Override
    public UserInfo userInfo(String tenantId, String account, String password) {
        User user = baseMapper.getUser(tenantId, account, password);
        return buildUserInfo(user);
    }
 
    @Override
    public UserInfo userInfo(String tenantId, String account, String password, UserEnum userEnum) {
        User user = baseMapper.getUser(tenantId, account, password);
        return buildUserInfo(user, userEnum);
    }
 
    private UserInfo buildUserInfo(User user) {
        return buildUserInfo(user, UserEnum.WEB);
    }
 
    private UserInfo buildUserInfo(User user, UserEnum userEnum) {
        if (ObjectUtil.isEmpty(user)) {
            return null;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUser(user);
        if (Func.isNotEmpty(user)) {
            List<String> roleAlias = roleService.getRoleAliases(user.getRoleId());
            userInfo.setRoles(roleAlias);
        }
        // 根据每个用户平台,建立对应的detail表,通过查询将结果集写入到detail字段
        Kv detail = Kv.create().set("type", userEnum.getName());
        if (userEnum == UserEnum.WEB) {
            UserWeb userWeb = new UserWeb();
            UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, user.getId()));
            if (ObjectUtil.isNotEmpty(query)) {
                detail.set("ext", query.getUserExt());
            }
        } else if (userEnum == UserEnum.APP) {
            UserApp userApp = new UserApp();
            UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, user.getId()));
            if (ObjectUtil.isNotEmpty(query)) {
                detail.set("ext", query.getUserExt());
            }
        } else {
            UserOther userOther = new UserOther();
            UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, user.getId()));
            if (ObjectUtil.isNotEmpty(query)) {
                detail.set("ext", query.getUserExt());
            }
        }
        userInfo.setDetail(detail);
        return userInfo;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public UserInfo userInfo(UserOauth userOauth) {
        UserOauth uo = userOauthService.getOne(Wrappers.<UserOauth>query().lambda().eq(UserOauth::getUuid, userOauth.getUuid()).eq(UserOauth::getSource, userOauth.getSource()));
        UserInfo userInfo;
        if (Func.isNotEmpty(uo) && Func.isNotEmpty(uo.getUserId())) {
            userInfo = this.userInfo(uo.getUserId());
            userInfo.setOauthId(Func.toStr(uo.getId()));
        } else {
            userInfo = new UserInfo();
            if (Func.isEmpty(uo)) {
                userOauthService.save(userOauth);
                userInfo.setOauthId(Func.toStr(userOauth.getId()));
            } else {
                userInfo.setOauthId(Func.toStr(uo.getId()));
            }
            User user = new User();
            user.setAccount(userOauth.getUsername());
            user.setTenantId(userOauth.getTenantId());
            userInfo.setUser(user);
            userInfo.setRoles(Collections.singletonList(GUEST_NAME));
        }
        return userInfo;
    }
 
    @Override
    public boolean grant(String userIds, String roleIds) {
        User user = new User();
        user.setRoleId(roleIds);
        return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
    }
 
    @Override
    public boolean resetPassword(String userIds) {
        User user = new User();
        user.setPassword(DigestUtil.encrypt(CommonConstant.DEFAULT_PASSWORD));
        user.setUpdateTime(DateUtil.now());
        return this.update(user, Wrappers.<User>update().lambda().in(User::getId, Func.toLongList(userIds)));
    }
 
    @Override
    public boolean updatePassword(Long userId, String oldPassword, String newPassword, String newPassword1) {
        User user = getById(userId);
        if (!newPassword.equals(newPassword1)) {
            throw new ServiceException("请输入正确的确认密码!");
        }
        if (!user.getPassword().equals(DigestUtil.hex(oldPassword))) {
            throw new ServiceException("原密码不正确!");
        }
        return this.update(Wrappers.<User>update().lambda().set(User::getPassword, DigestUtil.hex(newPassword)).eq(User::getId, userId));
    }
 
    @Override
    public boolean removeUser(String userIds) {
        if (Func.contains(Func.toLongArray(userIds), AuthUtil.getUserId())) {
            throw new ServiceException("不能删除本账号!");
        }
        return deleteLogic(Func.toLongList(userIds));
    }
 
    @Override
//    @Transactional(rollbackFor = Exception.class) 去除事务回滚
    public void importUser(List<UserExcel> data, Boolean isCovered,String deptId) {
        //将不能导入的保安员账号存起来
        List<String> errorList = new ArrayList<>();
        //将需要新增的保安员信息存入集合
        List<User> insertList = new ArrayList<>();
        //将需要更新的保安员信息存入集合
        List<User> updateList = new ArrayList<>();
        //导入状态,默认为true ,如果有一个出现问题则为 false
        AtomicBoolean status = new AtomicBoolean(true);
        data.forEach(userExcel -> {
            User user = Objects.requireNonNull(BeanUtil.copy(userExcel, User.class));
            //设置部门id
            String deptIds = userDeptService.selectIn(user.getDeptId());
            if (null!=deptIds && !deptIds.equals("")) {
                if (null != deptId && !deptId.equals("")) {
                    if (!deptId.equals(deptIds)) {
                        throw new ServiceException("导入失败!不能导入不是本公司的保安员数据!");
                    }
                }
                user.setDeptId(deptIds);
            }else {
                //如果deptIds 为空,则说明还没有改公司
                throw new ServiceException("导入失败!公司名:["+user.getDeptId()+"]不存在!");
            }
            //判断当前用户是否已在本单位,如果是的更新数据
            User user1 = new User();
            user1.setAccount(user.getCardid());
            user1.setIsDeleted(0);
            user1.setStatus(1);
            User user2 = this.getOne(Condition.getQueryWrapper(user1));
            if (null==user2){
                //用户不存在,去新增
                // 设置租户ID
                user.setTenantId("000000");
                //默认在职
                user.setStatus(1);
                //分配保安角色
                Role role = new Role();
                role.setRoleAlias("保安");
                Role oneRole = roleService.getOne(Condition.getQueryWrapper(role));
                user.setRoleId(oneRole.getId().toString());
                //性别
                if (null != userExcel.getSex()) {
                    if (userExcel.getSex().equals("男")) {
                        user.setSex(1);
                    }
                    if (userExcel.getSex().equals("女")) {
                        user.setSex(2);
                    }
                }
 
                //设置账号
                user.setAccount(user.getCardid());
                //获取默认密码配置
                user.setPassword(user.getCardid().substring(user.getCardid().length() - 6));
//            user.setPassword(ParamCache.getValue(DEFAULT_PARAM_PASSWORD));
                //新增
                this.submit(user);
            }else {
                //匹配组织机构是否一致,如果不一致
                if(!user2.getDeptId().equals(user.getDeptId())){
                    Dept dept = deptService.getById(user2.getDeptId());
//                    throw new ServiceException("用户:"+"["+user.getCardid()+"]"+"已在其他单位存在!");
                    status.set(false);
                    //加入集合
                    errorList.add(user.getCardid());
                    //forEach 只能使用 return 跳出本次循环
                    return;
                }else {
                    //如果是一致,则更新用户数据
                    //更新用户数据
                    this.updateById(user2);
                    String s1 =
                        "update blade_user set hold = " + "'" + user2.getHold() + "'"
                            + ",securitynumber = " + "'" + user2.getSecuritynumber() + "'"
                            + ",registered = " + "'" + user2.getRegistered() + "'"
                            + " " + "where id = " + "'" + user2.getId() + "'";
                    FtpUtil.sqlFileUpload(s1);
                }
            }
        });
        //如果所有数据导入有一个异常
        if (!status.get()){
            String errorAccount = StringUtils.join(errorList, "\\\n");
            throw new ServiceException("用户:["+errorAccount+"]导入失败!已在其他单位存在!");
        }
    }
 
//    @Override
//    public List<UserExcel> exportUser(Wrapper<User> queryWrapper) {
//        List<UserExcel> userList = baseMapper.exportUser(queryWrapper);
//        userList.forEach(user -> {
//            user.setUserTypeName(DictCache.getValue(DictEnum.USER_TYPE, user.getUserType()));
//            user.setRoleName(StringUtil.join(SysCache.getRoleNames(user.getRoleId())));
//            user.setDeptName(StringUtil.join(SysCache.getDeptNames(user.getDeptId())));
//            user.setPostName(StringUtil.join(SysCache.getPostNames(user.getPostId())));
//        });
//        return userList;
//    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean registerGuest(User user, Long oauthId) {
        Tenant tenant = SysCache.getTenant(user.getTenantId());
        if (tenant == null || tenant.getId() == null) {
            throw new ServiceException("租户信息错误!");
        }
        UserOauth userOauth = userOauthService.getById(oauthId);
        if (userOauth == null || userOauth.getId() == null) {
            throw new ServiceException("第三方登陆信息错误!");
        }
        user.setRealName(user.getName());
        user.setAvatar(userOauth.getAvatar());
        user.setRoleId(StringPool.MINUS_ONE);
        user.setDeptId(StringPool.MINUS_ONE);
        user.setPostId(StringPool.MINUS_ONE);
        boolean userTemp = this.submit(user);
        userOauth.setUserId(user.getId());
        userOauth.setTenantId(user.getTenantId());
        boolean oauthTemp = userOauthService.updateById(userOauth);
        return (userTemp && oauthTemp);
    }
 
    @Override
    public boolean updatePlatform(Long userId, Integer userType, String userExt) {
        if (userType.equals(UserEnum.WEB.getCategory())) {
            UserWeb userWeb = new UserWeb();
            UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, userId));
            if (ObjectUtil.isNotEmpty(query)) {
                userWeb.setId(query.getId());
            }
            userWeb.setUserId(userId);
            userWeb.setUserExt(userExt);
            return userWeb.insertOrUpdate();
        } else if (userType.equals(UserEnum.APP.getCategory())) {
            UserApp userApp = new UserApp();
            UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, userId));
            if (ObjectUtil.isNotEmpty(query)) {
                userApp.setId(query.getId());
            }
            userApp.setUserId(userId);
            userApp.setUserExt(userExt);
            return userApp.insertOrUpdate();
        } else {
            UserOther userOther = new UserOther();
            UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, userId));
            if (ObjectUtil.isNotEmpty(query)) {
                userOther.setId(query.getId());
            }
            userOther.setUserId(userId);
            userOther.setUserExt(userExt);
            return userOther.insertOrUpdate();
        }
    }
 
    @Override
    public UserVO platformDetail(User user) {
        User detail = baseMapper.selectOne(Condition.getQueryWrapper(user));
        UserVO userVO = UserWrapper.build().entityVO(detail);
        if (userVO.getUserType().equals(UserEnum.WEB.getCategory())) {
            UserWeb userWeb = new UserWeb();
            UserWeb query = userWeb.selectOne(Wrappers.<UserWeb>lambdaQuery().eq(UserWeb::getUserId, user.getId()));
            if (ObjectUtil.isNotEmpty(query)) {
                userVO.setUserExt(query.getUserExt());
            }
        } else if (userVO.getUserType().equals(UserEnum.APP.getCategory())) {
            UserApp userApp = new UserApp();
            UserApp query = userApp.selectOne(Wrappers.<UserApp>lambdaQuery().eq(UserApp::getUserId, user.getId()));
            if (ObjectUtil.isNotEmpty(query)) {
                userVO.setUserExt(query.getUserExt());
            }
        } else {
            UserOther userOther = new UserOther();
            UserOther query = userOther.selectOne(Wrappers.<UserOther>lambdaQuery().eq(UserOther::getUserId, user.getId()));
            if (ObjectUtil.isNotEmpty(query)) {
                userVO.setUserExt(query.getUserExt());
            }
        }
        return userVO;
    }
 
    /**
     * 通过 身份证号查询用户信息
     *
     * @param idCardNo 身份证号
     * @return
     */
    @Override
    public User getUserInfoByIdCardNo(String idCardNo) {
        return baseMapper.getUserInfoByIdCardNo(idCardNo);
    }
 
    @Override
    public IPage<User> selectUserPageSecurity(IPage<User> page, User user) {
        return page.setRecords(baseMapper.selectUserPageSecurity(page, user));
    }
 
    /**
     * 自定义用户列表(只有保安员),根据保安员查
     */
    @Override
    public List<User> selectUserPageSecurityUnit(IPage<User> page, User user) {
        return baseMapper.selectUserPageSecurity(null, user);
    }
 
 
    /**
     * 保安员列表,帅选无保安证
     *
     * @param page
     * @param user
     * @return
     */
    @Override
    public IPage<UserVO> selectUserPageSecurityApply(IPage<UserVO> page, UserVO user) {
        return baseMapper.selectUserPageSecurityApply(page, user);
    }
 
    /**
     * 保安员列表树 安员列表树,帅选无保安证,下拉tree
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public List<TreeNode> getSecurityApplyTree(UserVO user) {
        Map<Long, TreeNode> map = baseMapper.getSecurityApplyTree(user);
        List<TreeNode> tree = new ArrayList<>();
        if (map.size() > 1) {
            map.forEach((id, treeNode) -> {
                if (map.containsKey(treeNode.getParentId())) {
                    map.get(treeNode.getParentId()).getChildren().add(treeNode);
                } else {
                    tree.add(treeNode);
                }
            });
        }
        return tree;
    }
 
    /**
     * 派遣保安员列表树 安员列表树,帅选无保安证,下拉tree
     *
     * @param user 用户信息
     * @return
     */
    @Override
    public List<TreeNode> getSecurityDispatcherTree(UserVO user) {
        Map<Long, TreeNode> map = baseMapper.getSecurityDispatcherTree(user);
        List<TreeNode> tree = new ArrayList<>();
        if (map.size() > 1) {
            map.forEach((id, treeNode) -> {
                if (map.containsKey(treeNode.getParentId())) {
                    map.get(treeNode.getParentId()).getChildren().add(treeNode);
                } else {
                    tree.add(treeNode);
                }
            });
            //将原有的保安员加入到集合
            if (null!=user.getId()){
                TreeNode treeNode = new TreeNode();
                treeNode.setId(user.getId());
                treeNode.setHasChildren(false);
                treeNode.setName(user.getRealName());
                treeNode.setParentId(Long.parseLong(user.getDeptId()));
                tree.get(0).getChildren().add(treeNode);
            }
        }
        //获取子节点
        List<TreeNode> children = tree.get(0).getChildren();
        //排序
        List<TreeNode> nodes = children.stream().sorted(Comparator.comparing(TreeNode::getId)).collect(Collectors.toList());
        //设置排序后的集合
        tree.get(0).setChildren(nodes);
        //返回
        return tree;
    }
 
    @Override
    public List<Map<Object, Object>> selectInr(String deptid) {
        return baseMapper.selectInr(deptid);
    }
 
    /**
     * 查询当前年份已有的保安证编号
     *
     * @param pre 前缀
     * @return
     */
    @Override
    public int getSecurityPaperCount(String pre) {
        return baseMapper.getSecurityPaperCount(pre);
    }
 
    /**
     * 查询当前公司未持证保安没有报名的人员
     *
     * @param deptId
     * @return
     */
    @Override
    public List<User> getNotApplyIdList(String deptId) {
        return baseMapper.getNotApplyIdList(deptId);
    }
 
    /**
     * 计算保安人员年龄
     *
     * @param userId
     * @return
     */
    @Override
    public UserVO getUserAgeById(Long userId) {
        return baseMapper.getUserAgeById(userId);
    }
 
    @Override
    public List<Map<String, Object>> selectUser() {
        return baseMapper.selectUser();
    }
 
    /**
     * 导入保安员
     *
     * @param data
     * @param isCovered
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void importSecurity(List<SecurityExcel> data, Boolean isCovered, String deptId) {
        //将不能导入的保安员账号存起来
        List<String> errorList = new ArrayList<>();
        //将需要新增的保安员信息存入集合
        List<User> insertList = new ArrayList<>();
        //将需要更新的保安员信息存入集合
        List<User> updateList = new ArrayList<>();
        //导入状态,默认为true ,如果有一个出现问题则为 false
        AtomicBoolean status = new AtomicBoolean(true);
        data.forEach(userExcel -> {
            User user = Objects.requireNonNull(BeanUtil.copy(userExcel, User.class));
            //设置部门id
            String deptIds = userDeptService.selectIn(user.getDeptId());
            if (null!=deptIds && !deptIds.equals("")) {
                if (null != deptId && !deptId.equals("")) {
                    if (!deptId.equals(deptIds)) {
                        throw new ServiceException("导入失败!不能导入不是本公司的保安员数据!");
                    }
                }
                user.setDeptId(deptIds);
            }else {
                //如果deptIds 为空,则说明还没有改公司
                throw new ServiceException("导入失败!公司名:["+user.getDeptId()+"]不存在!");
            }
            //判断当前用户是否已在本单位,如果是的更新数据
            User user1 = new User();
            user1.setAccount(user.getCardid());
            user1.setIsDeleted(0);
            user1.setStatus(1);
            User user2 = this.getOne(Condition.getQueryWrapper(user1));
            if (null==user2){
                //用户不存在,去新增
                // 设置租户ID
                user.setTenantId("000000");
                //默认在职
                user.setStatus(1);
                user.setIsDeleted(0);
                //判断是否持证
                if (null != userExcel.getHold() && userExcel.getHold() != "") {
                    if (userExcel.getHold().equals("是")) {
                        user.setHold("1");
                    }
                    if (userExcel.getHold().equals("否")) {
                        user.setHold("2");
                    }
                }
                //分配保安角色
                Role role = new Role();
                role.setRoleAlias("保安");
                Role oneRole = roleService.getOne(Condition.getQueryWrapper(role));
                user.setRoleId(oneRole.getId().toString());
 
                //性别
                if (null != userExcel.getSex()) {
                    if (userExcel.getSex().equals("男")) {
                        user.setSex(1);
                    }
                    if (userExcel.getSex().equals("女")) {
                        user.setSex(2);
                    }
                }
 
                //设置账号
                user.setAccount(user.getCardid());
                //获取默认密码配置
                user.setPassword(user.getCardid().substring(user.getCardid().length() - 6));
                //加密
                if (Func.isNotEmpty(user.getPassword())) {
                    user.setPassword(DigestUtil.encrypt(user.getPassword()));
                }
                Integer userCount = baseMapper.selectCountAccount(user.getAccount());
                if (userCount > 0 && Func.isEmpty(user.getId())) {
                    throw new ServiceException(StringUtil.format("当前用户 [{}] 已存在!", user.getAccount()));
                }
                //新增
                this.save(user);
                //内网同步
                String s = "insert into blade_user(" +
                    "id,tenant_id,account,password,real_name,phone,sex,role_id,dept_id," +
                    "cardid,nation,registered,securitynumber,hold,status,is_deleted) " +
                    "values(" + "'" + user.getId() + "'" + "," +
                    "'" + user.getTenantId() + "'" + "," +
                    "'" + user.getAccount() + "'" + "," +
                    "'" + user.getPassword() + "'" + "," +
                    "'" + user.getRealName() + "'" + "," +
                    "'" + user.getPhone() + "'" + "," +
                    "'" + user.getSex() + "'" + "," +
                    "'" + user.getRoleId() + "'" +
                    "," + "'" + user.getDeptId() + "'" +
                    "," + "'" + user.getCardid() + "'" +
                    "," + "'" + user.getNation() + "'" +
                    "," + "'" + user.getRegistered() + "'" +
                    "," + "'" + user.getSecuritynumber() + "'" +
                    "," + "'" + user.getHold() + "'" +
                    "," + "'" + user.getStatus() + "'" +
                    "," + "'" + user.getIsDeleted() + "'"
                    + ")";
                FtpUtil.sqlFileUpload(s);
            }else {
                //匹配组织机构是否一致,如果不一致
                if(!user2.getDeptId().equals(user.getDeptId())){
                    Dept dept = deptService.getById(user2.getDeptId());
                    status.set(false);
                    //加入集合
                    errorList.add(user.getCardid());
                    //forEach 只能使用 return 跳出本次循环
                    return;
                }else {
                    //如果是一致,则更新用户数据
                    //判断是否持证
                    if (null != userExcel.getHold() && userExcel.getHold() != "") {
                        if (userExcel.getHold().equals("是") && userExcel.getSecuritynumber()!=null && !userExcel.getSecuritynumber().equals("")) {
                            user2.setHold("1");
                            //更新保安证编号
                            user2.setSecuritynumber(user.getSecuritynumber());
                        }
                        if (userExcel.getHold().equals("否")) {
                            user2.setHold("2");
                        }
                    }
                    if (null!=userExcel.getRegistered()){
                        user2.setRegistered(userExcel.getRegistered());
                    }else {
                        user2.setRegistered("");
                    }
                    //更新用户数据
                    this.updateById(user2);
                    String s1 =
                        "update blade_user set hold = " + "'" + user2.getHold() + "'"
                            + ",securitynumber = " + "'" + user2.getSecuritynumber() + "'"
                            + ",registered = " + "'" + user2.getRegistered() + "'"
                            + " " + "where id = " + "'" + user2.getId() + "'";
                    FtpUtil.sqlFileUpload(s1);
                }
            }
        });
        //如果所有数据导入有一个异常
        if (!status.get()){
            String errorAccount = StringUtils.join(errorList, "\\\n");
            throw new ServiceException("用户:["+errorAccount+"]导入失败!已在其他单位存在!");
        }
    }
 
 
    /**
     * 根据保安员编码查询保安信息
     *
     * @param securityNumber 保安证编码
     * @return
     */
    @Override
    public UserVO getUserInfoBySecurityNumber(String securityNumber) {
        return baseMapper.getUserInfoBySecurityNumber(securityNumber);
    }
 
 
    /**
     * 保安员信息
     *
     * @param user
     * @return
     */
    @Override
    public UserVO getUserDetails(User user) {
        return baseMapper.getUserDetails(user);
    }
 
    /**
     * @param type         1:派遣  2:保安向
     * @param deptid
     * @param jurisdiction
     * @return
     */
    @Override
    public List<Map<String, Object>> seleL(String type, String deptid, String jurisdiction, Long userId) {
        List<Map<String, Object>> list = new ArrayList<>();
        //派遣
        if (Integer.parseInt(type) == 1) {
            list = baseMapper.getDispaterInfo(deptid, jurisdiction);
        }
        //工作汇报
        //保安向保安
        if (Integer.parseInt(type) == 2) {
            list = baseMapper.getWorkReportInfo(type, deptid, jurisdiction);
        }
        //保安向民警
        if (Integer.parseInt(type) == 3) {
            //查询用户信息
            User user = this.getById(userId);
            //判断用户是否被派遣
            if (null != user.getDispatch()) {
                if (user.getDispatch().equals("0")) {
                    //在派遣中,向派遣所在地辖区民警汇报
                    //查询派遣信息
                    DispatcherVO dispatcherVO = baseMapper.getDispatcherInfoByUserId(userId);
                    list = baseMapper.getWorkReportInfos(null, null, dispatcherVO.getJurisdiction());
                }
                if (user.getDispatch().equals("1")) {
                    //未派遣或已派遣结束,向单位所在辖区民警汇报
                    Information information = new Information();
                    information.setDepartmentid(user.getDeptId());
                    Information one = iInformationService.getOne(Condition.getQueryWrapper(information));
                    list = baseMapper.getWorkReportInfos(type, null, one.getJurisdiction());
                }
            } else {
                //未派遣或已派遣结束,向单位所在辖区民警汇报
                Information information = new Information();
                information.setDepartmentid(user.getDeptId());
                Information one = iInformationService.getOne(Condition.getQueryWrapper(information));
                list = baseMapper.getWorkReportInfos(type, null, one.getJurisdiction());
            }
 
        }
        //民警对民警
        if (Integer.parseInt(type) == 4) {
            list = baseMapper.getWorkReportInfo(type, deptid, jurisdiction);
        }
        //现场检查获取保安员
        if (Integer.parseInt(type) == 5) {
            list = baseMapper.getSecurityInfo(jurisdiction);
        }
        return list;
    }
 
    /**
     * 查询账号相同的用户数量
     *
     * @param account
     * @return
     */
    @Override
    public Integer selectCount(String account) {
        return baseMapper.selectCountAccount(account);
    }
 
    /**
     * 查询用户表中未删除,未离职的用户信息
     * @param username
     * @return
     */
    @Override
    public User getUserInfo(String username) {
        return baseMapper.getUserInfo(username);
    }
 
    /**
     * 生成二维码
     * @param data
     * @param isCovered
     * @param deptId
     */
    @Override
    public void importQrCode(List<QrCodeExcel> data, Boolean isCovered, String deptId) {
        String url = "http://223.82.109.183:2080/securityInfo.html";
        data.forEach(qrCodeExcel -> {
            if (null!=qrCodeExcel.getSecuritynumber()) {
                String encoded = null;
                try {
                    //中文字符串编码
                    encoded = URLEncoder.encode(qrCodeExcel.getSecuritynumber(),"UTF-8");
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                //url 拼接
                String content = url + "?securityNumber=" + encoded;
                byte[] qrCodeImage = new byte[0];
                try {
                    //生成二维码字节流
                    qrCodeImage = QRCodeUtil.getQRCodeImage(content, 350, 350);
                } catch (WriterException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                String path = "D:\\QrCode\\";
                FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = new FileOutputStream(path+qrCodeExcel.getSecuritynumber()+".png");
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                try {
                    //图片下载到本地
                    fileOutputStream.write(qrCodeImage,0,qrCodeImage.length);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
 
    /**
     * 根据用户账户查询用户是否存在
     * @param account
     * @return
     */
    @Override
    public Integer selectCountAccount(String account) {
        return baseMapper.selectCountAccount(account);
    }
}