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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

import javax.validation.Valid;

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.RequestBody;
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 cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gic.api.base.commons.Page;
import com.gic.api.base.commons.ServiceResponse;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.dto.ClerkListDTO;
import com.gic.clerk.api.service.ClerkNewService;
import com.gic.clerk.api.service.ClerkService;
import com.gic.clerk.api.service.PowerService;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.webapi.reponse.RestResponse;
import com.gic.enterprise.api.constant.EnterpriseServiceEnum;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.dto.StoreSearchDTO;
import com.gic.enterprise.api.dto.enterprise.EnterpriseUsingStatusDTO;
import com.gic.enterprise.api.service.EnterpriseService;
import com.gic.enterprise.api.service.EnterpriseUseForbidService;
import com.gic.enterprise.api.service.StoreService;
import com.gic.enterprise.api.service.StoreWidgetService;
import com.gic.haoban.app.customer.service.api.service.CustomerApiService;
import com.gic.haoban.app.customer.service.api.service.DistributeApiService;
import com.gic.haoban.base.api.common.BasePageInfo;
import com.gic.haoban.base.api.common.PageResult2;
import com.gic.haoban.common.anno.HttpLimit;
import com.gic.haoban.common.anno.IgnoreLogin;
import com.gic.haoban.common.utils.GooglePhoneNumberUtil;
import com.gic.haoban.common.utils.HaobanResponse;
import com.gic.haoban.common.utils.PageUtil;
import com.gic.haoban.manage.api.dto.AuditDTO;
import com.gic.haoban.manage.api.dto.AuditSettingDTO;
import com.gic.haoban.manage.api.dto.ClerkMainStoreRelatedDTO;
import com.gic.haoban.manage.api.dto.EnterpriseDetailDTO;
import com.gic.haoban.manage.api.dto.ExternalClerkRelatedDTO;
import com.gic.haoban.manage.api.dto.StaffClerkInfoDTO;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.StaffDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseRelationDetailDTO;
import com.gic.haoban.manage.api.dto.role.HaobanRoleDTO;
import com.gic.haoban.manage.api.dto.role.StoreRoleDTO;
import com.gic.haoban.manage.api.enums.AuditStatus;
import com.gic.haoban.manage.api.enums.AuditType;
import com.gic.haoban.manage.api.enums.ChannelCodeEnum;
import com.gic.haoban.manage.api.enums.NoticeMessageTypeEnum;
import com.gic.haoban.manage.api.enums.SyncTaskTypeEnum;
import com.gic.haoban.manage.api.enums.role.RoleClerkTypeEnum;
import com.gic.haoban.manage.api.service.AuditApiService;
import com.gic.haoban.manage.api.service.AuditSettingApiService;
import com.gic.haoban.manage.api.service.ClerkMainStoreRelatedApiService;
import com.gic.haoban.manage.api.service.DealSyncOperationApiService;
import com.gic.haoban.manage.api.service.ExternalClerkRelatedApiService;
import com.gic.haoban.manage.api.service.StaffApiService;
import com.gic.haoban.manage.api.service.StaffClerkRelationApiService;
import com.gic.haoban.manage.api.service.StaffDepartmentRelatedApiService;
import com.gic.haoban.manage.api.service.SyncHaobanToGicApiService;
import com.gic.haoban.manage.api.service.WxEnterpriseApiService;
import com.gic.haoban.manage.api.service.WxEnterpriseRelatedApiService;
import com.gic.haoban.manage.api.service.role.HaobanRoleApiService;
import com.gic.haoban.manage.api.util.notify.NoticeMessageUtil;
import com.gic.haoban.manage.web.config.Config;
import com.gic.haoban.manage.web.errCode.HaoBanErrCode;
import com.gic.haoban.manage.web.qo.CommonQO;
import com.gic.haoban.manage.web.vo.AuditSettingVO;
import com.gic.haoban.manage.web.vo.BindClerkVO;
import com.gic.haoban.manage.web.vo.ClerkDetailVo;
import com.gic.haoban.manage.web.vo.ClerkEditInfoVO;
import com.gic.haoban.manage.web.vo.ClerkListVO;
import com.gic.haoban.manage.web.vo.ClerkStoreVO;
import com.gic.haoban.manage.web.vo.OperationSettingVO;
import com.gic.haoban.manage.web.vo.RightVO;
import com.gic.haoban.manage.web.vo.StaffStoreVO;
import com.gic.haoban.manage.web.vo.StaffVO;
import com.gic.haoban.manage.web.vo.StoreClerkVO;
import com.gic.haoban.manage.web.vo.StoreListVO;
import com.gic.haoban.manage.web.vo.StoreRoleVO;
import com.gic.haoban.manage.web.vo.notify.CustomerFriendMemberVO;
import com.gic.redis.data.util.RedisUtil;
import com.gic.wechat.api.service.qywx.QywxUserApiService;


@RestController
public class WxStaffController extends WebBaseController {
    private static final Logger logger = LoggerFactory.getLogger(WxStaffController.class);

    @Autowired
    private ClerkService clerkService;
    @Autowired
    private StaffApiService staffApiService;
    @Autowired
    private StaffDepartmentRelatedApiService staffDepartmentRelatedApiService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private SyncHaobanToGicApiService syncHaobanToGicApiService;
    @Autowired
    private ClerkMainStoreRelatedApiService clerkMainStoreRelatedApiService;
    @Autowired
    private DistributeApiService distributeApiService;
    @Autowired
    private WxEnterpriseRelatedApiService wxEnterpriseRelatedApiService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private AuditApiService auditApiService;
    @Autowired
    private StaffClerkRelationApiService staffClerkRelationApiService;
    @Autowired
    private ClerkNewService clerkNewService;
    @Autowired
    private AuditSettingApiService auditSettingApiService;
    @Autowired
    private DealSyncOperationApiService dealSyncOperationApiService;
    @Autowired
    private ExternalClerkRelatedApiService externalClerkRelatedApiService;
    @Autowired
    private CustomerApiService customerApiService;
    @Autowired
    private WxEnterpriseApiService wxEnterpriseApiService;
    @Autowired
    private QywxUserApiService qywxUserApiService;
    @Autowired
    private Config config;
    @Autowired
    private StoreWidgetService storeWidgetService;
    @Autowired
    private HaobanRoleApiService haobanRoleApiService;
    @Autowired
    private PowerService powerService;
    @Autowired
    private EnterpriseUseForbidService enterpriseUseForbidService;

    // 选择成员列表
    @RequestMapping("/staff-list")
    public HaobanResponse staffList(String storeId, Integer manageFlag, String clerkId, String wxEnterpriseId) {
        List<String> storeIds = new ArrayList<>();
        if (manageFlag != null && manageFlag == 1) {
            List<String> roleStoreIds = staffApiService.getHaoBanStoreIdsRolesByClerkId(clerkId, wxEnterpriseId);
            storeIds.addAll(roleStoreIds);
        } else {
            storeIds.add(storeId);
        }
        if (CollectionUtils.isEmpty(storeIds)) {
            return resultResponse(HaoBanErrCode.ERR_10009);
        }
        if (storeIds.contains("-1")) {
            storeIds = null;
        }
        List<StaffDTO> resultlist = staffApiService.listBindStoreIds(storeIds, wxEnterpriseId);
        List<StaffVO> resultList = new ArrayList<>();
        for (StaffDTO staffDTO : resultlist) {
            String enterpriseId = staffDTO.getEnterpriseId();
            String staffClerkId = staffDTO.getClerkId() ;
            ClerkDTO clerk = this.clerkService.getclerkById(staffClerkId) ;
            if(null != clerk) {
                staffDTO.setStaffName(clerk.getClerkName());
            }
            long memberCount = customerApiService.countMember(enterpriseId, storeId, staffDTO.getClerkId());
            logger.info("【获取会员数】enterpriseId={},clerkId={},storeId={},memberCount={}", enterpriseId, staffDTO.getClerkId(), storeId, memberCount);
            staffDTO.setMemberCount(Convert.toInt(memberCount, 0));
            resultList.add(EntityUtil.changeEntityNew(StaffVO.class, staffDTO));
        }
        return resultResponse(HaoBanErrCode.ERR_1, resultList);

    }

    /**
     * 门店成员列表
     *
     * @param basePageInfo
     * @param clerkId
     * @param enterpriseId
     * @param storeId
     * @param manageFlag
     * @return
     */
    @RequestMapping("/store-clerks")
    public HaobanResponse storeClerks(BasePageInfo basePageInfo, String clerkId, String enterpriseId, String storeId,
            Integer manageFlag, String wxEnterpriseId) {
        List<String> storeIds = new ArrayList<>();
        if (manageFlag != null && manageFlag == 1) {
            List<String> roleStoreIds = staffApiService.getHaoBanStoreIdsRolesByClerkId(clerkId, wxEnterpriseId);
            storeIds.addAll(roleStoreIds);
        } else {
            storeIds.add(storeId);
        }
        if (CollectionUtils.isEmpty(storeIds)) {
            return resultResponse(HaoBanErrCode.ERR_10009);
        }
        if (storeIds.contains("-1")) {
            storeIds = null;
        }
        Page<ClerkDTO> clerkDTOPage = clerkService.pageClerkByNameOrCode(enterpriseId, null, storeIds,
                basePageInfo.getPageNum(), basePageInfo.getPageSize());
        List<ClerkDTO> clerkDTOS = clerkDTOPage.getResult();
        if (CollectionUtils.isEmpty(clerkDTOS)) {
            return resultResponse(HaoBanErrCode.ERR_10016);
        }
        //统一处理：导购code替换为导购id
        Set<String> clerkCodeList = clerkDTOS.stream().map(ClerkDTO::getClerkId).collect(Collectors.toSet());
        List<StaffClerkRelationDTO> bindRelationList = staffClerkRelationApiService.listBindCode(wxEnterpriseId,
                enterpriseId, clerkCodeList);
        Map<String, StaffClerkRelationDTO> bindCodeMap = bindRelationList.stream()
                .collect(Collectors.toMap(StaffClerkRelationDTO::getClerkId, s -> s));
        List<StoreClerkVO> resultList = new ArrayList<>();
        for (ClerkDTO dto : clerkDTOS) {
            String clerkCode = dto.getClerkCode();
            StoreClerkVO vo = new StoreClerkVO();
            vo.setClerkCode(clerkCode);
            vo.setClerkId(dto.getClerkId());
            vo.setClerkType(dto.getClerkType());
            vo.setClerkImg(dto.getImageUrl());
            vo.setClerkName(dto.getClerkName());
            StaffClerkRelationDTO related = bindCodeMap.get(dto.getClerkId());
            if (related != null) {
                vo.setStaffId(related.getStaffId());
                vo.setBindFlag(1);
            } else {
                vo.setBindFlag(0);
            }
            resultList.add(vo);
        }
        Page<StoreClerkVO> page = new Page();
        page.setCurrentPage(clerkDTOPage.getCurrentPage());
        page.setPageSize(clerkDTOPage.getPageSize());
        page.setTotalCount(clerkDTOPage.getTotalCount());
        page.setResult(resultList);
        return resultResponse(HaoBanErrCode.ERR_1, page);
    }

