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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.gic.commons.util.DateUtil;
import com.gic.haoban.manage.service.entity.*;
import com.gic.redis.data.util.RedisUtil;
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 com.alibaba.fastjson.JSON;
import com.gic.api.base.commons.Page;
import com.gic.clerk.api.dto.ClerkDTO;
import com.gic.clerk.api.service.ClerkService;
import com.gic.clerk.api.service.RightService;
import com.gic.commons.util.EntityUtil;
import com.gic.enterprise.api.dto.StoreDTO;
import com.gic.enterprise.api.service.StoreService;
import com.gic.haoban.base.api.common.BasePageInfo;
import com.gic.haoban.common.utils.PageUtil;
import com.gic.haoban.common.utils.StringUtil;
import com.gic.haoban.manage.api.dto.CommonMQDTO;
import com.gic.haoban.manage.api.dto.StaffClerkRelationDTO;
import com.gic.haoban.manage.api.dto.WxEnterpriseQwDTO;
import com.gic.haoban.manage.api.dto.qdto.hm.HmQrcodeQDTO;
import com.gic.haoban.manage.api.enums.BindTypeEnum;
import com.gic.haoban.manage.api.enums.ChannelCodeEnum;
import com.gic.haoban.manage.api.service.HaobanCommonMQApiService;
import com.gic.haoban.manage.api.service.hm.HmClerkRelationApiService;
import com.gic.haoban.manage.api.service.hm.HmQrcodeApiService;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanExternalClerkRelatedMapper;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanMemberClerkChatConfigMapper;
import com.gic.haoban.manage.service.dao.mapper.TabHaobanStaffClerkRelationMapper;
import com.gic.haoban.manage.service.service.ClerkMainStoreRelatedService;
import com.gic.haoban.manage.service.service.ExternalClerkRelatedService;
import com.gic.haoban.manage.service.service.StaffClerkBindLogService;
import com.gic.haoban.manage.service.service.StaffClerkRelationService;
import com.gic.haoban.manage.service.service.StaffService;
import com.gic.haoban.manage.service.service.WxEnterpriseService;
import com.gic.member.api.service.MemberApiService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

@Service
public class StaffClerkRelationServiceImpl implements StaffClerkRelationService {

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

    @Autowired
    private TabHaobanStaffClerkRelationMapper mapper;

    @Autowired
    private StaffClerkBindLogService staffClerkBindLogService;

    @Autowired
    private ExternalClerkRelatedService externalClerkRelatedService;
    @Autowired
    private HaobanCommonMQApiService haobanCommonMQApiService ;
    @Autowired
    private ClerkMainStoreRelatedService clerkMainStoreRelatedService;
    @Autowired
    private TabHaobanExternalClerkRelatedMapper externalClerkRelatedMapper;
    @Autowired
    private TabHaobanMemberClerkChatConfigMapper memberClerkChatConfigMapper;
    @Autowired
    private StoreService storeService ;
    @Autowired
    private HmQrcodeApiService hmQrcodeApiService;
    @Autowired
    private StaffService staffService;
    @Autowired
    private HmClerkRelationApiService hmClerkRelationApiService;
    @Autowired
    private WxEnterpriseService wxEnterpriseService;
    @Autowired
    private MemberApiService memberApiService;
    @Autowired
    private ClerkService clerkService;

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

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

    private String changeExistClerk(String wxEnterpriseId , String staffId , String newClerkId) {
        if(StringUtils.isBlank(newClerkId)) {
            return newClerkId ;
        }
        ClerkDTO clerkDTO = this.clerkService.getclerkById(newClerkId) ;
        String storeId = clerkDTO.getStoreId() ;
        List<StaffClerkRelationDTO> relationList = this.listByStaffId(wxEnterpriseId, staffId) ;
        if(CollectionUtils.isEmpty(relationList)) {
            return newClerkId ;
        }
        relationList =  relationList.stream().filter(o->o.getStoreId().equals(storeId)).collect(Collectors.toList()) ;
        if(CollectionUtils.isEmpty(relationList)) {
            return newClerkId ;
        }
        return relationList.get(0).getClerkId() ;
    }


