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

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.commons.util.DateUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.dto.*;
import com.gic.enterprise.api.service.AuthorizeService;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.base.api.common.BasePageInfo;
import com.gic.haoban.base.api.common.ServiceResponse;
import com.gic.haoban.base.api.common.pojo.dto.WebLoginDTO;
import com.gic.haoban.common.anno.IgnoreLogin;
import com.gic.haoban.common.utils.AuthWebRequestUtil;
import com.gic.haoban.common.utils.EntityUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.manage.api.dto.DepartmentDTO;
import com.gic.haoban.manage.api.dto.*;
import com.gic.haoban.manage.api.dto.fee.HaobanQywxFeeDTO;
import com.gic.haoban.manage.api.enums.ChannelCodeEnum;
import com.gic.haoban.manage.api.enums.SecretTypeEnum;
import com.gic.haoban.manage.api.service.*;
import com.gic.haoban.manage.api.service.fee.HaobanQywxFeeApiService;
import com.gic.haoban.manage.api.service.out.SecretSettingApiService;
import com.gic.haoban.manage.web.config.Config;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.qo.MiniprogramSettingQo;
import com.gic.haoban.manage.web.vo.StoreVo;
import com.gic.haoban.manage.web.vo.*;
import com.gic.redis.data.util.RedisUtil;
import com.gic.wechat.api.service.qywx.QywxCorpApiService;
import com.gic.wechat.token.api.dto.QywxCorpInfoDTO;
import com.gic.wechat.token.api.service.QywxTokenManageService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
public class WxEnterpriseController extends WebBaseController {
    private static final Logger logger = LoggerFactory.getLogger(WxEnterpriseController.class);
    @Autowired
    private WxEnterpriseRelatedApiService wxEnterpriseRelatedApiService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private WxEnterpriseApiService wxEnterpriseApiService;
    @Autowired
    private DepartmentApiService departmentApiService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private QywxTokenManageService qywxTokenManageService;
    @Autowired
    private Config config;
    @Autowired
    private QywxCorpApiService qywxCorpApiService;
    @Autowired
    private DealSyncOperationApiService dealSyncOperationApiService;
    @Autowired
    private MaterialApiService materialApiService;
    @Autowired
    private AuthorizeService authorizeService;
    @Autowired
    private HaobanUserApiService haobanUserApiService ;
    @Autowired
    private HaobanQywxFeeApiService haobanQywxFeeApiService;
    @Autowired
    private SecretSettingApiService secretSettingApiService ;
    @Autowired
    private ClerkService clerkService;

