FrontUserServiceImpl.java 43.1 KB
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
package com.lhcredit.project.business.frontUser.service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;


import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.lhcredit.common.constant.UserConstants;
import com.lhcredit.common.utils.JsonUtils;
import com.lhcredit.common.utils.StringUtils;
import com.lhcredit.common.utils.security.ShiroUtils;
import com.lhcredit.framework.shiro.service.PasswordService;
import com.lhcredit.framework.web.domain.AjaxResult;
import com.lhcredit.project.business.customTemplate.domain.CustomTemplate;
import com.lhcredit.project.business.customTemplate.service.ICustomTemplateService;
import com.lhcredit.project.business.frontDept.service.IFrontDeptService;
import com.lhcredit.project.business.frontUser.domain.EmailAttachment;
import com.lhcredit.project.business.frontUser.domain.TempConf;
import com.lhcredit.project.business.frontUser.domain.FrontUser;
import com.lhcredit.project.business.frontDept.domain.FrontDept;
import com.lhcredit.project.business.frontDept.mapper.FrontDeptMapper;
import com.lhcredit.project.business.frontMenu.domain.FrontMenu;
import com.lhcredit.project.business.frontMenu.mapper.FrontMenuMapper;
import com.lhcredit.project.business.frontRole.mapper.FrontRoleMapper;
import com.lhcredit.project.business.frontUser.domain.FrontUserMon;
import com.lhcredit.project.business.frontUserRole.domain.FrontUserRole;
import com.lhcredit.project.business.frontUserRole.mapper.FrontUserRoleMapper;
import com.lhcredit.project.business.frontVx.domain.FrontVx;
import com.lhcredit.project.business.frontVx.mapper.FrontVxMapper;
import com.lhcredit.project.business.monitorGroup.domain.MonitorGroup;
import com.lhcredit.project.business.monitorGroup.service.IMonitorGroupService;
import com.lhcredit.project.business.monitorGroupTemplate.domain.MonitorGroupTemplate;
import com.lhcredit.project.business.monitorGroupTemplate.service.IMonitorGroupTemplateService;
import com.lhcredit.project.business.monitorSet.domain.MonitorSet;
import com.lhcredit.project.business.monitorSet.mapper.MonitorSetMapper;
import com.lhcredit.project.business.monitorSetNew.domain.MonitorSetNew;
import com.lhcredit.project.business.monitorSetNew.service.IMonitorSetNewService;
import com.lhcredit.project.business.monitorSetSf.domain.MonitorSetSf;
import com.lhcredit.project.business.monitorSetSf.mapper.MonitorSetSfMapper;
import com.lhcredit.project.business.monitorSetSfNew.domain.MonitorSetSfNew;
import com.lhcredit.project.business.monitorSetSfNew.service.IMonitorSetSfNewService;
import com.lhcredit.project.business.monitorTemplate.domain.MonitorTemplate;
import com.lhcredit.project.business.monitorTemplate.service.IMonitorTemplateService;
import com.lhcredit.project.business.price.service.PriceService;
import com.lhcredit.project.business.templateConfiguration.domain.TemplateConfiguration;
import com.lhcredit.project.business.templateConfiguration.service.ITemplateConfigurationService;
import com.lhcredit.project.system.dict.domain.DictData;
import com.lhcredit.project.system.dict.service.IDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import com.lhcredit.project.business.frontUser.mapper.FrontUserMapper;
import com.lhcredit.common.utils.text.Convert;
import org.springframework.ui.ModelMap;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import static com.lhcredit.framework.web.domain.AjaxResult.error;
import static com.lhcredit.framework.web.domain.AjaxResult.other;

/**
 * 前端用户 服务层实现
 *
 * @author lhcredit
 * @date 2024-05-13
 */
@Service
@Slf4j
public class FrontUserServiceImpl implements IFrontUserService {
    @Autowired
    private FrontUserMapper frontUserMapper;

    @Autowired
    private PasswordService passwordService;

    @Autowired
    private FrontUserRoleMapper frontUserRoleMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private FrontMenuMapper frontMenuMapper;

    @Autowired
    private TokenManager tokenManager;

    @Autowired
    private PriceService priceService;

    @Autowired
    private FrontDeptMapper frontDeptMapper;

    @Autowired
    private FrontRoleMapper frontRoleMapper;

    @Autowired
    private MonitorSetMapper monitorSetMapper;

    @Autowired
    private MonitorSetSfMapper monitorSetSfMapper;

    @Resource
    private ITemplateConfigurationService templateConfigurationService;

    @Resource
    private IDictDataService dictDataService;

    @Resource
    private ICustomTemplateService iCustomTemplateService;

    @Resource
    private IFrontDeptService frontDeptService;

    @Resource
    private IMonitorGroupService monitorGroupService;

    @Resource
    private IMonitorTemplateService monitorTemplateService;

    @Resource
    private IMonitorGroupTemplateService monitorGroupTemplateService;

    @Resource
    private IMonitorSetNewService monitorSetNewService;

    @Resource
    private IMonitorSetSfNewService monitorSetSfNewService;

    @Autowired
    private FrontVxMapper frontVxMapper;
    /**
     * 查询前端用户信息
     *
     * @param id 前端用户ID
     * @return 前端用户信息
     */
    @Override
    public FrontUser selectFrontUserById(Long id) {
        return frontUserMapper.selectFrontUserById(id);
    }