    /*
     *  导购进行解绑/换导购，更新好友和导购关联关系
     */
    @Override
    public boolean delBind(String oldClerkId, String optStaffId, int channelCode, String newClerkId, String wxEnterpriseId) {
        boolean changeClerkFlag = StringUtils.isNotEmpty(newClerkId) ;
        logger.info("导购解绑/换导购={},oldClerkId={},optStaffId={},newClerkId={},channelCode={}",changeClerkFlag,oldClerkId,optStaffId,newClerkId,channelCode);
        if(StringUtils.isNotEmpty(optStaffId) && !"-1".equals(optStaffId)) {
            TabHaobanStaff staff =  this.staffService.selectById(optStaffId) ;
            if(null != staff) {
                wxEnterpriseId = staff.getWxEnterpriseId() ;
            }
        }
        // wxEnterpriseId非必传
        StaffClerkRelationDTO clerkRelation = mapper.getOneByClerkId(oldClerkId, wxEnterpriseId);
        if (null == clerkRelation) {
            logger.info("老的绑定关联不存在,oldClerkId={}", oldClerkId);
            return true;
        }
        newClerkId = this.changeExistClerk(clerkRelation.getWxEnterpriseId() ,clerkRelation.getStaffId() , newClerkId) ;
        logger.info("转换后的新导购={}",newClerkId);
        // 如果是区经
        if(clerkRelation.getManageFlag()==1) {
            this.mapper.changeStatusByClerkId(oldClerkId, 0);
            return true ;
        }
        wxEnterpriseId = clerkRelation.getWxEnterpriseId() ; 
        String enterpriseId = clerkRelation.getEnterpriseId();
        logger.info("当前删除换绑的商户={},{}",enterpriseId,wxEnterpriseId);
        String staffId = clerkRelation.getStaffId() ;
        String storeId = clerkRelation.getStoreId() ;
        boolean needFlush = false ;
        boolean delFlag = true ;
        if(StringUtils.isEmpty(newClerkId)) {
            // 成员关联的门店
            List<StaffClerkRelationDTO> relationList = this.listByStaffId(wxEnterpriseId, staffId) ;
            Set<String> set = relationList.stream().map(o->o.getEnterpriseId()).collect(Collectors.toSet()) ;
            // 否关联的多个商户
            logger.info("关联商户={}",set.size());
            boolean multipleFlag = set.size() > 1 ;
            List<String> storeIdList = relationList.stream().filter(o->!storeId.equals(o.getStoreId()) && o.getEnterpriseId().equals(enterpriseId)).map(o->o.getStoreId()).collect(Collectors.toList()) ;
            logger.info("成员{},关联门店数={},同商户下的门店={}",staffId,relationList.size(),JSON.toJSON(storeIdList));
            if(CollectionUtils.isNotEmpty(storeIdList)) {
                if(multipleFlag) {
                    needFlush = true ;
                    TabHaobanClerkMainStoreRelated currentMainStore = this.clerkMainStoreRelatedService.selectStaffMainStore(staffId, wxEnterpriseId);
                    String mainStoreEnterpriseId = null ;
                    if(null == currentMainStore) {
                        mainStoreEnterpriseId = enterpriseId ;
                    }else {
                      String mainStoreId = currentMainStore.getStoreId() ;
                      StoreDTO store = this.storeService.getStore(mainStoreId) ;  
                      mainStoreEnterpriseId = store.getEnterpriseId() ;
                    }
                    logger.info("当前主门店商户和处理商户是否一致{},{}",mainStoreEnterpriseId,enterpriseId);
                    if(mainStoreEnterpriseId.equals(enterpriseId)) {
                        // 删除关联关系
                        this.mapper.changeStatusByClerkId(oldClerkId, 0);
                        delFlag = false ;
                        TabHaobanClerkMainStoreRelated mainStoreRelation = this.clerkMainStoreRelatedService.getMainStoreByStaffId(staffId, wxEnterpriseId, storeIdList) ;
                        String newStoreId = mainStoreRelation.getStoreId() ;
                        StaffClerkRelationDTO mainClerk = this.getOneBindByStoreId(staffId, newStoreId) ;
                        newClerkId = mainClerk.getClerkId() ;
                        logger.info("查询到成员的主门店导购={},{}",staffId,newClerkId);
                        needFlush = false ;
                    }
                }else {
                    // 删除关联关系
                    this.mapper.changeStatusByClerkId(oldClerkId, 0);
                    delFlag = false ;
                    TabHaobanClerkMainStoreRelated mainStore = this.clerkMainStoreRelatedService.getMainStoreByStaffId(staffId, wxEnterpriseId, storeIdList) ;
                    String newStoreId = mainStore.getStoreId() ;
                    StaffClerkRelationDTO mainClerk = this.getOneBindByStoreId(staffId, newStoreId) ;
                    newClerkId = mainClerk.getClerkId() ;
                    logger.info("查询到成员的主门店导购={},{}",staffId,newClerkId);
                }
            }else {
                if(multipleFlag) {
                    needFlush = true ;
                }
            }
        }
        // 删除关联关系
        if(delFlag) {
            this.mapper.changeStatusByClerkId(oldClerkId, 0);
        }
       
        if(StringUtils.isNotBlank(newClerkId)) {
            List<String> memberIdList = this.externalClerkRelatedMapper.listByClerkId(staffId, oldClerkId) ;
            this.externalClerkRelatedService.updateClerkInfo(staffId , oldClerkId , newClerkId) ;
            if(CollectionUtils.isNotEmpty(memberIdList)) {
                for(String memberId : memberIdList) {
                    logger.info("会员={}",memberId);
                    CommonMQDTO dto = new CommonMQDTO();
                    dto.setType(3);
                    Map<String,String> map = new HashMap<>() ;
                    map.put("enterpriseId", enterpriseId) ;
                    map.put("memberId", memberId) ;
                    map.put("clerkId", newClerkId) ;
                    dto.setParams(map);
                    this.haobanCommonMQApiService.putCommonMessage(dto);
                }
            }
        }else {
            logger.info("成员删除所有关联导购={}",staffId);
            List<String> memberIds = externalClerkRelatedService.getByStoreIdAndStaffId(storeId, staffId);
            //删除 并设置主门店
            clerkMainStoreRelatedService.delMainStore(staffId, storeId, wxEnterpriseId);
            //推入日志
            // delMemberQywxFlag(enterpriseId, memberIds);
            this.haobanCommonMQApiService.putToNoticeMemberMQ(enterpriseId,memberIds);
        }
        if(needFlush) {
            logger.info("解绑自动刷新好友,staffId={}",staffId);
            this.clerkMainStoreRelatedService.reflushExternal(wxEnterpriseId, staffId); 
        }
        this.staffClerkBindLogService.pushToMq(staffId, optStaffId, BindTypeEnum.UNBIND.getVal(), channelCode, clerkRelation.getStaffClerkRelationId());
        //废弃活码
        this.hmClerkRelationApiService.delByClerkId(oldClerkId, enterpriseId, wxEnterpriseId, channelCode, null);
        return true;
    }