    //授权企业列表
    @RequestMapping("wxa-enterprise-list")
    public HaobanResponse wxEnterpriseList() {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        String phoneNumber = login.getPhoneNumber() ;
        List<EnterpriseDetailDTO> list = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(wxEnterpriseId,phoneNumber,true);
        List<EnterpriseDetailVO> detailVOS = EntityUtil.changeEntityListByOrika(EnterpriseDetailVO.class, list);
        if (CollectionUtil.isNotEmpty(detailVOS)) {
            List<String> enterpriseIds = detailVOS.stream().map(s -> s.getEnterpriseId()).collect(Collectors.toList());
            List<EnterpriseDTO> enterpriseList = enterpriseService.listEnterpriseByIds(enterpriseIds);
            Map<String, EnterpriseDTO> map = com.gic.commons.util.CollectionUtil.toMap(enterpriseList, "enterpriseId");
            for (EnterpriseDetailVO dto : detailVOS) {
                List<EnterpriseWxaRelationDTO> relationDTOS = authorizeService.queryList(dto.getEnterpriseId());
                EnterpriseDTO enterpriseDTO = map.get(dto.getEnterpriseId());
                EnterpriseWxaRelationDTO wxaRelationDTO = relationDTOS.stream().filter(mid -> mid.getWxaAppkey().equals(enterpriseDTO.getMallMiniprogramAppid())).findFirst().orElse(null);
                if (wxaRelationDTO != null) {
                    dto.setEnterpriseName(enterpriseDTO.getEnterpriseName());
                    dto.setImageUrl(wxaRelationDTO.getAuthImg());
                    dto.setAppId(wxaRelationDTO.getWxaAppkey());
                    dto.setMiniprogramName(wxaRelationDTO.getAuthName());
                    dto.setTitle(wxaRelationDTO.getAuthName());
                }
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, detailVOS);
    }


    //授权企业列表 filteRight 是否过滤无登录权限的列表
    @RequestMapping("wx-enterprise-list")
    public HaobanResponse wxaEnterpriseList(@RequestParam(defaultValue="0") int filteRight) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        String phoneNumber = login.getPhoneNumber() ;
        List<EnterpriseDetailDTO> list = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(wxEnterpriseId,phoneNumber,filteRight==1);
        String userId = login.getHanbaoUserId() ;
        HaobanUserDTO dto =  this.haobanUserApiService.selectById(userId) ;
        if(null != dto) {
            String eid = dto.getDefaultGicEid() ;
            for(EnterpriseDetailDTO item : list) {
                if(null != eid && eid.equals(item.getEnterpriseId())) {
                    item.setDefaultFlag(1);
                }
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, list);
    }

    //企业信息
    @IgnoreLogin
    @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 resultResponse(HaoBanErrCode.ERR_100018);
        }
        wxEnterpriseDTO.setSmallVersion("免费版");
        wxEnterpriseDTO.setStoreTotal(departmentApiService.totalStoreCountByEnterpriseId(wxEnterpriseId));
        WxEnterpriseVO vo = com.gic.commons.util.EntityUtil.changeEntityNew( WxEnterpriseVO.class, wxEnterpriseDTO) ;
        vo.setCorpid(getCorpid(wxEnterpriseDTO));
        return resultResponse(HaoBanErrCode.ERR_1, vo);
    }

    //企业信息
    @IgnoreLogin
    @RequestMapping("wxEnterprise-refresh")
    public HaobanResponse enterpriseRefresh(String wxEnterpriseId) {
        if (StringUtils.isEmpty(wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_1);
        }
        WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseApiService.getOne(wxEnterpriseId);
        if (wxEnterpriseDTO == null) {
            return resultResponse(HaoBanErrCode.ERR_10012);
        }
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseApiService.getQwInfo(wxEnterpriseId) ;
        if(qwDTO.isSelf()) {
            return this.fail("自建应用不能刷新");
        }
        QywxCorpInfoDTO dto = qywxTokenManageService.getCorpInfo(qwDTO.getThirdCorpid(), config.getWxSuiteid());
        if (dto == null) {
            return resultResponse(HaoBanErrCode.ERR_10012);
        }
        Long verifiedEndTime = dto.getVerifiedEndTime();
        logger.info("【企业同步】dto={}", JSON.toJSONString(dto));
        WxEnterpriseDTO wxDTO = EntityUtil.changeEntityByJSON(WxEnterpriseDTO.class, dto);
        if (verifiedEndTime != null) {
            wxDTO.setVerifiedEndTime(new Date(verifiedEndTime * 1000));
        }
        wxDTO.setWxEnterpriseId(wxEnterpriseId);
        Integer contactFlag = wxEnterpriseDTO.getContactFlag();
        if (contactFlag == 0) {
            wxDTO.setContactFlag(1);
        }
        wxEnterpriseApiService.update(wxDTO);
        WxEnterpriseVO vo = com.gic.commons.util.EntityUtil.changeEntityNew( WxEnterpriseVO.class, wxEnterpriseDTO) ;
        vo.setCorpid(getCorpid(wxEnterpriseDTO));
        return resultResponse(HaoBanErrCode.ERR_1, vo);
    }


    private String getCorpid(WxEnterpriseDTO wxEnterpriseDTO) {
        Integer wxType =  wxEnterpriseDTO.getWxSecurityType() ;
        String wxEnterpriseId = wxEnterpriseDTO.getWxEnterpriseId() ;
        if(null == wxType || 0==wxType) {
            this.wxEnterpriseApiService.updateWxSecurityType(wxEnterpriseId);
             wxType = this.wxEnterpriseApiService.calcSecretType(wxEnterpriseId) ;
        }
        String desc = " (企微加密方式待确认,请联系运营人员) " ;
        if(wxType==1) {
            desc = "（全明文）" ;
        }
        if(wxType==2) {
            desc =  "（全密文）" ;
        }
        if(wxType==3) {
            desc =  "（第三方密文，代开明文）" ;
        }
        if(wxType==4) {
            desc =  "（第三方明文，代开密文）" ;
        }
        if(wxType==5) {
            desc = " （自建） " ;
        }
        int newType = this.wxEnterpriseApiService.calcSecretType(wxEnterpriseId) ;
        String diff = "";
        if(null != wxType && wxType.intValue() != newType && wxType != 5) {
            diff = "*";
        }
        return Arrays.asList(wxEnterpriseDTO.getWxCorpid(),wxEnterpriseDTO.getOpenCorpid()).stream().filter(str ->  StringUtils.isNotBlank(str)).collect(Collectors.joining(" / ")) + desc + diff;
    }

    //gic企业列表
    @IgnoreLogin
    @RequestMapping("enterprise-search")
    public HaobanResponse gicEnterpriseDetail(String enterpriseId) {
        if (org.apache.commons.lang.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("store-full-list")
    public HaobanResponse storeFullList(BasePageInfo basePageInfo, String keyWord) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        int maxVersionCount = 0;
        List<EnterpriseDetailDTO> enterpriseList = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(wxEnterpriseId);
        if (CollectionUtil.isEmpty(enterpriseList)) {
            return resultResponse(HaoBanErrCode.ERR_10010);
        }
        List<String> enterpriseIds = enterpriseList.stream().map(s -> s.getEnterpriseId()).collect(Collectors.toList());
        //获取门店列表
        Page page1 = new Page<>();
        page1.setCurrentPage(1);
        page1.setPageSize(Integer.MAX_VALUE);
        StoreSearchDTO storeSearchDTO = new StoreSearchDTO();
        storeSearchDTO.setEnterpriseIdList(enterpriseIds);
        storeSearchDTO.setSearchName(keyWord);
        Page storePage = storeService.storeListPage(page1, storeSearchDTO);
        if (storePage == null || storePage.getResult() == null) {
            return resultResponse(HaoBanErrCode.ERR_10009);
        }
        List<StoreDTO> t_list = storePage.getResult();
        List<String> storeIds = t_list.stream().map(s -> s.getStoreId()).collect(Collectors.toList());
        if (StringUtils.isEmpty(keyWord)) {
            storeIds = null;
        }
        Page<DepartmentDTO> page = departmentApiService.pageFullStoreByWxEnterpriseId(wxEnterpriseId, keyWord, storeIds, maxVersionCount, basePageInfo);
        List<DepartmentDTO> list = page.getResult();
        List<StoreVo> resultList = EntityUtil.changeEntityListByJSON(StoreVo.class, list);
        List<String> t_storeIds = list.stream().map(s -> s.getRelatedId()).collect(Collectors.toList());
        String[] storeIdArr = t_storeIds.toArray(new String[t_storeIds.size()]);
        List<StoreDTO> storeList = storeService.getStores(storeIdArr);
        Map<String, StoreDTO> map = com.gic.commons.util.CollectionUtil.toMap(storeList, "storeId");

        for (StoreVo vo : resultList) {
            if (map.get(vo.getRelatedId()) != null) {
                vo.setStoreCode(map.get(vo.getRelatedId()).getStoreCode());
                vo.setStoreId(map.get(vo.getRelatedId()).getStoreId());
                vo.setStoreName(map.get(vo.getRelatedId()).getStoreName());
            }
        }

        Page resultPage = new Page<>();
        resultPage.setCurrentPage(page.getCurrentPage());
        resultPage.setPageSize(page.getPageSize());
        resultPage.setTotalCount(page.getTotalCount());
        resultPage.setResult(resultList);
        return resultResponse(HaoBanErrCode.ERR_1, resultPage);

    }

    //微信企业是否设置key
    @RequestMapping("is-wx-enterprise-secret-set")
    public HaobanResponse isWxEnterpriseSecretSet() {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        List<SecretSettingDTO> listSecret = wxEnterpriseApiService.listSecret(wxEnterpriseId);
        if (CollectionUtils.isEmpty(listSecret)) {
            return resultResponse(HaoBanErrCode.ERR_1, false);
        }
        Set<Integer> secretTypeList = listSecret.stream().filter(secretSettingDTO -> secretSettingDTO.getCheckFlag() == 1).map(secretSettingDTO -> secretSettingDTO.getSecretType()).collect(Collectors.toSet());
        if (CollectionUtils.isEmpty(secretTypeList)) {
            return resultResponse(HaoBanErrCode.ERR_1, false);
        }
        if ((secretTypeList.contains(SecretTypeEnum.CUSTOMIZED_APP.getVal()))) {
            return resultResponse(HaoBanErrCode.ERR_1, true);
        } else {
            return resultResponse(HaoBanErrCode.ERR_1, false);
        }
    }

    /**
     * 微信企业绑定接口绑定通讯录key
     *
     * @param wxSecretKey
     * @return
     */
    @RequestMapping("wx-enterprise-wx-secret-set")
    public HaobanResponse wxEnterpriseWxSecretSet(String wxSecretKey) {
        if (StringUtils.isAnyBlank(wxSecretKey)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseApiService.getQwInfo(wxEnterpriseId) ;
        if (qwDTO == null) {
            return resultResponse(HaoBanErrCode.ERR_10012);
        }
        wxSecretKey = wxSecretKey.trim();
        String token = this.qywxCorpApiService.getToken(qwDTO.getDkCorpid(), wxSecretKey);
        logger.info("查询token", token) ;
        if(StringUtils.isEmpty(token) || token.length() < 10) {
            return this.fail("请确认secret是否正确") ;
        }
        SecretSettingDTO secretSetting = wxEnterpriseApiService.getSecretSetting(wxEnterpriseId, SecretTypeEnum.CONTACT_CUSTOMER.getVal(), null);
        if (null == secretSetting) {
            secretSetting = new SecretSettingDTO();
        }
        secretSetting.setSecretType(SecretTypeEnum.CONTACT_CUSTOMER.getVal());
        secretSetting.setSecretName(SecretTypeEnum.CONTACT_CUSTOMER.getName());
        secretSetting.setWxEnterpriseId(wxEnterpriseId);
        secretSetting.setEnterpriseId("-1");
        secretSetting.setSecretVal(wxSecretKey);
        secretSetting.setCheckFlag(1);
        wxEnterpriseApiService.saveSecretSetting(secretSetting);
        return resultResponse(HaoBanErrCode.ERR_1, true);
    }

    /**
     * 微信企业会员小程序
     *
     * @param memberSecret
     * @param enterpriseId
     * @param secretName
     * @return
     */
    @RequestMapping("wx-enterprise-member-secret-set")
    public HaobanResponse wxEnterpriseMemberSecretSet(String secretId,String memberSecret, String enterpriseId, String secretName) {
        if (StringUtils.isAnyBlank(memberSecret,enterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        WxEnterpriseDTO wxEnterprise = wxEnterpriseApiService.getOne(wxEnterpriseId);
        if (wxEnterprise == null) {
            return resultResponse(HaoBanErrCode.ERR_10012);
        }
        memberSecret = memberSecret.trim();
        SecretSettingDTO secretSetting = null ;
        if (StringUtils.isNotBlank(secretId)) {
           secretSetting = wxEnterpriseApiService.getSecretSettingById(secretId);
        }
        if(null == secretSetting) {
           secretSetting = new SecretSettingDTO();
        }
        List<SecretSettingDTO> enList = this.secretSettingApiService.exsitGicEidMemberApp(wxEnterpriseId) ;
        if(CollectionUtils.isNotEmpty(enList)) {
            Map<String,SecretSettingDTO> map = enList.stream().collect(Collectors.toMap(SecretSettingDTO::getEnterpriseId, dto->dto,(k1,k2)->k1));
            if(StringUtils.isEmpty(secretId)) {
                if(null != map.get(enterpriseId)) {
                    return this.fail("此商户小程序已存在") ;
                }
            }else {
                if(null != map.get(enterpriseId) && !secretId.equals(map.get(enterpriseId).getSecretId())) {
                    return this.fail("此商户小程序已存在") ;
                }
            }
        }
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseApiService.getQwInfo(wxEnterpriseId) ;
        String token = this.qywxCorpApiService.getToken(qwDTO.getMemberCorpid(), memberSecret);
        logger.info("查询token", token) ;
        if(StringUtils.isEmpty(token) || token.length() < 10) {
            return this.fail("请确认secret是否正确") ;
        }
        secretSetting.setSecretType(SecretTypeEnum.MEMBER_WAPP.getVal());
        secretSetting.setSecretName(secretName);
        secretSetting.setEnterpriseId(enterpriseId);
        secretSetting.setWxEnterpriseId(wxEnterpriseId);
        secretSetting.setSecretVal(memberSecret);
        secretSetting.setCheckFlag(1);
        wxEnterpriseApiService.saveSecretSetting(secretSetting);
        return resultResponse(HaoBanErrCode.ERR_1, true);
    }

    /**
     * 企微相关密钥列表
     *
     * @return
     */
    @RequestMapping("secret-list")
    public HaobanResponse secretList() {
        String wxEnterpriseId = "";
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        wxEnterpriseId = login.getWxEnterpriseId();
        WxEnterpriseDTO wxEnterprise = wxEnterpriseApiService.getOne(wxEnterpriseId);
        if (wxEnterprise == null) {
            return resultResponse(HaoBanErrCode.ERR_10012);
        }

        List<SecretSettingDTO> listSecret = wxEnterpriseApiService.listSecret(wxEnterpriseId);
        List<SecretSettingVO> listRet = EntityUtil.changeEntityListByJSON(SecretSettingVO.class, listSecret);
        if (CollectionUtils.isNotEmpty(listRet)) {
            listRet.forEach(secretSettingVO -> {
                if ((!StringUtils.isEmpty(secretSettingVO.getEnterpriseId())) && (!secretSettingVO.getEnterpriseId().equals("-1"))) {
                    EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(secretSettingVO.getEnterpriseId());
                    secretSettingVO.setEnterpriseName(enterpriseDTO == null ? "" : enterpriseDTO.getBrandName());
                }
            });
        }
        return resultResponse(HaoBanErrCode.ERR_1, listRet);
    }


    //微信企业会员小程序
    @RequestMapping("member-secret-del")
    public HaobanResponse delMemberSecret(String secretId) {
        if (StringUtils.isAnyBlank(secretId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        boolean b = wxEnterpriseApiService.delSecretSetting(secretId);
        return resultResponse(HaoBanErrCode.ERR_1, b);
    }

    /**
     * 刷新企业微信好友
     *
     * @return
     */
    @RequestMapping("/fresh-wx-friend")
    public HaobanResponse freshWxFriend() {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        String dayKey = "haoban_fresh-wx-friend-day" + wxEnterpriseId + DateUtil.dateToStr(new Date(), "yyyy-MM-dd");
        String monthKey = "haoban_fresh-wx-friend-month" + wxEnterpriseId + DateUtil.dateToStr(new Date(), "yyyy-MM");
        String dateKey = "haoban_fresh-wx-friend-date" + wxEnterpriseId;
        Integer dayCount = RedisUtil.getCache(dayKey) == null ? 0 : Integer.parseInt(RedisUtil.getCache(dayKey).toString());
        Integer monthCount = RedisUtil.getCache(monthKey) == null ? 0 : Integer.parseInt(RedisUtil.getCache(monthKey).toString());
        if (dayCount >= 1) {
            return resultResponse(HaoBanErrCode.ERR_100019);
        }
        if (monthCount >= 3) {
            return resultResponse(HaoBanErrCode.ERR_100020);
        }
        String taskId = dealSyncOperationApiService.createWxFriendTask(wxEnterpriseId, "刷新企微好友", login.getClerkId(), "刷新企微好友");
        if (StringUtils.isEmpty(taskId)) {
            return resultResponse(HaoBanErrCode.ERR_100021);
        }
        RedisUtil.setCache(dayKey, dayCount + 1);
        RedisUtil.setCache(monthKey, monthCount + 1);
        RedisUtil.setCache(dateKey, DateUtil.dateToStr(new Date(), DateUtil.FORMAT_DATETIME_19));
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 获取企业微信好友刷新时间
     *
     * @return
     */
    @RequestMapping("/get-fresh-detail")
    public HaobanResponse getFreshDetail() {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        String dateKey = "haoban_fresh-wx-friend-date" + wxEnterpriseId;
        RedisUtil.getCache(dateKey);
        return resultResponse(HaoBanErrCode.ERR_1, RedisUtil.getCache(dateKey));
    }

    /**
     * 微信企业绑定详情
     *
     * @param enterpriseId
     * @return
     */
    @RequestMapping("wx-enterprise-bind-detail")
    public HaobanResponse wxEnterpriseBindDetail(String enterpriseId) {
        if (StringUtils.isAnyBlank(enterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();

        WxEnterpriseRelationDetailDTO bindInfo = wxEnterpriseRelatedApiService.getEnterpriseBindInfo(wxEnterpriseId, enterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1, bindInfo);

    }

    /**
     * 绑定门店列表
     *
     * @param enterpriseId
     * @return
     */
    @RequestMapping("bind-store-list")
    public HaobanResponse bindStoreList(String enterpriseId, String search, BasePageInfo basePageInfo) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        Page<BindStoreInfoDTO> retPage = wxEnterpriseRelatedApiService.pageBindStoreByEnterpriseId(wxEnterpriseId, enterpriseId, search, basePageInfo);
        return resultResponse(HaoBanErrCode.ERR_1, retPage);
    }

    /**
     * 绑定门店列表
     *
     * @param enterpriseId
     * @return
     */
    @RequestMapping("flush-bind-store-list")
    public HaobanResponse flushBindStoreList(String enterpriseId) {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        ServiceResponse response = wxEnterpriseRelatedApiService.flushBindStoreByEnterpriseId(enterpriseId, wxEnterpriseId, login.getClerkId(), 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);
    }

    /**
     * 绑定小程序配置列表
     *
     * @return
     */
    @RequestMapping("list-miniprogram-setting")
    public HaobanResponse miniprogramList() {
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        List<MiniprogramSettingDTO> settingDTOS = wxEnterpriseApiService.listMiniprogramSetting(wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1, settingDTOS);
    }

    /**
     * 保存小程序配置列表
     *
     * @return
     */
    @RequestMapping("save-miniprogram-setting")
    public HaobanResponse saveMiniprogram(MiniprogramSettingQo settingDTO) {
        if (StringUtils.isAnyBlank(settingDTO.getAppId(),
                settingDTO.getImageUrl(), settingDTO.getMiniprogramName(), settingDTO.getTitle())) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        settingDTO.setWxEnterpriseId(wxEnterpriseId);
        settingDTO.setEnterpriseId(login.getEnterpriseId());
        MiniprogramSettingDTO miniprogramSettingDTO = wxEnterpriseApiService.getMiniprogramSettingByAppId(wxEnterpriseId, settingDTO.getAppId());
        if (null != miniprogramSettingDTO
                && (!miniprogramSettingDTO.getMiniprogramSettingId().equals(settingDTO.getMiniprogramSettingId()))) {
            return resultResponse(HaoBanErrCode.ERR_100031);
        }
        wxEnterpriseApiService.saveMiniprogramSetting(EntityUtil.changeEntityByOrika(MiniprogramSettingDTO.class, settingDTO));
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 获取小程序配置
     *
     * @return
     */
    @RequestMapping("get-miniprogram-setting")
    public HaobanResponse getMiniprogram(String enterpriseId) {
        if (StringUtils.isEmpty(enterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        WebLoginDTO login = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = login.getWxEnterpriseId();
        MiniprogramSettingDTO settingDTO = wxEnterpriseApiService.getMiniprogramSettingByEid(wxEnterpriseId, enterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1, settingDTO);
    }

    /**
     * 删除小程序配置
     *
     * @return
     */
    @RequestMapping("del-miniprogram-setting")
    public HaobanResponse delMiniprogram(String id) {
        if (StringUtils.isEmpty(id)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        wxEnterpriseApiService.delMiniprogramSettingByEid(id);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 分析素材
     *
     * @return
     */
    @RequestMapping("/agent-wx-enterprise-list")
    public HaobanResponse materialShare(String materialId) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        List<EnterpriseDetailDTO> detailDTOS = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(wxEnterpriseId);
        List<String> enterpriseIds = detailDTOS.stream().filter(dto -> dto.getWxEnterpriseType() == 0).map(dto -> dto.getEnterpriseId()).collect(Collectors.toList());
        
        List<EnterpriseDetailDTO> retList = wxEnterpriseRelatedApiService.listEnterpriseByEnterpriseIds(enterpriseIds);
        Map<String, EnterpriseDetailDTO> detailDTOMap = retList.stream().filter(dto -> dto.getWxEnterpriseType() == 1).collect(Collectors.toMap(dto -> dto.getWxEnterpriseId(), dto -> dto, (ne, ol) -> ol));
        Collection<EnterpriseDetailDTO> values = detailDTOMap.values();
        List<AgentEnterpriseDTO> enterpriseList = EntityUtil.changeEntityListByOrika(AgentEnterpriseDTO.class, values);

        if (CollectionUtils.isNotEmpty(values)) {
            List<MaterialDTO> materialDTOS = materialApiService.listByFromMaterialId(materialId);
            List<String> wxEids = new ArrayList<>();
            if (CollectionUtils.isNotEmpty(materialDTOS)) {
                wxEids = materialDTOS.stream().map(dto -> dto.getWxEnterpriseId()).collect(Collectors.toList());
            }
            List<String> finalWxEids = wxEids;
            for(AgentEnterpriseDTO dto : enterpriseList) {
                WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseApiService.getOne(dto.getWxEnterpriseId());
                if(null == wxEnterpriseDTO) {
                   continue ;
                }
                logger.info("wxEnterpriseDTO={},dto={}", JSON.toJSONString(wxEnterpriseDTO),JSON.toJSONString(dto));
                dto.setEnterpriseName(wxEnterpriseDTO.getCorpName());
                if (finalWxEids.contains(dto.getWxEnterpriseId())) {
                    dto.setBindFlag(1);
                } else {
                    dto.setBindFlag(0);
                }
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, enterpriseList);
    }

    /**
     * 删除欢迎语
     *
     * @return
     */
    @RequestMapping("del-welcome")
    public HaobanResponse delWelcome() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        wxEnterpriseApiService.delWelcome(wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 欢迎语开启关闭
     *
     * @return
     */
    @RequestMapping("set-welcome")
    public HaobanResponse setWelcome(int openFlag) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        wxEnterpriseApiService.setWelcome(wxEnterpriseId, openFlag);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 授权绑定-设置导购编辑权限
     *
     * @return
     */
    @IgnoreLogin
    @RequestMapping("set-clerk-edit")
    public HaobanResponse setClerkEdit(String wxEnterprieseRelatedId, int clerkEditFlag) {
        if (StringUtils.isBlank(wxEnterprieseRelatedId)) {
            logger.info("缺少参数");
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        boolean b = wxEnterpriseRelatedApiService.setClerkEditFlag(wxEnterprieseRelatedId, clerkEditFlag);
        if (b) {
            return resultResponse(HaoBanErrCode.ERR_1);
        } else {
            return resultResponse(HaoBanErrCode.ERR_100032);
        }
    }

    /**
     * 是否同意授权
     *
     * @param openFlag
     * @return
     */
    @RequestMapping("agree_external_userid_flag")
    public HaobanResponse agreeExternalUseridFlag(Integer openFlag) {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        wxEnterpriseApiService.agreeExternalUseridFlag(wxEnterpriseId, openFlag);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    @RequestMapping(path = "/current/enterprise/info")
    public RestResponse<?> queryCurrentInfo(){
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        com.gic.api.base.commons.ServiceResponse<EnterpriseDetailDTO> serviceResponse = wxEnterpriseRelatedApiService.queryEnterpriseDetail(loginUser.getWxEnterpriseId(), loginUser.getEnterpriseId());
        if (serviceResponse.isSuccess()){
            return RestResponse.successResult(serviceResponse.getResult());
        }
        return RestResponse.failure(serviceResponse.getCode(), serviceResponse.getMessage());
    }

    /**
     * 最新一条将要被拦截记录
     * @return
     */
    @RequestMapping(value = "qywx-fee-wxEnterprise-detail", method = RequestMethod.GET)
    public RestResponse qywxFeeWxEnterpriseListDetail() {
        WebLoginDTO loginUser = AuthWebRequestUtil.getLoginUser();
        String wxEnterpriseId = loginUser.getWxEnterpriseId();
        HaobanQywxFeeDTO haobanQywxFeeDTO = haobanQywxFeeApiService.queryByWxEnterpriseId(wxEnterpriseId);
        if (haobanQywxFeeDTO == null) {
            return RestResponse.successResult();
        }
        List<EnterpriseDetailDTO> enterpriseDetailDTOS = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(wxEnterpriseId);
        if (CollectionUtils.isNotEmpty(enterpriseDetailDTOS)) {
            StringBuffer stringBuffer = new StringBuffer();
            for (EnterpriseDetailDTO enterpriseDetailDTO : enterpriseDetailDTOS) {
                stringBuffer.append(enterpriseDetailDTO.getEnterpriseName()).append(" ");
            }
            haobanQywxFeeDTO.setEnterpriseNames(stringBuffer.toString());
        }
        return RestResponse.successResult(haobanQywxFeeDTO);
    }
}
