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

import cn.hutool.core.collection.CollectionUtil;
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.service.ClerkService;
import com.gic.commons.util.DateUtil;
import com.gic.commons.util.EntityUtil;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.enterprise.api.dto.EnterpriseDTO;
import com.gic.enterprise.api.dto.StoreDTO;
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.manage.api.dto.*;
import com.gic.haoban.manage.api.dto.qdto.ClerkSyncQDTO;
import com.gic.haoban.manage.api.dto.qdto.hm.HmQrcodeQDTO;
import com.gic.haoban.manage.api.enums.AuditType;
import com.gic.haoban.manage.api.enums.BindTypeEnum;
import com.gic.haoban.manage.api.enums.ChannelCodeEnum;
import com.gic.haoban.manage.api.service.AuditApiService;
import com.gic.haoban.manage.api.service.StaffClerkRelationApiService;
import com.gic.haoban.manage.api.service.hm.HmQrcodeApiService;
import com.gic.haoban.manage.service.config.Config;
import com.gic.haoban.manage.service.dao.mapper.StaffMapper;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanStaffClerkRelationMapper;
import com.gic.haoban.manage.service.entity.MemberClerkChatConfig;
import com.gic.haoban.manage.service.entity.TabHaobanStaff;
import com.gic.haoban.manage.service.entity.TabHaobanStaffClerkBindLog;
import com.gic.haoban.manage.service.entity.TabHaobanStaffClerkRelation;
import com.gic.haoban.manage.service.service.*;
import com.gic.haoban.manage.service.service.hm.HmQrcodeService;
import com.gic.haoban.manage.service.task.RouterConstant;
import com.gic.haoban.task.api.dto.MqMessageQo;
import com.gic.redis.data.util.RedisUtil;
import com.gic.wechat.api.dto.qywx.welcome.QywxExternalcontactDTO;
import com.gic.wechat.api.dto.qywx.welcome.QywxExternalcontactResultDTO;
import com.gic.wechat.api.service.qywx.QywxUserApiService;
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.stereotype.Service;

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

@Service
public class StaffClerkRelationApiServiceImpl implements StaffClerkRelationApiService {

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

    @Autowired
    private StaffClerkRelationService staffClerkRelationService;
    @Autowired
    private EnterpriseService enterpriseService;
    @Autowired
    private ClerkService clerkService;
    @Autowired
    private StoreService storeService;
    @Autowired
    private TabHaobanStaffClerkRelationMapper tabHaobanStaffClerkRelationMapper;
    @Autowired
    private AuditApiService auditApiService;
    @Autowired
    private ClerkMainStoreRelatedService clerkMainStoreRelatedService;
    @Autowired
    private StaffClerkBindLogService staffClerkBindLogService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private QywxUserApiService qywxUserApiService;
    @Autowired
    private WxEnterpriseService wxEnterpriseService;
    @Autowired
    private HmQrcodeService hmQrcodeService;
    @Autowired
    private StoreRangeService storeRangeService;
    @Autowired
    private StaffMapper staffMapper ;
    @Autowired
    private HmQrcodeApiService hmQrcodeApiService;