    public void delMemberQywxFlag(String enterpriseId, List<String> memberIds) {
        for (String memberId : memberIds) {
            //解绑通知会员
            int count = externalClerkRelatedService.getCountByMemberId(memberId);
            if (count == 0) {
                logger.info("通知会员 删除企微好友,该会员无任何好友关系，memberId:{}", memberId);
//                memberApiService.updateMemberQywxFlag(enterpriseId, memberId, 0);
                // 查询好办外部联系人接口,获取最近删除的时间
                List<TabHaobanExternalClerkRelated> memberList = externalClerkRelatedService.getAddTimeByMemberId(memberId, enterpriseId,null);
                Date date = new Date();
                Date opTime = new Date(0);
                if (CollectionUtils.isNotEmpty(memberList)){
                    for (TabHaobanExternalClerkRelated a : memberList){
                        if ((a.getStatusFlag() == 0 || a.getStatusFlag() == 2) && a.getUpdateTime().after(opTime)){
                            opTime= a.getUpdateTime();
                            date = opTime;
                        }
                    }
                }
                memberApiService.updateMemberQywxEveryOccasion(enterpriseId, memberId, 0, date,null);
                continue;
            }
            //logger.info("通知会员 删除企微好友 每次调用更新为非企微好友时间 memberId：{}", memberId);
            //memberApiService.updateMemberQywxEveryOccasion(enterpriseId, memberId, 1, new Date());
        }
    }

