package com.gic.haoban.manage.web.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.authcenter.commons.dto.AuthcenterUserDetails;
import com.gic.authcenter.commons.util.SessionContextUtil;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.GlobalVar;
import com.gic.enterprise.api.dto.EnterpriseAndUserDTO;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.dto.PowerStoreGroupDTO;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.enterprise.api.service.StoreGroupService;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.app.customer.service.api.service.QywxTagSyncApiService;
import com.gic.haoban.base.api.common.BasePageInfo;
import com.gic.haoban.base.api.common.PageResult;
import com.gic.haoban.base.api.common.ServiceResponse;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.common.utils.UuidUtil;
import com.gic.haoban.manage.api.dto.*;
import com.gic.haoban.manage.api.enums.ChannelCodeEnum;
import com.gic.haoban.manage.api.service.DepartmentApiService;
import com.gic.haoban.manage.api.service.ExternalClerkRelatedApiService;
import com.gic.haoban.manage.api.service.WxEnterpriseApiService;
import com.gic.haoban.manage.api.service.WxEnterpriseRelatedApiService;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.qo.WxEnterpriseBindQo;
import com.gic.haoban.manage.web.vo.EnterpriseDetailVo;
import com.gic.haoban.manage.web.vo.EnterpriseSearchVO;
import com.gic.haoban.manage.web.vo.StoreGroupVo;
import com.gic.redis.data.util.RedisUtil;
import com.gic.wechat.api.service.qywx.QywxUserApiService;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;
import java.util.stream.Collectors;

@RestController
public class EnterpriseController extends WebBaseController {

    private static final String LOGIN_URL = "/haoban-manage3-web/yw-login";

    private static final Logger logger = LoggerFactory.getLogger(EnterpriseController.class);

    @Autowired
    private WxEnterpriseApiService wxEnterpriseApiService;
    @Autowired
    private WxEnterpriseRelatedApiService wxEnterpriseRelatedApiService;
    @Autowired
    private DepartmentApiService departmentApiService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private QywxTagSyncApiService qywxTagSyncApiService;
    @Autowired
    private ExternalClerkRelatedApiService externalClerkRelatedApiService;
    @Autowired
    private QywxUserApiService qywxUserApiService;
    @Autowired
    private StoreGroupService storeGroupService ;
    @Autowired
    private ClerkService clerkService;

    private static final String QYWX_TAG_OPRN_KEY = "qywx-tag-open";
    private static final String QYWX_TAG_OPRN_KEY_LOCK = "qywx-tag-open-lock";
    private static final String MEMBER_RELATE_ENT_OPE_KEY = "mbr:rel:ope:%s:string";

    private static final int OPEN = 1;
    private static final int CLOSE = 0;
    private static final int ALL = 2;