    /**
     * 根据id 查询前台用户信息
     * @param id
     * @return
     */
    @Override
    public FrontUser getFrontUserById(Long id) {
        return frontUserMapper.getFrontUserById(id);
    }

    /**
     * 查询前端用户列表
     *
     * @param frontUser 前端用户信息
     * @return 前端用户集合
     */
    @Override
    public List<FrontUser> selectFrontUserList(FrontUser frontUser) {
        return frontUserMapper.selectFrontUserList(frontUser);
    }

    /**
     * 字段转换
     * @param frontUser 前端用户信息
     * @return 前端用户信息
     */
    @Override
    public FrontUser changeModel(FrontUser frontUser) {
//        //这里写各字段转换逻辑
//        if(frontUser!=null){
//            if(StringUtils.isNotEmpty(frontUser.getXXX())){
//               frontUser.setXXX(frontUser.getXXX());
//            }
//        }
        return frontUser;
    }

    /**
     * 列表转换
     *
     * @param frontUserList 前端用户集合
     * @return 前端用户集合
     */
    @Override
    public List<FrontUser> changeModel(List<FrontUser> frontUserList) {
        List<FrontUser> result = new ArrayList<FrontUser>();
        if (frontUserList.size() > 0) {
            for (FrontUser frontUser:frontUserList){
                result.add(changeModel(frontUser));
            }
        }
        return result;
    }

    /**
     * 新增前端用户
     *
     * @param frontUser 前端用户信息
     * @return 结果
     */
    @Override
    public int insertFrontUser(FrontUser frontUser) {
        //添加到用户表
        frontUser.setPassword(passwordService.encryptPassword(frontUser.getLoginName(), frontUser.getPassword(),null));
        frontUser.setCreateBy(ShiroUtils.getLoginName());
        frontUser.setCreditTime(new Date());
        int rows=frontUserMapper.insertFrontUser(frontUser);
        Long userId=frontUser.getId();
        //添加到角色用户表
        insertUserRole(frontUser);
        //根据用户查询组织机构类型
        Long orgId=frontUser.getOrgId();
        FrontDept fd=frontDeptMapper.selectFrontDeptByOrgId(orgId);
        //总公司默认分配监控列表
        if(fd.getDeptType().equals("0")){
            MonitorSet monitorSet=new MonitorSet();
            monitorSet.setUserId("-1");
            List<MonitorSet> list=monitorSetMapper.selectMonitorSetList(monitorSet);
            for(MonitorSet ms:list){
                ms.setUserId(userId+"");
                ms.setCreditTime(new Date());
                monitorSetMapper.insertMonitorSet(ms);
            }
            //司法大数据模板\
            MonitorSetSf msf=new MonitorSetSf();
            msf.setUserId("-1");
            List<MonitorSetSf> listSf=monitorSetSfMapper.selectMonitorSetSfList(msf);
            for(MonitorSetSf sf:listSf){
                sf.setUserId(userId+"");
                sf.setCreditTime(new Date());
                monitorSetSfMapper.insertMonitorSetSf(sf);
            }
        }else {
            //分公司和部门分配总公司监控列表
            String [] pids=fd.getAncestors().split(",");
            String pid=pids[0];
            //查询总公司用户
            FrontUser fu=new FrontUser();
            fu.setOrgId(Long.valueOf(pid));
            List<FrontUser> fuList=frontUserMapper.selectFrontUserList(fu);
            if(fuList.size()>0){
                //查询总公司模板
                MonitorSet monitorSet=new MonitorSet();
                monitorSet.setUserId(fuList.get(0).getId()+"");
                List<MonitorSet> list=monitorSetMapper.selectMonitorSetList(monitorSet);
                for(MonitorSet ms:list){
                    ms.setUserId(userId+"");
                    ms.setCreditTime(new Date());
                    monitorSetMapper.insertMonitorSet(ms);
                }
                //司法大数据模板\
                MonitorSetSf msf=new MonitorSetSf();
                msf.setUserId(fuList.get(0).getId()+"");
                List<MonitorSetSf> listSf=monitorSetSfMapper.selectMonitorSetSfList(msf);
                for(MonitorSetSf sf:listSf){
                    sf.setUserId(userId+"");
                    sf.setCreditTime(new Date());
                    monitorSetSfMapper.insertMonitorSetSf(sf);
                }
            }
        }

        return 1;
    }

    /**
     * 新增用户角色信息
     *
     * @param user 用户对象
     */
    public void insertUserRole(FrontUser user) {
        Long[] roles = user.getRoleIds();
        if (StringUtils.isNotNull(roles)) {
            // 新增用户与角色管理
            List<FrontUserRole> list = new ArrayList<FrontUserRole>();
            for (Long roleId : user.getRoleIds()) {
                FrontUserRole ur = new FrontUserRole();
                ur.setUserId(Long.parseLong(user.getId()+""));
                ur.setRoleId(roleId);
                list.add(ur);
            }
            if (list.size() > 0) {
                frontUserRoleMapper.batchFrontUserRole(list);
            }
        }
    }