    @Override
    public void addMemberQywxFlag(String enterpriseId, String memberId) {
        List<TabHaobanExternalClerkRelated> memberList = externalClerkRelatedService.getAddTimeByMemberId(memberId, enterpriseId,"1");
        Date date = new Date();
        Date opTime = new Date(0);
        Date firstTime = new Date();
        if (CollectionUtils.isNotEmpty(memberList)){
            for (TabHaobanExternalClerkRelated a : memberList){
                if(null == a.getAddTime()) {
                    continue;
                }
                Date addTime = new Date(a.getAddTime() * 1000L);
                if ((a.getStatusFlag() == 1 || a.getStatusFlag() == 3 || a.getStatusFlag() == 4) && opTime.before(addTime)){
                    opTime= addTime;
                    date = opTime;
                }
                if (firstTime.after(addTime)){
                    firstTime = addTime;
                }
            }
            this.memberApiService.updateMemberQywxEveryOccasion(enterpriseId, memberId, 1, date,firstTime);
        }
    }

    @Override
    public boolean delBindByStoreIds(String wxEnterpriseId, Set<String> storeIds, String optStaffId, int channelCode) {
        if (CollectionUtils.isEmpty(storeIds)) {
            logger.info("没有传门店列表：{}", wxEnterpriseId);
            return true;
        }
        List<String> storeIdList = new ArrayList<>();
        storeIdList.addAll(storeIds) ;
        List<StaffClerkRelationDTO> needUnbind = mapper.listByStoreIds(wxEnterpriseId, storeIdList);
        if (CollectionUtils.isEmpty(needUnbind)) {
            logger.info("没有门店绑定了需要解绑的：{}", wxEnterpriseId);
            return true;
        }

        for (StaffClerkRelationDTO staffClerkRelation : needUnbind) {
            String enterpriseId = staffClerkRelation.getEnterpriseId();
            //删除好友通知会员
            List<String> memberIds = externalClerkRelatedService.getByStoreIdAndStaffId(staffClerkRelation.getStoreId(), staffClerkRelation.getStaffId());
            // delMemberQywxFlag(enterpriseId, memberIds);
            this.haobanCommonMQApiService.putToNoticeMemberMQ(enterpriseId,memberIds);
        }

        List<String> need = needUnbind.stream().map(tab -> tab.getStaffClerkRelationId()).collect(Collectors.toList());
        //清除绑定
        mapper.delByStoreIds(storeIds);
        //删除主门店
        clerkMainStoreRelatedService.delMainStoreByStoreIds(storeIds);
        //放入队列
        staffClerkBindLogService.pushToMqBatch(optStaffId, BindTypeEnum.UNBIND.getVal(), channelCode, need);
        for (StaffClerkRelationDTO clerkRelation : needUnbind) {
            //废弃活码
            String enterpriseId = clerkRelation.getEnterpriseId();
            hmClerkRelationApiService.delByClerkId(clerkRelation.getClerkId(), enterpriseId, wxEnterpriseId, channelCode);
        }
        return true;
    }

    @Override
    public String bind(StaffClerkRelationDTO dto, String optStaffId, int channelCode) {
        String staffId = dto.getStaffId();
        TabHaobanStaff tabHaobanStaff = staffService.selectById(staffId);
        if (tabHaobanStaff == null) {
            logger.error("员工不存在:{}", staffId);
            return "";
        }
        ClerkDTO clerkDTO = clerkService.getClerkByClerkId(dto.getClerkId());
        if (clerkDTO != null) {
            dto.setClerkType(clerkDTO.getClerkType());
        }
        String staffClerkRelationId = insert(dto);
        if (StringUtils.isNotBlank(staffClerkRelationId)) {
            String wxEnterpriseId = dto.getWxEnterpriseId();
            Integer manageFlag = dto.getManageFlag();
            String enterpriseId = dto.getEnterpriseId();
            //导购和店长需要设置主门店
            if (manageFlag != null && manageFlag == 1) {
                //do nothing
            } else {
                logger.info("设置主门店并创建活码：manageFlag:{},staffId:{}", manageFlag, staffId);
                TabHaobanClerkMainStoreRelated mainStore = clerkMainStoreRelatedService.getMainStoreByStaffId(staffId, wxEnterpriseId);
                // 判断是主门店
                if(null != mainStore && mainStore.getStoreId().equals(dto.getStoreId())) {
                    this.clerkMainStoreRelatedService.reflushExternal(wxEnterpriseId, staffId);
                }
                //有活码权限的企业
                HmQrcodeQDTO hmQrcodeQDTO = new HmQrcodeQDTO();
                hmQrcodeQDTO.setHmType(1);
                hmQrcodeQDTO.setWxEnterpriseId(wxEnterpriseId);
                hmQrcodeQDTO.setEnterpriseId(enterpriseId);
                hmQrcodeQDTO.setName(tabHaobanStaff.getStaffName());
                hmQrcodeQDTO.setPassFlag(1);
                hmQrcodeQDTO.setStoreId(dto.getStoreId());
                hmQrcodeQDTO.setClerkIdList(Collections.singletonList(dto.getClerkId()));
                hmQrcodeQDTO.setInvokingType(channelCode);
                hmQrcodeApiService.add(hmQrcodeQDTO);
            }
            //推入日志
            staffClerkBindLogService.pushToMq(staffId, optStaffId, BindTypeEnum.BIND.getVal(), channelCode, staffClerkRelationId);
        }
        return staffClerkRelationId;
    }