    /**
     * 查询企业列表
     * <p>
     * 我们大致可以分为6种场景
     * <p>
     * 1、开启-无条件搜索：in(cache中id列表) - 展示状态全部为开启
     * 2、开启-有条件搜索：in(cache中列表与查询出的id取交集) - 展示状态全部为开启
     * 3、关闭-无条件搜索：not in(cache中id列表) - 展示状态全部为关闭
     * 4、关闭-有条件搜索：not in(cache中id列表) in (查询结果id列表) - 展示状态全部为关闭
     * 5、所有-无条件搜索：cache中id列表不参与sql - 展示状态通过判断得出
     * 6、所有-有条件搜索：cache中id列表不参与sql - 展示状态通过判断得出
     *
     * @param pageInfo          分页参数
     * @param keyword           授权方企业微信名称
     * @param openTagFlag       标签开启状态：0 未开启 1 开启 2 所有
     * @param gicEnterpriseName gic企业名称
     * @param gicContactHelper  是否开启通讯录应用1是0否
     * @param loginUserId       登录用户id
     * @param version           版本
     * @return res
     */
    @RequestMapping("wx-enterprise-list")
    public HaobanResponse wxEnterpriseListNew(BasePageInfo pageInfo,
                                              String keyword,
                                              Integer openTagFlag,
                                              String gicEnterpriseName,
                                              Integer gicContactHelper,
                                              String loginUserId,
                                              String version) {

        List<String> wxEnterpriseIdInList = Lists.newArrayList();

        if (haveCondition(gicEnterpriseName)) {
            wxEnterpriseIdInList = listWxEnterpriseIdByEnterpriseName(gicEnterpriseName);
            // 有条件并且查询为空返回
            if (CollectionUtil.isEmpty(wxEnterpriseIdInList)) {
                PageResult<Object> objectPageResult = new PageResult<>();
                objectPageResult.setPageNum(pageInfo.getPageNum());
                objectPageResult.setPageSize(pageInfo.getPageSize());
                objectPageResult.setList(Collections.emptyList());
                return resultResponse(HaoBanErrCode.ERR_1, objectPageResult);
            }
        }

        Set<String> wxEnterpriseIdSetInCache = listWxEnterpriseIdListInCache();

        PageResult<YwWxEnterpriseDTO> pageResult = new PageResult<>();
        Page<YwWxEnterpriseDTO> page = new Page<>();

        if (Objects.nonNull(openTagFlag) && ALL == openTagFlag) {
            page = queryAll(pageInfo, keyword, gicContactHelper, version, wxEnterpriseIdInList, wxEnterpriseIdSetInCache, loginUserId);
        }

        if (Objects.nonNull(openTagFlag) && OPEN == openTagFlag) {
            page = queryOpen(pageInfo, keyword, gicEnterpriseName, gicContactHelper, version, wxEnterpriseIdInList, wxEnterpriseIdSetInCache, loginUserId);
        }

        if (Objects.nonNull(openTagFlag) && CLOSE == openTagFlag) {
            page = queryClose(pageInfo, keyword, gicContactHelper, version, wxEnterpriseIdInList, wxEnterpriseIdSetInCache, loginUserId);
        }

        doProcessOpenSendMass(page.getResult());
        if(CollectionUtils.isNotEmpty(page.getResult())) {
           List<String> idList = page.getResult().stream().map(dto->dto.getWxEnterpriseId()).collect(Collectors.toList()) ;
           List<EnterpriseDetailDTO>  enList = this.wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseIdList(idList);
           if(CollectionUtils.isNotEmpty(enList)) {
              Map<String, List<EnterpriseDetailDTO>> map = enList.stream().collect(Collectors.groupingBy(EnterpriseDetailDTO::getWxEnterpriseId)) ;
              for(YwWxEnterpriseDTO item : page.getResult()) {
                   item.setEnList(map.get(item.getWxEnterpriseId()));
              }
           }
        }
        pageResult.setList(page.getResult());
        pageResult.setPageNum(page.getCurrentPage());
        pageResult.setPages(page.getPages());
        pageResult.setPageSize(page.getPageSize());
        pageResult.setTotal(page.getTotalCount());
        
        return resultResponse(HaoBanErrCode.ERR_1, pageResult);
    }

    private void doProcessOpenSendMass(List<YwWxEnterpriseDTO> list) {
        if (CollectionUtil.isEmpty(list)) {
            return;
        }
        list.forEach(one -> {
            if (one.getOpenMassFlag()) {
                String wxEnterpriseId = one.getWxEnterpriseId();
                String key = String.format(MEMBER_RELATE_ENT_OPE_KEY, wxEnterpriseId);
                Object cache = RedisUtil.getCache(key);
                if (Objects.nonNull(cache)) {
                    one.setOpenMassFlag(Boolean.FALSE);
                }
            }
        });
    }

    private List<String> listWxEnterpriseIdByEnterpriseName(String gicEnterpriseName) {
        if (StringUtils.isEmpty(gicEnterpriseName)) {
            return Collections.emptyList();
        }
        // 企业名称查询
        List<EnterpriseDTO> enterpriseList = enterpriseService.getEnterpriseByName(gicEnterpriseName);
        if (CollectionUtil.isEmpty(enterpriseList)) {
            return Collections.emptyList();
        }
        // 查询gic企业与wx企业关系
        List<String> gicEnterpriseIdList = enterpriseList.stream().map(EnterpriseDTO::getEnterpriseId).collect(Collectors.toList());
        List<EnterpriseDetailDTO> wxEnterpriseList = wxEnterpriseRelatedApiService.listEnterpriseByEnterpriseIds(gicEnterpriseIdList);
        if (CollectionUtil.isEmpty(wxEnterpriseList)) {
            return Collections.emptyList();
        }
        return wxEnterpriseList.stream().map(EnterpriseDetailDTO::getWxEnterpriseId).collect(Collectors.toList());
    }