    @Override
    public void bindLogMq(String params) {
        logger.info("成员绑定导购mq={}", params);
        StaffClerkBindLogInfoDTO infoDTO = JSONObject.parseObject(params, StaffClerkBindLogInfoDTO.class);
        if (null == infoDTO) {
            logger.info("数据不存在");
            return;
        }
        TabHaobanStaffClerkRelation clerkRelation = tabHaobanStaffClerkRelationMapper.selectByPrimaryKey(infoDTO.getRelationId());
        if (null == clerkRelation) {
            logger.info("不存在绑定数据");
            return;
        }
        ClerkDTO clerkDTO = clerkService.getClerkByClerkIdNoStatus(clerkRelation.getClerkId());
        String phoneNumber = "";
        String clerkName = null;
        if (null != clerkDTO) {
            phoneNumber = clerkDTO.getPhoneNumber();
            clerkName = clerkDTO.getClerkName();
        }
        String operClerkId = infoDTO.getOptStaffId();
        String operName = null;
        if(StringUtils.isNotEmpty(operClerkId)) {
            ClerkDTO operClerkDTO = clerkService.getClerkByClerkIdNoStatus(operClerkId);
            if (null != operClerkDTO) {
                operName = operClerkDTO.getClerkName();
            }
            //如果是小程序解绑，需要存储staffName
            if(infoDTO.getChannelCode() != null &&(infoDTO.getChannelCode().equals(ChannelCodeEnum.SELF_UNBIND.getCode()) || infoDTO.getChannelCode().equals(ChannelCodeEnum.SELF_BIND.getCode()))){
                TabHaobanStaff tabHaobanStaff = staffService.selectById(operClerkId);
                if (null != tabHaobanStaff) {
                    operName =tabHaobanStaff.getStaffName();
                }
            }
        }
        TabHaobanStaffClerkBindLog enity = new TabHaobanStaffClerkBindLog();
        enity.setClerkId(clerkRelation.getClerkId());
        enity.setChannelCode(infoDTO.getChannelCode());
        enity.setClerkCode(clerkRelation.getClerkCode());
        enity.setCreateTime(new Date());
        enity.setEnterpriseId(clerkRelation.getEnterpriseId());
        enity.setOptStaffId(operClerkId);
        enity.setOperName(operName);
        enity.setOptType(infoDTO.getOptType());
        enity.setStatusFlag(1);
        enity.setStaffId(clerkRelation.getStaffId());
        enity.setWxEnterpriseId(clerkRelation.getWxEnterpriseId());
        enity.setRelationId(infoDTO.getRelationId());
        enity.setClerkPhone(phoneNumber);
        enity.setUpdateTime(new Date());
        enity.setClerkName(clerkName);
        staffClerkBindLogService.insert(enity);
    }

    @Override
    public List<StaffClerkRelationDTO> listBindCode(String wxEnterpriseId, String enterpriseId, Set<String> clerkCodeList) {
        return staffClerkRelationService.listBindCode(wxEnterpriseId, enterpriseId, clerkCodeList);
    }

    @Override
    public List<StaffClerkRelationDTO> listBindCodeByStaffId(List<String> enterpriseIdList, String staffId) {
        return staffClerkRelationService.listBindCodeByStaffId(enterpriseIdList, staffId);
    }

    @Override
    public List<StaffClerkInfoDTO> listBindDetailByStaffId(String staffId) {
        List<StaffClerkRelationDTO> list = staffClerkRelationService.listBindCodeByStaffId(null, staffId);
        if (CollectionUtils.isEmpty(list)) {
            return null;
        }
        List<StaffClerkInfoDTO> infoDTOS = EntityUtil.changeEntityListByJSON(StaffClerkInfoDTO.class, list);

        infoDTOS.forEach(infoDTO -> {
            EnterpriseDTO enterpriseDTO = enterpriseService.getEnterpriseById(infoDTO.getEnterpriseId());
            if (enterpriseDTO != null) {
                infoDTO.setBrandName(enterpriseDTO.getBrandName());
                infoDTO.setEnterpriseName(enterpriseDTO.getEnterpriseName());
            }
            ClerkDTO clerkDTO = clerkService.getClerkByClerkId(infoDTO.getClerkId(), -1);
            if (null != clerkDTO) {
                infoDTO.setClerkPhoneNumber(clerkDTO.getPhoneNumber());
                infoDTO.setClerkName(clerkDTO.getClerkName());
                infoDTO.setClerkCode(clerkDTO.getClerkCode());
            }

            StoreDTO storeDTO = storeService.getStore(infoDTO.getStoreId());
            if (null != storeDTO) {
                infoDTO.setStoreName(storeDTO.getStoreName());
            }
        });
        return infoDTOS;
    }

    @Override
    public ServiceResponse bindStaffClerk(StaffClerkRelationDTO staffClerkRelationDTO, String optStaffId, int channelCode) {
        //加锁防止并发问题
        String clerkId = staffClerkRelationDTO.getClerkId();
        String storeId = staffClerkRelationDTO.getStoreId();
        String key = "haoban_bind_staff:" + clerkId+":"+storeId;
        RedisUtil.lock(key, 6L);
        ServiceResponse resp = this.bindCheck(staffClerkRelationDTO, optStaffId, channelCode);
        if (resp != null && !resp.isSuccess()) {
            logger.error("不允许绑定：{}", resp.getMessage());
            RedisUtil.unlock(key);
            return resp;
        }
        String relationId = staffClerkRelationService.bind(staffClerkRelationDTO, optStaffId, channelCode);
        RedisUtil.unlock(key);
        return ServiceResponse.success(relationId);
    }