    @Override
    public StaffClerkRelationDTO getBindByClerkId(String clerkId, String wxEnterpriseId) {
        return this.filterDelClerk(mapper.getOneByClerkId(clerkId, wxEnterpriseId));
    }

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

    @Override
    public StaffClerkRelationDTO getStaffClerkRelationDTO(String clerkCode, String enterpriseId) {
        return mapper.getStaffClerkRelationDTO(clerkCode, enterpriseId);
    }


    @Override
    public String insert(StaffClerkRelationDTO staffClerkRelation) {
        Integer manageFlag = staffClerkRelation.getManageFlag();
        String uuid = StringUtil.randomUUID();
        staffClerkRelation.setStaffClerkRelationId(uuid);
        staffClerkRelation.setCreateTime(new Date());
        staffClerkRelation.setUpdateTime(new Date());
        staffClerkRelation.setStatusFlag(1);
        staffClerkRelation.setOpenConcatFlag(1);
        staffClerkRelation.setManageFlag(manageFlag == null ? 0 : manageFlag);

        TabHaobanStaffClerkRelation relation = EntityUtil.changeEntityByJSON(TabHaobanStaffClerkRelation.class, staffClerkRelation);
        String lockKey = "staffclerk:"+staffClerkRelation.getStaffId()+staffClerkRelation.getClerkId() ;
        RedisUtil.lock(lockKey, 2L, TimeUnit.SECONDS, 2L);
        StaffClerkRelationDTO dto = this.mapper.getByStaffAndClerk(staffClerkRelation.getStaffId(),staffClerkRelation.getClerkId()) ;
        if(null != dto) {
            RedisUtil.unlock(lockKey);
            return dto.getStaffClerkRelationId() ;
        }
        mapper.insert(relation);
        RedisUtil.unlock(lockKey);
        return uuid;
    }

    @Override
    public int cleanStaffClerk(String wxEnterpriseId, List<String> delStaffIds) {
        delStaffIds.forEach(staffId -> {
            List<StaffClerkRelationDTO> relationDTOS = listBindCodeByStaffId(null, staffId);
            if (CollectionUtils.isNotEmpty(relationDTOS)) {
                relationDTOS.forEach(mid -> {
                    staffClerkBindLogService.pushToMq(mid.getStaffId(), "-1", BindTypeEnum.UNBIND.getVal(), ChannelCodeEnum.WEIXIN_DEL.getCode(), mid.getStaffClerkRelationId());
                });
            }
        });
        int ret = mapper.cleanStaffDepart(wxEnterpriseId, delStaffIds);
        externalClerkRelatedService.cleanStaffRelated(wxEnterpriseId, delStaffIds);
        return ret;
    }

    @Override
    public StaffClerkRelationDTO getOneBindByStoreId(String staffId, String storeId) {
        StaffClerkRelationDTO dto = this.filterDelClerk(mapper.getOneByStoreIdAndStaffId(storeId,staffId));
        return dto ;
    }

    @Override
    public StaffClerkRelationDTO getByClerkId(String clerkId) {
        return this.filterDelClerk(mapper.getOneByClerkId(clerkId, null));
    }

    @Override
    public StaffClerkRelationDTO getByClerkId(String clerkId, String wxEnterpriseId) {
        StaffClerkRelationDTO staffClerkRelation = mapper.getOneByClerkId(clerkId, wxEnterpriseId);
        return EntityUtil.changeEntityNew(StaffClerkRelationDTO.class, staffClerkRelation);
    }

