package com.kiisoo.ic.generalize.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.kiisoo.ic.customer.entity.OpSellerCustomerRelation;
import com.kiisoo.ic.customer.mapper.OpSellerCustomerRelationDOMapper;
import com.kiisoo.ic.domain.service.PrivilageDomainService;
import com.kiisoo.ic.generalize.bean.*;
import com.kiisoo.ic.generalize.entity.*;
import com.kiisoo.ic.generalize.mapper.OrganizationalMemberMapper;
import com.kiisoo.ic.generalize.mapper.PoiCustomerContactDataStatMapper;
import com.kiisoo.ic.generalize.mapper.RetailCompanyMapper;
import com.kiisoo.ic.store.entity.PoiStore;
import com.kiisoo.ic.store.entity.PoiStoreStaff;
import com.kiisoo.ic.store.mapper.PoiStoreDOMapper;
import com.kiisoo.ic.store.mapper.PoiStoreStaffDOMapper;
import com.kiisoo.ic.system.entity.PrivilageRoleDO;
import com.kiisoo.ic.system.entity.PrivilageUserDO;
import com.kiisoo.ic.system.enums.RoleEnum;
import com.kiisoo.ic.system.mapper.PrivilageUserDOMapper;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @ClassName: RetailCompanyService
 * @Description:
 * @Auther: Caps
 * @Date: 2020/4/15 0015 11:08
 * @Version:
 */
@Service
public class RetailCompanyService {

    /**
     * 区域
     */
    static final Integer LEVEL_REGION = 1;
    /**
     * 零售公司
     */
    static final Integer LEVEL_COMPANY = 2;
    /**
     * 客户
     */
    static final Integer LEVEL_CUSTOMER = 3;

    private RetailCompanyMapper retailCompanyMapper;

    private OrganizationalMemberMapper organizationalMemberMapper;

    private OpSellerCustomerRelationDOMapper opSellerCustomerRelationDOMapper;

    private PoiCustomerContactDataStatMapper poiCustomerContactDataStatMapper;

    private PoiStoreDOMapper poiStoreDOMapper;

    private PrivilageUserDOMapper privilageUserDOMapper;

    private PoiStoreStaffDOMapper poiStoreStaffDOMapper;
    /**
     * 用户权限mapper
     */
    @Autowired
    private PrivilageDomainService privilageDomainService;

    /**
     * 线程池(用多线程查数据)
     */
    private ThreadPoolExecutor pools = new ThreadPoolExecutor(10, 50, 3600L, TimeUnit.SECONDS,
            new ArrayBlockingQueue<Runnable>(5000), new ThreadPoolExecutor.CallerRunsPolicy());

    @Autowired
    public RetailCompanyService(RetailCompanyMapper retailCompanyMapper, OrganizationalMemberMapper organizationalMemberMapper, OpSellerCustomerRelationDOMapper opSellerCustomerRelationDOMapper, PoiCustomerContactDataStatMapper poiCustomerContactDataStatMapper, PoiStoreDOMapper poiStoreDOMapper, PrivilageUserDOMapper privilageUserDOMapper, PoiStoreStaffDOMapper poiStoreStaffDOMapper) {
        this.retailCompanyMapper = retailCompanyMapper;
        this.organizationalMemberMapper = organizationalMemberMapper;
        this.opSellerCustomerRelationDOMapper = opSellerCustomerRelationDOMapper;
        this.poiCustomerContactDataStatMapper = poiCustomerContactDataStatMapper;
        this.poiStoreDOMapper = poiStoreDOMapper;
        this.privilageUserDOMapper = privilageUserDOMapper;
        this.poiStoreStaffDOMapper = poiStoreStaffDOMapper;
    }