    private ServiceResponse bindCheck(StaffClerkRelationDTO staffClerkRelationDTO, String optStaffId, int channelCode) {
        logger.info("开始绑定clerk:{}", JSONObject.toJSONString(staffClerkRelationDTO));
        String clerkId = staffClerkRelationDTO.getClerkId();
        String wxEnterpriseId = staffClerkRelationDTO.getWxEnterpriseId();
        String enterpriseId = staffClerkRelationDTO.getEnterpriseId();
        String staffId = staffClerkRelationDTO.getStaffId();
        Integer manageFlag = staffClerkRelationDTO.getManageFlag();
        if (manageFlag != null && manageFlag == 1) {
            ServiceResponse serviceResponse = getManageFlagBind(staffClerkRelationDTO);
            if (!serviceResponse.isSuccess()) {
                return serviceResponse;
            }
        } else {
            StaffClerkRelationDTO relationDTO = staffClerkRelationService.getBindByClerkId(clerkId, wxEnterpriseId);
            if (null != relationDTO) {
                logger.info("已经被绑定，不能绑定");
                return ServiceResponse.failure("2", "已经被绑定，不能绑定");
            }
        }

        AuditDTO auditDTO = auditApiService.findByBindRelatedIdAndAuditType(clerkId, AuditType.CLERK_BIND.getCode(), wxEnterpriseId, enterpriseId);
        if (null != auditDTO) {
            logger.info("该导购已经被被申请绑定，请审核处理后再绑定");
            return ServiceResponse.failure("4", "该导购已经被被申请绑定，请审核处理后再绑定");
        }
        if (manageFlag == null || manageFlag == 0) {
            List<AuditDTO> list = auditApiService.listByStoreId(staffClerkRelationDTO.getStoreId());
            if (CollectionUtils.isNotEmpty(list)) {
                Set<String> staffIds = list.stream().map(AuditDTO::getCommitStaffId).collect(Collectors.toSet());
                if (staffIds.contains(staffId)) {
                    logger.info("该成员已经已经在该门店下申请了绑定，请审核处理后再绑定");
                    return ServiceResponse.failure("5", "该成员已经已经在该门店下申请了绑定，请审核处理后再绑定");
                }
            }
            StaffClerkRelationDTO storeHasBind = staffClerkRelationService.getOneBindByStoreId(staffId, staffClerkRelationDTO.getStoreId());
            if (storeHasBind != null) {
                logger.info("该导购已在该门店下有其它成员绑定");
                return ServiceResponse.failure("3", "该导购已在该门店下有其它成员绑定");
            }
            List<StaffClerkRelationDTO> staffClerkRelationDTOS = staffClerkRelationService.listManageBindByStaffId(staffId);
            if (CollectionUtils.isNotEmpty(staffClerkRelationDTOS)) {
                logger.info("该导购已绑定区经，不允许绑定导购");
                return ServiceResponse.failure("3", "该导购已绑定区经，不允许绑定导购");
            }
        }
        return null;
    }

    @Override
    public StaffClerkRelationDTO getByCodeAndEnterpriseId(String clerkCode, String enterpriseId) {
        return staffClerkRelationService.getByCodeAndEnterpriseId(clerkCode, enterpriseId);
    }


//    @Override
//    public void delBindByStoreId(String wxEnterpriseId, String storeId, String staffId, int channelCode) {
//        Set<String> needUnBindStoreIds = new HashSet<>();
//        needUnBindStoreIds.add(storeId);
//        staffClerkRelationService.delBindByStoreIds(wxEnterpriseId, needUnBindStoreIds, staffId, ChannelCodeEnum.SELF_UNBIND.getCode());
//    }

    @Override
    public List<StaffClerkRelationDTO> listByClerkIds(List<String> clerkIds) {
      return this.listByClerkIdsWxEnterpriseId(clerkIds, null) ;
    }

    @Override
    public List<StaffClerkRelationDTO> listByClerkIdsWxEnterpriseId(List<String> clerkIds, String wxEnterpriseId) {
        if (CollectionUtil.isEmpty(clerkIds)) {
            return Collections.emptyList();
        }
        return tabHaobanStaffClerkRelationMapper.listByClerkIds(clerkIds, wxEnterpriseId);
    }