    /**
     * 修改前端用户
     *
     * @param frontUser 前端用户信息
     * @return 结果
     */
    @Override
    public int updateFrontUser(FrontUser frontUser) {
        Long userId = frontUser.getId();
        frontUser.setUpdateBy(ShiroUtils.getLoginName());
        // 删除用户与角色关联
        frontUserRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(frontUser);
        return frontUserMapper.updateFrontUser(frontUser);
    }


    /**
     * 用户状态修改
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int changeStatus(FrontUser user) {

        return updateFrontUser(user);
    }

    @Override
    public int resetUserPwd(FrontUserMon user) {
        user.setPassword(passwordService.encryptPassword(user.getLoginName(), user.getPassword(), null));
        FrontUser user1 = new FrontUser();
        user1.setId(user.getId());
        user1.setPassword(user.getPassword());
        user1.setModifyPsdPage(user.getModifyPsdPage());
        int i = frontUserMapper.updateFrontUser(user1);
        return i;
    }

    @Override
    public List<FrontUser> selectFrontUserByPid(FrontUser frontUser) {
        return frontUserMapper.selectFrontUserByPid(frontUser);
    }

    /**
     * 删除前端用户对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteFrontUserByIds(String ids) {
        return frontUserMapper.deleteFrontUserByIds(Convert.toStrArray(ids));
    }

    @Override
    public String checkLoginNameUnique(String loginName) {
        int count = frontUserMapper.checkLoginNameUnique(loginName);
        if (count > 0) {
            return UserConstants.USER_NAME_NOT_UNIQUE;
        }
        return UserConstants.USER_NAME_UNIQUE;
    }

    @Override
    public String checkPhoneUnique(FrontUser user) {
        Long userId = StringUtils.isNull(user.getId()) ? -1L : user.getId();
        FrontUser info = frontUserMapper.checkPhoneUnique(user.getPhone());
        if (StringUtils.isNotNull(info) && info.getId().longValue() != userId.longValue()) {
            return UserConstants.USER_PHONE_NOT_UNIQUE;
        }
        return UserConstants.USER_PHONE_UNIQUE;
    }

    /**
     * 前台登录
     * @param request
     * @param frontUserMon
     * @return
     */
    @Override
    public AjaxResult webLogin(HttpServletRequest request, FrontUserMon frontUserMon) {
        HttpSession session = request.getSession(true);

        ValueOperations<String, String> operations = redisTemplate.opsForValue();

        ValueOperations<String, FrontUserMon> operations1 = redisTemplate.opsForValue();
        //判断登录是否为空
        if (StringUtils.isEmpty(frontUserMon.getLoginName())){
            return error("请输入用户名");
        }
        if (StringUtils.isEmpty(frontUserMon.getPassword())){
            return error("请输入密码");
        }
        //拿到加密后的密码 取数据库中查找
        String salt = passwordService.encryptPassword(frontUserMon.getLoginName(), frontUserMon.getPassword(),null);

        FrontUserMon frontUsers = frontUserMapper.findUserByLoginName(frontUserMon.getLoginName(), salt);
        if (ObjectUtils.isEmpty(frontUsers)){
            return error("用户/密码不正确");
        }

        //判断密码是否正确
        if (!salt.equals(frontUsers.getPassword())) {
            FrontUserMon userloginTime = new FrontUserMon();
            userloginTime.setLoginName(frontUsers.getLoginName());
            userloginTime = getLoginTimes(userloginTime, "1"); //1为输入错误
            if (5 <= Integer.valueOf(userloginTime.getLoginTimes())) {
                return error("尝试登录次数过多,请十分钟后重试。");
            }
            return error("账号或密码错误,您还有" + (5 - Integer.valueOf(userloginTime.getLoginTimes())) + "次机会");
        }

        operations.set("sessionid",session.getId(),3600, TimeUnit.SECONDS);

        boolean isToken = redisTemplate.hasKey(frontUserMon.getLoginName() + ":login");
        if (isToken) {
            String keywortd = operations.get(frontUserMon.getLoginName() + ":login");
            redisTemplate.delete(keywortd);
            operations.set("inoperativeToken_" + keywortd, keywortd, 60, TimeUnit.MINUTES);
        }

        //使用uuid作为源token
        String token = tokenManager.getToken(frontUsers);
        operations.set(frontUserMon.getLoginName() + ":login", "token_" + token, 3600, TimeUnit.SECONDS);
        frontUsers.setToken(token);
        //初始化
        session.invalidate();
        boolean hasKey = redisTemplate.hasKey("account_" + frontUsers.getLoginName() + "_loginTime");
        if (hasKey) {
            if (5 <= Integer.parseInt(Objects.requireNonNull(operations.get("account_" + frontUsers.getLoginName()  + "_loginTime")))) {
                return error("您的登录次数已达上限,请十分钟后再试!");
            } else {
                getLoginTimes(frontUserMon, "0");
            }
        }
        frontUsers.setPassword(null);
        //查询菜单
        List<FrontMenu> frontMenus = frontMenuMapper.selectMenuAllByUserId(Long.valueOf(frontUsers.getId()));
        //菜单去重
        if (CollectionUtils.isEmpty(frontMenus)){
            frontUsers.setFrontMenu(Collections.EMPTY_LIST);
        }else {
            //去重,并放入user实体类中
            List<FrontMenu> meuns = frontMenus.stream().collect(Collectors.toMap(FrontMenu::getMenuId, Function.identity(), (e, r) -> e)).values().stream().collect(Collectors.toList());
            frontUsers.setFrontMenu(meuns);
        }
        //放入user实体类中
//        frontUsers.setFrontMenu(frontMenus);
        //orgid   orgname   自己的
        FrontDept frontDept = frontDeptMapper.selectFrontDeptByOrgId(frontUsers.getOrgId());
        TemplateConfiguration tmp=templateConfigurationService.getTemppConfByOrg(frontUsers.getOrgId());
        frontUsers.setParentOrgName(frontDept.getDeptName());
        if(tmp!=null) {
            //通过获取crontractId 并录入价格记录到库中
            if (StringUtils.isNotEmpty(tmp.getContractId())) {
                frontUsers.setContractId(Long.parseLong(tmp.getContractId()));
            }
        }

        //获取biztypes
        frontUsers.setBizTypes(frontDept.getBizTypes());

        //下单身份 公司和 分公司 并存所有下属 并把deptType存入
        String orderOrgName = null;
        String deptType = null;
        if (frontDept.getDeptType().equals("1")){
            orderOrgName = frontDept.getDeptName();
            deptType = frontDept.getDeptType();
            frontUsers.setHeadId(frontDept.getParentId()+"");
        }
        if (frontDept.getDeptType().equals("0")) {
            orderOrgName = frontDept.getDeptName();
            deptType = frontDept.getDeptType();
            frontUsers.setHeadId(frontDept.getId()+"");
        }
        //部门存上一级 deptType是自己部门的
        if (frontDept.getDeptType().equals("2")){
            FrontDept frontDept1 = frontDeptMapper.selectFrontDeptByOrgId(frontDept.getParentId());
            orderOrgName = frontDept1.getDeptName();
            frontUsers.setOrderOrgName(orderOrgName);
            deptType = frontDept.getDeptType();
            frontUsers.setHeadId(frontDept1.getParentId()+"");
        }
        frontUsers.setOrderOrgName(orderOrgName);
        frontUsers.setDeptType(deptType);
        if (StringUtils.isNotEmpty(frontUsers.getReports())){
            List<TempConf> tempConfList = JsonUtils.fromJson(frontUsers.getReports(), new TypeReference<List<TempConf>>() {});
            frontUsers.setTempConfList(tempConfList);
        }
        System.out.println(JsonUtils.toJson(frontUsers));
        //反角色权限 frontMenus
        operations1.set("token_" + token, frontUsers);

        //AjaxResult.success(frontMenus)
        return AjaxResult.success(frontUsers);
    }