    /**
     * 找到用户公司
     *
     * @param parentId 父区域id
     * @param userId   用户id
     * @param level    等级
     * @return
     */
    public List<PrivilageOrganizational> getUserOrg(Long parentId, long userId, int level) {

        QueryWrapper<PrivilageOrganizationalMember> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id", userId);
        PrivilageOrganizational p = new PrivilageOrganizational();
        List<PrivilageOrganizationalMember> pm = organizationalMemberMapper.selectList(wrapper1);
        QueryWrapper<PrivilageOrganizational> wrapper = new QueryWrapper<>();
        if (check(userId)) {
            wrapper.eq("level", level).eq("type", 2).eq("status", 1);
            return retailCompanyMapper.selectList(wrapper);
        }
        if (pm.isEmpty()) {
            return new ArrayList<>();
        } else {
            wrapper.eq("type", 2).eq("status", 1).eq("level", level).
                    in("id", pm.stream().map(PrivilageOrganizationalMember::getOrgId).
                            collect(Collectors.toList()));
            if (null != parentId) {
                wrapper.eq("parent_id", parentId);
            }
            return retailCompanyMapper.selectList(wrapper);
        }
    }

    /**
     * 查询所有的大区信息
     */
    public List<PrivilageOrganizational> listOfBigRetailCompany(long userId) {
        QueryWrapper<PrivilageOrganizationalMember> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id", userId);
        List<PrivilageOrganizationalMember> pm = organizationalMemberMapper.selectList(wrapper1);
        QueryWrapper<PrivilageOrganizational> wrapper = new QueryWrapper<>();
        if (check(userId)) {
            wrapper.eq("type", 2).eq("level", 1).eq("status", 1);
            return retailCompanyMapper.selectList(wrapper);
        }
        if (pm.isEmpty()) {
            return new ArrayList<>();
        } else {
            wrapper.eq("type", 2).eq("level", 1).eq("status", 1).in("id", pm.stream().map(PrivilageOrganizationalMember::getOrgId).collect(Collectors.toList()));
            return retailCompanyMapper.selectList(wrapper);
        }
    }