    private Set<String> listWxEnterpriseIdListInCache() {
        // 查询开启标签同步缓存-详情在 /tag/open-tag 接口
        String wxEntIdStr = (String) RedisUtil.getCache(QYWX_TAG_OPRN_KEY);
        Set<String> wxEntIdSet = Sets.newHashSet();
        if (StringUtils.isNotEmpty(wxEntIdStr)) {
            wxEntIdSet = Arrays.stream(wxEntIdStr.split(",")).collect(Collectors.toSet());
        }
        return wxEntIdSet;
    }

    private Page<YwWxEnterpriseDTO> queryAll(BasePageInfo pageInfo,
                                             String keyword,
                                             Integer gicContactHelper,
                                             String version,
                                             List<String> wxEnterpriseIdInList,
                                             Set<String> wxEnterpriseIdSetInCache,
                                             String loginUserId) {
        // 查询所有状态
        Page<YwWxEnterpriseDTO> page = wxEnterpriseApiService.list(pageInfo, keyword, wxEnterpriseIdInList, gicContactHelper, version, null, loginUserId);
        if (CollectionUtil.isEmpty(page.getResult())) {
            return page;
        }
        page.getResult().forEach(one -> {
            one.setVersion("3.0");
            one.setBuyDate(new Date());
            one.setBuyStatus("1");
            List<EnterpriseDetailDTO> counts = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(one.getWxEnterpriseId());
            one.setRelationCount(counts.size());
            if (wxEnterpriseIdSetInCache.contains(one.getWxEnterpriseId())) {
                one.setTagOpenFlag(1);
            } else {
                one.setTagOpenFlag(0);
            }
        });
        return page;
    }

    private Page<YwWxEnterpriseDTO> queryOpen(BasePageInfo pageInfo,
                                              String keyword,
                                              String gicEnterpriseName,
                                              Integer gicContactHelper,
                                              String version,
                                              List<String> wxEnterpriseIdInList,
                                              Set<String> wxEnterpriseIdSetInCache,
                                              String loginUserId) {
        // 查询开启状态
        if (haveCondition(gicEnterpriseName)) {
            // 有条件-取交集
            wxEnterpriseIdSetInCache.retainAll(wxEnterpriseIdInList);
        }
        List<String> queryList = new ArrayList<>(wxEnterpriseIdSetInCache);
        Page<YwWxEnterpriseDTO> page = wxEnterpriseApiService.list(pageInfo, keyword, queryList, gicContactHelper, version, null, loginUserId);
        if (CollectionUtil.isEmpty(page.getResult())) {
            return page;
        }
        page.getResult().forEach(one -> {
            one.setVersion("3.0");
            one.setBuyDate(new Date());
            one.setBuyStatus("1");
            List<EnterpriseDetailDTO> counts = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(one.getWxEnterpriseId());
            one.setRelationCount(counts.size());
            // 全部打开
            one.setTagOpenFlag(1);
        });
        return page;
    }

    private Page<YwWxEnterpriseDTO> queryClose(BasePageInfo pageInfo,
                                               String keyword,
                                               Integer gicContactHelper,
                                               String version,
                                               List<String> wxEnterpriseIdInList,
                                               Set<String> wxEnterpriseIdSetInCache,
                                               String loginUserId) {
        // 查询关闭状态
        Page<YwWxEnterpriseDTO> page = wxEnterpriseApiService.list(pageInfo, keyword, wxEnterpriseIdInList, gicContactHelper, version, new ArrayList<>(wxEnterpriseIdSetInCache), loginUserId);
        if (CollectionUtil.isEmpty(page.getResult())) {
            return page;
        }
        page.getResult().forEach(one -> {
            one.setVersion("3.0");
            one.setBuyDate(new Date());
            one.setBuyStatus("1");
            List<EnterpriseDetailDTO> counts = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(one.getWxEnterpriseId());
            one.setRelationCount(counts.size());
            // 全部关闭
            one.setTagOpenFlag(0);
        });
        return page;
    }