    @Override
    public List<StaffClerkRelationDTO> listByStoreId(String storeId) {
        return tabHaobanStaffClerkRelationMapper.listByStoreIds(null,Arrays.asList(storeId));
    }
    
    @Override
    public List<StaffClerkRelationDTO> listByStoreIds(String wxEnterpriseId, List<String> storeIds) {
        return tabHaobanStaffClerkRelationMapper.listByStoreIds(wxEnterpriseId,storeIds);
    }

    @Override
    public boolean unbindByStaffAndClerkId(String staffId, String clerkId, int channelCode,String wxEnterpriseId) {
        return staffClerkRelationService.delBind(clerkId, staffId, channelCode, null,wxEnterpriseId);
    }

    @Override
    public StaffClerkRelationDTO getOneByClerkId(String clerkId) {
        return tabHaobanStaffClerkRelationMapper.getOneByClerkId(clerkId,null);
    }

    @Override
    public StaffClerkRelationDTO getOneByClerkId(String clerkId,String wxEnterpriseId) {
        return tabHaobanStaffClerkRelationMapper.getOneByClerkId(clerkId,wxEnterpriseId);
    }

    @Override
    public StaffClerkRelationDTO getByClerkId(String clerkId) {
        StaffClerkRelationDTO staffRelation = staffClerkRelationService.getByClerkId(clerkId);
        return staffRelation;
    }

    @Override
    public StaffClerkRelationDTO getByClerkIdForWxUserId(String clerkId) {
        return this.getByClerkId(clerkId);
    }

    @Override
    public StaffClerkRelationDTO getOneByStoreIdAndStaffId(String storeId,String staffId) {
        StaffClerkRelationDTO tab = tabHaobanStaffClerkRelationMapper.getOneByStoreIdAndStaffId(storeId, staffId);
        if (tab == null) {
            return null;
        }
        return tab;
    }

    @Override
    public ServiceResponse wxBindStaffClerk(StaffClerkRelationDTO staffClerkRelation, String optStaffId, int channelCode) {
        Integer manageFlag = staffClerkRelation.getManageFlag();
        if (manageFlag != null && manageFlag.intValue() == 1) {
            ServiceResponse serviceResponse = getManageFlagBind(staffClerkRelation);
            if (!serviceResponse.isSuccess()) {
                return serviceResponse;
            }
        }else {
            String staffId = staffClerkRelation.getStaffId();
            List<StaffClerkRelationDTO> staffClerkRelationDTOS = staffClerkRelationService.listManageBindByStaffId(staffId);
            if (CollectionUtils.isNotEmpty(staffClerkRelationDTOS)) {
                logger.info("该导购已绑定区经，不允许绑定导购");
                return ServiceResponse.failure("3", "该导购已绑定区经，不允许绑定导购");
            }
        }
        if (StringUtils.isNotBlank(staffClerkRelation.getStaffClerkRelationId())) {
            TabHaobanStaffClerkRelation oldStaffClerkRelation = tabHaobanStaffClerkRelationMapper.selectByPrimaryKey(staffClerkRelation.getStaffClerkRelationId());
            tabHaobanStaffClerkRelationMapper.delByPrimaryKey(staffClerkRelation.getStaffClerkRelationId());
            staffClerkBindLogService.pushToMq(oldStaffClerkRelation.getStaffId(), optStaffId, BindTypeEnum.UNBIND.getVal(), channelCode, staffClerkRelation.getStaffClerkRelationId());
            clerkMainStoreRelatedService.delMainStore(oldStaffClerkRelation.getStaffId(), oldStaffClerkRelation.getStoreId(), oldStaffClerkRelation.getWxEnterpriseId());
        }

        staffClerkRelationService.bind(staffClerkRelation, optStaffId, channelCode);
        return ServiceResponse.success();
    }


    private ServiceResponse getManageFlagBind(StaffClerkRelationDTO staffClerkRelation) {
        String enterpriseId = staffClerkRelation.getEnterpriseId();
        String wxEnterpriseId = staffClerkRelation.getWxEnterpriseId();
        String clerkId = staffClerkRelation.getClerkId();
        String staffId = staffClerkRelation.getStaffId();
        boolean bindFlag = staffClerkRelationService.getBindByStaffIdAndEnterpriseId(enterpriseId, staffId);
        if (bindFlag) {
            return ServiceResponse.failure("3", "该员工已经绑定，不允许绑定区经/督导");
        }
        StaffClerkRelationDTO staffClerkRelationDTO = staffClerkRelationService.getByClerkId(clerkId, wxEnterpriseId);
        if (staffClerkRelationDTO != null) {
            return ServiceResponse.failure("3", "该导购已经被绑定，不允许绑定");
        }
        return ServiceResponse.success();
    }