    public boolean check(long userId) {
        //根据userId查询角色
        PrivilageRoleDO p = privilageUserDOMapper.selecctRoleByUserId(userId);
        if (p.getCode().equals(RoleEnum.ROLE_CODE_GLY.getRoleCode()) || p.getCode().equals(RoleEnum.ROLE_CODE_ALL_YYRY.getRoleCode())) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 查询所有的组织数据信息
     */
    public List<PrivilageOrganizational> listOfRetailOrg(long userId, Long regionId, Long companyId, Long customerId) {
        QueryWrapper<PrivilageOrganizationalMember> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id", userId);
        List<PrivilageOrganizationalMember> pm = organizationalMemberMapper.selectList(wrapper1);
        if (check(userId)) {
            return retailCompanyMapper.selectList(null);
        }
        if (pm.isEmpty()) {
            return new ArrayList<>();
        } else {
            List<Long> orgIds = pm.stream().map(PrivilageOrganizationalMember::getOrgId).collect(Collectors.toList());
            List<PrivilageOrganizationalRelationVO> orgRelationList = retailCompanyMapper.selectAllOrgListByOrgIds(orgIds, regionId, companyId, customerId);
            //所以组织list
            List<PrivilageOrganizational> tmpOrgList = new ArrayList<>();
            orgRelationList.forEach(orgRelationVO -> {
                PrivilageOrganizational regionDO = new PrivilageOrganizational();
                regionDO.setId(orgRelationVO.getRegionId());
                regionDO.setName(orgRelationVO.getRegion());
                regionDO.setLevel((long) LEVEL_REGION);
                regionDO.setParentId(0L);
                PrivilageOrganizational companyDO = new PrivilageOrganizational();
                companyDO.setId(orgRelationVO.getCompanyId());
                companyDO.setName(orgRelationVO.getCompany());
                companyDO.setLevel((long) LEVEL_COMPANY);
                companyDO.setParentId(orgRelationVO.getRegionId());
                PrivilageOrganizational customerDO = new PrivilageOrganizational();
                customerDO.setId(orgRelationVO.getCustomerId());
                customerDO.setName(orgRelationVO.getCustomer());
                customerDO.setLevel((long) LEVEL_CUSTOMER);
                customerDO.setParentId(orgRelationVO.getCompanyId());
                tmpOrgList.add(regionDO);
                tmpOrgList.add(companyDO);
                tmpOrgList.add(customerDO);
            });
            List<PrivilageOrganizational> orgList = tmpOrgList.stream().distinct().collect(Collectors.toList());
            return orgList;
        }
    }

    /**
     * 查询所有的零售公司信息
     */
    public List<PrivilageOrganizational> listOfRetailCompany(long userId, Long bigRegionId, Long orgId) {
        if (bigRegionId == null || bigRegionId == 0L) {
            bigRegionId = null;
        }
        QueryWrapper<PrivilageOrganizationalMember> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id", userId);
        List<PrivilageOrganizationalMember> pm = organizationalMemberMapper.selectList(wrapper1);
        QueryWrapper<PrivilageOrganizational> wrapper = new QueryWrapper<>();
        if (check(userId)) {
            wrapper.eq("type", 2).eq("level", 2).eq("status", 1);
            if (orgId != null) {
                wrapper.eq("id", orgId);
            }
            return retailCompanyMapper.selectList(wrapper);
        }
        if (pm.isEmpty()) {
            return new ArrayList<>();
        } else {
            wrapper.eq("type", 2).eq("level", 2).eq("status", 1).in("id", pm.stream().map(PrivilageOrganizationalMember::getOrgId).collect(Collectors.toList()));
            if (bigRegionId != null) {
                wrapper.eq("parent_id", bigRegionId);
            }
            if (orgId != null) {
                wrapper.eq("id", orgId);
            }
            return retailCompanyMapper.selectList(wrapper);
        }
    }

    /**
     * 查询所有的零售公司信息
     */
    public List<PrivilageOrganizational> listOfRetailCompanyPage(long userId, Long bigRegionId, Long orgId, int pageNum, int pageSize) {
        if (bigRegionId == null || bigRegionId == 0L) {
            bigRegionId = null;
        }
        QueryWrapper<PrivilageOrganizationalMember> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id", userId);
        List<PrivilageOrganizationalMember> pm = organizationalMemberMapper.selectList(wrapper1);
        QueryWrapper<PrivilageOrganizational> wrapper = new QueryWrapper<>();
        if (check(userId)) {
            wrapper.eq("type", 2).eq("level", 2).eq("status", 1);
            if (orgId != null) {
                wrapper.eq("id", orgId);
            }
            PageHelper.startPage(pageNum, pageSize);
            return retailCompanyMapper.selectList(wrapper);
        }
        if (pm.isEmpty()) {
            return new ArrayList<>();
        } else {
            wrapper.eq("type", 2).eq("level", 2).eq("status", 1).in("id", pm.stream().map(PrivilageOrganizationalMember::getOrgId).collect(Collectors.toList()));
            if (bigRegionId != null) {
                wrapper.eq("parent_id", bigRegionId);
            }
            if (orgId != null) {
                wrapper.eq("id", orgId);
            }
            PageHelper.startPage(pageNum, pageSize);
            return retailCompanyMapper.selectList(wrapper);
        }
    }

    /**
     * 查询零售公司下的店铺
     *
     * @param orgId 零售公司id
     * @return 门店信息
     */
    public List<PoiStore> selectShopByCompany(Long orgId) {
        //查询客户
        Set<Long> companyIds = new HashSet<>();
        companyIds.add(orgId);
        Set<Long> customerIds = retailCompanyMapper.selectChildList(companyIds);
        return poiStoreDOMapper.selectShopByCustomerIds(new ArrayList<>(customerIds));
    }

    /**
     * 查询零售公司下的店铺
     *
     * @param orgId 零售公司id
     * @return 门店ID集合
     * @author dexiang.jiang
     * @date 2020/05/17 12:07
     */
    public List<Long> selectStoreIdListByCompanyId(Long orgId) {
        //查询客户
        List<Long> storeIds = poiStoreDOMapper.selectShopIdByCustomerId(orgId);
        return storeIds;
    }

    /**
     * 查询零售公司下的店铺
     *
     * @param bigRegionId 零售公司id
     * @return 门店信息
     */
    public List<PoiStore> selectShopByBigRegion(Long bigRegionId) {
        //查询零售公司
        Set<Long> bigRegionIds = new HashSet<>();
        bigRegionIds.add(bigRegionId);
        Set<Long> companyIds = retailCompanyMapper.selectChildList(bigRegionIds);
        //查询客户
        Set<Long> customerIds = retailCompanyMapper.selectChildList(companyIds);
        return poiStoreDOMapper.selectShopByCustomerIds(new ArrayList<>(customerIds));
    }


    /**
     * 查询客户公司下的店铺
     *
     * @param orgId 零售公司id
     * @return 门店信息
     */
    public List<PoiStore> selectCustomerShopByCompany(Long orgId) {
        return poiStoreDOMapper.selectCustomerShopByCompany(orgId);
    }

    /**
     * 查询零售公司下的店铺
     *
     * @param shopId 零售公司id
     * @return 门店信息
     */
    public List<PrivilageUserDO> selectSellerByShop(Long shopId) {
        return poiStoreDOMapper.selectSellerByShop(shopId);
    }

    /**
     * 查询所有零售公司的推广数据
     *
     * @param userId    用户id
     * @param startTime 日期
     * @param endTime   日期
     * @param orgId     零售公司
     * @return 零售公司的推广数据
     */
    public OrganizationVO generalizeOfRetail(Long userId, String startTime, String endTime, Long orgId, int pageNum, int pageSize) {
        List<PrivilageOrganizational> listOfOrg = listOfRetailCompanyPage(userId, null, orgId, pageNum, pageSize);

        List<RetailOrganizationalVO> list = new ArrayList<>();
        listOfOrg.forEach(org -> {
            RetailOrganizationalVO organizationalVO = new RetailOrganizationalVO();
            organizationalVO.setRetailCompany(org.getName());

            //查询零售公司的门店
            List<Long> stores = selectStoreIdListByCompanyId(org.getId());

            if(CollectionUtils.isEmpty(stores)){
                organizationalVO.setAllCustomer(0);
                organizationalVO.setDelCustomer(0);
                organizationalVO.setDelRate(0);
                organizationalVO.setEffectiveCustomer(0);
                organizationalVO.setAvgNewCustomer(0);
                organizationalVO.setAvgNewEffectiveCustomer(0);
                organizationalVO.setNewCustomer(0);
                organizationalVO.setNewEffectiveCustomer(0);
                organizationalVO.setAvgStoreCustomer(0);
                list.add(organizationalVO);
                return;
            }
//            //根据门店查询导购人数
//            QueryWrapper<PoiStoreStaff> wrapperStaff = new QueryWrapper<>();
//            wrapperStaff.in("store_id",stores);
//            List<PoiStoreStaff> listStaff = poiStoreStaffDOMapper.selectList(wrapperStaff);

            //组织成员的客户个数
            QueryWrapper<OpSellerCustomerRelation> wrapper2 = new QueryWrapper<>();
            wrapper2.in("store_id", stores);
            List<OpSellerCustomerRelation> opRelations = opSellerCustomerRelationDOMapper.selectList(wrapper2);
            long count = opRelations.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
            organizationalVO.setAllCustomer((int) count);
            //组织成员的客户有效个数
            QueryWrapper<OpSellerCustomerRelation> wrapper4 = new QueryWrapper<>();
            wrapper4.in("store_id", stores);
            wrapper4.eq("type", 1);
            Integer countAble = opSellerCustomerRelationDOMapper.selectCount(wrapper4);
//            long countAble = opRelations1.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
            organizationalVO.setEffectiveCustomer(countAble);

            //计算新增客户数据
            newCustomerStore(startTime, endTime, organizationalVO, stores);

            //被拉黑的客户数
            if (!stores.isEmpty()) {
//                stores.add(-1L);
                QueryWrapper<PoiCustomerContactDataStat> wrapper3 = new QueryWrapper<>();
                wrapper3.in("store_id", stores);
                Integer allAge = poiCustomerContactDataStatMapper.sumNegativeFeedbackCntByStoreIds(stores);

                organizationalVO.setDelCustomer(allAge);
                organizationalVO.setDelRate(check(new Long(allAge), count));
            }

            Integer avgStoreCustomer = new BigDecimal(organizationalVO.getAllCustomer()).divide(new BigDecimal(stores.size()), BigDecimal.ROUND_HALF_UP).intValue();
            organizationalVO.setAvgStoreCustomer(avgStoreCustomer);
            list.add(organizationalVO);
        });
        OrganizationVO vo = new OrganizationVO();
        //总条数
        if (listOfOrg.size() > 0) {
            vo.setDataVOS(list);
            Page<PrivilageOrganizational> pageList = (Page<PrivilageOrganizational>) listOfOrg;
            long totalSize = pageList.getTotal();
            vo.setSizeNum(totalSize);
        } else {
            return new OrganizationVO();
        }
        return vo;
    }

    /**
     * 计算新增客户数和新增有效客户数
     *
     * @param startTime        开始时间
     * @param endTime          结束时间
     * @param organizationalVO 封装实体
     */
    private void newCustomerUser(String startTime, String endTime, DataVO organizationalVO, List<Long> userIds) {
        if (userIds.size() == 0) {
            return;
        }
        LocalDate l;
        //最初时间的总客户人数
        QueryWrapper<OpSellerCustomerRelation> wrapper2 = new QueryWrapper<>();
        wrapper2.in("user_id", userIds);
        wrapper2.lt("create_time", startTime);
        List<OpSellerCustomerRelation> opRelations = opSellerCustomerRelationDOMapper.selectList(wrapper2);
        long count = opRelations.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
        //最初时间的有效总客户人数
        wrapper2.in("user_id", userIds);
        wrapper2.eq("type", 1);
        wrapper2.lt("create_time", startTime);
        List<OpSellerCustomerRelation> opRelations2 = opSellerCustomerRelationDOMapper.selectList(wrapper2);
        long count2 = opRelations2.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
        //最后时间的总客户人数
        QueryWrapper<OpSellerCustomerRelation> wrapper3 = new QueryWrapper<>();
        wrapper3.in("user_id", userIds);
        l = LocalDate.parse(endTime);
        wrapper3.lt("create_time", l.plus(1, ChronoUnit.DAYS));
        List<OpSellerCustomerRelation> opRelationsEnd = opSellerCustomerRelationDOMapper.selectList(wrapper3);
        long countEnd = opRelationsEnd.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
        //最后时间的有效总客户人数
        wrapper3.in("user_id", userIds);
        wrapper3.eq("type", 1);
        wrapper3.lt("create_time", l.plus(1, ChronoUnit.DAYS));
        List<OpSellerCustomerRelation> opRelationsEnd2 = opSellerCustomerRelationDOMapper.selectList(wrapper3);
        long countEnd2 = opRelationsEnd2.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();

        //计算两个时间间隔用于计算平均值
        LocalDate start = LocalDate.parse(startTime);
        LocalDate end = LocalDate.parse(endTime);
        long days = start.until(end, ChronoUnit.DAYS) + 1;

        organizationalVO.setNewCustomer((int) (countEnd - count));
        organizationalVO.setNewEffectiveCustomer((int) (countEnd2 - count2));
        organizationalVO.setAvgNewCustomer(check1(countEnd - count, days));
        organizationalVO.setAvgNewEffectiveCustomer(check1(countEnd2 - count2, days));
    }

    private void newCustomerStore(String startTime, String endTime, DataVO organizationalVO, List<Long> storeIds) {
        LocalDate l;
        l = LocalDate.parse(endTime);
        //最初时间的总客户人数
        QueryWrapper<OpSellerCustomerRelation> wrapper2 = new QueryWrapper<>();
        wrapper2.in("store_id", storeIds);
        wrapper2.lt("create_time", startTime);
        List<OpSellerCustomerRelation> opRelations = opSellerCustomerRelationDOMapper.selectList(wrapper2);
        long count = opRelations.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
        //最初时间的有效总客户人数
        wrapper2.in("store_id", storeIds);
        wrapper2.eq("type", 1);
        wrapper2.lt("create_time", startTime);
        List<OpSellerCustomerRelation> opRelations2 = opSellerCustomerRelationDOMapper.selectList(wrapper2);
        long count2 = opRelations2.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
        //最后时间的总客户人数
        QueryWrapper<OpSellerCustomerRelation> wrapper3 = new QueryWrapper<>();
        wrapper3.in("store_id", storeIds);
        wrapper3.lt("create_time", l.plus(1, ChronoUnit.DAYS));
        List<OpSellerCustomerRelation> opRelationsEnd = opSellerCustomerRelationDOMapper.selectList(wrapper3);
        long countEnd = opRelationsEnd.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();
        //最后时间的有效总客户人数
        wrapper3.in("store_id", storeIds);
        wrapper3.eq("type", 1);
        wrapper3.lt("create_time", l.plus(1, ChronoUnit.DAYS));
        List<OpSellerCustomerRelation> opRelationsEnd2 = opSellerCustomerRelationDOMapper.selectList(wrapper3);
        long countEnd2 = opRelationsEnd2.stream().map(OpSellerCustomerRelation::getCustomerId).distinct().count();

        //计算两个时间间隔用于计算平均值
        LocalDate start = LocalDate.parse(startTime);
        LocalDate end = LocalDate.parse(endTime);
        long days = start.until(end, ChronoUnit.DAYS) + 1;

        organizationalVO.setNewCustomer((int) (countEnd - count));
        organizationalVO.setNewEffectiveCustomer((int) (countEnd2 - count2));
        organizationalVO.setAvgNewCustomer(check1(countEnd - count, days));
        organizationalVO.setAvgNewEffectiveCustomer(check1(countEnd2 - count2, days));
    }

    /**
     * 除法计算
     *
     * @param l1 被除数
     * @param l2 除数
     * @return 值
     */
    public Integer check(Long l1, Long l2) {
        if (l2 == null || l1 == null || l2 == 0) {
            return 0;
        } else {
            return Math.round((l1 / l2) * 100);
        }
    }

    /**
     * 除法计算
     *
     * @param l1 被除数
     * @param l2 除数
     * @return 值
     */
    public Integer check1(Long l1, Long l2) {
        if (l2 == null || l1 == null || l2 == 0) {
            return 0;
        } else {
            return Math.round((Float.parseFloat(l1.toString()) / Float.parseFloat(l2.toString())));
        }
    }

    /**
     * 查询门店推广数据
     *
     * @param startTime 日期
     * @param endTime   日期
     * @param orgId     零售公司id
     * @param shopId    门店id
     * @param pageNum   页码
     * @param pageSize  页面显示个数
     * @return 门店推广数据
     */
    public OrganizationVO generalizeOfStore(long userId, String startTime, String endTime, Long orgId, Long shopId, int pageNum, int pageSize) {
        //根据零售公司查询门店
        List<Long> shopIds = new ArrayList<>();
        if (shopId != null) {
            shopIds.add(shopId);
        } else {
            shopIds = privilageDomainService.listUserDatePermission(userId);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<CompanyStoreDO> list = retailCompanyMapper.selectShopIdByRetail(orgId, shopIds);

        //查询所有的店铺信息
        QueryWrapper<PoiStore> poiStoreQueryWrapper = new QueryWrapper<>();
        poiStoreQueryWrapper.in("id", shopIds);
        List<PoiStore> list2 = shopIds.size() == 0 ? new ArrayList<>() : poiStoreDOMapper.selectList(poiStoreQueryWrapper);

        Map<Long, PoiStore> map = list2.stream().collect(Collectors.toMap(PoiStore::getId, p -> p));

        //所有的导购客户个数
        List<Map<String, Object>> map1 = shopIds.size() == 0 ? new ArrayList<>() : opSellerCustomerRelationDOMapper.selectAllCustomerShop(shopIds);
        Map<Long, Object> collect = map1 == null ? new HashMap<>() : map1.stream().collect(Collectors.toMap(m -> Long.parseLong(m.get("store_id").toString()), m1 -> m1.get("count")));

        List<Map<String, Object>> map2 = shopIds.size() == 0 ? new ArrayList<>() : opSellerCustomerRelationDOMapper.selectAllCustomerShop1(shopIds);
        Map<Long, Object> collect1 = map2 == null ? new HashMap<>() : map2.stream().collect(Collectors.toMap(m -> Long.parseLong(m.get("store_id").toString()), m1 -> m1.get("count")));
        List<StoreOrganizationalVO> list1 = new ArrayList<>();

        list.forEach(li -> {
            QueryWrapper<PrivilageOrganizational> wrapperx = new QueryWrapper<>();
            wrapperx.eq("id", li.getParentId()).eq("level", 2).last("limit 1");
            PrivilageOrganizational privilageOrganizational = retailCompanyMapper.selectOne(wrapperx);

            StoreOrganizationalVO storeOrganizationalVO = new StoreOrganizationalVO();
            long count = 0;
            //查询所有的客户
            count = collect.get(li.getShopId()) == null ? 0 : Long.parseLong(collect.get(li.getShopId()).toString());
            long countAble = 0;
            //查询所有的有效客户
            countAble = collect1.get(li.getShopId()) == null ? 0 : Long.parseLong(collect1.get(li.getShopId()).toString());
            //计算新客户数据
            newCustomerStore(startTime, endTime, storeOrganizationalVO, Collections.singletonList(li.getShopId()));
            //查询店铺的名称
            PoiStore poiStore = map.get(li.getShopId());

            //被拉黑的客户数
            QueryWrapper<PoiCustomerContactDataStat> wrapper3 = new QueryWrapper<>();
            wrapper3.eq("store_id", li.getShopId());
            List<PoiCustomerContactDataStat> dataStats = poiCustomerContactDataStatMapper.selectList(wrapper3);
            long allAge = dataStats.stream().mapToLong(PoiCustomerContactDataStat::getNegativeFeedbackCnt).sum();

            storeOrganizationalVO.setShopName(poiStore == null ? null : poiStore.getName());
            storeOrganizationalVO.setShopCode(poiStore == null ? null : poiStore.getCode());
            storeOrganizationalVO.setAllCustomer((int) count);
            storeOrganizationalVO.setEffectiveCustomer((int) countAble);
            storeOrganizationalVO.setDelCustomer((int) allAge);
            storeOrganizationalVO.setCompanyName(privilageOrganizational.getName());
            storeOrganizationalVO.setDelRate(check(allAge, count));
            list1.add(storeOrganizationalVO);
        });
        OrganizationVO vo = new OrganizationVO();
        //总条数
        if (list.size() > 0) {
            vo.setDataVOS(list1);
            Page<CompanyStoreDO> pageList = (Page<CompanyStoreDO>) list;
            long totalSize = pageList.getTotal();
            vo.setSizeNum(totalSize);
        } else {
            return new OrganizationVO();
        }
        return vo;
    }

    /**
     * 50个一组
     *
     * @param list
     * @return
     */
    public Map<String, List<Long>> groupBySize(List<Long> list,int num,int size) {
        Map<String, List<Long>> map = new HashMap<>();
        for (int i = 0; i < num; i++) {
            List<Long> list1;
            if (i == num - 1) {
                list1 = list.subList(i * size, list.size());
            } else {
                list1 = list.subList(i * size, (i + 1) * size);
            }
            map.put(String.valueOf(i), list1);
        }
        return map;
    }

    /**
     * 查询导购的推广数据
     *
     * @param startTime 日期
     * @param endTime   日期
     * @param orgId     零售哦给弄死id
     * @param shopId    门店id
     * @param sellerId  导购id
     * @param pageNum   页码
     * @param pageSize  页面个数
     * @return 导购的推广数据
     */
    public OrganizationVO generalizeOfSeller(long userId, String startTime, String endTime, Long orgId, Long shopId, Long sellerId, int pageNum, int pageSize) throws InterruptedException {
        //根据零售公司查询门店
        List<Long> shopIds = new ArrayList<>();
        if (shopId != null) {
            shopIds.add(shopId);
        } else {
            shopIds = privilageDomainService.listUserDatePermission(userId);
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Long> sellerIds = retailCompanyMapper.selectSellerIdsByShop(orgId, shopIds, sellerId);

        List<SellerOrganizationalVO> list = new ArrayList<>();
        OrganizationVO vo = new OrganizationVO();

        if (CollectionUtils.isNotEmpty(sellerIds)) {
            //总条数
            Page<Long> pageList = (Page<Long>) sellerIds;
            long totalSize = pageList.getTotal();
            vo.setSizeNum(totalSize);
            int num = pageSize / 50 + 1;
            final CountDownLatch latch = new CountDownLatch(num);
            Map<String,List<Long>> mapEntity = groupBySize(sellerIds,num,50);
            for (final String key : mapEntity.keySet()) {
                pools.execute(() -> {
                    try {
                        //查询所有的用户信息
                        List<PrivilageUserDO> list2 = privilageUserDOMapper.selectListPr(mapEntity.get(key));
                        Map<Long, PrivilageUserDO> map = list2.stream().collect(Collectors.toMap(PrivilageUserDO::getSellerId, p -> p));

                        //所有的导购客户个数
                        List<Map<String, Object>> map1 = opSellerCustomerRelationDOMapper.selectAllCustomer(mapEntity.get(key));
                        Map<Long, Object> collect = map1 == null ? new HashMap<>() : map1.stream().collect(Collectors.toMap(m -> Long.parseLong(m.get("user_id").toString()), m1 -> m1.get("count")));
                        //所有的导购有效客户个数
                        List<Map<String, Object>> map3 = opSellerCustomerRelationDOMapper.selectAllCustomer1(mapEntity.get(key));
                        Map<Long, Object> collect1 = map3 == null ? new HashMap<>() : map3.stream().collect(Collectors.toMap(m -> Long.parseLong(m.get("user_id").toString()), m1 -> m1.get("count")));

                        List<PoiStoreStaff> list1 = poiStoreStaffDOMapper.selectList(null);
                        Map<Long, PoiStoreStaff> map2 = list1.stream().collect(Collectors.toMap(PoiStoreStaff::getId, p -> p));

                        mapEntity.get(key).forEach(seller -> {
                            SellerOrganizationalVO sellerOrganizationalVO = new SellerOrganizationalVO();
                            long count = 0;
                            //查询所有的客户
                            count = collect.get(seller) == null ? 0 : Long.parseLong(collect.get(seller).toString());
                            long countAble = 0;
                            countAble = collect1.get(seller) == null ? 0 : Long.parseLong(collect1.get(seller).toString());

                            //查询导购信息
                            PrivilageUserDO privilageUserDO = map.get(seller);
                            PoiStoreStaff poiStoreStaff = map2.get(seller);
                            //计算新客户数据
                            newCustomerUser(startTime, endTime, sellerOrganizationalVO, Collections.singletonList(seller));
                            //查询导购所属公司门店
                            CompanyStoreDO companyStoreDO = poiStoreDOMapper.selectCompanyStore(seller);
                            sellerOrganizationalVO.setShopName(companyStoreDO == null ? null : companyStoreDO.getShopName());
                            sellerOrganizationalVO.setShopCode(companyStoreDO == null ? null : companyStoreDO.getShopCode());
                            sellerOrganizationalVO.setSellerCode(poiStoreStaff == null ? null : poiStoreStaff.getStaffCode());
                            sellerOrganizationalVO.setCompanyName(companyStoreDO == null ? null : companyStoreDO.getCompanyName());
                            sellerOrganizationalVO.setSellerName(privilageUserDO == null ? null : privilageUserDO.getName());
                            sellerOrganizationalVO.setAllCustomer((int) count);
                            sellerOrganizationalVO.setEffectiveCustomer((int) countAble);
                            list.add(sellerOrganizationalVO);
                        });
                    } finally {
                        latch.countDown();
                    }
                });
            }
            // 等待
            latch.await();
            vo.setDataVOS(list);
            return vo;
        } else {
            OrganizationVO organizationVO = new OrganizationVO();
            organizationVO.setSizeNum(0);
            organizationVO.setDataVOS(new ArrayList<>());
            return organizationVO;
        }
    }

    /**
     * 找到最小公司集合
     */
    public void getMinCompany(Set<Long> companys, Set<Long> needs) {
        companys.forEach(item -> {
            getMinCompany(item, needs);
        });
    }

    /**
     * 找到最小公司集合
     */
    public void getMinCompany(Long company, Set<Long> needs) {
        QueryWrapper<PrivilageOrganizational> q = new QueryWrapper();
        q.eq("parent_id", company);
        List<PrivilageOrganizational> listOfOrg = retailCompanyMapper.selectList(q);
        Set<Long> companys = listOfOrg.stream().map(item -> item.getId()).collect(Collectors.toSet());
        if (companys.size() > 0) {
            getMinCompany(companys, needs);
        } else {
            needs.add(company);
        }
    }

}
