package com.gree.mall.manager.logic.admin;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.gree.mall.manager.bean.ExcelData;
import com.gree.mall.manager.bean.SVerification;
import com.gree.mall.manager.bean.admin.AdminModuleTree;
import com.gree.mall.manager.bean.admin.AdminUserBean;
import com.gree.mall.manager.bean.admin.AdminUserCom;
import com.gree.mall.manager.bean.admin.AdminWebsitGrantBean;
import com.gree.mall.manager.bean.admin.reqDto.AdminUserAddReqBean;
import com.gree.mall.manager.bean.admin.respDto.AdminCompanyWechatRespPageBean;
import com.gree.mall.manager.commonmapper.AdminMapper;
import com.gree.mall.manager.enums.RedisPrefixEnum;
import com.gree.mall.manager.enums.admin.AdminWebsitTypeEnum;
import com.gree.mall.manager.exception.RemoteServiceException;
import com.gree.mall.manager.logic.big.BigLogic;
import com.gree.mall.manager.logic.common.CommonLogic;
import com.gree.mall.manager.plus.entity.*;
import com.gree.mall.manager.plus.service.*;
import com.gree.mall.manager.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdminUserLogic {
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    DefaultKaptcha defaultKaptcha;
    @Autowired
    CommonLogic commonLogic;
    @Autowired
    AdminUserService adminUserService;
    @Autowired
    AdminModuleService adminModuleService;
    @Autowired
    AdminRoleService adminRoleService;
    @Autowired
    AdminUserModuleRelaService adminUserModuleRelaService;
    @Autowired
    AdminCompanyWechatService adminCompanyWechatService;
    @Autowired
    AdminWebsitService adminWebsitService;
    @Autowired
    AdminUserWebsitRelaService adminUserWebsitRelaService;
    @Autowired
    AdminMapper adminMapper;
    @Autowired
    BuyCompanyInfoService buyCompanyInfoService;
    @Autowired
    AdminUserDeptRelaService adminUserDeptRelaService;

    @Autowired
    AdminDeptWebsitService adminDeptWebsitService;

    @Autowired
    AdminDeptService adminDeptService;


    @Autowired
    BigLogic bigLogic;
//    @Value("${front.top.url}")
//    private String frontTopUrl;

    /**
     * 验证码
     */
    public SVerification defaultKaptcha() throws IOException {
        // 生成文字验证码
        String text = defaultKaptcha.createText();

        // 生成图片验证码
        ByteArrayOutputStream outputStream = null;
        BufferedImage image = defaultKaptcha.createImage(text);
        outputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "png", outputStream);
        byte b[] = outputStream.toByteArray();//从流中获取数据数组。
//        String baseStr = new BASE64Encoder().encode(b);
        String baseStr = Base64.getEncoder().encodeToString(b);
        //生成一个token
        String code = UUID.randomUUID().toString();
        redisUtil.set(RedisPrefixEnum.TOKEN_VERIFICATION + code, text, 2 * 60);
        SVerification verification = new SVerification();
        verification.setCode(code);
        verification.setPic(baseStr);
        return verification;
    }

    /**
     * 登录
     */
    public AdminUserCom login(String userName, String password, String code, String codeValue) throws RemoteServiceException {

        AdminUser adminUser = adminUserService.lambdaQuery().eq(AdminUser::getUserName, userName).one();
        if (adminUser == null) {
            throw new RemoteServiceException("帐号不存在");
        }
        //如果是admin操作非admin账号登陆不需要判断密码是否正确
        AdminUserCom adminUser1 = commonLogic.getAdminUser();
        if (adminUser1 == null || !(adminUser1.getUserName().equals("admin")) && !StringUtils.equals(userName, "admin")) {

            String value = (String) redisUtil.get(RedisPrefixEnum.TOKEN_VERIFICATION + code);
            if (StringUtils.isBlank(value)) {
                throw new RemoteServiceException("验证码过期，请刷新验证码重试");
            }
            if (!value.equals(codeValue)) {
                throw new RemoteServiceException("验证码错误");
            }

            if (adminUser.getLoginErrNum() >= 3) {
                throw new RemoteServiceException("登陆失败，您已连续输入错误3次密码，请联系管理人员重置密码");
            }

            if (!StringUtils.equals(adminUser.getPassword(), MD5Utils.md5(password))) {
                adminUser.setLoginErrNum(adminUser.getLoginErrNum() + 1);
                adminUser.updateById();
                //记录错误次数
                throw new RemoteServiceException("帐号密码错误");
            }
        }

        if (!adminUser.getStatus()) {
            throw new RemoteServiceException("帐号冻结中，请联系相关管理人员");
        }

        adminUser.setLoginErrNum(0);
        adminUser.setLastLoginTime(new Date());
        adminUser.updateById();

        String token = JwtUtils.createJWT(adminUser.getAdminUserId(), adminUser.getNickName(), adminUser.getUserName(), 20 * 60 * 60 * 1000);
        AdminUserCom adminUserCom = commonLogic.getAdminUser(adminUser.getAdminUserId(), token);
        adminUserCom.setToken(token);
        //存放到redis
        redisUtil.set(RedisPrefixEnum.TOKEN_MGR.toString() + adminUserCom.getToken(), adminUserCom, 20 * 60 * 60 * 1000);

        bigLogic.addUserLog(adminUser.getAdminUserId());

        return adminUserCom;

    }

    /**
     * 修改密码
     */
    public void updatePassword(String userName, String password, String newPwd) throws RemoteServiceException {
        AdminUser adminUser = adminUserService.lambdaQuery().eq(AdminUser::getUserName, userName)
                .eq(AdminUser::getPassword, MD5Utils.md5(password)).one();
        if (adminUser == null) {
            throw new RemoteServiceException("帐号密码错误");
        }
        adminUser.setLoginErrNum(0);
        adminUser.setPassword(MD5Utils.md5(newPwd));
        adminUserService.updateById(adminUser);
    }

    /**
     * 修改帐号状态
     */
    public void updateStatus(String adminUserId, Boolean status) {
        adminUserService.lambdaUpdate().set(AdminUser::getStatus, status).eq(AdminUser::getAdminUserId, adminUserId).update();
    }

    /**
     * 重置密码
     */
    public void resetPassword(String adminUserId, String password, HttpServletRequest request) throws RemoteServiceException {
        //检查是否拥有重置的密码权限
        String nickName = CommonUtils.getNickName(request);
        AdminUserCom adminUser1 = commonLogic.getAdminUser();
        if (adminUser1.getType() == 0) {
            throw new RemoteServiceException("只有超级管理员或商户账号才有重置密码的权限");
        }

        //开始重置
        AdminUser adminUser = adminUserService.getById(adminUserId);
        adminUser.setPassword(MD5Utils.md5(password));
        adminUser.setLoginErrNum(0);
        adminUser.updateById();
    }


    /**
     * 新增帐号
     */
    @Transactional
    public void add(AdminUserAddReqBean adminUser, Boolean addMch) throws RemoteServiceException {
        AdminUserCom curAdminUser = commonLogic.getAdminUser();
        if (StringUtils.isBlank(adminUser.getUserName()) || StringUtils.isBlank(adminUser.getPassword())) {
            throw new RemoteServiceException("参数错误");
        }
        if (Objects.nonNull(adminUser.getIsVender())
                && adminUser.getIsVender()
                && StringUtils.isBlank(adminUser.getVenderId())) {
            throw new RemoteServiceException("请选择供应商");
        }
        Integer count = adminUserService.lambdaQuery().eq(AdminUser::getUserName, adminUser.getUserName()).count();
        if (count > 0) {
            throw new RemoteServiceException("帐号已被注册");
        }
        //当前用户选择的部门
        if (CollectionUtils.isEmpty(adminUser.getAdminDeptId()) && CollectionUtils.isEmpty(adminUser.getAdminWebsitId()))
            throw new RemoteServiceException("请选择部门/网点");

        if (!CollectionUtils.isEmpty(adminUser.getAdminWebsitId())) {


            AdminWebsit adminWebsit = adminWebsitService.getById(adminUser.getAdminWebsitId().get(0));

            if (adminWebsit.getType().equals(AdminWebsitTypeEnum.A.getKey()) && curAdminUser.getType() != 2) {
                throw new RemoteServiceException("当前账号非“平台”类型不能创建平台账号");
            }

            //非平台账号
            if (!StringUtils.equals(adminWebsit.getType(), AdminWebsitTypeEnum.A.getKey())) {
                adminUser.setCompanyWechatId(adminWebsit.getCompanyWechatId());
                adminUser.setCompanyName(adminWebsit.getCompanyWechatName());
            }

            //是否为入驻商户
            if (addMch) {
                adminUser.setType(1);
            } else {
                if (!curAdminUser.getType().equals(AdminWebsitTypeEnum.A.getKey()) && StringUtils.equals(adminWebsit.getType(), AdminWebsitTypeEnum.A.getKey())) {
                    throw new RemoteServiceException("暂无权限创建当前网点的账号");
                }
                if (StringUtils.equals(adminWebsit.getType(), AdminWebsitTypeEnum.C.getKey())) {
                    adminUser.setType(0);
                } else if (StringUtils.equals(adminWebsit.getType(), AdminWebsitTypeEnum.B.getKey())) {
                    adminUser.setType(1);
                } else if (StringUtils.equals(adminWebsit.getType(), AdminWebsitTypeEnum.A.getKey())) {
                    adminUser.setType(2);
                }
            }

        }
        if (!CollectionUtils.isEmpty(adminUser.getAdminDeptId())) {
            AdminDept adminDept = adminDeptService.getById(adminUser.getAdminDeptId().get(0));

            if (!curAdminUser.getType().equals("2") && adminDept.getAdminDeptId().equals("1")) {
                throw new RemoteServiceException("不可选高于商户得平台权限");
            }

            adminUser.setCompanyWechatId(adminDept.getCompanyWechatId());
            adminUser.setCompanyName(adminDept.getCompanyWechatName());

            adminUser.setType(0);
        }

        //需要用户roleId
        AdminRole addUserRole = null;
        if (StringUtils.isBlank(adminUser.getRoleId()) ||
                (addUserRole = adminRoleService.getById(adminUser.getRoleId())) == null) {
            throw new RemoteServiceException("请为用户选择角色");
        }
        adminUser.setRoleName(addUserRole.getName());
        adminUser.setPassword(MD5Utils.md5(adminUser.getPassword()));
        adminUser.setCreateTime(new Date());
        adminUserService.save(adminUser);

        //部门账号(商户账号在生成商户的时候已经处理了部门)
        if (adminUser.getType() != 2) {
            //添加部门
            this.addAdminUserWebsit(adminUser);
        }

        //添加部门
        this.addAdminUserDept(adminUser);
    }

    private void addAdminUserDept(AdminUserAddReqBean adminUser) {

        //先清除
        if (CollectionUtils.isEmpty(adminUser.getAdminDeptId())) {
            return;
        }
        adminUserDeptRelaService.lambdaUpdate().eq(AdminUserDeptRela::getAdminUserId, adminUser.getAdminUserId()).remove();

        List<AdminDept> adminDepts = adminDeptService.lambdaQuery().in(AdminDept::getAdminDeptId, adminUser.getAdminDeptId()).list();
        if (adminDepts.size() == 0) {
            throw new RemoteServiceException("请选择至少1个部门");
        }
        log.info("【添加用户部门关系】:{}", com.alibaba.fastjson.JSONObject.toJSONString(adminUser));
        for (AdminDept adminDept : adminDepts) {
            AdminUserDeptRela adminUserDeptRela = new AdminUserDeptRela();
            adminUserDeptRela.setAdminUserId(adminUser.getAdminUserId());
            adminUserDeptRela.setAdminDeptId(adminDept.getAdminDeptId());
            adminUserDeptRela.setCompanyWechatId(adminDept.getCompanyWechatId());
            adminUserDeptRela.setCreateTime(new Date());
            adminUserDeptRela.insert();
        }

    }

    /**
     * 修改帐号
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(HttpServletRequest request, AdminUserAddReqBean newUser) {

        AdminUserCom admin = commonLogic.getAdminUser(request);
        AdminUser oldUser = adminUserService.getById(newUser.getAdminUserId());
        //需要用户roleId
        AdminRole loginRole = adminRoleService.getById(admin.getRoleId());
        AdminRole addUserRole = null;
        if (StringUtils.isBlank(newUser.getRoleId()) || (addUserRole = adminRoleService.getById(newUser.getRoleId())) == null) {
            throw new RemoteServiceException("请为用户选择角色");
        }
        if (Objects.nonNull(newUser.getIsVender())
                && newUser.getIsVender()
                && StringUtils.isBlank(newUser.getVenderId())) {
            throw new RemoteServiceException("请选择供应商");
        }
        //  添加用户的角色级别 <= 被添加的用户的角色级别
//        if (loginRole.getType() <= addUserRole.getType()) {
//            throw new RemoteServiceException("无法为用户赋予与自身级别相当的角色");
//        }
        //当前用户选择的部门
        if (!CollectionUtils.isEmpty(newUser.getAdminWebsitId())) {
            AdminWebsit adminWebsit = adminWebsitService.getById(newUser.getAdminWebsitId().get(0));
            if (adminWebsit == null) {
                throw new RemoteServiceException("请选择部门");
            }

            if (adminWebsit.getType().equals(AdminWebsitTypeEnum.A.getKey()) && admin.getType() != 2) {
                throw new RemoteServiceException("当前账号非“平台”类型不能创建平台账号");
            }

            if (admin.getType() == 0 && !StringUtils.equals(adminWebsit.getType(), AdminWebsitTypeEnum.C.getKey())) {
                throw new RemoteServiceException("网点账号请选择普通网点");
            }

            if (!oldUser.getType().equals(AdminWebsitTypeEnum.A.getKey()) && StringUtils.equals(adminWebsit.getType(), AdminWebsitTypeEnum.A.getKey())) {
                throw new RemoteServiceException("暂无权限创建当前网点的账号");
            }

            if (StringUtils.equals(adminWebsit.getType(), AdminWebsitTypeEnum.C.getKey())) {
                newUser.setType(0);
            } else if (StringUtils.equals(adminWebsit.getType(), AdminWebsitTypeEnum.B.getKey())) {
                newUser.setType(1);
            } else if (StringUtils.equals(adminWebsit.getType(), AdminWebsitTypeEnum.A.getKey())) {
                newUser.setType(2);
            }
        }

        if (!CollectionUtils.isEmpty(newUser.getAdminDeptId())) {

            if (!CollectionUtils.isEmpty(newUser.getAdminDeptId())) {

                AdminDept adminDept = adminDeptService.getById(newUser.getAdminDeptId().get(0));

                if (!admin.getType().equals("2") && newUser.getAdminDeptId().contains("1")) {
                    throw new RemoteServiceException("不可选高于商户得平台权限");
                }


                newUser.setCompanyWechatId(adminDept.getCompanyWechatId());
                newUser.setCompanyName(adminDept.getCompanyWechatName());

                newUser.setType(0);
            }
        }


        newUser.setRoleName(addUserRole.getName());
        newUser.setUserName(null);
        newUser.setPassword(StringUtils.isBlank(newUser.getPassword()) ? null : MD5Utils.md5(newUser.getPassword()));
        newUser.setCompanyWechatId(oldUser.getCompanyWechatId());
        newUser.updateById();


        adminUserWebsitRelaService.lambdaUpdate().eq(AdminUserWebsitRela::getAdminUserId, newUser.getAdminUserId()).remove();
        adminUserDeptRelaService.lambdaUpdate().eq(AdminUserDeptRela::getAdminUserId, newUser.getAdminUserId()).remove();

        //部门账号(商户账号在生成商户的时候已经处理了部门)
        if (newUser.getType() != 2) {
            //添加部门
            this.addAdminUserWebsit(newUser);
        }

        //添加部门
        this.addAdminUserDept(newUser);

    }


    //添加用户部门关系
    private void addAdminUserWebsit(AdminUserAddReqBean adminUser) {
        //先清除
        if (CollectionUtils.isEmpty(adminUser.getAdminWebsitId())) {
            return;
        }
        adminUserWebsitRelaService.lambdaUpdate().in(AdminUserWebsitRela::getAdminUserId, adminUser.getAdminUserId()).remove();
        List<AdminWebsit> websits = adminWebsitService.lambdaQuery().in(AdminWebsit::getWebsitId, adminUser.getAdminWebsitId()).list();
        if (websits.size() == 0) {
            throw new RemoteServiceException("请选择至少1个部门");
        }
        log.info("【添加用户部门关系】:{}", com.alibaba.fastjson.JSONObject.toJSONString(adminUser));
        for (AdminWebsit adminWebsit : websits) {
            AdminUserWebsitRela adminUserWebsitRela = new AdminUserWebsitRela();
            adminUserWebsitRela.setAdminUserId(adminUser.getAdminUserId());
            adminUserWebsitRela.setAdminWebsitId(adminWebsit.getWebsitId());
            adminUserWebsitRela.setCompanyWechatId(adminUser.getCompanyWechatId());
            adminUserWebsitRela.setCreateTime(new Date());
            adminUserWebsitRela.insert();
        }

    }


    /**
     * 运营后台用户列表
     *
     * @return
     */
    public IPage<AdminUser> list(String companyWechatId, String companyWechatName, String roleId, Boolean status, String userName, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();

        if (adminUser.getType() != 2) {
            companyWechatId = adminUser.getAdminCompanyWechat().getCompanyWechatId();
        }
        IPage<AdminUser> page = adminUserService.lambdaQuery()
                .eq(StringUtils.isNotBlank(companyWechatId), AdminUser::getCompanyWechatId, companyWechatId)
                .like(StringUtils.isNotBlank(companyWechatName), AdminUser::getCompanyName, companyWechatName)
                .eq(StringUtils.isNotBlank(roleId), AdminUser::getRoleId, roleId)
                .eq(status != null, AdminUser::getStatus, status)
                .in(CollectionUtils.isNotEmpty(adminUser.getCompanyWechatIds()), AdminUser::getCompanyWechatId, adminUser.getCompanyWechatIds())
                .like(StringUtils.isNotBlank(userName), AdminUser::getUserName, userName)
                .orderByDesc(AdminUser::getCompanyWechatId)
                .orderByAsc(AdminUser::getCreateTime)
                .page(new Page<>(pageNum, pageSize));

        for (AdminUser record : page.getRecords()) {
            AdminUserWebsitRela adminUserWebsitRela = adminUserWebsitRelaService.lambdaQuery().eq(AdminUserWebsitRela::getAdminUserId, record.getAdminUserId()).last("limit 1").one();

            AdminUserDeptRela adminUserDeptRela = adminUserDeptRelaService.lambdaQuery().eq(AdminUserDeptRela::getAdminUserId, record.getAdminUserId()).last("limit 1").one();


            if (adminUserDeptRela != null) {

                AdminDept adminDept = adminDeptService.getById(adminUserDeptRela.getAdminDeptId());

                record.setDeptWebsitName(adminDept.getDeptName());

            } else if (adminUserWebsitRela != null) {

                AdminWebsit adminWebsit = adminWebsitService.getById(adminUserWebsitRela.getAdminWebsitId());
                if (adminWebsit != null)
                 record.setDeptWebsitName(adminWebsit.getName());
            }


        }


        return page;
    }


    /**
     * 账号列表
     */
    public IPage<AdminUser> list(String companyWechatId, String userName, String nickName, String linkPhone, String email, Boolean status, Integer pageNum, Integer pageSize) {
        AdminUserCom adminUser = commonLogic.getAdminUser();
        IPage<AdminUser> adminUserIPage = adminMapper.mchList(new Page(pageNum, pageSize), userName, nickName, linkPhone, email, status, companyWechatId, adminUser.getCompanyWechatIds());
        return adminUserIPage;
    }


    /**
     * 导出商户列表
     */
    public ExcelData exportMch(List<AdminCompanyWechatRespPageBean> list) {
        String[] titles = new String[]{"用户名", "负责人", "联系电话", "邮箱", "地址", "创建时间"};
        List<List<Object>> rows = new ArrayList<>();
        for (AdminCompanyWechatRespPageBean adminUser : list) {
            List<Object> row = new ArrayList<>();
            row.add(adminUser.getUserName());
            row.add(adminUser.getNickName());
            row.add(adminUser.getLinkPhone());
            row.add(adminUser.getEmail());
            row.add(adminUser.getAddress());
            row.add(DateUtils.formatDate(adminUser.getCreateTime()));
            rows.add(row);
        }
        ExcelData excelData = new ExcelData();
        excelData.setRows(rows);
        excelData.setTitles(Arrays.asList(titles));
        excelData.setName("sheet1");
        return excelData;
    }

    /**
     * 运营后台用户详情
     *
     * @param adminUserId
     * @return
     */
    public AdminUserBean detail(String adminUserId) {
        AdminUser adminUser = adminUserService.getById(adminUserId);
        AdminUserBean adminUserBean = new AdminUserBean();
        BeanUtils.copyProperties(adminUser, adminUserBean);

        AdminWebsit adminWebsit = adminWebsitService.lambdaQuery()
                .eq(AdminWebsit::getCompanyWechatId, adminUser.getCompanyWechatId())
                .eq(AdminWebsit::getType, AdminWebsitTypeEnum.B.getKey())
                .last("limit 1")
                .one();
        if (adminWebsit != null) {
            adminUserBean.setJoinCode(adminWebsit.getJoinCode());
        }

        if (adminUser.getType() != 2) {
            String companyWechatId = adminUser.getCompanyWechatId();
            AdminCompanyWechat adminCompanyWechat = adminCompanyWechatService.getById(companyWechatId);
            BeanUtils.copyProperties(adminCompanyWechat, adminUserBean);
            adminUserBean.setProvince(adminCompanyWechat.getProvince());
            adminUserBean.setCity(adminCompanyWechat.getCity());
            adminUserBean.setArea(adminCompanyWechat.getArea());
            adminUserBean.setStreet(adminCompanyWechat.getStreet());
            adminUserBean.setCompanyOpenTime(adminCompanyWechat.getCreateTime());
            adminUserBean.setCompanyExpireTime(adminCompanyWechat.getExpireTime());
            adminUserBean.setBuyCompanyInfo(adminCompanyWechat.getBuyCompanyInfo());
            adminUserBean.setPubAppId(adminCompanyWechat.getSubAppId());
            adminUserBean.setPubAppSecret(adminCompanyWechat.getSubSecret());
            adminUserBean.setAppletAppid(adminCompanyWechat.getAppletAppid());
            adminUserBean.setAppletSecret(adminCompanyWechat.getAppletSecret());
            adminUserBean.setPubTemplateId1(adminCompanyWechat.getPubTemplateId1());
            adminUserBean.setPubTemplateId2(adminCompanyWechat.getPubTemplateId2());
            adminUserBean.setPubTemplateId3(adminCompanyWechat.getPubTemplateId3());
            adminUserBean.setPubTemplateId4(adminCompanyWechat.getPubTemplateId4());
            adminUserBean.setPubTemplateId5(adminCompanyWechat.getPubTemplateId5());
            adminUserBean.setPubTemplateId6(adminCompanyWechat.getPubTemplateId6());
            adminUserBean.setPubTemplateId7(adminCompanyWechat.getPubTemplateId7());
            adminUserBean.setPubTemplateId8(adminCompanyWechat.getPubTemplateId8());
            adminUserBean.setLinkPhone(adminUser.getLinkPhone());
            adminUserBean.setLinkName(adminUser.getLinkName());
            adminUserBean.setPayQrcode(adminCompanyWechat.getPayQrcode());
            adminUserBean.setBillTitle(adminCompanyWechat.getBillTitle());
            adminUserBean.setStorePay(adminCompanyWechat.getStorePay());
            adminUserBean.setIsShareTax(adminCompanyWechat.getIsShareTax());
            adminUserBean.setAppModuleJson(adminCompanyWechat.getAppModuleJson());
            List<AdminUserWebsitRela> websitIds = adminUserWebsitRelaService.lambdaQuery()
                    .eq(AdminUserWebsitRela::getAdminUserId, adminUser.getAdminUserId()).list();
            if (websitIds.size() > 0) {
                List<String> collect = websitIds.stream().map(AdminUserWebsitRela::getAdminWebsitId).collect(Collectors.toList());
                adminUserBean.setAdminWebsitId(collect);
            }

            List<AdminUserDeptRela> adminUserDeptRelaList = adminUserDeptRelaService.lambdaQuery()
                    .eq(AdminUserDeptRela::getAdminUserId, adminUser.getAdminUserId()).list();

            if (!CollectionUtils.isEmpty(adminUserDeptRelaList)) {

                List<String> deptIds = adminUserDeptRelaList.stream().map(AdminUserDeptRela::getAdminDeptId).collect(Collectors.toList());
                adminUserBean.setAdminDeptId(deptIds);

                List<AdminDeptWebsit> adminDeptWebsitList = adminDeptWebsitService.lambdaQuery()
                        .in(AdminDeptWebsit::getAdminDeptId, deptIds).list();

                List<String> collect = adminDeptWebsitList.stream().map(AdminDeptWebsit::getWebsitId).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(adminUserBean.getAdminWebsitId()))
                    collect.addAll(adminUserBean.getAdminWebsitId());
                adminUserBean.setAdminWebsitIds(collect);
            }


            return adminUserBean;
        }
        return adminUserBean;
    }


    /**
     * 退出登录
     */
    public void logout(HttpServletRequest request) {
        String token = CommonUtils.getToken(request);
        redisUtil.del(RedisPrefixEnum.TOKEN_MGR + token);
    }


    /**
     * 根据登录帐号查询权限模块
     */
    public List<AdminModuleTree> queryAdminModule(String adminUserId) {
        //String adminUserId = CommonUtils.getUserId(request);
        AdminUser adminUser = adminUserService.getById(adminUserId);
        if (adminUser.getUserName().equals("admin")) {
            return this.queryAdminModuleTree(null, true, null, null);
        } else {
            return this.queryAdminModuleTree(adminUser.getRoleId(), false, null, null);
        }
    }

    /**
     * 给角色授权
     */
    @Transactional
    public void grantModules(AdminWebsitGrantBean adminWebsitGrantBean) {
        String roleId = adminWebsitGrantBean.getAdminRoleId();
        //1.清空该角色的权限
        adminUserModuleRelaService.lambdaUpdate().eq(AdminUserModuleRela::getAdminRoleId, roleId).remove();

        //2.生成权限
        List<AdminUserModuleRela> list = new ArrayList<>();
        for (String adminModuleId : adminWebsitGrantBean.getAdminModuleIds()) {
            AdminUserModuleRela adminUserModuleRela = new AdminUserModuleRela();
            adminUserModuleRela.setAdminRoleId(roleId);
            adminUserModuleRela.setCreateTime(new Date());
            adminUserModuleRela.setStatus(true);
            adminUserModuleRela.setAdminModuleId(adminModuleId);
            adminUserModuleRela.setFlag(1);
            list.add(adminUserModuleRela);
        }
        for (String adminModuleId : adminWebsitGrantBean.getAdminModuleIds2()) {
            AdminUserModuleRela adminUserModuleRela = new AdminUserModuleRela();
            adminUserModuleRela.setAdminRoleId(roleId);
            adminUserModuleRela.setCreateTime(new Date());
            adminUserModuleRela.setStatus(true);
            adminUserModuleRela.setAdminModuleId(adminModuleId);
            adminUserModuleRela.setFlag(0);
            list.add(adminUserModuleRela);
        }
        adminUserModuleRelaService.saveBatch(list);
    }

    /**
     * 根据角色id查询拥有的权限ids
     */
    public List<String> queryModuleIdChecked(String adminRoleId) {
        AdminRole adminRole = adminRoleService.getById(adminRoleId);
        Boolean admin = adminRole.getName().equals("超级管理员");
        if (admin) {
            List<AdminModule> list = adminModuleService.list();
            if (list.size() == 0) {
                return new ArrayList<>();
            }
            return list.stream().map(AdminModule::getModuleId).collect(Collectors.toList());
        }
        List<AdminUserModuleRela> list = adminUserModuleRelaService.lambdaQuery()
                .eq(AdminUserModuleRela::getFlag, 1)
                .eq(AdminUserModuleRela::getAdminRoleId, adminRoleId).list();
        if (CollectionUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        return list.stream().map(AdminUserModuleRela::getAdminModuleId).collect(Collectors.toList());
    }

    /**
     * 根据角色查询所有功能模块权限
     */
    public List<AdminModuleTree> queryAllAdminModuleTree(String adminRoleId, HttpServletRequest request) {
        String userId = CommonUtils.getUserId(request);
        AdminUser adminUser = adminUserService.getById(userId);

        //更改的角色
        AdminRole adminRole = adminRoleService.getById(adminRoleId);
        //查询该角色有的权限d
        List<AdminUserModuleRela> hasModules = adminUserModuleRelaService.lambdaQuery().eq(AdminUserModuleRela::getAdminRoleId, adminRoleId).list();
        List<String> collect = new ArrayList<>();
        if (!CollectionUtils.isEmpty(hasModules)) {
            collect = hasModules.stream().map(AdminUserModuleRela::getAdminModuleId).collect(Collectors.toList());
        }
        List<AdminModuleTree> adminModuleTrees = this.queryAdminModuleTree(adminRoleId, adminRole.getName().equals("超级管理员"), collect, adminUser);
        return adminModuleTrees;
    }


    private List<AdminModuleTree> queryAdminModuleTree(String roleId, Boolean admin, List<String> hasModule, AdminUser adminUser) {

        List<AdminModule> adminModules = null;

        if (admin != null && !admin) {
            //非超管角色
            List<AdminUserModuleRela> list = adminUserModuleRelaService.lambdaQuery()
                    .eq(StringUtils.isNotBlank(roleId), AdminUserModuleRela::getAdminRoleId, roleId)
                    .list();
            if (list.size() == 0) {
                return new ArrayList<>();
            }
            List<String> moduleIds = list.stream().map(AdminUserModuleRela::getAdminModuleId).collect(Collectors.toList());
            adminModules = adminModuleService.lambdaQuery().in(AdminModule::getModuleId, moduleIds)
                    .orderByAsc(AdminModule::getSortNum).list();
        } else {
            //超管角色
            List<AdminUserModuleRela> list = adminUserModuleRelaService.lambdaQuery().list();
            if (list.size() == 0) {
                return new ArrayList<>();
            }
            adminModules = adminModuleService.lambdaQuery().orderByAsc(AdminModule::getSortNum).list();
        }
        List<AdminModuleTree> trees = new ArrayList<>();
        for (AdminModule adminModule : adminModules) {
            AdminModuleTree adminModuleTree = new AdminModuleTree();
            BeanUtils.copyProperties(adminModule, adminModuleTree);
            if ((hasModule != null && hasModule.contains(adminModule.getModuleId())) || admin) {
                adminModuleTree.setShow(true);
            }
            trees.add(adminModuleTree);
        }
        List<AdminModuleTree> parents = trees.stream().filter(v -> v.getLevel() == 1).collect(Collectors.toList());
        for (AdminModuleTree adminModuleTree : parents) {
            adminModuleTree.setChildren(this.treeModule(trees, adminModuleTree.getModuleId(), hasModule, admin));
        }
        return parents;
    }

    private List<AdminModuleTree> treeModule(List<AdminModuleTree> list, String parentId, List<String> hasModule, Boolean admin) {
        //最父级资源树
        if (StringUtils.isBlank(parentId)) {
            return new ArrayList<>();
        }
        List<AdminModuleTree> collect = list.stream().filter(e -> e.getParentId().equals(parentId)).collect(Collectors.toList());
        for (AdminModuleTree bean : collect) {
            if ((hasModule != null && hasModule.contains(bean.getModuleId())) || admin) {
                bean.setShow(true);
            }
            bean.setChildren(this.treeModule(list, bean.getModuleId(), hasModule, admin));
        }
        return collect;
    }


}