    @Override
    public List<StaffClerkRelationDTO> listByEnterpriseIdAndStaffid(String enterpriseId, String staffid) {
        return tabHaobanStaffClerkRelationMapper.listByEnterpriseIdAndStaffid(enterpriseId, staffid);
    }

    @Override
    public Page<StaffClerkBindLogDetailDTO> pageStaffClerkBindLog(String wxEnterpriseId, String search, String enterpriseId, int optType, BasePageInfo pageInfo) {
        Page<StaffClerkBindLogDetailDTO> retList = staffClerkBindLogService.pageBindLog(wxEnterpriseId, enterpriseId, optType, search, pageInfo);
        if (CollectionUtils.isNotEmpty(retList.getResult())) {
            retList.getResult().forEach(item -> {
                TabHaobanStaff haobanStaff = staffMapper.selectByPrimaryKeyNoStatus(item.getStaffId());
                if (null != haobanStaff) {
                    item.setStaffName(haobanStaff.getStaffName());
                    item.setWxUserId(haobanStaff.getWxUserId());
                } else {
                    item.setStaffName("未知成员");
                }
                if ("-1".equals(item.getOptStaffId())) {
                    item.setOptStaffName("系统");
                } else {
                    item.setOptStaffName(item.getOperName());
                }
                if (StringUtils.isBlank(item.getOptStaffName())) {
                    item.setOptStaffName("未知成员");
                }
                if (StringUtils.isBlank(item.getClerkName())) {
                    ClerkDTO clerkDTO = clerkService.getClerkByClerkIdNoStatus(item.getClerkId());
                    if (null != clerkDTO) {
                        item.setClerkName(clerkDTO.getClerkName());
                    }
                }
                item.setClerkPhoneNumber(item.getClerkPhone());
            });
        }
        return retList;
    }

    @Override
    public Page<StaffClerkBindLogDetailDTO> pageStaffClerkUnBindLog(String wxEnterpriseId, String clerkId, String enterpriseId, int optType, BasePageInfo pageInfo) {
        if (wxEnterpriseId == null) {
            logger.info("没有关联企业");
            return null;
        }
        Page<StaffClerkBindLogDetailDTO> retList = staffClerkBindLogService.pageUnBindLog(wxEnterpriseId, clerkId, enterpriseId, optType, pageInfo);
        if (CollectionUtils.isNotEmpty(retList.getResult())) {
            retList.getResult().forEach(item -> {
                TabHaobanStaff haobanStaff = staffService.selectById(item.getStaffId());
                if (null != haobanStaff) {
                    item.setStaffName(haobanStaff.getStaffName());
                    item.setWxUserId(haobanStaff.getWxUserId());
                } else {
                    item.setStaffName("未知成员");
                }
                if ("-1".equals(item.getOptStaffId())) {
                    item.setOptStaffName("系统");
                } else {
                    item.setOptStaffName(item.getOperName());
                }
                if (StringUtils.isBlank(item.getOptStaffName())) {
                    item.setOptStaffName("未知成员");
                }
                if (StringUtils.isBlank(item.getClerkName())) {
                    ClerkDTO clerkDTO = clerkService.getClerkByClerkIdNoStatus(item.getClerkId());
                    if (null != clerkDTO) {
                        item.setClerkName(clerkDTO.getClerkName());
                    }
                }
                item.setClerkPhoneNumber(item.getClerkPhone());
            });
        }
        return retList;
    }

    @Override
    public void pushToBindLog(String staffId, String optStaffId, int optType, int channelCode, String relationId) {
        staffClerkBindLogService.pushToMq(staffId, optStaffId, optType, channelCode, relationId);
    }