    private boolean haveCondition(String gicEnterpriseName) {
        return StringUtils.isNotEmpty(gicEnterpriseName);
    }

    /**
     * 开启关闭标签同步
     *
     * @param wxEnterpriseId 微信企业id
     * @param flag           操作标记  1 开启 0 关闭
     * @return res
     */
    @RequestMapping("operate-tag-sync")
    public HaobanResponse operateTagSync(String wxEnterpriseId, Integer flag) {
        if (StringUtils.isEmpty(wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        if (Objects.isNull(flag)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        try {
            RedisUtil.lock(QYWX_TAG_OPRN_KEY_LOCK, 5L);

            String wxEntIdStr = (String) RedisUtil.getCache(QYWX_TAG_OPRN_KEY);

            if (flag == 1) {
                // 开启
                if (StringUtils.isEmpty(wxEntIdStr)) {
                    wxEntIdStr = wxEnterpriseId;
                } else {
                    wxEntIdStr = wxEntIdStr + "," + wxEnterpriseId;
                }
                logger.info("开启企业标签同步, wxEntIdStr:{}", wxEntIdStr);
                RedisUtil.setCache(QYWX_TAG_OPRN_KEY, wxEntIdStr);
            }

            if (flag == 0) {
                // 关闭标签检查是否有任务在进行
                boolean tagSync = qywxTagSyncApiService.checkQywxTagSync(wxEnterpriseId);
                if (!tagSync) {
                    // 有同步任务
                    return resultResponse(HaoBanErrCode.ERR_30001);
                }
            }

            if (flag == 0 && StringUtils.isNotEmpty(wxEntIdStr)) {
                // 关闭标签同步，只有在字符串不为空时才能关
                List<String> filterList = Arrays.stream(wxEntIdStr.split(","))
                        .filter(one -> !one.equals(wxEnterpriseId))
                        .collect(Collectors.toList());
                String closeStr = StringUtils.join(filterList, ",");
                logger.info("关闭企业标签同步, closeStr:{}", closeStr);
                RedisUtil.setCache(QYWX_TAG_OPRN_KEY, closeStr);
            }

        } finally {
            RedisUtil.unlock(QYWX_TAG_OPRN_KEY_LOCK);
        }

        // 文案提示-根据开启关闭类型提示
        if (flag == 1) {
            return resultResponse(HaoBanErrCode.ERR_1, "开启企微标签同步");
        }
        if (flag == 0) {
            return resultResponse(HaoBanErrCode.ERR_1, "关闭企微标签同步");
        }

        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 授权详情列表
     *
     * @param wxEnterpriseId 企业微信id
     * @return res
     */
    @RequestMapping("authorize-detail")
    public HaobanResponse authorizeDetail(String wxEnterpriseId) {
        List<EnterpriseDetailDTO> list = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(wxEnterpriseId);
        List<EnterpriseDetailVo> result = EntityUtil.changeEntityListByJSON(EnterpriseDetailVo.class, list);
        for (EnterpriseDetailVo vo : result) {
            List<StoreDTO> stores = storeService.getStoreByEnterId(vo.getEnterpriseId(), null, null);
            if (CollectionUtil.isEmpty(stores)) {
                continue;
            } else {
                List<String> storeIds = stores.stream().map(s -> s.getStoreId()).collect(Collectors.toList());
                List<DepartmentDTO> countList = departmentApiService.listByRelatedIds(storeIds);
                vo.setStoreCount(countList.size());
            }
            EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(vo.getEnterpriseId());
            vo.setEnterpriseName(enterpriseDTO.getEnterpriseName());
            vo.setEnterpriseLogo(enterpriseDTO.getQcloudImageUrl());
        }
        return resultResponse(HaoBanErrCode.ERR_1, result);
    }

    /**
     * 登录
     * @param wxEnterpriseId      企业微信id
     */
    @RequestMapping("yw-login")
    public HaobanResponse ywLogin(String wxEnterpriseId, String gicEnterpriseId, HttpServletResponse httpServletResponse,
                                  HttpServletRequest request) throws IOException {
        String host = GlobalVar.ctxPropertiesMap.get("haoban_service_host");
        logger.info("好办运维login,host={},gicEnterpriseId={},wxEnterpriseId={}", host,gicEnterpriseId,wxEnterpriseId);
        if(org.apache.commons.lang3.StringUtils.isAnyBlank(wxEnterpriseId,gicEnterpriseId)) {
            return this.fail("wxEnterpriseId和gicEnterpriseId都不能为空") ;
        }
        AuthcenterUserDetails loginUser = (AuthcenterUserDetails) SessionContextUtil.getUser(request) ;
        String operationUserId = String.valueOf(loginUser.getId());
        //运维信息参数
        String operationInfo = "&operationUserId=" + operationUserId + "&userName=" + URLEncoder.encode(loginUser.getRealName(), "UTF-8")
                + "&userMobile=" + loginUser.getUserMobile();

        String random = "ywLogin:" + UuidUtil.randomUUID();
        RedisUtil.setCache(random, 1, 10L);
        String url = host + LOGIN_URL + "?gicEnterpriseId="+gicEnterpriseId+"&wxEnterpriseId=" + wxEnterpriseId + "&random=" + random
                + operationInfo;
        httpServletResponse.sendRedirect(url);
        return this.success(null) ;
    }


    /**
     * 更新新的外部联系人id
     *
     * @param wxEnterpriseId wx企业标识
     * @return {@link HaobanResponse }
     * @author mozhu
     * @date 2021-12-13 15:46:25
     */
    @RequestMapping("/updateNewExternalUserid")
    public HaobanResponse updateNewExternalUserid(String wxEnterpriseId) {
        ServiceResponse serviceResponse = externalClerkRelatedApiService.updateNewExternalUserid(wxEnterpriseId);
        int code = serviceResponse.getCode();
        if (HaoBanErrCode.ERR_1.getCode() == code) {
            return resultResponse(HaoBanErrCode.ERR_1);
        } else {
            String message = serviceResponse.getMessage();
            return resultResponse(HaoBanErrCode.ERR_0, message);
        }
    }

    /**
     * 设置迁移完成
     *
     * @param corpid
     * @param serviceCorpid
     * @return
     */
    @RequestMapping("/finishExternalUseridMigration")
    public HaobanResponse finishExternalUseridMigration(String corpid, String serviceCorpid) {
        boolean flag = qywxUserApiService.finishExternalUseridMigration(corpid, serviceCorpid);
        if (flag) {
            WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseApiService.getEnterpriseBycorpId(corpid);
            if (wxEnterpriseDTO == null) {
                return resultResponse(HaoBanErrCode.ERR_20001);
            }
            wxEnterpriseApiService.agreeExternalUseridFlag(wxEnterpriseDTO.getWxEnterpriseId(), 1);
            return resultResponse(HaoBanErrCode.ERR_1);
        } else {
            return resultResponse(HaoBanErrCode.ERR_0);
        }
    }

    // 绑定门店列表
    @RequestMapping("bind-store-list")
    public HaobanResponse bindStoreList(String wxEnterpriseId,String enterpriseId, String search, BasePageInfo basePageInfo) {
        Page<BindStoreInfoDTO> retPage = wxEnterpriseRelatedApiService.pageBindStoreByEnterpriseId(wxEnterpriseId, enterpriseId, search, basePageInfo);
        return resultResponse(HaoBanErrCode.ERR_1, retPage);
    }
    
    //企业信息
    @RequestMapping("wxEnterprise-detail")
    public HaobanResponse enterpriseDetail(String wxEnterpriseId) {
        if (StringUtils.isEmpty(wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_1);
        }
        WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseApiService.getOne(wxEnterpriseId);
        if (wxEnterpriseDTO == null) {
            return this.fail("微信企业差不到") ;
        }
        wxEnterpriseDTO.setSmallVersion("免费版");
        wxEnterpriseDTO.setStoreTotal(departmentApiService.totalStoreCountByEnterpriseId(wxEnterpriseId));
        return resultResponse(HaoBanErrCode.ERR_1, wxEnterpriseDTO);
    }

    //gic企业列表
    @RequestMapping("enterprise-search")
    public HaobanResponse gicEnterpriseDetail(String enterpriseId) {
        if (StringUtils.isEmpty(enterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_1);
        }
        EnterpriseSearchVO vo = new EnterpriseSearchVO();
        EnterpriseDTO enterprise = enterpriseService.getEnterpriseById(enterpriseId);
        if (enterprise != null) {
            vo.setEnterpriseId(enterpriseId);
            vo.setEnterpriseName(enterprise.getEnterpriseName());
            vo.setBrandName(enterprise.getBrandName());
            ClerkDTO clerk = clerkService.getSuperAdminByEnterpriseId(enterpriseId);
            if (clerk != null) {
                vo.setClerkId(clerk.getClerkId());
                vo.setClerkCode(clerk.getClerkCode());
                vo.setClerkName(clerk.getClerkName());
                vo.setPhoneNumber(clerk.getPhoneNumber());
                vo.setNationCode(clerk.getNationcode());
            }
        }else {
            //enterpriseId 参数可以是企业id，也可以是企业名称
            //按名称去查
            EnterpriseAndUserDTO dto = enterpriseService.getEnterpriseAndUserByName(enterpriseId);
            vo = EntityUtil.changeEntityByJSON(EnterpriseSearchVO.class, dto);
            if (vo != null) {
                EnterpriseDTO enterprise1 = enterpriseService.getEnterpriseById(vo.getEnterpriseId());
                if (enterprise1 != null) {
                    vo.setBrandName(enterprise1.getBrandName());
                }
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, vo);
    }
    
    @RequestMapping("gic-store-group-list")
    public HaobanResponse storeGroupList(String wxEnterpriseId,String enterpriseId, String keyWord) {
        if(org.apache.commons.lang3.StringUtils.isAnyBlank(wxEnterpriseId,enterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        List<PowerStoreGroupDTO> departmentList = storeGroupService.getStoreGroupList(enterpriseId, keyWord);
        List<StoreRangeInfoDTO> rangeInfoDTOList = wxEnterpriseRelatedApiService.listAllBindStoreOrGroup(enterpriseId);
        Map<String, StoreRangeInfoDTO> storeRangeMap = new HashMap<>();
        if (CollectionUtils.isNotEmpty(rangeInfoDTOList)) {
            List<WxEnterpriseDTO> wxEnterpriseDTOS = wxEnterpriseRelatedApiService.listWxEnterpriseByEid(enterpriseId);
            if (CollectionUtils.isNotEmpty(wxEnterpriseDTOS)) {
                Map<String, WxEnterpriseDTO> wxEnterpriseDTOMap = wxEnterpriseDTOS.stream().collect(Collectors.toMap(WxEnterpriseDTO::getWxEnterpriseId, dto -> dto));
                storeRangeMap = rangeInfoDTOList.stream()
                        .filter(dto -> (!dto.getWxEnterpriseId().equals(wxEnterpriseId))
                                && dto.getRelationType() == 1
                                && wxEnterpriseDTOMap.get(dto.getWxEnterpriseId()) != null)
                        .peek(dto -> dto.setWxEnterpriseName(wxEnterpriseDTOMap.get(dto.getWxEnterpriseId()).getCorpName()))
                        .collect(Collectors.toMap(StoreRangeInfoDTO::getRelationId, dto -> dto));
            }
        }
        Map<String, StoreRangeInfoDTO> finalStoreRangeMap = storeRangeMap;
        List<StoreGroupVo> ret = departmentList.stream().map(dto -> {
            StoreRangeInfoDTO mid = finalStoreRangeMap.get(dto.getStoreGroupId());
            StoreGroupVo storeGroupVo = new StoreGroupVo();
            storeGroupVo.setRelationId(dto.getStoreGroupId());
            storeGroupVo.setParentRelationId(dto.getParentGroupId());
            if (mid != null) {
                storeGroupVo.setIsBind(1);
                storeGroupVo.setWxEnterpriseId(mid.getWxEnterpriseId());
                storeGroupVo.setWxEnterpriseName(mid.getWxEnterpriseName());
            }
            storeGroupVo.setRelationType(1);
            storeGroupVo.setRelationName(dto.getStoreGroupName());
            return storeGroupVo;
        }).collect(Collectors.toList());
        return resultResponse(HaoBanErrCode.ERR_1, ret);
    }
    
    //微信企业绑定接口 - 迁移到运维
    @RequestMapping("wx-enterprise-bind")
    public HaobanResponse wxEnterpriseBind(HttpServletRequest request , @RequestBody WxEnterpriseBindQo bindQo) {
        if (org.apache.commons.lang3.StringUtils.isAnyBlank(bindQo.getEnterpriseId())) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        String wxEnterpriseId = bindQo.getWxEnterpriseId();
        if(StringUtils.isBlank(wxEnterpriseId)) {
            return this.fail("微信企业ID未传") ;
        }
        AuthcenterUserDetails loginUser = (AuthcenterUserDetails) SessionContextUtil.getUser(request) ;
        String staffName = loginUser.getRealName() ;
        WxEnterpriseRelationDetailDTO detailDTO = new WxEnterpriseRelationDetailDTO();
        detailDTO.setWxEnterpriseRelatedId(bindQo.getWxEnterpriseRelatedId());
        detailDTO.setEnterpriseId(bindQo.getEnterpriseId());
        detailDTO.setWxEnterpriseId(wxEnterpriseId);
        detailDTO.setStaffId("-1");
        detailDTO.setStaffName(staffName);
        detailDTO.setMemberOpenCardFlag(bindQo.getMemberOpenCardFlag());
        detailDTO.setWxEnterpriseType(bindQo.getWxEnterpriseType());
        List<StoreOrGroupInfoDTO> storeOrGroupInfoDTOS = JSONObject.parseArray(bindQo.getRelations(), StoreOrGroupInfoDTO.class);
        detailDTO.setRelations(storeOrGroupInfoDTOS);
        ServiceResponse resp = wxEnterpriseRelatedApiService.wxEnterpriseBind(detailDTO);
        if (resp.getCode() != 1) {
            HaoBanErrCode.ERR_DEFINE.setMsg(resp.getMessage());
            return resultResponse(HaoBanErrCode.ERR_DEFINE);
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }
    
    //授权企业列表 filteRight 是否过滤无登录权限的列表
    @RequestMapping("gic-enterprise-list")
    public HaobanResponse wxaEnterpriseList(String  wxEnterpriseId) {
        if(org.apache.commons.lang3.StringUtils.isAnyBlank(wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        List<EnterpriseDetailDTO> list = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(wxEnterpriseId,null,false);
        return resultResponse(HaoBanErrCode.ERR_1, list);
    }
    
    /**
     * 绑定门店列表
     *
     * @param enterpriseId
     * @return
     */
    @RequestMapping("flush-bind-store-list")
    public HaobanResponse flushBindStoreList(String wxEnterpriseId,String enterpriseId) {
        if(org.apache.commons.lang3.StringUtils.isAnyBlank(wxEnterpriseId,enterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        ServiceResponse response = wxEnterpriseRelatedApiService.flushBindStoreByEnterpriseId(enterpriseId, wxEnterpriseId, null, ChannelCodeEnum.SYNC_UNBIND.getCode());
        logger.info("返回信息：{}", JSONObject.toJSONString(response));
        if (response.getCode() != 1) {
            HaoBanErrCode.ERR_DEFINE.setMsg(response.getMessage());
            return resultResponse(HaoBanErrCode.ERR_DEFINE);
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }
    
    /**
     * 微信企业绑定详情
     *
     * @param enterpriseId
     * @return
     */
    @RequestMapping("wx-enterprise-bind-detail")
    public HaobanResponse wxEnterpriseBindDetail(String wxEnterpriseId , String enterpriseId) {
        if(org.apache.commons.lang3.StringUtils.isAnyBlank(wxEnterpriseId,enterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        WxEnterpriseRelationDetailDTO bindInfo = wxEnterpriseRelatedApiService.getEnterpriseBindInfo(wxEnterpriseId, enterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1, bindInfo);
    }
}