    /**
     * 查询前台用户信息
     *
     * @param frontUserMon 前台用户
     * @return 前台用户信息
     */
    public FrontUserMon getLoginTimes(FrontUserMon frontUserMon, String type) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        String res = null;
        // 缓存存在
        boolean hasKey = redisTemplate.hasKey("account_" + frontUserMon.getLoginName() + "_loginTime");
        if (hasKey) {
            res = operations.get("account_" + frontUserMon.getLoginName() + "_loginTime");
            frontUserMon.setLoginTimes(String.valueOf(Integer.valueOf(res)));
            if (5 <= Integer.valueOf(frontUserMon.getLoginTimes())) {
                return frontUserMon;
            }
            if ("1".equals(type)) {
                res = String.valueOf(Integer.valueOf(res) + 1);
                operations.set("account_" + frontUserMon.getLoginName() + "_loginTime", res, 10, TimeUnit.MINUTES);
                frontUserMon.setLoginTimes(res);
            } else {
                redisTemplate.delete("account_" + frontUserMon.getLoginName() + "_loginTime");
                frontUserMon.setLoginTimes("0");
            }
        } else {
            if ("1".equals(type)) {
                operations.set("account_" + frontUserMon.getLoginName() + "_loginTime", "1", 10, TimeUnit.MINUTES);
                frontUserMon.setLoginTimes("12");
            }
        }
        return frontUserMon;
    }

    /**
     * 根据 部门id  查询前台用户
     * @param orgId
     * @return
     */
    @Override
    public List<FrontUser> getFrontUserByOrgId(Long orgId) {

        return frontUserMapper.getFrontUserByOrgId(orgId);
    }

    @Override
    public ModelMap getTempConfByOrgId(Long orgId, Long userId) {
        log.info("getTempConfByOrgId方法入参orgId:{},userId:{}",orgId,userId);

        ModelMap mmap = new ModelMap();
        List<TempConf> tempConf = new ArrayList<>();
            List<DictData> dictDataList;
            List<String> typeNameList = Arrays.asList("监控企业", "财务大数","司法导出","税务信息");
        TemplateConfiguration temppConfByOrg = getTemplateConfiguration(orgId);
        if (Objects.nonNull(temppConfByOrg)) {
                // 拆分业务类型  普通模板
                String[] split;
                if (temppConfByOrg.getTypeId().contains(",")){
                    split = temppConfByOrg.getTypeId().split(",");
                }else {
                    split = new String[]{temppConfByOrg.getTypeId()};
                }

                List<DictData> backgroundReportType = dictDataService.selectDictDataByType("background_report_type");

                dictDataList = backgroundReportType.stream()
                        .filter(dictData -> Arrays.asList(split).contains(dictData.getDictValue()))
                        .collect(Collectors.toList());
                for (DictData dictData : dictDataList) {
                    // 把定制报告排除
                    if (!dictData.getDictValue().equals("-11")) {
                        TempConf tempConf1 = new TempConf();
                        tempConf1.setOrgId(orgId);
                        tempConf1.setName(dictData.getDictLabel());
                        tempConf1.setValue(dictData.getDictValue());
                        tempConf1.setTempType(1);
                        tempConf1.setNum("-1");
                        tempConf.add(tempConf1);
                    }
                }

                // 组装定制模板
                if (StringUtils.isNotEmpty(temppConfByOrg.getClientId())){
                    String[] dingZhiSplit;
                    if (temppConfByOrg.getClientId().contains(",")){
                        dingZhiSplit = temppConfByOrg.getClientId().split(",");
                    }else {
                        dingZhiSplit = new String[]{temppConfByOrg.getClientId()};
                    }
                    List<TempConf> finalTempConf = tempConf;
                    Arrays.asList(dingZhiSplit).forEach(dingZhi -> {
                        CustomTemplate customTemplate = iCustomTemplateService.selectCustomTemplateById(Integer.valueOf(dingZhi));
                        TempConf tempConf1 = new TempConf();
                        tempConf1.setOrgId(orgId);
                        tempConf1.setName(customTemplate.getTName());
                        tempConf1.setValue(customTemplate.getId().toString());
                        tempConf1.setTempType(2);
                        tempConf1.setNum("-1");
                        finalTempConf.add(tempConf1);
                    });
                }
            }
            // 组装 监控企业、财务大数
            for (int i = 0; i < typeNameList.size(); i++) {
                String s = typeNameList.get(i);
                TempConf tempConf1 = new TempConf();
                tempConf1.setOrgId(orgId);
                tempConf1.setName(s);
                tempConf1.setValue(String.valueOf(i));
                tempConf1.setTempType(3);
                tempConf1.setNum("-1");
                tempConf.add(tempConf1);
            }
        // 编辑时需要用到
        if (Objects.nonNull(userId)){
            FrontUser frontUser = frontUserMapper.selectFrontUserById(userId);
            if (StringUtils.isNotEmpty(frontUser.getReports())){
                List<TempConf> tempConfList = JsonUtils.fromJson(frontUser.getReports(), new TypeReference<List<TempConf>>() {});

                // 将 tempConfList 转换为 Map,以便快速查找
                Map<String, TempConf> tempConfMap = tempConfList.stream()
                        .collect(Collectors.toMap(TempConf::getName, conf -> conf));

                // 遍历 tempConfByOrg,如果存在相同id的对象,则拷贝属性
                for (TempConf orgConf : tempConf) {
                    TempConf sourceConf = tempConfMap.get(orgConf.getName());
                    if (sourceConf != null) {
                        // 使用 Spring 的 BeanUtils 拷贝非空属性
                        BeanUtils.copyProperties(sourceConf, orgConf);
                    }
                }
            }

            // 过滤掉模板类型不为3的对象
            List<TempConf> tempConfList = tempConf.stream()
                    .filter(tc -> tc.getTempType() != 3)
                    .collect(Collectors.toList());
            List<EmailAttachment> emailAttachmentListInfo = JsonUtils.fromJson(frontUser.getEmailAttachmentInfo(), new TypeReference<List<EmailAttachment>>() {});
            List<EmailAttachment> emailAttachmentList = new ArrayList<>();

            if (CollectionUtils.isNotEmpty(tempConfList)){
                //最新模板信息如果和已保存的附件信息的模板值相等则赋值
                tempConfList.forEach(tem -> {
                    EmailAttachment emailAttachmentInfo = new EmailAttachment();
                    emailAttachmentInfo.setName(tem.getName());
                    emailAttachmentInfo.setTempType(tem.getTempType());
                    emailAttachmentInfo.setValue(tem.getValue());
                    emailAttachmentInfo.setAttachmentType("");

                    if(CollectionUtils.isNotEmpty(emailAttachmentListInfo)){
                        emailAttachmentListInfo.forEach(emailAttachment -> {
                            if (tem.getValue().equals(emailAttachment.getValue())){
                                emailAttachmentInfo.setName(tem.getName());
                                emailAttachmentInfo.setTempType(emailAttachment.getTempType());
                                emailAttachmentInfo.setValue(tem.getValue());
                                emailAttachmentInfo.setAttachmentType(emailAttachment.getAttachmentType());
                            }
                        });
                    }
                    emailAttachmentList.add(emailAttachmentInfo);
                });
            }
            mmap.put("emailAttachmentList", emailAttachmentList);
            log.info("邮箱附件信息emailAttachmentList:{}",emailAttachmentList);
        }
        mmap.put("tempConfList", tempConf);
        log.info("模板信息tempConfList:{}", JSON.toJSON(tempConf));
        return mmap;
    }

    @Override
    public int insertFrontUserNew(FrontUser frontUser) {
        //添加到用户表
        frontUser.setPassword(passwordService.encryptPassword(frontUser.getLoginName(), frontUser.getPassword(),null));
        frontUser.setCreateBy(ShiroUtils.getLoginName());
        frontUser.setCreditTime(new Date());
        if (StringUtils.isNotEmpty(frontUser.getOpenId())) {
            frontUser.setVxType(1);
            FrontUserMon frontUserMon = frontUserMapper.selectFrontUserByOpenId(frontUser.getOpenId());
            if (frontUserMon != null) {
                return 0;
            }
            frontUserMapper.deleteByOpenId(frontUser.getOpenId());
        }
        int i = frontUserMapper.insertFrontUser(frontUser);
        if (i > 0) {
            if (StringUtils.isNotEmpty(frontUser.getOpenId())) {
                FrontVx frontVx = new FrontVx();
                frontVx.setOpenId(frontUser.getOpenId());
                frontVx.setVxStatus("1");
                frontVxMapper.updateFrontVxByOpenId(frontVx);
            }
        }
        Long userId=frontUser.getId();
        //添加到角色用户表
        insertUserRole(frontUser);
        //添加到监控分组表
        Date date = new Date();
        //创建监控分组、模板
        createGroupTemplate(frontUser, userId, date);

        return 1;
    }

    public void createGroupTemplate(FrontUser frontUser, Long userId, Date date) {
        MonitorGroup monitorGroup = new MonitorGroup();
        monitorGroup.setUserId(Math.toIntExact(userId));
        monitorGroup.setGroupName("默认分组");
        monitorGroup.setCreateBy(frontUser.getUserName());
        monitorGroup.setCreateTime(date);
        monitorGroupService.insertMonitorGroup(monitorGroup);

        //添加到监控模板表
        MonitorTemplate monitorTemplate = new MonitorTemplate();
        monitorTemplate.setTemplateName("默认模板");
        monitorTemplate.setGroupId(monitorGroup.getId());
        monitorTemplate.setGroupName(monitorGroup.getGroupName());
        monitorTemplate.setUserId(Math.toIntExact(userId));
        monitorTemplate.setCreateBy(frontUser.getUserName());
        monitorTemplate.setCreateTime(date);
        monitorTemplateService.insertMonitorTemplate(monitorTemplate);

        //添加到监控分组模板表
        MonitorGroupTemplate monitorGroupTemplate = new MonitorGroupTemplate();
        monitorGroupTemplate.setGroupId(monitorGroup.getId());
        monitorGroupTemplate.setTemplateId(monitorTemplate.getId());
        monitorGroupTemplateService.insertMonitorGroupTemplate(monitorGroupTemplate);

        //添加到监控设置表 默认模板子信息
        MonitorSetNew monitorSetNew = new MonitorSetNew();
        monitorSetNew.setUserId("-1");
        monitorSetNew.setTemplateId(0);
        List<MonitorSetNew> monitorSetNews = monitorSetNewService.selectMonitorSetNewList(monitorSetNew);
        monitorSetNews.forEach(monitor -> {
            monitor.setId(null);
            monitor.setUserId(String.valueOf(userId));
            monitor.setCreateBy(frontUser.getUserName());
            monitor.setCreditTime(date);
            monitor.setTemplateId(monitorTemplate.getId());
            monitorSetNewService.insertMonitorSetNew(monitor);
        });

        //添加到监控设置司法串联
        MonitorSetSfNew monitorSetSfNew = new MonitorSetSfNew();
        monitorSetSfNew.setUserId("-1");
        List<MonitorSetSfNew> monitorSetSfNews = monitorSetSfNewService.selectMonitorSetSfNewList(monitorSetSfNew);
        monitorSetSfNews.forEach(monitor -> {
            monitor.setId(null);
            monitor.setUserId(String.valueOf(userId));
            monitor.setCreateBy(frontUser.getUserName());
            monitor.setCreditTime(date);
            monitor.setTemplateId(monitorTemplate.getId());
            monitorSetSfNewService.insertMonitorSetSfNew(monitor);
        });
    }

    @Override
    public  AjaxResult getFrontUserByOpenId(HttpServletRequest request,String openid1) {
        FrontUserMon frontUsers= frontUserMapper.selectFrontUserByOpenId(openid1);

        if (Objects.nonNull(frontUsers)){
            HttpSession session = request.getSession(true);
            ValueOperations<String, String> operations = redisTemplate.opsForValue();

            ValueOperations<String, FrontUserMon> operations1 = redisTemplate.opsForValue();

            operations.set("sessionid",session.getId(),3600, TimeUnit.SECONDS);

            boolean isToken = redisTemplate.hasKey(frontUsers.getLoginName() + ":login");
            if (isToken) {
                String keywortd = operations.get(frontUsers.getLoginName() + ":login");
                redisTemplate.delete(keywortd);
                operations.set("inoperativeToken_" + keywortd, keywortd, 60, TimeUnit.MINUTES);
            }

            //使用uuid作为源token
            String token = tokenManager.getToken(frontUsers);
            operations.set(frontUsers.getLoginName() + ":login", "token_" + token, 3600, TimeUnit.SECONDS);
            frontUsers.setToken(token);
            //初始化
            session.invalidate();
            boolean hasKey = redisTemplate.hasKey("account_" + frontUsers.getLoginName() + "_loginTime");
            if (hasKey) {
                getLoginTimes(frontUsers, "0");

            }
            frontUsers.setPassword(null);
            //查询菜单
            List<FrontMenu> frontMenus = frontMenuMapper.selectMenuAllByUserId(Long.valueOf(frontUsers.getId()));
            //菜单去重
            if (CollectionUtils.isEmpty(frontMenus)){
                frontUsers.setFrontMenu(Collections.EMPTY_LIST);
            }else {
                //去重,并放入user实体类中
                List<FrontMenu> meuns = frontMenus.stream().collect(Collectors.toMap(FrontMenu::getMenuId, Function.identity(), (e, r) -> e)).values().stream().collect(Collectors.toList());
                frontUsers.setFrontMenu(meuns);
            }
            //放入user实体类中
//        frontUsers.setFrontMenu(frontMenus);
            //orgid   orgname   自己的
            FrontDept frontDept = frontDeptMapper.selectFrontDeptByOrgId(frontUsers.getOrgId());
            TemplateConfiguration tmp=templateConfigurationService.getTemppConfByOrg(frontUsers.getOrgId());
            frontUsers.setParentOrgName(frontDept.getDeptName());
            //通过获取crontractId 并录入价格记录到库中
            if(StringUtils.isNotEmpty(tmp.getContractId())){
                frontUsers.setContractId(Long.parseLong(tmp.getContractId()));
            }

            //获取biztypes
            frontUsers.setBizTypes(frontDept.getBizTypes());

            //下单身份 公司和 分公司 并存所有下属 并把deptType存入
            String orderOrgName = null;
            String deptType = null;
            if (frontDept.getDeptType().equals("1")){
                orderOrgName = frontDept.getDeptName();
                deptType = frontDept.getDeptType();
                frontUsers.setHeadId(frontDept.getParentId()+"");
            }
            if (frontDept.getDeptType().equals("0")) {
                orderOrgName = frontDept.getDeptName();
                deptType = frontDept.getDeptType();
                frontUsers.setHeadId(frontDept.getId()+"");
            }
            //部门存上一级 deptType是自己部门的
            if (frontDept.getDeptType().equals("2")){
                FrontDept frontDept1 = frontDeptMapper.selectFrontDeptByOrgId(frontDept.getParentId());
                orderOrgName = frontDept1.getDeptName();
                frontUsers.setOrderOrgName(orderOrgName);
                deptType = frontDept.getDeptType();
                frontUsers.setHeadId(frontDept1.getParentId()+"");
            }
            frontUsers.setOrderOrgName(orderOrgName);
            frontUsers.setDeptType(deptType);
            if (StringUtils.isNotEmpty(frontUsers.getReports())){
                List<TempConf> tempConfList = JsonUtils.fromJson(frontUsers.getReports(), new TypeReference<List<TempConf>>() {});
                frontUsers.setTempConfList(tempConfList);
            }
            System.out.println(JsonUtils.toJson(frontUsers));
            //反角色权限 frontMenus
            operations1.set("token_" + token, frontUsers);

            //AjaxResult.success(frontMenus)
            return AjaxResult.success(frontUsers);
        } else {
              FrontUser user = new FrontUser();
            if (StringUtils.isEmpty(openid1)) {
                return error("请重新授权微信");
            }
            user.setOpenId(openid1);
            FrontUserMon frontUsers1 = frontUserMapper.selectFrontUserByOpenId1(openid1);
            if (Objects.nonNull(frontUsers1)){
                return AjaxResult.other(4009,openid1);
            }
            user.setVxType(2);
            frontUserMapper.insertFrontUser(user);
            return AjaxResult.other(4009,openid1);
        }

    }

    @Override
    public AjaxResult webWxLogin(HttpServletRequest request, FrontUserMon frontUserMon) {

        HttpSession session = request.getSession(true);

        ValueOperations<String, String> operations = redisTemplate.opsForValue();

        ValueOperations<String, FrontUserMon> operations1 = redisTemplate.opsForValue();
        //判断登录是否为空
        if (StringUtils.isEmpty(frontUserMon.getLoginName())){
            return error("请输入用户名");
        }
        if (StringUtils.isEmpty(frontUserMon.getPassword())){
            return error("请输入密码");
        }
        //拿到加密后的密码 取数据库中查找
        String salt = passwordService.encryptPassword(frontUserMon.getLoginName(), frontUserMon.getPassword(),null);

        FrontUserMon frontUsers = frontUserMapper.findUserByLoginName(frontUserMon.getLoginName(), salt);
        if (ObjectUtils.isEmpty(frontUsers)){
            return error("用户/密码不正确");
        }

        //判断密码是否正确
        if (!salt.equals(frontUsers.getPassword())) {
            FrontUserMon userloginTime = new FrontUserMon();
            userloginTime.setLoginName(frontUsers.getLoginName());
            userloginTime = getLoginTimes(userloginTime, "1"); //1为输入错误
            if (5 <= Integer.valueOf(userloginTime.getLoginTimes())) {
                return error("尝试登录次数过多,请十分钟后重试。");
            }
            return error("账号或密码错误,您还有" + (5 - Integer.valueOf(userloginTime.getLoginTimes())) + "次机会");
        }
        if (frontUserMon.getOpenId().equals("请重新授权微信")){
            return other(5009,"请重新授权微信");
        }

        FrontUserMon frontUserMon1 = frontUserMapper.selectFrontUserByOpenId(frontUserMon.getOpenId());
        if (frontUserMon1 == null && frontUsers.getOpenId() == null ){
            frontUserMapper.deleteByOpenId(frontUserMon.getOpenId());
            int i = frontUserMapper.updateUserOpenId(frontUsers.getId(),frontUserMon.getOpenId());
            if (i > 0){
                operations.set("sessionid",session.getId(),3600, TimeUnit.SECONDS);

                boolean isToken = redisTemplate.hasKey(frontUserMon.getLoginName() + ":login");
                if (isToken) {
                    String keywortd = operations.get(frontUserMon.getLoginName() + ":login");
                    redisTemplate.delete(keywortd);
                    operations.set("inoperativeToken_" + keywortd, keywortd, 60, TimeUnit.MINUTES);
                }

                //使用uuid作为源token
                String token = tokenManager.getToken(frontUsers);
                operations.set(frontUserMon.getLoginName() + ":login", "token_" + token, 3600, TimeUnit.SECONDS);
                frontUsers.setToken(token);
                //初始化
                session.invalidate();
                boolean hasKey = redisTemplate.hasKey("account_" + frontUsers.getLoginName() + "_loginTime");
                if (hasKey) {
                    if (5 <= Integer.parseInt(Objects.requireNonNull(operations.get("account_" + frontUsers.getLoginName()  + "_loginTime")))) {
                        return error("您的登录次数已达上限,请十分钟后再试!");
                    } else {
                        getLoginTimes(frontUserMon, "0");
                    }
                }
                frontUsers.setPassword(null);
                //查询菜单
                List<FrontMenu> frontMenus = frontMenuMapper.selectMenuAllByUserId(Long.valueOf(frontUsers.getId()));
                //菜单去重
                if (CollectionUtils.isEmpty(frontMenus)){
                    frontUsers.setFrontMenu(Collections.EMPTY_LIST);
                }else {
                    //去重,并放入user实体类中
                    List<FrontMenu> meuns = frontMenus.stream().collect(Collectors.toMap(FrontMenu::getMenuId, Function.identity(), (e, r) -> e)).values().stream().collect(Collectors.toList());
                    frontUsers.setFrontMenu(meuns);
                }
                //放入user实体类中
//        frontUsers.setFrontMenu(frontMenus);
                //orgid   orgname   自己的
                FrontDept frontDept = frontDeptMapper.selectFrontDeptByOrgId(frontUsers.getOrgId());
                TemplateConfiguration tmp=templateConfigurationService.getTemppConfByOrg(frontUsers.getOrgId());
                frontUsers.setParentOrgName(frontDept.getDeptName());
                //通过获取crontractId 并录入价格记录到库中
                if(StringUtils.isNotEmpty(tmp.getContractId())){
                    frontUsers.setContractId(Long.parseLong(tmp.getContractId()));
                }

                //获取biztypes
                frontUsers.setBizTypes(frontDept.getBizTypes());

                //下单身份 公司和 分公司 并存所有下属 并把deptType存入
                String orderOrgName = null;
                String deptType = null;
                if (frontDept.getDeptType().equals("1")){
                    orderOrgName = frontDept.getDeptName();
                    deptType = frontDept.getDeptType();
                    frontUsers.setHeadId(frontDept.getParentId()+"");
                }
                if (frontDept.getDeptType().equals("0")) {
                    orderOrgName = frontDept.getDeptName();
                    deptType = frontDept.getDeptType();
                    frontUsers.setHeadId(frontDept.getId()+"");
                }
                //部门存上一级 deptType是自己部门的
                if (frontDept.getDeptType().equals("2")){
                    FrontDept frontDept1 = frontDeptMapper.selectFrontDeptByOrgId(frontDept.getParentId());
                    orderOrgName = frontDept1.getDeptName();
                    frontUsers.setOrderOrgName(orderOrgName);
                    deptType = frontDept.getDeptType();
                    frontUsers.setHeadId(frontDept1.getParentId()+"");
                }
                frontUsers.setOrderOrgName(orderOrgName);
                frontUsers.setDeptType(deptType);
                if (StringUtils.isNotEmpty(frontUsers.getReports())){
                    List<TempConf> tempConfList = JsonUtils.fromJson(frontUsers.getReports(), new TypeReference<List<TempConf>>() {});
                    frontUsers.setTempConfList(tempConfList);
                }
                System.out.println(JsonUtils.toJson(frontUsers));
                //反角色权限 frontMenus
                operations1.set("token_" + token, frontUsers);
                //AjaxResult.success(frontMenus)
                return AjaxResult.success(frontUsers);
            }
        }else {
            return other(5010 ,"该用户已绑定微信");
        }
        return AjaxResult.error("登录失败");
    }

    @Override
    public List<FrontUser> selectFrontUserByMonList(FrontUser frontUser) {
        return frontUserMapper.selectFrontUserByMonList(frontUser);
    }

    //新增用户递归查询模板信息
    public TemplateConfiguration getTemplateConfiguration(Long orgId) {
        TemplateConfiguration temppConfByOrg = templateConfigurationService.getTemppConfByOrg(orgId);
        if (Objects.isNull(temppConfByOrg)){
            // 获取上级部门
            FrontDept frontDept = frontDeptService.selectFrontDeptById(orgId);
            if (Objects.nonNull(frontDept) && frontDept.getParentId() != 0L) {
                // 递归查询上级部门
                return getTemplateConfiguration(frontDept.getParentId());
            } else {
                // 上级部门为空,返回null
                return null;
            }
        }
        return temppConfByOrg;
    }
}