package com.gic.haoban.manage.service.service.out.impl.role;

import com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.right.EnterpriseSuperAdminRightMenuQDTO;
import com.gic.clerk.api.dto.right.RightMenuDTO;
import com.gic.clerk.api.service.RightService;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.UniqueIdUtils;
import com.gic.haoban.app.customer.service.api.service.ManageSettingApiService;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.utils.RolesListUtils;
import com.gic.haoban.manage.api.dto.ClerkEditInfoDTO;
import com.gic.haoban.manage.api.dto.TemplateEnterpriseRelatedDTO;
import com.gic.haoban.manage.api.dto.qdto.role.ContentMaterialROleInitQDTO;
import com.gic.haoban.manage.api.dto.qdto.role.HaobanRoleMenuQDTO;
import com.gic.haoban.manage.api.dto.qdto.role.HaobanRoleQDTO;
import com.gic.haoban.manage.api.dto.role.HaobanMenuDTO;
import com.gic.haoban.manage.api.dto.role.HaobanRoleDTO;
import com.gic.haoban.manage.api.enums.role.RoleClerkTypeEnum;
import com.gic.haoban.manage.api.service.ApplicationSettingApiService;
import com.gic.haoban.manage.api.service.role.HaobanRoleApiService;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanTemplateApplicationRelatedMapper;
import com.gic.haoban.manage.service.entity.TabHaobanWxEnterprise;
import com.gic.haoban.manage.service.entity.TabHaobanWxEnterpriseRelated;
import com.gic.haoban.manage.service.entity.role.TabHaobanRole;
import com.gic.haoban.manage.service.entity.role.TabHaobanRoleMenu;
import com.gic.haoban.manage.service.pojo.bo.role.HaobanMenuBO;
import com.gic.haoban.manage.service.pojo.bo.role.HaobanRoleBO;
import com.gic.haoban.manage.service.service.TemplateEnterpriseRelatedService;
import com.gic.haoban.manage.service.service.WxEnterpriseRelatedService;
import com.gic.haoban.manage.service.service.content.adaptor.MaterialEnterpriseAdaptor;
import com.gic.haoban.manage.service.service.role.HaobanMenuService;
import com.gic.haoban.manage.service.service.role.HaobanRoleMenuService;
import com.gic.haoban.manage.service.service.role.HaobanRoleService;
import com.google.common.collect.Lists;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class HaobanRoleApiServiceImpl implements HaobanRoleApiService {

    private static final Logger logger = LogManager.getLogger(HaobanRoleApiServiceImpl.class);

    @Autowired
    private HaobanRoleService haobanRoleService;
    @Autowired
    private HaobanRoleMenuService haobanRoleMenuService;
    @Autowired
    private ManageSettingApiService manageSettingApiService;
    @Autowired
    private WxEnterpriseRelatedService wxEnterpriseRelatedService;
    @Autowired
    private ApplicationSettingApiService applicationSettingApiService;
    @Autowired
    private HaobanMenuService haobanMenuService;
    @Autowired
    private TabHaobanTemplateApplicationRelatedMapper tabHaobanTemplateApplicationRelatedMapper;
    @Autowired
    private TemplateEnterpriseRelatedService templateEnterpriseRelatedService;
    @Autowired
    private MaterialEnterpriseAdaptor materialEnterpriseAdaptor;
    @Autowired
    private RightService rightService ;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResponse add(HaobanRoleQDTO haobanRoleQDTO, WebLoginDTO login) {
        HaobanRoleMenuQDTO clerkMenus = haobanRoleQDTO.getClerkMenus();
        HaobanRoleMenuQDTO manegeClerkMenus = haobanRoleQDTO.getManegeClerkMenus();
        HaobanRoleMenuQDTO managerMenus = haobanRoleQDTO.getManagerMenus();
        String wxEnterpriseId = login.getWxEnterpriseId();
        String clerkId = login.getClerkId();
        String clerkName = login.getClerkName();
        List<TabHaobanRole> haobanRoles = new ArrayList<>();
        List<TabHaobanRoleMenu> tabHaobanRoleMenus = new ArrayList<>();
        Date now = new Date();
        //导购
        if (clerkMenus != null) {
            TabHaobanRole tabHaobanRole = getTabHaobanRole(haobanRoleQDTO, wxEnterpriseId, clerkId, clerkName, haobanRoles, RoleClerkTypeEnum.CLERK.getCode());
            List<String> menuCodes = clerkMenus.getMenuCodes();
            for (String menuCode : menuCodes) {
                getTabHaobanRoleMenu(wxEnterpriseId, tabHaobanRoleMenus, now, tabHaobanRole, menuCode);
            }
        }

        //店长
        if (manegeClerkMenus != null) {
            TabHaobanRole tabHaobanRole = getTabHaobanRole(haobanRoleQDTO, wxEnterpriseId, clerkId, clerkName, haobanRoles, RoleClerkTypeEnum.SHOP.getCode());
            List<String> menuCodes = manegeClerkMenus.getMenuCodes();
            for (String menuCode : menuCodes) {
                getTabHaobanRoleMenu(wxEnterpriseId, tabHaobanRoleMenus, now, tabHaobanRole, menuCode);
            }
        }

        //区经
        if (managerMenus != null) {
            TabHaobanRole tabHaobanRole = getTabHaobanRole(haobanRoleQDTO, wxEnterpriseId, clerkId, clerkName, haobanRoles, RoleClerkTypeEnum.MANAGE.getCode());
            List<String> menuCodes = managerMenus.getMenuCodes();
            for (String menuCode : menuCodes) {
                getTabHaobanRoleMenu(wxEnterpriseId, tabHaobanRoleMenus, now, tabHaobanRole, menuCode);
            }
        }
        haobanRoleService.insertBatch(haobanRoles);
        haobanRoleMenuService.insertBatch(tabHaobanRoleMenus);
        return ServiceResponse.success();
    }

    private void getTabHaobanRoleMenu(String wxEnterpriseId, List<TabHaobanRoleMenu> tabHaobanRoleMenus, Date now, TabHaobanRole tabHaobanRole, String menuCode) {
        TabHaobanRoleMenu tabHaobanRoleMenu = new TabHaobanRoleMenu();
        tabHaobanRoleMenu.setRoleMenuId(UniqueIdUtils.uniqueLong());
        tabHaobanRoleMenu.setRoleId(tabHaobanRole.getRoleId());
        tabHaobanRoleMenu.setWxEnterpriseId(wxEnterpriseId);
        tabHaobanRoleMenu.setMenuCode(menuCode);
        tabHaobanRoleMenu.setStatusFlag(1);
        tabHaobanRoleMenu.setCreateTime(now);
        tabHaobanRoleMenu.setUpdateTime(now);
        tabHaobanRoleMenus.add(tabHaobanRoleMenu);
    }

    private TabHaobanRole getTabHaobanRole(HaobanRoleQDTO haobanRoleQDTO, String wxEnterpriseId, String clerkId, String clerkName, List<TabHaobanRole> haobanRoles, int clerkType) {
        TabHaobanRole tabHaobanRole = new TabHaobanRole();
        tabHaobanRole.setRoleId(UniqueIdUtils.uniqueLong());
        tabHaobanRole.setRoleName(haobanRoleQDTO.getRoleName());
        tabHaobanRole.setClerkType(clerkType);
        tabHaobanRole.setWxEnterpriseId(wxEnterpriseId);
        tabHaobanRole.setStatusFlag(1);
        tabHaobanRole.setSystemFlag(haobanRoleQDTO.getSystemFlag());
        tabHaobanRole.setCreatorId(clerkId);
        tabHaobanRole.setCreatorName(clerkName);
        haobanRoles.add(tabHaobanRole);
        return tabHaobanRole;
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResponse edit(HaobanRoleQDTO haobanRoleQDTO, WebLoginDTO login) {
        HaobanRoleMenuQDTO clerkMenus = haobanRoleQDTO.getClerkMenus();
        HaobanRoleMenuQDTO manegeClerkMenus = haobanRoleQDTO.getManegeClerkMenus();
        HaobanRoleMenuQDTO managerMenus = haobanRoleQDTO.getManagerMenus();
        Integer systemFlag = haobanRoleQDTO.getSystemFlag();
        String wxEnterpriseId = login.getWxEnterpriseId();
        String clerkId = login.getClerkId();
        String clerkName = login.getClerkName();
        List<TabHaobanRoleMenu> tabHaobanRoleMenus = new ArrayList<>();
        Date now = new Date();
        //导购
        if (clerkMenus != null) {
            TabHaobanRole tabHaobanRole = updateTabHaobanRole(haobanRoleQDTO, clerkMenus, wxEnterpriseId, clerkId, clerkName, now);
            List<String> menuCodes = clerkMenus.getMenuCodes();
            for (String menuCode : menuCodes) {
                getTabHaobanRoleMenu(wxEnterpriseId, tabHaobanRoleMenus, now, tabHaobanRole, menuCode);
            }
            if (systemFlag == 0 && !"-1".equals(wxEnterpriseId)) {
                List<String> delMenuCodes = clerkMenus.getDelMenuCodes();
                for (String delMenuCode : delMenuCodes) {
                    //需要删除好办后台的菜单按钮
                    HaobanRoleBO haobanRoleBO = haobanRoleService.getByWxEnterpriseIdAndClerkType(wxEnterpriseId, 0, 1);
                    if (haobanRoleBO != null){
                        haobanRoleMenuService.deleteByMenuCodeAndRoleId(delMenuCode, wxEnterpriseId,haobanRoleBO.getRoleId());
                    }
                }
            }
        }

        //店长
        if (manegeClerkMenus != null) {
            TabHaobanRole tabHaobanRole = updateTabHaobanRole(haobanRoleQDTO, manegeClerkMenus, wxEnterpriseId, clerkId, clerkName, now);
            List<String> menuCodes = manegeClerkMenus.getMenuCodes();
            for (String menuCode : menuCodes) {
                getTabHaobanRoleMenu(wxEnterpriseId, tabHaobanRoleMenus, now, tabHaobanRole, menuCode);
            }
            if (systemFlag == 0 && !"-1".equals(wxEnterpriseId)) {
                List<String> delMenuCodes = manegeClerkMenus.getDelMenuCodes();
                for (String delMenuCode : delMenuCodes) {
                    //需要删除好办后台的菜单按钮
                    HaobanRoleBO haobanRoleBO = haobanRoleService.getByWxEnterpriseIdAndClerkType(wxEnterpriseId, 1, 1);
                    if (haobanRoleBO != null){
                        haobanRoleMenuService.deleteByMenuCodeAndRoleId(delMenuCode, wxEnterpriseId,haobanRoleBO.getRoleId());
                    }
                }
            }
        }

        //区经
        if (managerMenus != null) {
            TabHaobanRole tabHaobanRole = updateTabHaobanRole(haobanRoleQDTO, managerMenus, wxEnterpriseId, clerkId, clerkName, now);
            List<String> menuCodes = managerMenus.getMenuCodes();
            for (String menuCode : menuCodes) {
                getTabHaobanRoleMenu(wxEnterpriseId, tabHaobanRoleMenus, now, tabHaobanRole, menuCode);
            }
            if (systemFlag == 0 && !"-1".equals(wxEnterpriseId)) {
                List<String> delMenuCodes = managerMenus.getDelMenuCodes();
                for (String delMenuCode : delMenuCodes) {
                    //需要删除好办后台的菜单按钮
                    HaobanRoleBO haobanRoleBO = haobanRoleService.getByWxEnterpriseIdAndClerkType(wxEnterpriseId, 2, 1);
                    if (haobanRoleBO != null){
                        haobanRoleMenuService.deleteByMenuCodeAndRoleId(delMenuCode, wxEnterpriseId,haobanRoleBO.getRoleId());
                    }
                }
            }
        }
        haobanRoleMenuService.insertBatch(tabHaobanRoleMenus);
        return ServiceResponse.success();
    }

    private TabHaobanRole updateTabHaobanRole(HaobanRoleQDTO haobanRoleQDTO, HaobanRoleMenuQDTO managerMenus, String wxEnterpriseId, String clerkId, String clerkName, Date now) {
        Long roleId = managerMenus.getRoleId();
        if (roleId == null) {
            logger.error("roleId为空");
            return null;
        }
        //删除已删除的权限
        haobanRoleMenuService.deleteByRoleId(roleId);
        TabHaobanRole tabHaobanRole = new TabHaobanRole();
        tabHaobanRole.setRoleId(roleId);
        tabHaobanRole.setRoleName(haobanRoleQDTO.getRoleName());
        tabHaobanRole.setWxEnterpriseId(wxEnterpriseId);
        tabHaobanRole.setModifierId(clerkId);
        tabHaobanRole.setModifierName(clerkName);
        tabHaobanRole.setStatusFlag(1);
        tabHaobanRole.setUpdateTime(now);
        haobanRoleService.update(tabHaobanRole);
        return haobanRoleService.queryById(roleId);
    }


    @Override
    public ServiceResponse<HaobanRoleDTO> getMenuByWxEnterpriseIdAndClerkType(String wxEnterpriseId, Integer clerkType, Integer systemFlag) {
        return this.getMenuByWxEnterpriseIdAndClerkType(wxEnterpriseId,clerkType,systemFlag,null) ;
    }

    @Override
    public ServiceResponse<HaobanRoleDTO> getMenuByWxEnterpriseIdAndClerkType(String wxEnterpriseId, Integer clerkType, Integer systemFlag, String enterpriseId) {
        logger.info("查询好办小程序权限={},{},{},{}",systemFlag,wxEnterpriseId,clerkType,enterpriseId);
        // 查询商户普通权限是,需要过滤超管没有的
        HaobanRoleBO superRoleBO = haobanRoleService.getByWxEnterpriseIdAndClerkType(wxEnterpriseId, clerkType, 0);
        if(null == superRoleBO) {
            return ServiceResponse.failure("9999","未配置运维权限") ;
        }
        List<HaobanMenuBO> allMenuList = haobanMenuService.getAllMenuList();
        Long superRoleId = superRoleBO.getRoleId() ;
        List<String> superMenuCodeList = this.listRoleMenuCode(allMenuList,wxEnterpriseId, superRoleId);
        // 查询gic配置的权限
        List<String> gicBuyCodes = this.haobanMenuService.getGicBuyCodes(enterpriseId,clerkType) ;
        if(CollectionUtils.isNotEmpty(gicBuyCodes)) {
            superMenuCodeList.addAll(gicBuyCodes) ;
        }
        logger.info("超管的权限={}",superMenuCodeList);
        // 如果查询的后台的子管理员权限
        HaobanRoleBO subRoleBO = null ;
        List<String> subMenuCodes = null ;
        if(systemFlag==1) {
            subRoleBO = haobanRoleService.getByWxEnterpriseIdAndClerkType(wxEnterpriseId, clerkType, 1);
            if(null == subRoleBO) {
                return ServiceResponse.failure("9999","未配置子管理员权限") ;
            }
            Long  subRoleId = subRoleBO.getRoleId() ;
            subMenuCodes = this.listRoleMenuCode(allMenuList,wxEnterpriseId,subRoleId) ;
        }
        HaobanRoleBO retBO = null ;
        if(systemFlag==0) {
            retBO = superRoleBO ;
            retBO.setMenuCodes(superMenuCodeList);
        }else {
            retBO = subRoleBO ;
            List<String> subCodeList = new ArrayList<>() ;
            for(String subCode : subMenuCodes) {
                if(superMenuCodeList.contains(subCode)) {
                    subCodeList.add(subCode) ;
                }
            }
            retBO.setMenuCodes(subCodeList);
        }
        List<HaobanMenuBO> haobanMenuList = new ArrayList<>() ;
        Map<String,HaobanMenuBO> map = allMenuList.stream().collect(Collectors.toMap(HaobanMenuBO::getMenuCode,o->o,(k1,k2)->k1)) ;
        for(String code : retBO.getMenuCodes()) {
            HaobanMenuBO bo = map.get(code) ;
            if(null != bo) {
                haobanMenuList.add(bo) ;
            }
        }
        retBO.setMenuList(EntityUtil.changeEntityListNew(HaobanMenuDTO.class, haobanMenuList));
        return ServiceResponse.success(EntityUtil.changeEntityNew(HaobanRoleDTO.class, retBO));
    }

    private List<String> listRoleMenuCode(List<HaobanMenuBO> allMenuList , String wxEnterpriseId , Long  roleId) {
        List<String> menuCodes = haobanRoleMenuService.getByWxEnterpriseIdAndRoleId(wxEnterpriseId, roleId);
        // 添加关联的权限
        for(HaobanMenuBO item : allMenuList) {
            String code = item.getMenuCode() ;
            // 开启的权限
            if(menuCodes.contains(code)) {
                continue ;
            }
            // 无需授权的权限
            if(0==item.getAuthControl() && StringUtils.isEmpty(item.getBtnCodeRel())) {
                menuCodes.add(code) ;
                continue ;
            }
        }
        for(HaobanMenuBO item : allMenuList) {
            String code = item.getBtnCodeRel() ;
            if(0==item.getAuthControl() && StringUtils.isNotEmpty(item.getBtnCodeRel()) && menuCodes.contains(code)) {
                menuCodes.add(code) ;
                continue ;
            }
        }
        return menuCodes ;
    }

    @Override
    public ServiceResponse addHaobanRole(String wxEnterpriseId) {
        List<HaobanRoleBO> haobanRoleBOList = haobanRoleService.getListByWxEnterpriseId("-1", null);
        HaobanRoleQDTO haobanRoleQDTO = new HaobanRoleQDTO();
        HaobanRoleQDTO haobanRoleSystemQDTO = new HaobanRoleQDTO();

        int count = haobanRoleService.getCountByWxEnterpriseId(wxEnterpriseId, null);
        //清除历史权限
        if (count > 0) {
            haobanRoleService.deleteByWxEnterpriseId(wxEnterpriseId, null);
            haobanRoleMenuService.deleteByWxEnterpriseId(wxEnterpriseId);
        }
        for (HaobanRoleBO haobanRoleBO : haobanRoleBOList) {
            Long roleId = haobanRoleBO.getRoleId();
            Integer clerkType = haobanRoleBO.getClerkType();
            String roleName = haobanRoleBO.getRoleName();
            haobanRoleQDTO.setRoleName(roleName);
            haobanRoleSystemQDTO.setRoleName(roleName);
            haobanRoleQDTO.setSystemFlag(1);
            haobanRoleSystemQDTO.setSystemFlag(0);
            List<String> menuCodes = haobanRoleMenuService.getByWxEnterpriseIdAndRoleId("-1", roleId);

            if (RoleClerkTypeEnum.CLERK.getCode().equals(clerkType)) {
                HaobanRoleMenuQDTO clerkMenus = new HaobanRoleMenuQDTO();
                clerkMenus.setClerkType(clerkType);
                clerkMenus.setMenuCodes(menuCodes);
                haobanRoleQDTO.setClerkMenus(clerkMenus);
                haobanRoleSystemQDTO.setClerkMenus(clerkMenus);
            } else if (RoleClerkTypeEnum.SHOP.getCode().equals(clerkType)) {
                HaobanRoleMenuQDTO manegeClerkMenus = new HaobanRoleMenuQDTO();
                manegeClerkMenus.setClerkType(clerkType);
                manegeClerkMenus.setMenuCodes(menuCodes);
                haobanRoleQDTO.setManegeClerkMenus(manegeClerkMenus);
                haobanRoleSystemQDTO.setManegeClerkMenus(manegeClerkMenus);
            } else if (RoleClerkTypeEnum.MANAGE.getCode().equals(clerkType)) {
                HaobanRoleMenuQDTO managerMenus = new HaobanRoleMenuQDTO();
                managerMenus.setClerkType(clerkType);
                managerMenus.setMenuCodes(menuCodes);
                haobanRoleQDTO.setManagerMenus(managerMenus);
                haobanRoleSystemQDTO.setManagerMenus(managerMenus);
            }
        }
        WebLoginDTO login = new WebLoginDTO();
        login.setWxEnterpriseId(wxEnterpriseId);
        login.setClerkId("-1");
        login.setClerkName("系统");
        //商户权限
        add(haobanRoleQDTO, login);
        //运维系统权限
        add(haobanRoleSystemQDTO, login);
        return ServiceResponse.success();
    }

    /**
     * 内容 权限初始化
     *
     * @param contentMaterialROleInitQDTO
     * @return
     * ● 基础版：GIC后台-内容、好办-素材中心、好办商品中心下的发圈素材与素材数量；
     * ● 高级版：GIC后台-内容、好办-素材中心、好办商品中心下的发圈素材与素材数量、微商城所有功能、好办小程序销售线索功能
     *
     * 权限初始化的时候：
     * 导购：销售线索、互动记录、发圈素材 、素材数量
     * 店长：素材管理卡片、销售线索、互动记录列表、发圈素材 、素材数量
     * 区经：素材管理卡片、、发圈素材 、素材数量
     */
    @Override
    public ServiceResponse<Void> contentMaterialRoleInit(ContentMaterialROleInitQDTO contentMaterialROleInitQDTO) {

        logger.info("好办权限初始化 {}", JSON.toJSONString(contentMaterialROleInitQDTO));
        if (contentMaterialROleInitQDTO.getVersion() == null) {
            return ServiceResponse.success();
        }

        // 查询企业下所有的微信企业id
        List<TabHaobanWxEnterprise> tabHaobanWxEnterprises = wxEnterpriseRelatedService.listByEnterpriseId(contentMaterialROleInitQDTO.getEnterpriseId());
        if (CollectionUtils.isEmpty(tabHaobanWxEnterprises)) {
            logger.info("企业 {} 未关联企微 ", contentMaterialROleInitQDTO.getEnterpriseId());
            return ServiceResponse.success();
        }

        for (TabHaobanWxEnterprise wxEnterpris : tabHaobanWxEnterprises) {
            // 查询企微下 导购、店长、区经 的role_id
            String wxEnterpriseId = wxEnterpris.getWxEnterpriseId();
            // 处理商户权限
            handlerMerchant(contentMaterialROleInitQDTO, wxEnterpriseId);
        }
        return ServiceResponse.success();
    }
    private void handlerMerchant(ContentMaterialROleInitQDTO contentMaterialROleInitQDTO, String wxEnterpriseId) {
        // 运维 + 好办后台
        List<HaobanRoleBO> haobanRoleBOS = haobanRoleService.getListByWxEnterpriseId(wxEnterpriseId, null);
        if (CollectionUtils.isEmpty(haobanRoleBOS)) {
            logger.info("企业{} 企微 {} 下没有角色 ", contentMaterialROleInitQDTO.getEnterpriseId(), wxEnterpriseId);
            return;
        }
        if (contentMaterialROleInitQDTO.getOldVersion() != null
                && MaterialEnterpriseAdaptor.MaterialLevel.HIGH.getCode().equals(contentMaterialROleInitQDTO.getOldVersion())
                && MaterialEnterpriseAdaptor.MaterialLevel.LOW.getCode().equals(contentMaterialROleInitQDTO.getVersion()) ) {
            logger.info("从高级版到低级版, 菜单不做调整 {}", JSON.toJSONString(contentMaterialROleInitQDTO));
            return;
        }
        List<TabHaobanRoleMenu>  haobanRoleMenus = new ArrayList<>();
        for (HaobanRoleBO haobanRoleBO : haobanRoleBOS) {
            List<String> menuCodes = menuCodeMap.get(haobanRoleBO.getClerkType() + "" + contentMaterialROleInitQDTO.getVersion());
            if (CollectionUtils.isEmpty(menuCodes)) {
                continue;
            }
            // 处理当前版本 如果是低到高 只处理版本差异的
            if (contentMaterialROleInitQDTO.getOldVersion() != null
                    && MaterialEnterpriseAdaptor.MaterialLevel.LOW.getCode().equals(contentMaterialROleInitQDTO.getOldVersion())
                    && MaterialEnterpriseAdaptor.MaterialLevel.HIGH.getCode().equals(contentMaterialROleInitQDTO.getVersion())) {
                // 从低版本 升级到 高版本, 此时菜单code只取 版本 差异的菜单
                List<String> lowMenuCodes = menuCodeMap.get(haobanRoleBO.getClerkType() + "" + contentMaterialROleInitQDTO.getOldVersion());
                List<String> highMenuCodes = menuCodeMap.get(haobanRoleBO.getClerkType() + "" + contentMaterialROleInitQDTO.getVersion());
                if (CollectionUtils.isEmpty(highMenuCodes) || CollectionUtils.isEmpty(lowMenuCodes)) {
                    continue;
                }
                menuCodes = highMenuCodes
                        .stream()
                        .filter(item -> !lowMenuCodes.contains(item))
                        .collect(Collectors.toList());
            }
            logger.info("本次对应的menuCode：{}", JSON.toJSONString(menuCodes));
            List<String> hasExistMenuCodes = haobanRoleMenuService.getByWxEnterpriseIdAndRoleId(wxEnterpriseId, haobanRoleBO.getRoleId());
            if (CollectionUtils.isEmpty(hasExistMenuCodes)) {
                hasExistMenuCodes = new ArrayList<>();
            }
            List<String> excludeMenuCodes = hasExistMenuCodes;
            List<TabHaobanRoleMenu> tabHaobanRoleMenus = menuCodes.stream()
                    .filter(item -> !excludeMenuCodes.contains(item))
                    .map(item -> {
                        TabHaobanRoleMenu temp = new TabHaobanRoleMenu();
                        temp.setRoleMenuId(UniqueIdUtils.uniqueLong());
                        temp.setRoleId(haobanRoleBO.getRoleId());
                        temp.setWxEnterpriseId(wxEnterpriseId);
                        temp.setStatusFlag(1);
                        temp.setMenuCode(item);
                        temp.setCreateTime(new Date());
                        temp.setUpdateTime(new Date());
                        return temp;
                    })
                    .collect(Collectors.toList());
            logger.info("企微:{} roleId:{} 新增权限code: {}", wxEnterpriseId, haobanRoleBO.getRoleId(), JSON.toJSONString(tabHaobanRoleMenus));
            haobanRoleMenus.addAll(tabHaobanRoleMenus);

            if (haobanRoleBO.getSystemFlag() == 0) {
                // 处理只加运维权限逻辑
                List<String> adminMenuCodes = superManagementMenuCode.get(haobanRoleBO.getClerkType() + "" + contentMaterialROleInitQDTO.getVersion());
                if (CollectionUtils.isNotEmpty(adminMenuCodes)) {
                    List<TabHaobanRoleMenu> roleMenus = adminMenuCodes
                            .stream()
                            .filter(item -> StringUtils.isNotBlank(item) && !excludeMenuCodes.contains(item))
                            .map(item -> {
                                TabHaobanRoleMenu temp = new TabHaobanRoleMenu();
                                temp.setRoleMenuId(UniqueIdUtils.uniqueLong());
                                temp.setRoleId(haobanRoleBO.getRoleId());
                                temp.setWxEnterpriseId(wxEnterpriseId);
                                temp.setStatusFlag(1);
                                temp.setMenuCode(item);
                                temp.setCreateTime(new Date());
                                temp.setUpdateTime(new Date());
                                return temp;
                            })
                            .collect(Collectors.toList());
                    haobanRoleMenus.addAll(roleMenus);
                }
            }
        }
        logger.info("企微:{} 新增权限code: {}", wxEnterpriseId, JSON.toJSONString(haobanRoleMenus));
        if (CollectionUtils.isNotEmpty(haobanRoleMenus)) {
            haobanRoleMenuService.insertBatch(haobanRoleMenus);
        }
    }

    private static final Map<String, List<String> > menuCodeMap = new HashMap<>();
    private static final Map<String, List<String>> superManagementMenuCode = new HashMap<>();

    static {
        // 导购
        menuCodeMap.put("0" + ContentMaterialROleInitQDTO.Version.LOW.getCode(), Arrays.asList("materialMain", "commodityCenter", "commodityCenterTab", "materialCenterTab",
                "goodsDetail_material", "goodsCenter_Count", "salesClue", "customerDetail_interact"));
        menuCodeMap.put("0" + ContentMaterialROleInitQDTO.Version.HIGH.getCode(), Arrays.asList("materialMain","commodityCenter", "commodityCenterTab", "materialCenterTab",
                "goodsDetail_material", "goodsCenter_Count", "salesClue", "customerDetail_interact", "publishMaterial", "userCenter_createCenter"));
        // 店长
        menuCodeMap.put("1" + ContentMaterialROleInitQDTO.Version.LOW.getCode(), Arrays.asList("materialMain", "commodityCenter", "commodityCenterTab", "materialCenterTab", "goodsDetail_material", "goodsCenter_Count", "materialManage", "salesClue", "customerDetail_interact"));
        menuCodeMap.put("1" + ContentMaterialROleInitQDTO.Version.HIGH.getCode(), Arrays.asList("materialMain", "commodityCenter", "commodityCenterTab", "materialCenterTab",
                "goodsDetail_material", "goodsCenter_Count", "materialManage", "salesClue", "customerDetail_interact", "publishMaterial", "userCenter_createCenter"));

        // 区经
        menuCodeMap.put("2" + ContentMaterialROleInitQDTO.Version.LOW.getCode(), Arrays.asList("materialMain", "commodityCenter", "commodityCenterTab", "materialCenterTab", "goodsDetail_material", "goodsCenter_Count", "materialManage"));
        menuCodeMap.put("2" + ContentMaterialROleInitQDTO.Version.HIGH.getCode(), Arrays.asList("materialMain", "commodityCenter", "commodityCenterTab", "materialCenterTab",
                "goodsDetail_material", "goodsCenter_Count", "materialManage", "publishMaterial", "userCenter_createCenter"));

        // 只添加(勾选)好办运维权限 不加商户权限
        superManagementMenuCode.put("0" + ContentMaterialROleInitQDTO.Version.LOW.getCode(), Arrays.asList("knowledgeBase","AICreate","textCreate_create","videoCreate"));
        superManagementMenuCode.put("0" + ContentMaterialROleInitQDTO.Version.HIGH.getCode(), Arrays.asList("knowledgeBase","AICreate","textCreate_create","videoCreate"));
        superManagementMenuCode.put("1" + ContentMaterialROleInitQDTO.Version.LOW.getCode(), Arrays.asList("knowledgeBase","AICreate","textCreate_create","videoCreate"));
        superManagementMenuCode.put("1" + ContentMaterialROleInitQDTO.Version.HIGH.getCode(), Arrays.asList("knowledgeBase","AICreate","textCreate_create","videoCreate"));
        superManagementMenuCode.put("2" + ContentMaterialROleInitQDTO.Version.LOW.getCode(), Arrays.asList("knowledgeBase","AICreate","textCreate_create","videoCreate"));
        superManagementMenuCode.put("2" + ContentMaterialROleInitQDTO.Version.HIGH.getCode(), Arrays.asList("knowledgeBase","AICreate","textCreate_create","videoCreate"));
    }


    /**
     * 刷新企业权限
     *
     * @param params
     * @return
     */
    @Override
    public ServiceResponse<Void> flushRightOneTime(String params) {

        logger.info("flushRightOneTime 刷新企业内容权限:{}", params);

        List<String> enterpriseIds = materialEnterpriseAdaptor.queryHasRightEnterpriseIds(MaterialEnterpriseAdaptor.MaterialLevel.LOW.getCode());
        // 执行刷新权限
        String enterpriseId = "";
        if (StringUtils.isNotBlank(params) && !StringUtils.equals("-1", params)) {
            enterpriseId = params;
        }
        List<String> menuCodes = new ArrayList<>();
        menuCodes.add("videoCreate");

        for (String tempId : enterpriseIds) {
            if (StringUtils.isNotBlank(enterpriseId) && !StringUtils.equalsIgnoreCase(enterpriseId, tempId)) {
                logger.info("【flushRightOneTime】当前企业:{} 不是目标企业:{}, 忽略", tempId, enterpriseId);
                continue;
            }
            logger.info("【flushRightOneTime】添加企业素材纬度权限: {}", tempId);
            // 查询企业下所有的微信企业id
            List<TabHaobanWxEnterprise> tabHaobanWxEnterprises = wxEnterpriseRelatedService.listByEnterpriseId(tempId);
            if (CollectionUtils.isEmpty(tabHaobanWxEnterprises)) {
                logger.info("【flushRightOneTime】企业 {} 未关联企微 ", tempId);
                continue;
            }

            for (TabHaobanWxEnterprise wxEnterpris : tabHaobanWxEnterprises) {
                // 查询企微下 导购、店长、区经 的role_id
                String wxEnterpriseId = wxEnterpris.getWxEnterpriseId();
                // 处理商户权限
                // 运维
                List<HaobanRoleBO> haobanRoleBOS = haobanRoleService.getListByWxEnterpriseId(wxEnterpriseId, 0);
                if (CollectionUtils.isEmpty(haobanRoleBOS)) {
                    logger.info("【flushRightOneTime】企业{} 企微 {} 下没有角色 ", tempId, wxEnterpriseId);
                    continue;
                }
                logger.info("【flushRightOneTime】企业 {} 企微 {} 下角色个数: {}", enterpriseId, wxEnterpriseId, haobanRoleBOS.size());
                // 为role 添加菜单
                List<TabHaobanRoleMenu>  haobanRoleMenus = new ArrayList<>();
                for (HaobanRoleBO haobanRoleBO : haobanRoleBOS) {
                    logger.info("本次对应的menuCode：{}", JSON.toJSONString(menuCodes));
                    List<String> hasExistMenuCodes = haobanRoleMenuService.getByWxEnterpriseIdAndRoleId(wxEnterpriseId, haobanRoleBO.getRoleId());
                    if (CollectionUtils.isEmpty(hasExistMenuCodes)) {
                        hasExistMenuCodes = new ArrayList<>();
                    }
                    List<String> excludeMenuCodes = hasExistMenuCodes;
                    List<TabHaobanRoleMenu> tabHaobanRoleMenus = menuCodes.stream()
                            .filter(item -> !excludeMenuCodes.contains(item))
                            .map(item -> {
                                TabHaobanRoleMenu temp = new TabHaobanRoleMenu();
                                temp.setRoleMenuId(UniqueIdUtils.uniqueLong());
                                temp.setRoleId(haobanRoleBO.getRoleId());
                                temp.setWxEnterpriseId(wxEnterpriseId);
                                temp.setStatusFlag(1);
                                temp.setMenuCode(item);
                                temp.setCreateTime(new Date());
                                temp.setUpdateTime(new Date());
                                return temp;
                            })
                            .collect(Collectors.toList());
                    logger.info("【flushRightOneTime】企微:{} roleId:{} 新增权限code: {}", wxEnterpriseId, haobanRoleBO.getRoleId(), JSON.toJSONString(tabHaobanRoleMenus));
                    haobanRoleMenus.addAll(tabHaobanRoleMenus);
                }
                logger.info("【flushRightOneTime】企微:{} 新增权限code: {}", wxEnterpriseId, JSON.toJSONString(haobanRoleMenus));
                if (CollectionUtils.isNotEmpty(haobanRoleMenus)) {
                    haobanRoleMenuService.insertBatch(haobanRoleMenus);
                }
            }
        }
        return ServiceResponse.success();
    }
}