    @Override
    public com.gic.haoban.base.api.common.ServiceResponse<String> getClerkMemberChatConfig(String clerkId) {
        com.gic.haoban.base.api.common.ServiceResponse response = new com.gic.haoban.base.api.common.ServiceResponse();
        StaffClerkRelationDTO relationDTO = staffClerkRelationService.getByClerkId(clerkId);
        if (null == relationDTO) {
            logger.info("导购没有关联企业微信：{}", clerkId);
            response.setCode(2);
            response.setMessage("导购没有关联企业微信");
            return response;
        }

        MemberClerkChatConfig chatConfig = staffClerkRelationService.getChatConfig(relationDTO.getStaffId(), "-1");
        if (chatConfig != null) {
            response.setResult(chatConfig.getConfigId());
            return response;
        }

        QywxExternalcontactDTO send = new QywxExternalcontactDTO();
        send.setType(1);
        send.setScene(1);
        send.setRemark("导购:" + relationDTO.getClerkCode());
        List<String> userIds = new ArrayList<>();
        send.setUser(userIds);

        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(relationDTO.getWxEnterpriseId());
        if (qwDTO.needOpenUserId3th()) {
            userIds.add(relationDTO.getOpenUserId());
        } else {
            userIds.add(relationDTO.getQwUserId());
        }
        QywxExternalcontactResultDTO configResp = qywxUserApiService.addContactWay(qwDTO.getThirdCorpid(), qwDTO.getSelf3thSecret(), send,qwDTO.isSelf(),qwDTO.getUrlHost());
        logger.info("configId:{}", JSON.toJSONString(configResp));
        String configId = configResp.getConfig_id();
        if (StringUtils.isBlank(configId)) {
            logger.info("staff:{}", configId, JSONObject.toJSONString(relationDTO));
            response.setCode(4);
            response.setMessage("创建config失败");
            return response;
        }
        MemberClerkChatConfig clerkChatConfig = new MemberClerkChatConfig();
        clerkChatConfig.setConfigId(configId);
        clerkChatConfig.setEnterpriseId(relationDTO.getEnterpriseId());
        clerkChatConfig.setMemberId("-1");
        clerkChatConfig.setStaffId(relationDTO.getStaffId());
        staffClerkRelationService.saveChatConfig(clerkChatConfig);

        response.setResult(clerkChatConfig.getConfigId());
        return response;
    }

    @Override
    public Page<StaffClerkRelationDTO> pageByWxEnterpriseId(String wxEnterpriseId, BasePageInfo pageInfo) {
        return staffClerkRelationService.pageByWxEnterpriseId(wxEnterpriseId, pageInfo);
    }

    @Override
    public List<StaffClerkRelationDTO> listByStaffId(String wxEnterpriseId, String staffId) {
        return staffClerkRelationService.listByStaffId(wxEnterpriseId, staffId);
    }

