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.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 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;

    @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) {
        HaobanRoleBO haobanRoleBO = haobanRoleService.getByWxEnterpriseIdAndClerkType(wxEnterpriseId, clerkType, systemFlag);
        if (haobanRoleBO != null) {
            List<String> menuCodes = haobanRoleMenuService.getByWxEnterpriseIdAndRoleId(wxEnterpriseId, haobanRoleBO.getRoleId());
            List<HaobanMenuBO> allMenuList = haobanMenuService.getAllMenuList();
            // 添加关联的权限
            List<HaobanMenuBO> haobanMenuList = new ArrayList<>() ;
            for(HaobanMenuBO item : allMenuList) {
                String code = item.getMenuCode() ;
                // 开启的权限
                if(menuCodes.contains(code)) {
                    haobanMenuList.add(item) ;
                    continue ;
                }
                // 无需授权的权限
                if(0==item.getAuthControl() && StringUtils.isEmpty(item.getBtnCodeRel())) {
                    haobanMenuList.add(item) ;
                    menuCodes.add(code) ;
                    continue ;
                }
            }
            for(HaobanMenuBO item : allMenuList) {
                String code = item.getBtnCodeRel() ;
                if(0==item.getAuthControl() && StringUtils.isNotEmpty(item.getBtnCodeRel()) && menuCodes.contains(code)) {
                    haobanMenuList.add(item) ;
                    menuCodes.add(code) ;
                    continue ;
                }
            }
            haobanRoleBO.setMenuCodes(menuCodes);
            haobanRoleBO.setMenuList(EntityUtil.changeEntityListNew(HaobanMenuDTO.class, haobanMenuList));
        }
        return ServiceResponse.success(EntityUtil.changeEntityNew(HaobanRoleDTO.class, haobanRoleBO));
    }

    @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();
    }

    @Override
    public ServiceResponse addHaobanRoleInit(String wxEnterpriseId) {
        List<TabHaobanWxEnterpriseRelated> enterpriseRelateds = wxEnterpriseRelatedService.getByWxEnterpriseId(wxEnterpriseId);
        if (CollectionUtils.isEmpty(enterpriseRelateds)) {
            logger.error("无关联企业：{}", wxEnterpriseId);
            return ServiceResponse.success();
        }
        //全品牌搜索
        boolean searchFlag = false;
        //离职继承
        boolean handoverFlag = false;
        boolean addClerkFlag = false;
        boolean editClerkFlag = false;
        boolean delClerkFlag = false;
        for (TabHaobanWxEnterpriseRelated enterpriseRelated : enterpriseRelateds) {
            ClerkEditInfoDTO clerkEditInfoDTO = ClerkEditInfoDTO.info(enterpriseRelated.getClerkEditFlag());
            logger.info("导购状态：{}", JSON.toJSONString(clerkEditInfoDTO));
            addClerkFlag = clerkEditInfoDTO.getAddClerkFlag() == 1;
            editClerkFlag = clerkEditInfoDTO.getEditClerkFlag() == 1;
            delClerkFlag = clerkEditInfoDTO.getDelClerkFlag() == 1;
            boolean searchFlagEnterpriseId = manageSettingApiService.getEnterpriseIdByFlag(enterpriseRelated.getEnterpriseId(), 1, null);
            if (searchFlagEnterpriseId) {
                searchFlag = true;
                break;
            }
        }

        for (TabHaobanWxEnterpriseRelated enterpriseRelated : enterpriseRelateds) {
            boolean handoverFlagEnterpriseId = manageSettingApiService.getEnterpriseIdByFlag(enterpriseRelated.getEnterpriseId(), null, 1);
            if (handoverFlagEnterpriseId) {
                handoverFlag = true;
                break;
            }
        }

        List<HaobanRoleBO> haobanRoleBOList = haobanRoleService.getListByWxEnterpriseId("-1", null);
        //导购店长
        List<String> menuCodes = new ArrayList<>();
        //运维后台 导购店长
        List<String> ywMenuCodes = new ArrayList<>();
        //区经
        List<String> menuManageCodes = new ArrayList<>();
        if (searchFlag) {
            menuCodes.add("customerList_allSearch");
            menuManageCodes.add("customerList_allSearch");
        }
        if (handoverFlag) {
            menuCodes.add("customerList_inheritCustomer");
        }
        ywMenuCodes.add("customerList_allSearch");
        ywMenuCodes.add("customerList_inheritCustomer");

        if (addClerkFlag) {
            menuCodes.add("userCenter_addClerk");
        }
        if (editClerkFlag) {
            menuCodes.add("storeClerkList_edit");
        }
        if (delClerkFlag) {
            menuCodes.add("userCenter_delClerk");
        }

        menuCodes.add("workbench");
        menuCodes.add("userCenter");
        menuCodes.add("dataSummary");

        ywMenuCodes.add("workbench");
        ywMenuCodes.add("userCenter");
        ywMenuCodes.add("dataSummary");

        //导购和店长初始化权限以好办web为准
        List<String> menuCodesOld = applicationSettingApiService.findMenuCodes(wxEnterpriseId, 1);
        if (CollectionUtils.isEmpty(menuCodesOld)) {
            logger.error("无权限：{}", wxEnterpriseId);
            return ServiceResponse.success();
        }
        List<String> clerkMenuCodes = haobanMenuService.getHaobanMenuByPid(menuCodesOld);
        menuCodes.addAll(clerkMenuCodes);

        TemplateEnterpriseRelatedDTO templateEnterpriseRelatedDTO = templateEnterpriseRelatedService.selectByWxEnterpriseId(wxEnterpriseId);
        if (templateEnterpriseRelatedDTO == null) {
            logger.error("无模板权限：{}", wxEnterpriseId);
            return ServiceResponse.success();
        }

        List<String> ywMenuCodesOld = tabHaobanTemplateApplicationRelatedMapper.listMenuCodesByTemplateId(templateEnterpriseRelatedDTO.getApplicationTemplateId());
        List<String> ywClerkMenuCodes = haobanMenuService.getHaobanMenuByPid(ywMenuCodesOld);
        ywMenuCodes.addAll(ywClerkMenuCodes);

        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);

            if (RoleClerkTypeEnum.CLERK.getCode().equals(clerkType)) {
                ywMenuCodes.add("storeClerkList_edit");
                //导购
                //初始化我的
                List<String> userCenter = haobanMenuService.getHaobanMenuByPid(Collections.singletonList("userCenter"));
                List<String> menuList = haobanRoleMenuService.getMenuInMenuCodes("-1", roleId, userCenter);
                List<String> codes = RolesListUtils.unionList(menuList, menuCodes);
                List<String> ywCodes = RolesListUtils.unionList(menuList, ywMenuCodes);

                HaobanRoleMenuQDTO clerkMenus = new HaobanRoleMenuQDTO();
                clerkMenus.setClerkType(clerkType);
                clerkMenus.setMenuCodes(new ArrayList<>(new HashSet<>(codes)));
                haobanRoleQDTO.setClerkMenus(clerkMenus);

                HaobanRoleMenuQDTO ywClerkMenus = new HaobanRoleMenuQDTO();
                ywClerkMenus.setClerkType(clerkType);
                ywClerkMenus.setMenuCodes(new ArrayList<>(new HashSet<>(ywCodes)));
                haobanRoleSystemQDTO.setClerkMenus(ywClerkMenus);

            } else if (RoleClerkTypeEnum.SHOP.getCode().equals(clerkType)) {
                ywMenuCodes.add("userCenter_addClerk");
                ywMenuCodes.add("storeClerkList_edit");
                ywMenuCodes.add("userCenter_delClerk");
                //店长
                //我的
                List<String> userCenter = haobanMenuService.getHaobanMenuByPid(Collections.singletonList("userCenter"));
                List<String> menuList = haobanRoleMenuService.getMenuInMenuCodes("-1", roleId, userCenter);
                List<String> unionListcodes = RolesListUtils.unionList(menuList, menuCodes);
                List<String> ywUnionListcodes = RolesListUtils.unionList(menuList, ywMenuCodes);

                HaobanRoleMenuQDTO manegeClerkMenus = new HaobanRoleMenuQDTO();
                manegeClerkMenus.setClerkType(clerkType);
                manegeClerkMenus.setMenuCodes(new ArrayList<>(new HashSet<>(unionListcodes)));
                haobanRoleQDTO.setManegeClerkMenus(manegeClerkMenus);

                HaobanRoleMenuQDTO ywManegeClerkMenus = new HaobanRoleMenuQDTO();
                ywManegeClerkMenus.setClerkType(clerkType);
                ywManegeClerkMenus.setMenuCodes(new ArrayList<>(new HashSet<>(ywUnionListcodes)));
                haobanRoleSystemQDTO.setManegeClerkMenus(ywManegeClerkMenus);

            } else if (RoleClerkTypeEnum.MANAGE.getCode().equals(clerkType)) {
                List<String> manageCodes = haobanRoleMenuService.getByWxEnterpriseIdAndRoleId("-1", roleId);
                menuManageCodes.addAll(manageCodes);

                HaobanRoleMenuQDTO managerMenus = new HaobanRoleMenuQDTO();
                managerMenus.setClerkType(clerkType);
                managerMenus.setMenuCodes(menuManageCodes);
                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();
            // 处理商户权限
            handlerMaterchant(contentMaterialROleInitQDTO, wxEnterpriseId);
        }
        return ServiceResponse.success();
    }
    private void handlerMaterchant(ContentMaterialROleInitQDTO contentMaterialROleInitQDTO, String wxEnterpriseId) {
        // 运维 + 好办后台
        List<HaobanRoleBO> haobanRoleBOS = haobanRoleService.getListByWxEnterpriseId(wxEnterpriseId, null);
        if (CollectionUtils.isEmpty(haobanRoleBOS)) {
            logger.info("企业{} 企微 {} 下没有角色 ", contentMaterialROleInitQDTO.getEnterpriseId(), wxEnterpriseId);
            return;
        }
        // 为role 添加菜单

        List<TabHaobanRoleMenu>  haobanRoleMenus = new ArrayList<>();
        for (HaobanRoleBO haobanRoleBO : haobanRoleBOS) {
            List<String> menuCodes = menuCodeMap.get(haobanRoleBO.getClerkType() + "" + contentMaterialROleInitQDTO.getVersion());
            if (CollectionUtils.isEmpty(menuCodes)) {
                continue;
            }
            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);
        }
        logger.info("企微:{} 新增权限code: {}", wxEnterpriseId, JSON.toJSONString(haobanRoleMenus));
        if (CollectionUtils.isNotEmpty(haobanRoleMenus)) {
            haobanRoleMenuService.insertBatch(haobanRoleMenus);
        }
    }

    private static final Map<String, List<String> > menuCodeMap = 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"));
    }


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

        logger.info("flushRightOneTime 刷新企业内容权限:{}", params);
        // 获取所有开通内容高级版的企业
        List<String> enterpriseIds = materialEnterpriseAdaptor.queryHasRightEnterpriseIds(MaterialEnterpriseAdaptor.MaterialLevel.HIGH.getCode());
        // 执行刷新权限
        String enterpriseId = "";
        if (StringUtils.isNotBlank(params) && StringUtils.equals("-1", params)) {
            enterpriseId = params;
        }
        for (String tempId : enterpriseIds) {
            if (StringUtils.isNotBlank(tempId) && !StringUtils.equalsIgnoreCase(enterpriseId, tempId)) {
                logger.info("当前企业:{} 不是目标企业:{}, 忽略", tempId, enterpriseId);
                continue;
            }
            ContentMaterialROleInitQDTO contentMaterialROleInitQDTO = new ContentMaterialROleInitQDTO();
            contentMaterialROleInitQDTO.setEnterpriseId(enterpriseId);
            contentMaterialROleInitQDTO.setVersion(MaterialEnterpriseAdaptor.MaterialLevel.HIGH.getCode());
            logger.info("添加企业素材纬度权限: {}", JSON.toJSONString(contentMaterialROleInitQDTO));
            this.contentMaterialRoleInit(contentMaterialROleInitQDTO);
        }
        return ServiceResponse.success();
    }
}