    @Override
    public List<StaffClerkRelationDTO> listByClerkIds(List<String> clerkList) {
        if (CollectionUtils.isEmpty(clerkList)) {
            return Collections.EMPTY_LIST;
        }
        return mapper.listByClerkIds(clerkList, null);
    }

    @Override
    public List<StaffClerkRelationDTO> listByStaffId(String wxEnterpriseId, String staffId) {
        return EntityUtil.changeEntityListByJSON(StaffClerkRelationDTO.class, mapper.lisByStaffId(wxEnterpriseId, staffId, null));
    }

    @Override
    public List<StaffClerkRelationDTO> listByStaffId(String wxEnterpriseId, String staffId, List<String> storeIdList) {
        return EntityUtil.changeEntityListByJSON(StaffClerkRelationDTO.class, mapper.lisByStaffId(wxEnterpriseId, staffId, storeIdList));
    }

    @Override
    public void saveChatConfig(MemberClerkChatConfig memberClerkChatConfig) {
        memberClerkChatConfig.setStatus(1);
        memberClerkChatConfig.setCreateTime(new Date());
        memberClerkChatConfig.setUpdateTime(new Date());
        memberClerkChatConfigMapper.insert(memberClerkChatConfig);
    }

    @Override
    public MemberClerkChatConfig getChatConfig(String staffId, String memberId) {
        MemberClerkChatConfig chatConfig = memberClerkChatConfigMapper.getChatByMemberIdStaffId(memberId, staffId);
        return chatConfig;
    }

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

    @Override
    public Page<StaffClerkRelationDTO> pageByWxEnterpriseId(String wxEnterpriseId, BasePageInfo pageInfo) {
        PageHelper.startPage(pageInfo);
        List<StaffClerkRelationDTO> clerkBindList = mapper.pageByWxEnterpriseId(wxEnterpriseId);
        Page<StaffClerkRelationDTO> retPage = PageUtil.changePageHelperToCurrentPage(new PageInfo<>(clerkBindList), StaffClerkRelationDTO.class);
        return retPage;
    }

    @Override
    public List<StaffClerkRelationDTO> listBindByStoreId(String wxEnterpriseId, String storeId) {
        return mapper.listByStoreIds(wxEnterpriseId, Arrays.asList(storeId));
    }

    @Override
    public List<StaffClerkRelationDTO> listBindStoreIdByEnterpriseId(String enterpriseId) {
        List<StaffClerkRelationDTO> clerkRelations = mapper.listBindStoreIdByEnterpriseId(enterpriseId);
        if (CollectionUtils.isEmpty(clerkRelations)) {
            return new ArrayList<>();
        }
        return EntityUtil.changeEntityListNew(StaffClerkRelationDTO.class, clerkRelations);
    }

    @Override
    public List<String> listRelationsStaffId(Set<String> staffIdList) {
        return mapper.listRelationsStaffId(staffIdList);
    }