    // 门店成员列表
    @RequestMapping("/clerk-edit-flag")
    public HaobanResponse clerkEditFlag(String wxEnterpriseId, String storeId) {
        if (StringUtils.isAnyBlank(storeId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        StoreDTO storeDTO = storeService.getStore(storeId);
        if (storeDTO == null) {
            return resultResponse(HaoBanErrCode.ERR_10009);
        }
        WxEnterpriseRelationDetailDTO enterpriseBindInfo = wxEnterpriseRelatedApiService
                .getEnterpriseBindInfo(wxEnterpriseId, storeDTO.getEnterpriseId());
        return resultResponse(HaoBanErrCode.ERR_1, ClerkEditInfoVO.info(enterpriseBindInfo.getClerkEditFlag()));

    }

    /**
     * 会员小程序-获取后台认证配置
     *
     * @param wxEnterpriseId
     * @return
     */
    @IgnoreLogin
    @RequestMapping("/get-audit-setting")
    public HaobanResponse getAuditSetting(String wxEnterpriseId) {
        if (StringUtils.isAnyBlank(wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        AuditSettingDTO auditSetting = auditSettingApiService.findSettingByWxEnterpriseId(wxEnterpriseId);

        AuditSettingVO auditSettingVO = EntityUtil.changeEntityNew(AuditSettingVO.class, auditSetting);

        return resultResponse(HaoBanErrCode.ERR_1, auditSettingVO);
    }

    /**
     * 会员小程序-获取后台认证配置
     *
     * @param wxEnterpriseId
     * @param staffId
     * @return
     */
    @IgnoreLogin
    @RequestMapping("/get-user-setting")
    public HaobanResponse getUserSetting(String wxEnterpriseId, String staffId) {
        if (StringUtils.isAnyBlank(wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }

        AuditSettingVO auditSettingVO = new AuditSettingVO();
        ClerkMainStoreRelatedDTO mainStore = clerkMainStoreRelatedApiService.getWxEnterpriseIdAndStaffId(wxEnterpriseId,
                staffId);
        if (mainStore == null) {
            logger.info("该门店不存在");
            return resultResponse(HaoBanErrCode.ERR_400023);
        }
        String mainStoreId = mainStore.getStoreId();
        StoreDTO storeDTO = storeService.getStore(mainStoreId);
        if (null == storeDTO) {
            logger.info("该门店不存在");
            return resultResponse(HaoBanErrCode.ERR_400023);
        }
        WxEnterpriseRelationDetailDTO enterpriseBindInfo = wxEnterpriseRelatedApiService
                .getEnterpriseBindInfo(wxEnterpriseId, storeDTO.getEnterpriseId());
        if (null == enterpriseBindInfo) {
            logger.info("该企业未关联");
            return resultResponse(HaoBanErrCode.ERR_400022);
        }
        WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseApiService.getOne(wxEnterpriseId);
        if (null == wxEnterpriseDTO) {
            logger.info("该企业不存在");
            return resultResponse(HaoBanErrCode.ERR_400002);
        }
        Integer agreeExternalUseridFlag = wxEnterpriseDTO.getAgreeExternalUseridFlag();
        int memberOpenCardFlag = enterpriseBindInfo.getMemberOpenCardFlag();
        boolean agreeExternalUserid = agreeExternalUseridFlag == null || agreeExternalUseridFlag != 1;
        // 同一开平并且未同意转换
        if (memberOpenCardFlag == 0 && agreeExternalUserid) {
            auditSettingVO.setMemberOpenCardFlag(0);
        } else {
            auditSettingVO.setMemberOpenCardFlag(1);
        }
        auditSettingVO.setWxEnterpriseType(enterpriseBindInfo.getWxEnterpriseType());
        auditSettingVO.setFreshFriendFlag(mainStore.getFreshFriendFlag());
        return resultResponse(HaoBanErrCode.ERR_1, auditSettingVO);
    }

    @IgnoreLogin
    @RequestMapping("/get-operation-setting")
    public HaobanResponse getOperatorSetting(String wxEnterpriseId, String enterpriseId) {
        OperationSettingVO vo = new OperationSettingVO();
        vo.setClerkPhoneFlag(1);
        return resultResponse(HaoBanErrCode.ERR_1, vo);
    }

    // 新增店员
    @HttpLimit
    @RequestMapping("/staff-add")
    public HaobanResponse staffAdd(StaffDTO staffDTO, String storeId, String clerkCode, String commitName,
            Integer version) {

        String wxEnterpriseId = staffDTO.getWxEnterpriseId();
        String staffName = staffDTO.getStaffName();
        String phoneNumber = staffDTO.getPhoneNumber();
        String nationcode = staffDTO.getNationCode();
        String postion = staffDTO.getPostion();
        Integer sex = staffDTO.getSex();
        if (StringUtils.isAnyBlank(staffName, commitName)) {
            return resultResponse(HaoBanErrCode.ERR_10004);
        }
        if (StringUtils.isEmpty(clerkCode)) {
            return resultResponse(HaoBanErrCode.ERR_111116);
        }
        if (StringUtils.isNotEmpty(phoneNumber) && !GooglePhoneNumberUtil.checkPhoneNumber(phoneNumber, nationcode)) {
            return resultResponse(HaoBanErrCode.ERR_10012);
        }
        // 导购code校验-字母和数字
        // if (!clerkCode.matches("[a-zA-Z0-9]+")) {
        // return resultResponse(HaoBanErrCode.ERR_10023);
        // }
        if (version == null) {
            StaffDTO staff = staffApiService.selectByNationcodeAndPhoneNumber(wxEnterpriseId, nationcode, phoneNumber);
            if (staff != null) {
                return resultResponse(HaoBanErrCode.ERR_10005);
            }
        }
        com.gic.enterprise.api.dto.StoreDTO store = storeService.getStoreByIdNoStatus(storeId);
        // 校验手机是否唯一
        if (store == null) {
            return resultResponse(HaoBanErrCode.ERR_10009);
        }
        String enterpriseId = store.getEnterpriseId();
        boolean b = auditApiService.judgeHavePhoneNumberOrCode(enterpriseId, clerkCode, phoneNumber, wxEnterpriseId);
        if (b) {
            // 待审核中存在code或该手机号
            return resultResponse(HaoBanErrCode.ERR_10021);
        }
        ClerkDTO clerk = clerkService.getClerkByCodeNoDel(store.getEnterpriseId(), clerkCode);
        logger.info("【新增店员】clerk={}", JSON.toJSONString(clerk));
        if (clerk != null) {
            return resultResponse(HaoBanErrCode.ERR_10013);
        }
        AuditSettingDTO dto = auditSettingApiService.findSettingByWxEnterpriseId(wxEnterpriseId);
        if (dto.getAuditFlag() == 1 && dto.getClerkChangeFlag() == 1) {
            AuditDTO auditDTO = auditApiService.findByBindRelatedIdAndAuditType(clerkCode,
                    AuditType.CLERK_ADD.getCode(), wxEnterpriseId, enterpriseId);
            if (auditDTO != null) {
                logger.info("已经存在了审核记录，待审核{}", clerkCode);
                return resultResponse(HaoBanErrCode.ERR_10018);
            }
            // 需要审核
            StaffDTO staff = staffApiService.selectById(staffDTO.getStaffId());
            AuditDTO audit = new AuditDTO();
            audit.setCommitStaffName(commitName);
            audit.setCommitStaffId(staffDTO.getStaffId());
            audit.setCommitStaffImg(staff.getHeadImg());
            audit.setCommitStoreId(storeId);
            audit.setCommitStoreName(store.getStoreName());
            audit.setAuditStatus(AuditStatus.NO_AUDIT.getCode());
            audit.setWxEnterpriseId(wxEnterpriseId);
            audit.setEnterpriseId(store.getEnterpriseId());
            audit.setStatusFlag(1);

            JSONObject json = new JSONObject();
            json.put("clerkCode", clerkCode);
            json.put("clerkName", staffName);
            json.put("headPic", staff.getHeadImg());
            json.put("sex", sex);
            json.put("postion", postion);
            json.put("phoneNumber", phoneNumber);
            json.put("nationcode", nationcode);

            audit.setOldValue(json.toJSONString());
            audit.setCommitTime(new Date());
            audit.setAuditType(AuditType.CLERK_ADD.getCode());
            audit.setRelatedId(clerkCode);
            auditApiService.insert(audit);
            return resultResponse(HaoBanErrCode.ERR_1);
        } else {
            // 不用审核
            StaffDTO staff = staffApiService.selectById(staffDTO.getStaffId());
            AuditDTO audit = new AuditDTO();
            audit.setCommitStaffName(commitName);
            audit.setCommitStaffId(staffDTO.getStaffId());
            audit.setCommitStaffImg(staff.getHeadImg());
            audit.setCommitStoreId(storeId);
            audit.setCommitStoreName(store.getStoreName());
            audit.setAuditStatus(AuditStatus.NOT_NEED_AUDIT.getCode());
            audit.setWxEnterpriseId(wxEnterpriseId);
            audit.setEnterpriseId(store.getEnterpriseId());
            audit.setStatusFlag(1);
            audit.setAuditName(commitName);

            JSONObject json = new JSONObject();
            json.put("clerkCode", clerkCode);
            json.put("clerkName", staffName);
            json.put("headPic", staff.getHeadImg());
            json.put("sex", sex);
            json.put("postion", postion);
            json.put("phoneNumber", phoneNumber);
            json.put("nationcode", nationcode);

            audit.setOldValue(json.toJSONString());
            audit.setCommitTime(new Date());
            audit.setAuditType(AuditType.CLERK_ADD.getCode());
            audit.setRelatedId(clerkCode);
            auditApiService.insert(audit);
        }
        // 只新增gic那边的，不新增好办这边
        boolean flag = syncHaobanToGicApiService.syncClerkToGicClerkAdd(storeId, clerkCode, sex, staffName, phoneNumber,
                nationcode, postion);
        if (!flag) {
            return resultResponse(HaoBanErrCode.ERR_10010);
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    // 删除店员
    @HttpLimit
    @RequestMapping("/staff-del")
    public HaobanResponse staffDel(String wxEnterpriseId, String storeId, String clerkIds, String staffId) {
        if (StringUtils.isAnyBlank(clerkIds)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        com.gic.enterprise.api.dto.StoreDTO store = storeService.getStoreByIdNoStatus(storeId);
        // 校验手机是否唯一
        if (store == null) {
            return resultResponse(HaoBanErrCode.ERR_400001);
        }
        AuditSettingDTO dto = auditSettingApiService.findSettingByWxEnterpriseId(wxEnterpriseId);
        if (dto.getClerkChangeFlag() == 1) {
            // 需要审核
            String[] clerkIdArr = clerkIds.split(",");
            for (String clerkId : clerkIdArr) {
                AuditDTO auditDTO = auditApiService.findByBindRelatedIdAndAuditType(clerkId,
                        AuditType.CLERK_DEL.getCode(), wxEnterpriseId, store.getEnterpriseId());
                if (auditDTO != null) {
                    logger.info("已经存在了审核记录，待审核{}", clerkId);
                    continue;
                }
                ClerkDTO clerkDTO = clerkService.getClerkByClerkId(clerkId);
                if (clerkDTO == null) {
                    logger.info("导购不存在", clerkId);
                    continue;
                }
                StaffDTO staff = staffApiService.selectById(staffId);
                AuditDTO audit = new AuditDTO();
                audit.setCommitStaffName(staff.getStaffName());
                audit.setCommitStaffId(staffId);
                audit.setCommitStaffImg(staff.getHeadImg());
                audit.setCommitStoreId(storeId);
                audit.setCommitStoreName(store.getStoreName());
                audit.setAuditStatus(AuditStatus.NO_AUDIT.getCode());
                audit.setWxEnterpriseId(wxEnterpriseId);
                audit.setEnterpriseId(store.getEnterpriseId());
                audit.setStatusFlag(1);
                audit.setRelatedId(clerkId);

                JSONObject json = new JSONObject();
                json.put("clerkId", clerkId);
                json.put("clerkCode", clerkDTO.getClerkCode());
                json.put("clerkName", clerkDTO.getClerkName());
                json.put("headPic", staff.getHeadImg());

                audit.setOldValue(json.toJSONString());
                audit.setCommitTime(new Date());
                audit.setAuditType(AuditType.CLERK_DEL.getCode());
                auditApiService.insert(audit);
            }
        } else {
            // 无需审核
            String[] clerkIdArr = clerkIds.split(",");
            for (String clerkId : clerkIdArr) {
                ClerkDTO clerkDTO = clerkService.getClerkByClerkId(clerkId);
                if (clerkDTO == null) {
                    logger.info("导购不存在：{}", clerkId);
                    continue;
                }
                if (distributeApiService.getClerkMemberCount(clerkDTO.getEnterpriseId(), clerkId, storeId) == 0) {
                    if (clerkDTO.getClerkType() == 1) {
                        logger.info("店长不能删除：{}", clerkId);
                        continue;
                    }
                }
                StaffDTO staff = staffApiService.selectById(staffId);
                AuditDTO audit = new AuditDTO();
                audit.setCommitStaffName(staff.getStaffName());
                audit.setCommitStaffId(staffId);
                audit.setCommitStaffImg(staff.getHeadImg());
                audit.setCommitStoreId(storeId);
                audit.setCommitStoreName(store.getStoreName());
                audit.setAuditStatus(AuditStatus.NOT_NEED_AUDIT.getCode());
                audit.setWxEnterpriseId(wxEnterpriseId);
                audit.setEnterpriseId(store.getEnterpriseId());
                audit.setStatusFlag(1);
                audit.setRelatedId(clerkId);
                audit.setAuditName(staff.getStaffName());

                JSONObject json = new JSONObject();
                json.put("clerkId", clerkId);
                json.put("clerkCode", clerkDTO.getClerkCode());
                json.put("clerkName", clerkDTO.getClerkName());
                json.put("headPic", staff.getHeadImg());
                audit.setOldValue(json.toJSONString());
                audit.setCommitTime(new Date());
                audit.setAuditType(AuditType.CLERK_DEL.getCode());
                auditApiService.insert(audit);

                syncHaobanToGicApiService.delGicClerk(clerkId);
            }
        }

        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 删除设置主门店和刷新微信好友的缓存限制
     *
     * @param staffId  : 关联标识
     * @param dateTime : 时间, 13位时间戳
     * @param type     : 类型, 1 : 主门店, 2 : 刷新微信好友
     */
    @RequestMapping("/delCache")
    public void deleteCache(String staffId, Long dateTime, Integer type) {
        if (StringUtils.isBlank(staffId) || dateTime == null || type == null) {
            return;
        }
        String yyyyMM = DateUtil.dateToStr(new Date(dateTime), "yyyyMMdd");
        String key = null;
        // 设置主门店缓存
        if (Objects.equals(type, 1)) {
            int i = cn.hutool.core.date.DateUtil.weekOfYear(new Date());
            key = "haoban_set_main_store_" + i + ":" + staffId;
        }
        if (Objects.equals(type, 2)) {
            key = "haoban_fresh_wx_friend" + yyyyMM + staffId;
        }
        if (StringUtils.isBlank(key)) {
            return;
        }
        RedisUtil.delCache(key);
    }

    // 设置主导购
    @HttpLimit
    @RequestMapping("/set-main-store")
    public HaobanResponse setMainStore(String staffId, String storeId, String wxEnterpriseId, String dateStr) {
        StaffDTO staff = staffApiService.selectById(staffId);
        Date curDate = new Date();
        if (staff == null) {
            return resultResponse(HaoBanErrCode.ERR_10006);
        }
        // 给测试使用
        if (StringUtils.isNotBlank(dateStr)) {
            curDate = cn.hutool.core.date.DateUtil.parse(dateStr);
        }
        int i = cn.hutool.core.date.DateUtil.weekOfYear(curDate);
        String key = "haoban_set_main_store_" + i + ":" + staffId;
        Object hasSet = RedisUtil.getCache(key);
        if (hasSet == null) {
            RedisUtil.setCache(key, true, 7 * 24 * 60 * 60L);
            clerkMainStoreRelatedApiService.setMainStore(staffId, storeId, wxEnterpriseId);
        } else {
            return resultResponse(HaoBanErrCode.ERR_10031);
        }
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    // 设置主导购
    @HttpLimit
    @RequestMapping("/check-main-store")
    public HaobanResponse checkMainStore(String staffId, String storeId, String wxEnterpriseId, String dateStr) {
        Date curDate = new Date();
        int i = cn.hutool.core.date.DateUtil.weekOfYear(curDate);
        String key = "haoban_set_main_store_" + i + ":" + staffId;
        Object hasSet = RedisUtil.getCache(key);
        if (hasSet == null) {
            // 可修改
            return resultResponse(HaoBanErrCode.ERR_1, 1);
        } else {
            // 不可以设置
            return resultResponse(HaoBanErrCode.ERR_1, 0);
        }
    }

    // 刷新微信好友
    @RequestMapping("/fresh-wx-friend")
    public HaobanResponse freshWxFrend(String staffId, String storeId, String wxEnterpriseId,
            String staffDepartmentRelatedId, @RequestParam(defaultValue = "0") Integer flushType) {
        StaffDTO staff = staffApiService.selectById(staffId);
        String yyyyMM = DateUtil.dateToStr(new Date(), "yyyyMMdd");
        if (staff == null) {
            return resultResponse(HaoBanErrCode.ERR_10006);
        }
        String key = "haoban_fresh_wx_friend" + yyyyMM + staffId;
        Integer count = RedisUtil.getCache(key) == null ? 0 : (Integer) RedisUtil.getCache(key);
        if (count != null && count > 0) {
            logger.info("次数超出限制：{}", staffId);
            return resultResponse(HaoBanErrCode.ERR_10011);
        }
        if (flushType == 0) {
            String taskName = "刷新企业微信好友（" + staff.getStaffName() + "）";
            String taskId = dealSyncOperationApiService.createWxFriendTaskSingle(wxEnterpriseId, taskName, staffId,
                    staff.getStaffName(), SyncTaskTypeEnum.FRIEND_SINGLE.getType());
            if (StringUtils.isNotBlank(taskId)) {
                dealSyncOperationApiService.dealWxFriendClerkSingle(taskId, staffId, staffId, wxEnterpriseId);
            } else {
                return resultResponse(HaoBanErrCode.ERR_10022);
            }
        } else {
            String taskName = "刷新门店好友";
            String taskId = dealSyncOperationApiService.createWxFriendTaskSingle(wxEnterpriseId, taskName, staffId,
                    staff.getStaffName(), SyncTaskTypeEnum.FRIEND_STORE.getType());
            if (StringUtils.isNotBlank(taskId)) {
                dealSyncOperationApiService.dealWxFriendStore(taskId, storeId, wxEnterpriseId);
            } else {
                return resultResponse(HaoBanErrCode.ERR_10022);
            }
        }
        RedisUtil.setCache(key, 1, 31 * 24 * 60 * 60L);
        // 刷新状态变更
        clerkMainStoreRelatedApiService.setFreshFriend(wxEnterpriseId, staffId);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 刷新好友状态
     *
     * @param staffId
     * @param storeId
     * @param wxEnterpriseId
     * @return
     */
    @HttpLimit
    @RequestMapping("/check-fresh-friend")
    public HaobanResponse checkFreshFriend(String staffId, String storeId, String wxEnterpriseId, String version) {
        boolean freshFriendSyncTask = dealSyncOperationApiService.getFreshFriendSyncTask(wxEnterpriseId, staffId);
        return resultResponse(HaoBanErrCode.ERR_1, freshFriendSyncTask);
    }

    /**
     * 刷新好友状态
     *
     * @param staffId
     * @param storeId
     * @param wxEnterpriseId
     * @return
     */
    @HttpLimit
    @RequestMapping("/fresh-friend-count")
    public HaobanResponse checkFreshFriend(String staffId, String storeId, String wxEnterpriseId) {
        String yyyyMM = DateUtil.dateToStr(new Date(), "yyyyMMdd");
        String key = "haoban_fresh_wx_friend" + yyyyMM + staffId;
        // 1代表能刷新 0 不能刷新
        Integer count = RedisUtil.getCache(key) == null ? 1 : 0;
        return resultResponse(HaoBanErrCode.ERR_1, count);
    }

    // 精确查，根据手机号或者code，查找
    @RequestMapping("query-clerk-list-by-code")
    public HaobanResponse queryClerkListByCode(String keyword, String wxEnterpriseId, String staffId,
            Integer manageFlag) {
        if (StringUtils.isAnyBlank(staffId, wxEnterpriseId, keyword)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        if (manageFlag == null) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        if ("-1".equals(staffId)) {
            return resultResponse(HaoBanErrCode.ERR_400022);
        }
        List<EnterpriseDetailDTO> list = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(wxEnterpriseId);
        if (list == null || list.isEmpty()) {
            return resultResponse(HaoBanErrCode.ERR_1);
        }
        List<String> enterpriseIdList = list.stream().filter(s -> {
            boolean over = wxEnterpriseApiService.haobanIsStop(s.getEnterpriseId());
            return !over;
        }).map(EnterpriseDetailDTO::getEnterpriseId).collect(Collectors.toList());
        List<String> storeIds = wxEnterpriseRelatedApiService.listStoreIdByWxEnterpriseId(wxEnterpriseId);
        if (CollectionUtils.isEmpty(storeIds)) {
            return resultResponse(HaoBanErrCode.ERR_1, new ArrayList<>());
        }
        logger.info("查询到企微门店数={},{}", storeIds.size(), storeIds);
        List<ClerkDTO> clerkList = new ArrayList<>();
        if (manageFlag == -1) {
            clerkList.addAll(clerkService.listClerkEnableHaoban(enterpriseIdList, keyword));
            clerkList.addAll(
                    clerkNewService.listClerkByEnterpriseIdAndSearchAndClerkType(enterpriseIdList, storeIds, keyword));
        } else if (manageFlag == 1) {
            clerkList.addAll(clerkService.listClerkEnableHaoban(enterpriseIdList, keyword));
        } else {
            clerkList.addAll(
                    clerkNewService.listClerkByEnterpriseIdAndSearchAndClerkType(enterpriseIdList, storeIds, keyword));
        }
        List<ClerkStoreVO> clerkStoreList = buildClerkRelation(clerkList, enterpriseIdList, wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1, clerkStoreList);
    }

    /**
     * 未关联导购列表
     *
     * @param wxEnterpriseId
     * @param staffId
     * @return
     */
    @RequestMapping("query-unbind-clerk-list")
    @IgnoreLogin
    public HaobanResponse queryUnbindClerkList(String wxEnterpriseId, String staffId) {
        if (StringUtils.isAnyBlank(staffId, wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        List<EnterpriseDetailDTO> list = wxEnterpriseRelatedApiService.listEnterpriseByWxEnterpriseId(wxEnterpriseId);
        if (CollectionUtils.isEmpty(list)) {
            return resultResponse(HaoBanErrCode.ERR_1);
        }
        List<String> enterpriseIdList = list.stream().filter(s -> {
            boolean over = wxEnterpriseApiService.haobanIsStop(s.getEnterpriseId());
            return !over;
        }).map(s -> s.getEnterpriseId()).collect(Collectors.toList());
        List<String> storeIds = wxEnterpriseRelatedApiService.listStoreIdByWxEnterpriseId(wxEnterpriseId);
        List<ClerkDTO> clerkList = this.getUnbindClerkList(enterpriseIdList, storeIds, staffId);
        List<ClerkStoreVO> clerkStoreList = buildClerkRelation(clerkList, enterpriseIdList, wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1, clerkStoreList);
    }

    /**
     * 组装关联导购的显示信息 view
     *
     * @param clerkList
     * @param enterpriseIdList
     * @return
     */
    private List<ClerkStoreVO> buildClerkRelation(List<ClerkDTO> clerkList, List<String> enterpriseIdList,
            String wxEnterpriseId) {
        List<ClerkStoreVO> clerkStoreList = new ArrayList<>();
        if (CollectionUtil.isEmpty(clerkList)) {
            return clerkStoreList;
        }
        List<EnterpriseDTO> enterpriselist = enterpriseService.listEnterpriseByIds(enterpriseIdList);
        Map<String, EnterpriseDTO> map = com.gic.commons.util.CollectionUtil.toMap(enterpriselist, "enterpriseId");
        List<String> clerkIds = clerkList.stream().map(s -> s.getClerkId()).collect(Collectors.toList());
        List<StaffClerkRelationDTO> clerkRelations = staffClerkRelationApiService.listByClerkIds(clerkIds);
        Map<String, StaffClerkRelationDTO> clerkBindMap = com.gic.commons.util.CollectionUtil.toMap(clerkRelations,
                "clerkId");

        for (ClerkDTO clerk : clerkList) {
            String enterpriseId = clerk.getEnterpriseId();
            EnterpriseDTO enterpriseDTO = map.get(enterpriseId);
            String clerkId = clerk.getClerkId();
            StaffClerkRelationDTO staffClerkRelationDTO = clerkBindMap.get(clerkId);
            Integer clerkType = clerk.getClerkType();
            ClerkStoreVO vo = new ClerkStoreVO();
            vo.setClerkId(clerkId);
            vo.setClerkCode(clerk.getClerkCode());
            vo.setClerkName(clerk.getClerkName());
            vo.setClerkType(clerkType);
            vo.setEnterpriseName(enterpriseDTO == null ? "" : enterpriseDTO.getEnterpriseName());
            vo.setHeadImg(clerk.getHeadImgUrl());
            vo.setPhoneNumber(clerk.getPhoneNumber());
            vo.setNationCode(clerk.getNationcode());
            StoreDTO store = storeService.getStore(clerk.getStoreId());
            vo.setStoreName(store == null ? "" : store.getStoreName());
            vo.setStoreAddress(store == null ? "" : store.getStoreAddress());
            vo.setBindFlag(staffClerkRelationDTO == null ? 0 : 1);
            vo.setStaffId(staffClerkRelationDTO == null ? "" : staffClerkRelationDTO.getStaffId());
            vo.setStoreId(clerk.getStoreId());
            // 区经
            if (clerkType == 2) {
                vo.setManageFlag(1);
                vo.setManageStoreCount(
                        staffApiService.getCountHaoBanStoreIdsByClerkId(clerkId, wxEnterpriseId).getStoreCount());
            } else {
                vo.setManageFlag(0);
                vo.setManageStoreCount(0);
            }
            clerkStoreList.add(vo);
        }
        return clerkStoreList;
    }

    /**
     * 未绑定导购列表
     *
     * @param enterpriseIdList
     * @param storeIdList
     * @param staffId
     * @return
     */
    private List<ClerkDTO> getUnbindClerkList(List<String> enterpriseIdList, List<String> storeIdList, String staffId) {
        List<ClerkDTO> ret = new ArrayList<>();
        StaffDTO staffDTO = staffApiService.selectById(staffId);
        if (staffDTO != null) {
            String phoneNumber = staffDTO.getPhoneNumber();
            if (StringUtils.isBlank(phoneNumber)) {
                logger.error("成员表手机号为空,不进行查询,staffId：{}", staffId);
                return ret;
            }
            List<ClerkDTO> clerkList = clerkNewService.listClerkByEnterpriseIdAndSearchAndClerkType(enterpriseIdList,
                    storeIdList, phoneNumber);
            if (CollectionUtils.isNotEmpty(clerkList)) {
                ret.addAll(clerkList);
            }
        }

        List<StaffClerkInfoDTO> staffClerkInfoDTOS = staffClerkRelationApiService.listBindDetailByStaffId(staffId);
        if (CollectionUtils.isEmpty(staffClerkInfoDTOS)) {
            return ret;
        }
        Set<String> clerkIds = staffClerkInfoDTOS.stream().map(mid -> mid.getClerkId()).collect(Collectors.toSet());
        List<ClerkDTO> clerkDTOS = clerkService.getClerkByClerkIds(clerkIds);

        for (ClerkDTO clerkDTO : clerkDTOS) {
            if (StringUtils.isEmpty(clerkDTO.getPhoneNumber())) {
                continue;
            }
            List<ClerkDTO> clerkList = clerkNewService.listClerkByEnterpriseIdAndSearchAndClerkType(enterpriseIdList,
                    storeIdList, clerkDTO.getPhoneNumber());
            if (CollectionUtils.isNotEmpty(clerkList)) {
                ret.addAll(clerkList);
            }
        }
        if (CollectionUtils.isEmpty(clerkDTOS)) {
            return ret;
        }
        return ret.stream().filter(mid -> (!clerkIds.contains(mid.getClerkId())))
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(n -> n.getClerkId()))),
                        ArrayList::new));
    }

    /**
     * 绑定好办
     *
     * @param clerkId
     * @param staffId
     * @param auditType
     * @param manageFlag
     * @return
     */
    @HttpLimit
    @RequestMapping("bind-staff")
    public HaobanResponse bindStaff(String clerkId, String staffId, Integer auditType, Integer manageFlag,
            String wxEnterpriseId) {
        if (StringUtils.isAnyBlank(clerkId, staffId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        if (auditType == null) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        ClerkDTO clerk = clerkService.getclerkById(clerkId);
        if (clerk == null) {
            return resultResponse(HaoBanErrCode.ERR_10016);
        }
        StaffDTO staff = staffApiService.selectById(staffId);
        if (staff == null) {
            return resultResponse(HaoBanErrCode.ERR_10006);
        }
        AuditDTO auditDTO = auditApiService.findByBindRelatedIdAndAuditType(clerkId, AuditType.CLERK_BIND.getCode(),
                wxEnterpriseId, clerk.getEnterpriseId());
        if (auditDTO != null) {
            // 验证码登录不需要管理员审核，需要删除该记录
            if(auditType == 2){
                auditDTO.setStatusFlag(0);
                auditApiService.update(auditDTO);
            }else {
                return resultResponse(HaoBanErrCode.ERR_10018);
            }
        }
        String storeId = "";
        String storeName = "";
        if (manageFlag != null && manageFlag == 1) {
            // 区经无门店
        } else {
            storeId = clerk.getStoreId();
            StaffClerkRelationDTO haveClerkCode = staffClerkRelationApiService.getOneByStoreIdAndStaffId(storeId,
                    staffId);
            if (haveClerkCode != null) {
                return resultResponse(HaoBanErrCode.ERR_10020);
            }
            StoreDTO store = storeService.getStore(clerk.getStoreId());
            if (store != null) {
                storeName = store.getStoreName();
            }
        }

        String clerkCode = clerk.getClerkCode();
        String enterpriseId = clerk.getEnterpriseId();
        String wxUserId = staff.getWxUserId();
        //统一替换导购code
        StaffClerkRelationDTO staffClerkRelation = staffClerkRelationApiService.getByCodeAndEnterpriseId(clerkId,
                enterpriseId);

        if (auditType == 2) {
            // 无需审核
            if (staffClerkRelation == null) {
                staffClerkRelation = new StaffClerkRelationDTO();
            }
            staffClerkRelation.setClerkId(clerkId);
            staffClerkRelation.setClerkCode(clerkCode);
            staffClerkRelation.setStoreId(storeId);
            staffClerkRelation.setEnterpriseId(clerk.getEnterpriseId());
            staffClerkRelation.setWxEnterpriseId(wxEnterpriseId);
            staffClerkRelation.setStaffId(staffId);
            staffClerkRelation.setManageFlag(manageFlag);

            ServiceResponse serviceResponse = staffClerkRelationApiService.wxBindStaffClerk(staffClerkRelation, staffId,
                    ChannelCodeEnum.SELF_BIND.getCode());
            if (!serviceResponse.isSuccess()) {
                return resultResponse(HaoBanErrCode.ERR_DEFINE, serviceResponse.getMessage(), null,
                        serviceResponse.getMessage());
            }

            // 无需审核
            AuditDTO audit = new AuditDTO();
            audit.setCommitStaffName(staff.getStaffName());
            audit.setCommitStaffId(staffId);
            audit.setCommitStaffImg(staff.getHeadImg());
            audit.setCommitStoreId(storeId);
            audit.setCommitStoreName(storeName);
            audit.setAuditStatus(AuditStatus.NOT_NEED_AUDIT.getCode());
            audit.setWxEnterpriseId(wxEnterpriseId);
            audit.setEnterpriseId(enterpriseId);
            audit.setStatusFlag(1);
            audit.setRelatedId(clerkId);
            audit.setAuditName(staff.getStaffName());

            JSONObject json = new JSONObject();
            json.put("clerkId", clerkId);
            json.put("clerkCode", clerkCode);
            json.put("clerkName", clerk.getClerkName());
            json.put("staffName", staff.getStaffName());
            json.put("staffId", staffId);
            json.put("wxUserId", wxUserId);
            json.put("headPic", staff.getHeadImg());
            audit.setOldValue(json.toJSONString());
            audit.setCommitTime(new Date());
            audit.setAuditType(2);
            auditApiService.insert(audit);
            //统一替换导购code
            StaffClerkRelationDTO resultDTO = staffClerkRelationApiService.getByCodeAndEnterpriseId(clerkId,
                    clerk.getEnterpriseId());
            return resultResponse(HaoBanErrCode.ERR_1, resultDTO);
        } else {
            // 需要审核
            AuditDTO audit = new AuditDTO();
            audit.setCommitStaffName(staff.getStaffName());
            audit.setCommitStaffId(staffId);
            audit.setCommitStaffImg(staff.getHeadImg());
            audit.setCommitStoreId(storeId);
            audit.setCommitStoreName(storeName);
            audit.setAuditStatus(0);
            audit.setWxEnterpriseId(wxEnterpriseId);
            audit.setEnterpriseId(enterpriseId);
            audit.setStatusFlag(1);
            audit.setRelatedId(clerkId);

            JSONObject json = new JSONObject();
            json.put("clerkId", clerkId);
            json.put("clerkCode", clerkCode);
            json.put("clerkName", clerk.getClerkName());
            json.put("staffName", staff.getStaffName());
            json.put("staffId", staffId);
            json.put("wxUserId", wxUserId);
            json.put("headPic", staff.getHeadImg());
            audit.setOldValue(json.toJSONString());
            audit.setCommitTime(new Date());
            audit.setAuditType(2);
            auditApiService.insert(audit);

            ClerkDTO gicClerk = clerkService.getClerkLeaderByStoreId(storeId);
            if (gicClerk == null) {
                logger.info("无需发送消息");
                return resultResponse(HaoBanErrCode.ERR_1);
            }
            Map<String, String> fieldMap = new HashMap<String, String>();
            fieldMap.put("staffName", staff.getStaffName());
            fieldMap.put("clerkName", clerk.getClerkName());
            fieldMap.put("clerkCode", clerk.getClerkCode());

            JSONObject jsonObject = new JSONObject();
            jsonObject.put("storeId", storeId);

            NoticeMessageUtil.sendNoticeMessage(clerk.getEnterpriseId(), gicClerk.getClerkId(),
                    NoticeMessageTypeEnum.STORE_ACCOUNT.getType(), null, fieldMap, jsonObject);

            return resultResponse(HaoBanErrCode.ERR_1);
        }
    }

    // 解绑
    @RequestMapping("unbind-staff")
    public HaobanResponse unBindStaff(String wxEnterpriseId, String clerkId, String clerkCode, String staffId,
            String storeId, String enterpriseId, Integer manageFlag) {
        logger.info("解绑 操作人：{}，备操作人：{},操作门店：{}", staffId, clerkId, storeId);
        if (StringUtils.isAnyBlank(clerkId, clerkCode, staffId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        ClerkDTO clerk = clerkService.getclerkById(clerkId);
        if (clerk == null) {
            return resultResponse(HaoBanErrCode.ERR_10016);
        }
        StaffDTO staff = staffApiService.selectById(staffId);
        if (staff == null) {
            return resultResponse(HaoBanErrCode.ERR_10006);
        }
        //统一替换导购code
        StaffClerkRelationDTO staffClerkRelation = staffClerkRelationApiService.getByCodeAndEnterpriseId(clerkId,
                enterpriseId);
        if (staffClerkRelation == null) {
            return resultResponse(HaoBanErrCode.ERR_111145);
        }
        staffClerkRelationApiService.unbindByStaffAndClerkId(staffId, clerkId, ChannelCodeEnum.SELF_UNBIND.getCode(),
                wxEnterpriseId);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 门店导购列表
     *
     * @param storeId
     * @param enterpriseId
     * @return
     */
    @RequestMapping("store-clerk-list")
    public HaobanResponse storeClerkList(String storeId, String enterpriseId, String wxEnterpriseId) {
        List<ClerkDTO> list = clerkService.listClerkByNameOrCode(enterpriseId, null,
                Collections.singletonList(storeId));
        if (CollectionUtils.isEmpty(list)) {
            return resultResponse(HaoBanErrCode.ERR_10016);
        }
        //统一处理：导购code替换为导购id
        Set<String> clerkCodeList = list.stream().map(ClerkDTO::getClerkId).collect(Collectors.toSet());
        List<StaffClerkRelationDTO> bindRelationList = staffClerkRelationApiService.listBindCode(wxEnterpriseId,
                enterpriseId, clerkCodeList);
        Map<String, StaffClerkRelationDTO> bindCodeMap = bindRelationList.stream()
                .collect(Collectors.toMap(StaffClerkRelationDTO::getClerkId, s -> s));
        List<BindClerkVO> bindList = new ArrayList<>();
        List<BindClerkVO> unBindList = new ArrayList<>();
        for (ClerkDTO dto : list) {
            BindClerkVO vo = EntityUtil.changeEntityNew(BindClerkVO.class, dto);
            if (bindCodeMap.containsKey(dto.getClerkId())) {
                String staffId = bindCodeMap.get(dto.getClerkId()).getStaffId();
                StaffDTO staffDTO = staffApiService.selectById(staffId);
                vo.setStaffId(staffId);
                String phoneNumber = dto.getPhoneNumber();
                if (StringUtils.isNotBlank(phoneNumber)) {
                    vo.setPhoneNumber(phoneNumber);
                    if (StringUtils.isNotBlank(dto.getNationcode())) {
                        vo.setNationCode(dto.getNationcode());
                    }
                } else {
                    vo.setPhoneNumber("");
                    vo.setNationCode("");
                }
                vo.setStaffName(staffDTO == null ? "" : staffDTO.getStaffName());
                bindList.add(vo);
            } else {
                unBindList.add(vo);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("bindList", bindList);
        map.put("unBindList", unBindList);
        return resultResponse(HaoBanErrCode.ERR_1, map);
    }

    /**
     * 查询区经列表
     *
     * @param enterpriseId
     * @return
     */
    @RequestMapping("clerk-manage-list")
    public RestResponse clerkManageList(String enterpriseId, String wxEnterpriseId) {
        List<ClerkDTO> list = clerkService.listClerkEnableHaoban(Collections.singletonList(enterpriseId), null);
        if (CollectionUtils.isEmpty(list)) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_10016.getCode()),
                    HaoBanErrCode.ERR_10016.getMsg());
        }
        //统一处理：导购code替换为导购id
        Set<String> clerkCodeList = list.stream().map(ClerkDTO::getClerkId).collect(Collectors.toSet());
        List<StaffClerkRelationDTO> bindRelationList = staffClerkRelationApiService.listBindCode(wxEnterpriseId,
                enterpriseId, clerkCodeList);
        Map<String, StaffClerkRelationDTO> bindCodeMap = bindRelationList.stream()
                .collect(Collectors.toMap(StaffClerkRelationDTO::getClerkId, s -> s));
        List<BindClerkVO> bindList = new ArrayList<>();
        List<BindClerkVO> unBindList = new ArrayList<>();
        for (ClerkDTO dto : list) {
            BindClerkVO vo = EntityUtil.changeEntityByJSON(BindClerkVO.class, dto);
            if (bindCodeMap.containsKey(dto.getClerkId())) {
                String staffId = bindCodeMap.get(dto.getClerkId()).getStaffId();
                StaffDTO staffDTO = staffApiService.selectById(staffId);
                vo.setStaffId(staffId);
                vo.setNationCode(dto.getNationcode());
                vo.setPhoneNumber(dto.getPhoneNumber());
                vo.setStaffName(staffDTO == null ? "" : staffDTO.getStaffName());
                bindList.add(vo);
            } else {
                unBindList.add(vo);
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("bindList", bindList);
        map.put("unBindList", unBindList);
        return RestResponse.successResult(map);
    }

    /**
     * 门店列表
     *
     * @param staffId
     * @param wxEnterpriseId
     * @return
     */
    @RequestMapping("staff-store-list")
    public HaobanResponse staffStoreList(String staffId, String wxEnterpriseId) {
        if (StringUtils.isAnyBlank(staffId, wxEnterpriseId)) {
            return resultResponse(HaoBanErrCode.ERR_2);
        }
        List<StaffStoreVO> list = new ArrayList<>();
        List<EnterpriseDetailDTO> enterpriseList = wxEnterpriseRelatedApiService
                .listEnterpriseByWxEnterpriseId(wxEnterpriseId);
        List<String> enterpriseIdList = enterpriseList.stream().map(EnterpriseDetailDTO::getEnterpriseId)
                .collect(Collectors.toList());
        List<StaffClerkRelationDTO> bindRelationList = staffClerkRelationApiService
                .listBindCodeByStaffId(enterpriseIdList, staffId);
        // 主门店
        ClerkMainStoreRelatedDTO mainDTO = clerkMainStoreRelatedApiService.getWxEnterpriseIdAndStaffId(wxEnterpriseId,
                staffId);
        String storeId = mainDTO == null ? "" : mainDTO.getStoreId();
        for (StaffClerkRelationDTO staffClerkRelationDTO : bindRelationList) {
            //统一根据导购id查询
            ClerkDTO clerk = clerkService.getClerkByClerkId(staffClerkRelationDTO.getClerkId());
            if (clerk != null) {
                StoreDTO store = storeService.getStore(clerk.getStoreId());
                // 主门店标志
                int mainStoreFlag = 0;
                if (StringUtils.isEmpty(storeId)) {
                    mainStoreFlag = 0;
                } else if (storeId.equals(store.getStoreId())) {
                    mainStoreFlag = 1;
                }
                staffDepartmentRelatedApiService.listByStaffId(staffId);
                StaffStoreVO vo = new StaffStoreVO();
                vo.setClerkCode(clerk.getClerkCode());
                vo.setClerkId(clerk.getClerkId());
                vo.setClerkType(clerk.getClerkType());
                vo.setEnterpriseId(clerk.getEnterpriseId());
                vo.setMainStoreFlag(mainStoreFlag);
                vo.setPhoneNumber(clerk.getPhoneNumber());
                vo.setStaffId(staffId);
                vo.setStoreId(clerk.getStoreId());
                vo.setStoreImg(store.getStoreImage());
                vo.setStoreName(store.getStoreName());
                vo.setWxEnterpriseId(wxEnterpriseId);
                vo.setBindFlag(1);
                list.add(vo);
            }
        }
        return resultResponse(HaoBanErrCode.ERR_1, list);

    }

    /**
     * 刷新导购信息
     *
     * @param clerkId
     * @return
     */
    @RequestMapping("/fresh-clerk-info")
    public HaobanResponse freshClerkInfo(String clerkId) {
        StaffClerkRelationDTO staffRelation = staffClerkRelationApiService.getByClerkId(clerkId);
        if (staffRelation == null) {
            return resultResponse(HaoBanErrCode.ERR_10006);
        }
        String staffId = staffRelation.getStaffId();
        StaffDTO staff = staffApiService.selectById(staffId);
        if (staff == null) {
            return resultResponse(HaoBanErrCode.ERR_10006);
        }
        String headPic = staff.getHeadImg();
        String phoneNumber = staff.getPhoneNumber();
        String nationCode = staff.getNationCode();
        Integer sex = staff.getSex();

        ClerkDTO clerk = clerkService.getClerkByClerkId(clerkId);
        if (clerk == null) {
            return resultResponse(HaoBanErrCode.ERR_10006);
        }
        if (StringUtils.isNotBlank(headPic)) {
            clerk.setHeadImgUrl(headPic);
            clerk.setImageUrl(headPic);
        }
        if (StringUtils.isNotBlank(phoneNumber)) {
            List<ClerkListDTO> list = clerkService.getClerkByStoreId(clerk.getEnterpriseId(), clerk.getStoreId());
            for (ClerkListDTO clerkListDTO : list) {
                if (clerkListDTO.getPhoneNumber().equals(phoneNumber) && !clerkListDTO.getClerkId().equals(clerkId)) {
                    return resultResponse(HaoBanErrCode.ERR_11122);
                }
            }
            clerk.setPhoneNumber(phoneNumber);
        }
        if (StringUtils.isNotBlank(nationCode)) {
            clerk.setNationcode(nationCode);
        }
        if (sex != null) {
            clerk.setClerkGender(sex.toString());
        }
        clerkService.updateClerk(clerk);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 导购详情
     *
     * @param clerkId
     * @return
     */
    @RequestMapping("/clerk-detail")
    public HaobanResponse clerkDetail(String clerkId) {
        if (StringUtils.isBlank(clerkId)) {
            return resultResponse(HaoBanErrCode.ERR_5);
        }
        ClerkDTO clerk = clerkService.getClerkByClerkId(clerkId);
        if (clerk == null) {
            return resultResponse(HaoBanErrCode.ERR_10006);
        }
        return resultResponse(HaoBanErrCode.ERR_1, EntityUtil.changeEntityByJSON(ClerkDetailVo.class, clerk));
    }

    /**
     * 更新导购
     *
     * @param clerkId
     * @param fieldType
     * @return
     */
    @RequestMapping("/save-clerk")
    public HaobanResponse clerkSave(String clerkId, String fieldValue, Integer fieldType) {
        if (StringUtils.isBlank(clerkId) || StringUtils.isBlank(fieldValue) || null == fieldType) {
            return resultResponse(HaoBanErrCode.ERR_5);
        }

        ClerkDTO clerk = clerkService.getClerkByClerkId(clerkId);
        if (clerk == null) {
            return resultResponse(HaoBanErrCode.ERR_10006);
        }
        if (fieldType == 0) {
            clerk.setClerkName(fieldValue);
        } else if (fieldType == 1) {
            clerk.setClerkGender(fieldValue);
        } else if (fieldType == 2) {
            String[] split = fieldValue.split("-");
            if (split.length == 2) {
                clerk.setPhoneNumber(split[1]);
                clerk.setNationcode(split[0]);
            } else {
                logger.info("手机号不争取：{}", fieldValue);
                return resultResponse(HaoBanErrCode.ERR_5);
            }
        } else if (fieldType == 3) {
            clerk.setHeadImgUrl(fieldValue);
        }
        String res = clerkService.updateClerk(clerk);
        if (StringUtils.isBlank(res)) {
            return resultResponse(HaoBanErrCode.ERR_1);
        }
        return resultResponse(HaoBanErrCode.ERR_0, res, null, res);
    }

    /**
     * 外部联系人需要发送的好友
     *
     * @param staffId
     * @param status
     * @param pageInfo
     * @return
     */
    @RequestMapping("external-friend-list")
    public HaobanResponse friendList(String staffId, Integer status, BasePageInfo pageInfo) {
        List<Integer> statusFlags = new ArrayList<>();
        if (status == null) {
            statusFlags.add(3);
            statusFlags.add(4);
        } else {
            statusFlags.add(status);
        }
        StaffDTO staff = staffApiService.selectById(staffId);
        Page<ExternalClerkRelatedDTO> page = externalClerkRelatedApiService.pageExternalClerk(staff.getWxEnterpriseId(),
                staffId, statusFlags, pageInfo);
        PageResult2 retPage = PageUtil.getPageInfo(page);
        return resultResponse(HaoBanErrCode.ERR_1, retPage);
    }

    /**
     * 会员小程序-外部联系人需要发送的好友
     *
     * @return
     */
    @IgnoreLogin
    @RequestMapping("push-friend")
    public HaobanResponse friendList(String relationKey) {
        externalClerkRelatedApiService.pushExternalByRelationKey(relationKey);
        return resultResponse(HaoBanErrCode.ERR_1);
    }

    /**
     * 我的-好友会员数
     *
     * @return
     */
    @RequestMapping("customer-info")
    @IgnoreLogin
    public RestResponse customerInfo(@RequestBody @Valid CommonQO qo) {
        CustomerFriendMemberVO ret = new CustomerFriendMemberVO();
        StaffDTO staffDTO = staffApiService.selectById(qo.getStaffId());
        if (staffDTO == null) {
            return RestResponse.failure(HaoBanErrCode.ERR_6.getCode() + "", HaoBanErrCode.ERR_6.getMsg());
        }
        int friendCount = externalClerkRelatedApiService.countFriendCountByClerkId(qo.getWxEnterpriseId(),
                qo.getEnterpriseId(), staffDTO.getStaffId(), qo.getClerkId());
        int memberCount = customerApiService.countMember(qo.getEnterpriseId(), qo.getStoreId(), qo.getClerkId());

        ret.setFriendCount(friendCount);
        ret.setMemberCount(memberCount);

        return RestResponse.successResult(ret);
    }

    /**
     * 我的-关联导购数量
     *
     * @return
     */
    @RequestMapping("can-relation-count")
    public RestResponse canRelationCount(@RequestBody @Valid CommonQO qo) {
        List<StaffClerkInfoDTO> staffClerkInfoDTOS = staffClerkRelationApiService
                .listBindDetailByStaffId(qo.getStaffId());
        if (CollectionUtils.isEmpty(staffClerkInfoDTOS)) {
            return RestResponse.successResult(0);
        }
        return RestResponse.successResult(staffClerkInfoDTOS.size());
    }

    /**
     * 好友数量
     *
     * @param clerkId
     * @return
     */
    @RequestMapping(value = "manage-store-count", method = RequestMethod.GET)
    public RestResponse<Integer> manageStoreCount(String clerkId) {
        return RestResponse.successResult(storeWidgetService.getClerkWidgetStore(clerkId));
    }

    /**
     * 根据员工id获取openId
     *
     * @return {@link RestResponse }
     * @author mozhu
     * @date 2021-12-29 10:42:24
     */
    @RequestMapping(value = "getOpenIdByStaffId", method = { RequestMethod.POST, RequestMethod.GET })
    public RestResponse<String> getOpenIdByStaffId(String staffId, String wxEnterpriseId) {
        StaffDTO staffDTO = staffApiService.selectById(staffId);
        if (staffDTO == null) {
            int code = HaoBanErrCode.ERR_6.getCode();
            return RestResponse.failure(String.valueOf(code), HaoBanErrCode.ERR_6.getMsg());
        }
        String wxOpenId = staffDTO.getWxOpenId();
        if (StringUtils.isNotBlank(wxOpenId)) {
            return RestResponse.successResult(wxOpenId);
        }
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseApiService.getQwInfo(wxEnterpriseId);
        if (qwDTO == null) {
            int code = HaoBanErrCode.ERR_400002.getCode();
            return RestResponse.failure(String.valueOf(code), HaoBanErrCode.ERR_400002.getMsg());
        }
        String wxUserId = staffDTO.getWxUserId();
        if (qwDTO.needOpenUserId3th()) {
            wxUserId = staffDTO.getWxOpenUseId();
        }
        String secret = config.getWxSuiteid();
        if (qwDTO.isSelf()) {
            secret = qwDTO.getSelfSecret();
        }
        String openid = qywxUserApiService.getSelfOpenIdByUserId(qwDTO.getThirdCorpid(), secret,
                wxUserId,qwDTO.isSelf(),qwDTO.getUrlHost());
        if (StringUtils.isBlank(openid)) {
            int code = HaoBanErrCode.ERR_600003.getCode();
            return RestResponse.failure(String.valueOf(code), HaoBanErrCode.ERR_600003.getMsg());
        }
        staffApiService.updateOpenIdByStaffId(staffId, openid);
        return RestResponse.successResult(openid);
    }

    /**
     * 根据角色查询菜单
     *
     * @return
     */
    @RequestMapping(value = "/queryMenuCodesByClerkType", method = RequestMethod.GET)
    public RestResponse<HaobanRoleDTO> queryMenuByClerkType(Integer clerkType, String staffId, String wxEnterpriseId) {
        if (clerkType == null) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_2.getCode()), HaoBanErrCode.ERR_2.getMsg());
        }
        if (clerkType == -1) {
            logger.info("导购类型为-1，游客获取系统级别的导购权限");
            // 游客获取系统级别的导购权限
            ServiceResponse<HaobanRoleDTO> serviceResponse = haobanRoleApiService
                    .getMenuByWxEnterpriseIdAndClerkType("-1", RoleClerkTypeEnum.CLERK.getCode(), 0);
            return RestResponse.successResult(serviceResponse.getResult());
        }
        if (StringUtils.isBlank(staffId) || "-1".equals(staffId)) {
            logger.info("未登录游客获取系统级别的导购权限");
            // 游客获取系统级别的导购权限
            ServiceResponse<HaobanRoleDTO> serviceResponse = haobanRoleApiService
                    .getMenuByWxEnterpriseIdAndClerkType("-1", RoleClerkTypeEnum.CLERK.getCode(), 0);
            return RestResponse.successResult(serviceResponse.getResult());
        }
        ServiceResponse<HaobanRoleDTO> serviceResponse = haobanRoleApiService
                .getMenuByWxEnterpriseIdAndClerkType(wxEnterpriseId, clerkType, 1);
        return RestResponse.successResult(serviceResponse.getResult());
    }

    /**
     * 获取导购管辖门店数量
     *
     * @param clerkId
     * @return
     */
    @RequestMapping(value = "/getCountHaoBanStoreIdsByClerkId", method = RequestMethod.GET)
    public RestResponse<StoreRoleVO> getCountHaoBanStoreIdsByClerkId(String clerkId, String wxEnterpriseId) {
        StoreRoleDTO storeRoleDTO = staffApiService.getCountHaoBanStoreIdsByClerkId(clerkId, wxEnterpriseId);
        StoreRoleVO storeRoleVO = new StoreRoleVO();
        storeRoleVO.setStoreCount(storeRoleDTO.getStoreCount());
        storeRoleVO.setStoreDTO(storeService.getStore(storeRoleDTO.getStoreId()));
        return RestResponse.successResult(storeRoleVO);
    }

    /**
     * 导购gic门店和好办企业门店交集
     *
     * @param clerkId
     * @return
     */
    @RequestMapping(value = "/getHaoBanStoreIdsRolesByClerkId", method = RequestMethod.GET)
    public RestResponse<List<String>> getHaoBanStoreIdsRolesByClerkId(String clerkId, String wxEnterpriseId) {
        List<String> storeIds = staffApiService.getHaoBanStoreIdsRolesByClerkId(clerkId, wxEnterpriseId);
        return RestResponse.successResult(storeIds);
    }

    /**
     * 绑定商户或者门店列表
     *
     * @return
     */
    @RequestMapping(value = "/getEnterpriseStoreListByStaffId", method = RequestMethod.GET)
    public RestResponse<List<StaffStoreVO>> getEnterpriseStoreListByStaffId(String staffId, String wxEnterpriseId,
            Integer manageFlag, String gicEnterpriseId) {
        if (manageFlag == null) {
            return RestResponse.failure(Convert.toStr(HaoBanErrCode.ERR_2.getCode()), HaoBanErrCode.ERR_2.getMsg());
        }
        List<StaffClerkRelationDTO> bindRelationList = new ArrayList<>();
        List<StaffStoreVO> list = new ArrayList<>();
        // 区经商户
        if (manageFlag == 1) {
            bindRelationList = staffClerkRelationApiService.listManageBindByStaffId(staffId);
            if (CollectionUtils.isEmpty(bindRelationList)) {
                logger.info("没有关联任何商户导购：{}", wxEnterpriseId);
                return RestResponse.successResult();
            }
            for (StaffClerkRelationDTO staffClerkRelationDTO : bindRelationList) {
                String clerkId = staffClerkRelationDTO.getClerkId();
                String enterpriseId = staffClerkRelationDTO.getEnterpriseId();
                ClerkDTO clerk = clerkService.getclerkById(clerkId);
                if (clerk == null) {
                    continue;
                }
                StaffDTO staffDTO = staffApiService.selectById(staffId);
                if (staffDTO == null) {
                    continue;
                }
                WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseApiService.getOne(wxEnterpriseId);
                if (wxEnterpriseDTO == null) {
                    continue;
                }
                EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(enterpriseId);
                if (enterpriseDTO == null) {
                    continue;
                }
                StaffStoreVO vo = new StaffStoreVO();
                vo.setClerkCode(clerk.getClerkCode());
                vo.setClerkId(clerk.getClerkId());
                vo.setClerkType(clerk.getClerkType());
                vo.setEnterpriseId(enterpriseId);
                vo.setPhoneNumber(clerk.getPhoneNumber());
                vo.setStaffId(staffId);
                vo.setWxEnterpriseId(wxEnterpriseId);
                vo.setClerkName(clerk.getClerkName());
                vo.setHeadImg(staffDTO.getHeadImg());
                vo.setBindFlag(1);
                vo.setEnterpriseName(enterpriseDTO.getBrandName());
                vo.setCorpName(wxEnterpriseDTO.getCorpName());
                vo.setEnterpriseImg(enterpriseDTO.getQcloudImageUrl());
                list.add(vo);
            }
            return RestResponse.successResult(list);
        }
        // 门店列表
        List<EnterpriseDetailDTO> enterpriseList = wxEnterpriseRelatedApiService
                .listEnterpriseByWxEnterpriseId(wxEnterpriseId);
        if (CollectionUtils.isEmpty(enterpriseList)) {
            logger.info("没有关联任何商户：{}", wxEnterpriseId);
            return RestResponse.successResult();
        }
        List<String> enterpriseIdList = enterpriseList.stream().filter(dto -> {
            String enterpriseId = dto.getEnterpriseId();
            return !this.wxEnterpriseApiService.haobanIsStop(enterpriseId);
        }).map(EnterpriseDetailDTO::getEnterpriseId).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(enterpriseIdList)) {
            logger.info("没有关联任何商户或商户都已停用：{}", wxEnterpriseId);
            return RestResponse.successResult();
        }

        Map<String, EnterpriseDetailDTO> enterpriseTypeMap = enterpriseList.stream()
                .collect(Collectors.toMap(dto -> dto.getEnterpriseId(), dto -> dto));
        bindRelationList = staffClerkRelationApiService.listBindCodeByStaffId(enterpriseIdList, staffId);
        if (CollectionUtils.isEmpty(bindRelationList)) {
            logger.info("没有关联任何商户导购：{}", wxEnterpriseId);
            return RestResponse.successResult();
        }
        logger.info("成员绑定导购数据={}", JSON.toJSONString(bindRelationList));
        for (StaffClerkRelationDTO staffClerkRelationDTO : bindRelationList) {
            String storeId = staffClerkRelationDTO.getStoreId();
            StoreDTO store = storeService.getStore(storeId);
            if (store == null) {
                continue;
            }
            String enterpriseId = store.getEnterpriseId();
            if (StringUtils.isNotBlank(gicEnterpriseId) && !gicEnterpriseId.equals(enterpriseId)) {
                logger.info("非当前商户,直接跳过={},{}", gicEnterpriseId, enterpriseId);
                continue;
            }
            //统一根据导购id查询
            ClerkDTO clerk = clerkService.getClerkByClerkId(staffClerkRelationDTO.getClerkId());
            if (clerk == null) {
                continue;
            }
            StaffDTO staffDTO = staffApiService.selectById(staffId);
            if (staffDTO == null) {
                continue;
            }
            WxEnterpriseDTO wxEnterpriseDTO = wxEnterpriseApiService.getOne(wxEnterpriseId);
            if (wxEnterpriseDTO == null) {
                continue;
            }
            EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(enterpriseId);
            if (enterpriseDTO == null) {
                continue;
            }
            // 主门店标志
            int mainStoreFlag = 0;
            EnterpriseDetailDTO enterpriseDetailDTO = enterpriseTypeMap.get(enterpriseId);
            staffDepartmentRelatedApiService.listByStaffId(staffId);
            StaffStoreVO vo = new StaffStoreVO();
            vo.setClerkCode(clerk.getClerkCode());
            vo.setWxEnterpriseType(enterpriseDetailDTO != null ? enterpriseDetailDTO.getWxEnterpriseType() : null);
            vo.setMemberOpenCardFlag(enterpriseDetailDTO != null ? enterpriseDetailDTO.getMemberOpenCardFlag() : null);
            vo.setClerkId(clerk.getClerkId());
            vo.setClerkType(clerk.getClerkType());
            vo.setEnterpriseId(enterpriseId);
            vo.setMainStoreFlag(mainStoreFlag);
            vo.setPhoneNumber(clerk.getPhoneNumber());
            vo.setStaffId(staffId);
            vo.setStoreCode(clerk.getStoreCode());
            vo.setStoreId(clerk.getStoreId());
            vo.setStoreImg(store.getStoreImage());
            vo.setStoreName(store.getStoreName());
            vo.setWxEnterpriseId(wxEnterpriseId);
            vo.setClerkName(clerk.getClerkName());
            vo.setHeadImg(staffDTO.getHeadImg());
            vo.setBindFlag(1);
            vo.setEnterpriseName(enterpriseDTO.getBrandName());
            vo.setCorpName(wxEnterpriseDTO.getCorpName());
            vo.setEnableHaoban(clerk.getEnableHaoban());
            list.add(vo);
        }
        if (CollectionUtils.isEmpty(list)) {
            return RestResponse.successResult(list);
        }
        List<String> storeIdList = list.stream().map(dto -> dto.getStoreId()).collect(Collectors.toList());
        // 处理主门店
        if (StringUtils.isBlank(gicEnterpriseId)) {
            ClerkMainStoreRelatedDTO mainDTO = clerkMainStoreRelatedApiService
                    .getWxEnterpriseIdAndStaffId(wxEnterpriseId, staffId, storeIdList);
            String mainStoreId = mainDTO == null ? "" : mainDTO.getStoreId();
            if (null != mainStoreId) {
                list.forEach(item -> {
                    if (item.getStoreId().equals(mainStoreId)) {
                        item.setMainStoreFlag(1);
                    }
                });
            }
        }
        return RestResponse.successResult(list);
    }

    /**
     * 会员关联数量
     */
    @RequestMapping("external-friend-count")
    public RestResponse<Object> friendCount(String staffId) {
        StaffDTO staff = staffApiService.selectById(staffId);
        if (staff == null) {
            return RestResponse.successResult(0);
        }
        List<Integer> statusFlags = Arrays.asList(3, 4);
        int countExternalClerk = externalClerkRelatedApiService.getCountExternalClerk(staff.getWxEnterpriseId(),
                staffId, statusFlags);
        return RestResponse.successResult(countExternalClerk);
    }

    // 区经门店列表
    @RequestMapping("/list-clerk-store")
    public RestResponse<Object> listClerkStore(String wxEnterpriseId, String enterpriseId, String clerkId,
            @RequestParam(defaultValue = "20") int pageSize, @RequestParam(defaultValue = "1") int currentPage,
            String storeSearchParams) {
        List<String> storeIdList = this.staffApiService.getHaoBanStoreIdsRolesByClerkId(clerkId, wxEnterpriseId);
        if (CollectionUtils.isEmpty(storeIdList)) {
            return RestResponse.failure("-1", "无授权门店");
        }
        List<StoreListVO> voList = new ArrayList<>();
        int totalCount = 0;
        List<StoreDTO> storeDTOList = new ArrayList<>();
        if (storeIdList.get(0).contains("-1")) {
            String storeWidgetId = this.powerService.getStoreWidgetId(new Date(), clerkId);
            logger.info("权限-所有门店storeWidgetId={}", storeWidgetId);
            Page<Object> pageParam = new Page<Object>();
            pageParam.setCurrentPage(currentPage);
            pageParam.setPageSize(pageSize);
            Page<StoreDTO> page = storeWidgetService.getStoreWidgetStore(storeWidgetId, null, enterpriseId, pageParam,
                    null, null);
            if (page != null) {
                storeDTOList = page.getResult();
                totalCount = page.getTotalCount();
            }
        } else {
            totalCount = storeIdList.size();
            int start = pageSize * (currentPage - 1);
            if (start < totalCount) {
                int end = start + pageSize;
                if (end > totalCount) {
                    end = totalCount;
                }
                List<String> subStoreIdList = storeIdList.subList(start, end);
                if (CollectionUtils.isNotEmpty(subStoreIdList)) {
                    logger.info("分页当前页storeid数={}", subStoreIdList.size());
                    String[] arr = new String[subStoreIdList.size()];
                    List<StoreDTO> storeList = this.storeService.getStores(subStoreIdList.toArray(arr));
                    Map<String, StoreDTO> storeMap = storeList.stream()
                            .collect(Collectors.toMap(StoreDTO::getStoreId, o -> o, (k1, k2) -> k1));
                    for (String id : subStoreIdList) {
                        if (null != storeMap.get(id)) {
                            storeDTOList.add(storeMap.get(id));
                        }
                    }
                }
            }
        }
        if (CollectionUtils.isNotEmpty(storeDTOList)) {
            for (StoreDTO store : storeDTOList) {
                StoreListVO vo = new StoreListVO();
                vo.setStoreId(store.getStoreId());
                vo.setStoreName(store.getStoreName());
                vo.setStoreCode(store.getStoreCode());
                vo.setEnterpriseId(store.getEnterpriseId());
                voList.add(vo);
            }
        }
        Page<StoreListVO> page = new Page<>();
        page.setResult(voList);
        page.setTotalCount(totalCount);
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        return RestResponse.successResult(page);
    }

    @RequestMapping("/search-clerk-store-page")
    public RestResponse<Object> listClerkStorePage(String wxEnterpriseId, String enterpriseId, String clerkId,
            @RequestParam(defaultValue = "20") int pageSize, @RequestParam(defaultValue = "1") int currentPage,
            String storeSearchParams) {
        // 如果有权限控制,进行管辖门店过0滤
        List<String> authStoreIdList = this.staffApiService.getHaoBanStoreIdsRolesByClerkId(clerkId, wxEnterpriseId);
        if (CollectionUtils.isEmpty(authStoreIdList)) {
            return RestResponse.failure("-1", "无授权门店");
        }
        Page page = this.page(wxEnterpriseId, enterpriseId, clerkId, pageSize, currentPage, storeSearchParams,
                authStoreIdList);
        List<StoreDTO> storeList = (List<StoreDTO>) page.getResult();
        List<StoreListVO> retList = this.toList(storeList);
        Page<StoreListVO> retPage = new Page<>();
        retPage.setResult(retList);
        retPage.setTotalCount(page.getTotalCount());
        retPage.setCurrentPage(currentPage);
        retPage.setPageSize(pageSize);
        return RestResponse.successResult(retPage);
    }

    private Page page(String wxEnterpriseId, String enterpriseId, String clerkId,
            @RequestParam(defaultValue = "20") int pageSize, @RequestParam(defaultValue = "1") int currentPage,
            String storeSearchParams, List<String> authStoreIdList) {
        StoreSearchDTO searchDTO = new StoreSearchDTO();
        searchDTO.setRecycleStoreCount(0);
        searchDTO.setMemberCountFlag(0);
        searchDTO.setSearchName(storeSearchParams);
        // 企业ID
        searchDTO.setEnterpriseId(enterpriseId);
        if (!authStoreIdList.contains("-1")) {
            searchDTO.setAuthStoreIdList(authStoreIdList);
        }
        // 门店参数
        Page page = new Page();
        page.setPageSize(pageSize);
        page.setCurrentPage(currentPage);
        Map<String, Object> params = new HashMap<>();
        params.put("searchDto", searchDTO);
        page.setParams(params);
        logger.info("查询条件={}", JSON.toJSONString(page));
        Map<String, Object> result = storeService.getStoreListPage(page);
        page = (Page) result.get("page");
        return page;
    }

    private List<StoreListVO> toList(List<StoreDTO> storeList) {
        List<StoreListVO> retList = new ArrayList<StoreListVO>();
        StoreListVO vo = null;
        for (StoreDTO dto : storeList) {
            vo = new StoreListVO();
            vo.setStoreId(dto.getStoreId());
            vo.setStoreName(dto.getStoreName());
            vo.setStoreCode(dto.getStoreCode());
            vo.setEnterpriseId(dto.getEnterpriseId());
            retList.add(vo);
        }
        return retList;
    }

    // 区经门店查询
    @RequestMapping("search-clerk-store")
    public RestResponse<Object> listClerkStoreByParams(String wxEnterpriseId, String enterpriseId, String clerkId,
            String storeSearchParams) {
        if (StringUtils.isEmpty(storeSearchParams)) {
            return RestResponse.failure("-1", "查询条件为空");
        }
        // 如果有权限控制,进行管辖门店过0滤
        List<String> authStoreIdList = this.staffApiService.getHaoBanStoreIdsRolesByClerkId(clerkId, wxEnterpriseId);
        if (CollectionUtils.isEmpty(authStoreIdList)) {
            return RestResponse.failure("-1", "无授权门店");
        }
        Page page = this.page(wxEnterpriseId, enterpriseId, clerkId, 20, 1, storeSearchParams, authStoreIdList);
        List<StoreDTO> storeList = (List<StoreDTO>) page.getResult();
        return RestResponse.successResult(toList(storeList));
    }

    /**
     * 门店导购查询
     */
    @RequestMapping("list-clerk")
    public RestResponse<Object> listClerk(String enterpriseId, String wxEnterpriseId, String clerkId,
            String clerkSearchParams, BasePageInfo basePageInfo) {
        ClerkDTO clerk = this.clerkService.getclerkById(clerkId);
        int clerkType = clerk.getClerkType();
        List<ClerkListVO> resultList = null;
        if (clerkType != 1) {
            return RestResponse.failure("-1", "非店长身份");
        }
        List<ClerkListDTO> clerkList = clerkService.getClerkByStoreId(enterpriseId, clerk.getStoreId());
        if (CollectionUtils.isNotEmpty(clerkList) && StringUtils.isNotEmpty(clerkSearchParams)) {
            clerkList = clerkList.stream().filter(dto -> dto.getClerkCode().contains(clerkSearchParams)
                    || dto.getClerkName().contains(clerkSearchParams)).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(clerkList)) {
            return RestResponse.failure("-1", "无导购");
        }
        resultList = EntityUtil.changeEntityListByJSON(ClerkListVO.class, clerkList);
        List<String> clerkIdList = resultList.stream().map(dto -> dto.getClerkId()).collect(Collectors.toList());
        List<StaffClerkRelationDTO> relationList = this.staffClerkRelationApiService
                .listByClerkIdsWxEnterpriseId(clerkIdList, wxEnterpriseId);
        if (CollectionUtils.isEmpty(relationList)) {
            return RestResponse.failure("-1", "无导购");
        }
        List<String> retlationIdList = relationList.stream().map(dto -> dto.getClerkId()).collect(Collectors.toList());
        resultList.removeIf(item -> {
            return !retlationIdList.contains(item.getClerkId());
        });
        Page<ClerkListVO> retPage = new Page<>();
        retPage.setPageSize(resultList.size());
        retPage.setCurrentPage(1);
        retPage.setTotalCount(resultList.size());
        retPage.setTotalPage(1);
        retPage.setResult(resultList);
        return RestResponse.successResult(retPage);
    }

    /**
     * 判断成员是否授权获取敏感信息
     */
    @RequestMapping("get-sensitive-status")
    public RestResponse<Object> getSensitiveStatus(String staffId) {
        int result = staffApiService.getSensitiveStatus(staffId);
        return RestResponse.successResult(result);
    }

    @RequestMapping("update-qr-code")
    public RestResponse<Object> updateQrCode(String staffId , String qrCode){
        //需要把qrcode中http替换为https
        if(StrUtil.isBlank(qrCode)){
            return RestResponse.failure("-1", "参数不能为空！！！");
        }
        String s = qrCode.substring(qrCode.indexOf(":"));
        String q = "https"+s;
        this.staffApiService.updateQrCodeByStaffId(staffId, q) ;
        return RestResponse.successResult() ;
    }

    // 判断是否有内容中台权限
    @RequestMapping("has-content-right")
    public RestResponse<Object> hasContentRight(String enterpriseId) {
        ServiceResponse<List<EnterpriseUsingStatusDTO>>  resp = this.enterpriseUseForbidService.getUseEnterpriseByCode(EnterpriseServiceEnum.CONTENT.getRightMenuCode(), enterpriseId);
        logger.info("内容中台权限={},{}",JSON.toJSONString(resp),enterpriseId);
        List<EnterpriseUsingStatusDTO> list = resp.getResult() ;
        RightVO vo = new RightVO();
        if(CollectionUtils.isEmpty(list)) {
            return RestResponse.successResult(vo);
        }
        EnterpriseUsingStatusDTO dto = list.get(0) ;
        if(dto.getVaild()) {
            vo.setStatus(1);
        }else {
            vo.setStatus(2);
        }
        return RestResponse.successResult(vo);
    }
}