    @Override
    public void clerkStoreMoveDel(String param) {
        logger.info("导购转移删除修改通知：{}", param);
        if (StringUtils.isBlank(param)) {
            logger.error("参数为空");
            return;
        }
        ClerkSyncQDTO clerkSyncQDTO = JSON.parseObject(param, ClerkSyncQDTO.class);
        Integer type = clerkSyncQDTO.getType();
        String clerkId = clerkSyncQDTO.getClerkId();
        String oldClerkId = clerkSyncQDTO.getOldClerkId();
        String clerkCode = clerkSyncQDTO.getClerkCode();
        String enterpriseId = clerkSyncQDTO.getEnterpriseId();
        ClerkDTO clerkDTO = clerkService.getClerkByClerkId(clerkId, -1);
        if (clerkDTO == null) {
            logger.error("导购为空,clerkId={}", clerkId);
            return;
        }
        if (type == 1) {
            Integer status = clerkDTO.getStatus();
            logger.info("导购删除,clerkId:{},status:{}", clerkId, status);
            if (!status.equals(1)) {
                staffClerkRelationService.delBind(clerkId, "-1", ChannelCodeEnum.GIC_CLERK_DEL_UNBIND.getCode(), null,null);
            }
        } else if (type == 2) {
            logger.info("导购门店转移,新的导购和门店,clerkId={},storeId={}", clerkId, clerkSyncQDTO.getStoreId());
            //统一处理：导购code替换为导购id
            StaffClerkRelationDTO oldRelationDTO = staffClerkRelationService.getStaffClerkRelationDTO(oldClerkId, enterpriseId);
            if (null == oldRelationDTO) {
                logger.info("导购未关联成员,oldClerkId={}", oldClerkId);
                return;
            }
            // 如果新门店未关联好办,进行解绑
            boolean hasFlag = this.storeRangeService.hasStore(oldRelationDTO.getWxEnterpriseId(),enterpriseId,clerkDTO.getStoreId()) ;
            if(!hasFlag) {
                logger.info("新门店未关联好办,storeId={}",clerkDTO.getStoreId());
                staffClerkRelationService.delBind(oldClerkId, "-1", ChannelCodeEnum.STORE_CHANGE_UNBIND.getCode(), null,null);
                return ;
            }
            logger.info("导购门店转移,老的绑定导购id={}", oldRelationDTO.getClerkId());
            this.moveOrAddClerk(clerkSyncQDTO, oldRelationDTO);
        } else if (type == 3) {
            //店长任务重新分配
            Integer clerkType = clerkDTO.getClerkType();
            if (clerkType == null) {
                logger.error("导购类型为空：{}", clerkId);
                return;
            }
            logger.info("店长任务重新分配,clerkId:{},clerkType:{}", clerkId, clerkType);
            if (clerkType == 1) {
                //发消息处理新增店长，任务重新分配问题
                try {
                    logger.info("待分配任务重分配======>{}", clerkId);
                    MqMessageQo mqMessageQo = new MqMessageQo();
                    //任务分配给店长
                    mqMessageQo.setType(MqMessageQo.DISTRIBUTE_TASK);
                    mqMessageQo.setData(clerkId);
                    String s = JSONObject.toJSONString(mqMessageQo);
                    GICMQClientUtil.getClientInstance().sendCommonMessage(RouterConstant.ROUTERTYPE, s,
                            "com.gic.haoban.task.api.service.MqAsynApiService", "run");
                } catch (Exception e) {
                    logger.error("任务重新分配问题发送消息队列出错", e);
                }
                hmQrcodeService.updateClerkNameByClerkId(enterpriseId, clerkId, clerkDTO.getClerkName(), clerkDTO.getClerkCode());
            } else if (clerkType == 2) {
                logger.info("区经变更为导购,解绑：{}", clerkId);
                //解绑,判断当前区经是否开启好办权限，不开启则解绑
                if (clerkDTO.getEnableHaoban() == null || clerkDTO.getEnableHaoban()==false){
                    staffClerkRelationService.delBind(clerkId, "-1", ChannelCodeEnum.GIC_CLERK_DEL_UNBIND.getCode(), null,null);
                }
            }
        }
    }

    // 导购门店转移
    private void moveOrAddClerk(ClerkSyncQDTO clerkSyncQDTO, StaffClerkRelationDTO oldRelationDTO) {
       /* boolean flag = false;
        if (null != RedisUtil.getCache("clerkMoveFlag2022")) {
            flag = true;
        }
        if (flag) {*/
            String oldClerkId = oldRelationDTO.getClerkId();
            this.staffClerkRelationService.delBind(oldClerkId, "-1", ChannelCodeEnum.SYNC_UNBIND.getCode(), clerkSyncQDTO.getClerkId(),oldRelationDTO.getWxEnterpriseId());
            // 设置新的ID
            oldRelationDTO.setClerkId(clerkSyncQDTO.getClerkId());
            oldRelationDTO.setStoreId(clerkSyncQDTO.getStoreId());
            ServiceResponse response = this.bindCheck(oldRelationDTO, "-1", ChannelCodeEnum.SYNC_BIND.getCode());
            logger.info("绑定结果正常：{}，{}", JSONObject.toJSONString(response), oldRelationDTO.getClerkId());
            if (response == null) {
                TabHaobanStaff staff = this.staffMapper.selectByPrimaryKey(oldRelationDTO.getStaffId()) ;
                if(null == staff) {
                    logger.info("staff is del");
                    return;
                }
                this.staffClerkRelationService.insert(oldRelationDTO);
                logger.info("换门店后,查询主门店,newClerkId={}",oldRelationDTO.getStaffId());
                // 设置主门店
                List<StaffClerkRelationDTO> relationList = this.listByStaffId(oldRelationDTO.getWxEnterpriseId(), oldRelationDTO.getStaffId()) ;
                List<String> storeIdList = relationList.stream().map(o->o.getStoreId()).collect(Collectors.toList()) ;
                this.clerkMainStoreRelatedService.getMainStoreByStaffId(oldRelationDTO.getStaffId(), oldRelationDTO.getWxEnterpriseId(), storeIdList) ;

                // 新增活码
                HmQrcodeQDTO hmQrcodeQDTO = new HmQrcodeQDTO();
                hmQrcodeQDTO.setHmType(1);
                hmQrcodeQDTO.setWxEnterpriseId(oldRelationDTO.getWxEnterpriseId());
                hmQrcodeQDTO.setEnterpriseId(oldRelationDTO.getEnterpriseId());
                hmQrcodeQDTO.setName(staff.getStaffName());
                hmQrcodeQDTO.setPassFlag(1);
                hmQrcodeQDTO.setStoreId(clerkSyncQDTO.getStoreId());
                hmQrcodeQDTO.setClerkIdList(Collections.singletonList(clerkSyncQDTO.getClerkId()));
                this.hmQrcodeApiService.add(hmQrcodeQDTO);
            }
        /*} else {
            String oldClerkId = oldRelationDTO.getClerkId();
            this.staffClerkRelationService.delBind(oldClerkId, "-1", ChannelCodeEnum.SYNC_UNBIND.getCode(), null,null);
            // 设置新的ID
            oldRelationDTO.setClerkId(clerkSyncQDTO.getClerkId());
            oldRelationDTO.setStoreId(clerkSyncQDTO.getStoreId());
            ServiceResponse resp = this.bindStaffClerk(oldRelationDTO, "-1", ChannelCodeEnum.SYNC_BIND.getCode());
            logger.info("绑定结果正常：{}，{}", JSONObject.toJSONString(resp), oldRelationDTO.getClerkId());*/
       // }
    }