    @Override
    public List<String> listWxUserIdByClerkIds(List<String> clerkList, String wxEnterpriseId) {
        if (CollectionUtils.isEmpty(clerkList)) {
            return null;
        }
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId);
        if (qwDTO.needOpenUserId3th()) {
            return mapper.listWxUserIdByClerkIds(clerkList, wxEnterpriseId,2);
        }
        return mapper.listWxUserIdByClerkIds(clerkList, wxEnterpriseId,1);
    }

    @Override
    public List<StaffClerkRelationDTO> listIdsByWxUserIds(List<String> wxUserIds, String wxEnterpriseId, String enterpriseId) {
        if (CollectionUtils.isEmpty(wxUserIds)) {
            return null;
        }
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId);
        if (qwDTO.needOpenUserId3th()) {
            return mapper.listIdsByWxUserIds(wxUserIds, wxEnterpriseId, enterpriseId,2);
        }
        return mapper.listIdsByWxUserIds(wxUserIds, wxEnterpriseId, enterpriseId,1);
    }

    @Override
    public List<StaffClerkRelationDTO> listIdsByNotInWxUserIds(List<String> wxUserIds, String wxEnterpriseId, String enterpriseId) {
        if (CollectionUtils.isEmpty(wxUserIds)) {
            return null;
        }
        WxEnterpriseQwDTO qwDTO = this.wxEnterpriseService.getQwInfo(wxEnterpriseId);
        if (qwDTO.needOpenUserId3th()) {
            return mapper.listIdsByNotInWxOpenUserIds(wxUserIds, wxEnterpriseId, enterpriseId);
        }
        return mapper.listIdsByNotInWxUserIds(wxUserIds, wxEnterpriseId, enterpriseId);
    }

    @Override
    public int updateOpenConcatFlagById(Integer openConcatFlag, String staffClerkRelationId) {
        return mapper.updateOpenConcatFlagById(openConcatFlag, staffClerkRelationId);
    }

    @Override
    public boolean getBindByStaffIdAndEnterpriseId(String enterpriseId, String staffId) {
        return mapper.getBindByStaffIdAndEnterpriseId(enterpriseId, staffId) > 0;
    }

    @Override
    public List<StaffClerkRelationDTO> listManageBindByStaffId(String staffId) {
        return this.filterDelClerkList(mapper.listManageBindByStaffId(staffId));
    }
    
    private List<StaffClerkRelationDTO> filterDelClerkList(List<StaffClerkRelationDTO> list) {
        if(CollectionUtils.isEmpty(list)) {
            return list ;
        }
        List<StaffClerkRelationDTO> retList = new ArrayList<>() ;
        for(StaffClerkRelationDTO item : list) {
            boolean delFlag = false ;
            String clerkId = item.getClerkId() ;
            ClerkDTO clerk = this.clerkService.getclerkById(clerkId) ;
            if(null == clerk || clerk.getStatus() != 1) {
                delFlag = true ;
            }
            if(!delFlag && null != clerk && clerk.getClerkType()<2 && StringUtils.isNotEmpty(clerk.getStoreId())) {
                StoreDTO store = this.storeService.getStore(clerk.getStoreId()) ;
                if(null == store || store.getStatus() == -3) {
                    delFlag = true ;
                }
            }
            if(delFlag) {
                Date time = DateUtil.addDay(new Date(),-1);
                if (null != clerk && clerk.getUpdateTime().before(time)){
                    this.mapper.delByClerkId(clerkId);
                }
            }else {
                retList.add(item) ;
            }
        }
        return retList ;
    }
    
    private StaffClerkRelationDTO filterDelClerk(StaffClerkRelationDTO dto) {
        if(null == dto) {
            return dto ;
        }
        String clerkId = dto.getClerkId() ;
        ClerkDTO clerk = this.clerkService.getclerkById(clerkId) ;
        boolean delFlag = false ;
        if(null == clerk || clerk.getStatus() != 1) {
            delFlag = true ;
        }
        if(!delFlag &&  null != clerk && clerk.getClerkType() <2 && StringUtils.isNotEmpty(clerk.getStoreId())) {
            StoreDTO store = this.storeService.getStore(clerk.getStoreId()) ;
            if(null == store || store.getStatus() == -3) {
                delFlag = true ;
            }
        }
        if(delFlag) {
            Date time = DateUtil.addDay(new Date(),-1);
            if (null != clerk && clerk.getUpdateTime().before(time)){
                this.mapper.delByClerkId(clerkId);
            }
            dto = null ;
        }
        return dto ;
    }

    /**
     * 获取企业下所有关联关系
     *
     * @param enterpriseId
     * @return
     */
    @Override
    public List<String> listAllClerkIdsByEnterpriseId(String enterpriseId) {
        return this.mapper.listAllClerkIdsByEnterpriseId(enterpriseId);
    }

    @Override
    public List<StaffClerkRelationDTO>listByWxEnterpriseIdAndStaffId(String wxEnterpriseId, Set<String> staffIdList) {
        return this.mapper.listByWxEnterpriseIdAndStaffId(wxEnterpriseId,staffIdList);
    }

    @Override
    public List<String> listAllStaffIdByEnterpriseId(String enterpriseId, String wxEnterpriseId) {
        return this.mapper.listAllStaffIdByEnterpriseId(enterpriseId,wxEnterpriseId);
    }

    @Override
    public List<String> listAllStaffIdForOpenStaff(String enterpriseId, String wxEnterpriseId, String clerkId, List<String> storeIdList) {
        return this.mapper.listAllStaffIdForOpenStaff(enterpriseId,wxEnterpriseId,clerkId,storeIdList);
    }
}