    @Override
    public int getCanAddHmCount(String wxEnterpriseId, String enterpriseId, String clerkId) {
        return this.hmQrcodeService.getCanAddCount(wxEnterpriseId, enterpriseId, clerkId);
    }

    @Override
    public List<String> listStaffIdByWxEnterpriseId(String wxEnterpriseId) {
        return this.staffClerkRelationService.listByWxEnterpriseId(wxEnterpriseId);
    }

    @Override
    public List<StaffClerkRelationDTO> listManageBindByStaffId(String staffId) {
        return staffClerkRelationService.listManageBindByStaffId(staffId);
    }

    // 只用于离职继承的查询
    @Override
    public List<String> getTakeoverClerkIdList(List<String> staffIdList) {
        List<String> takeoverClerkIdList = new ArrayList<>() ;
        if(CollectionUtils.isNotEmpty(staffIdList)) {
            for(int i=0;i<staffIdList.size();i++) {
                List<String> clerkIdList = null ;
                String staffId = staffIdList.get(i) ;
                TabHaobanStaff staff = this.staffMapper.selectByPrimaryKeyNoStatus(staffId) ;
                if(null != staff) {
                    if (null != staff.getDelTime()) {
                        Date delTime = DateUtil.addNumForMinute(staff.getDelTime(), -5);
                        clerkIdList = this.tabHaobanStaffClerkRelationMapper.taskoverClerkIdList(staffId, delTime);
                        if (CollectionUtils.isNotEmpty(clerkIdList)) {
                            takeoverClerkIdList.addAll(clerkIdList);
                        }
                        if (CollectionUtils.isEmpty(clerkIdList)) {
                            List<TabHaobanStaffClerkRelation> list = this.tabHaobanStaffClerkRelationMapper.taskoverClerkIdListAll(staffId);
                            if (CollectionUtils.isNotEmpty(list)) {
                                takeoverClerkIdList.add(list.get(0).getClerkId());
                            }
                        }
                    }
                }
            }
        }
        return takeoverClerkIdList;
    }

    @Override
    public List<String> listAllClerkIdsByEnterpriseId(String enterpriseId) {
        return this.staffClerkRelationService.listAllClerkIdsByEnterpriseId(enterpriseId);
    }

    @Override
    public List<String> listAlStoreIdsByEnterpriseId(String enterpriseId) {
        return this.staffClerkRelationService.listAlStoreIdsByEnterpriseId(enterpriseId);
    }

    @Override
    public ServiceResponse<Map<String, List<String>>> listClerkForCanvas(String wxEnterpriseId, String enterpriseId, String creatorId, String storeFilterId) {
        return staffClerkRelationService.listClerkForCanvas(wxEnterpriseId,enterpriseId,creatorId,storeFilterId);
    }
}
