package com.kiisoo.ic.store.service;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kiisoo.ic.common.utils.MD5FileUtil;
import com.kiisoo.ic.common.utils.httpClientUtil.HttpClientUtil;
import com.kiisoo.ic.common.utils.httpClientUtil.HttpResult;
import com.kiisoo.ic.config.WxCpConfiguration;
import com.kiisoo.ic.customer.entity.OpSellerCustomerRelation;
import com.kiisoo.ic.customer.service.CustomerViewService;
import com.kiisoo.ic.domain.mapper.PrivilageDomainEntityDOMapper;
import com.kiisoo.ic.domain.service.PrivilageDomainService;
import com.kiisoo.ic.employee.entity.PrivilageCpUserDO;
import com.kiisoo.ic.employee.mapper.PrivilageCpUserDOMapper;
import com.kiisoo.ic.generalize.entity.PoiCustomerContactDataStat;
import com.kiisoo.ic.generalize.entity.PrivilageOrganizational;
import com.kiisoo.ic.generalize.mapper.PoiCustomerContactDataStatMapper;
import com.kiisoo.ic.generalize.mapper.RetailCompanyMapper;
import com.kiisoo.ic.store.bean.BsdShareCodeResponse;
import com.kiisoo.ic.store.constant.Constants;
import com.kiisoo.ic.store.entity.*;
import com.kiisoo.ic.store.mapper.PoiStoreDOMapper;
import com.kiisoo.ic.store.mapper.PrivilageCpUserStoreDOMapper;
import com.kiisoo.ic.store.mapper.StorePromotionDataDOMapper;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import static com.kiisoo.ic.config.WxCpConfiguration.APPLICATIONID;

/**
 * @Description:
 * @Author: JYJ
 * @Date: 2020/4/10 10:50
 * @Version: v1.0
 */
@Service
@Slf4j
public class StorePromotionDataService {

    private WxCpService mainService = WxCpConfiguration.getCpService(APPLICATIONID);

    /**
     * 门店数据mapper
     */
    @Autowired
    private StorePromotionDataDOMapper storePromotionDataDOMapper;

    /**
     * 门店数据mapper
     */
    @Autowired
    private PoiCustomerContactDataStatMapper poiCustomerContactDataStatMapper;

    /**
     * 门店数据mapper
     */
    @Autowired
    private PrivilageDomainEntityDOMapper privilageDomainEntityDOMapper;

    /**
     * 门店数据mapper
     */
    @Autowired
    private RetailCompanyMapper retailCompanyMapper;

    /**
     * 门店数据mapper
     */
    @Autowired
    private PoiStoreDOMapper poiStoreDOMapper;

    /**
     * 权限业务
     */
    @Autowired
    private PrivilageDomainService privilageDomainService;

    /**
     * 权限业务
     */
    @Autowired
    private CustomerViewService customerViewService;

    /**
     * 权限业务
     */
    @Autowired
    private PrivilageCpUserDOMapper privilageCpUserDOMapper;

    /**
     * 权限业务
     */
    @Autowired
    private PrivilageCpUserStoreDOMapper privilageCpUserStoreDOMapper;


    @Value("${bsd.userBehavior}")
    private String userBehavior;

    /**
     * 查询门店推广数据列表
     *
     * @param storeId
     * @param regionId
     * @param sellerId
     * @param startDate
     * @param endDate
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageInfo<StorePromotionDataDO> listStorePromotionData(Long userId, Long storeId, Long regionId, Long sellerId,
                                                                 Date startDate, Date endDate, String type, int pageNum, int pageSize) {
        //用户权限下的店铺
        List<Long> storeIds = privilageDomainService.listUserDatePermission(userId);
        // 查询三种类型的新增客户数
        List<StorePromotionDataDO> promotionDataDOS;
        // 查询三种类型的新增客户数 (去重完) 转map
        List<StorePromotionDataDO> newCusNumDOSExclude;
        Map<Long, Integer> newCusNumMapExclude;

        // 查询三种类型的总客户数 日期区间 转map
        List<StorePromotionDataDO> cusNumDataDOS;
        Map<Long, StorePromotionDataDO> cusNumMap;
        // 查询三种类型的总客户数 日期区间 (去重完) 转map
        List<StorePromotionDataDO> cusNumDataDOSExclude;
        Map<Long, StorePromotionDataDO> cusNumMapExclude;

        // 查询拉黑数量 转map
        List<StorePromotionDataDO> wxCusInfoDO;
        Map<Long, Integer> delCusNumMap = null;
        if (Constants.STORE_DATA_TYPE_REGION.equals(type)) {
            PageHelper.startPage(pageNum, pageSize);
            promotionDataDOS = storePromotionDataDOMapper.selectPromotionDataGroupByRegion(storeIds, regionId, startDate, endDate, null);

            newCusNumDOSExclude = storePromotionDataDOMapper.selectPromotionDataGroupByRegion(storeIds, regionId, startDate, endDate, Constants.STORE_SELLER_CUS_RELATION_TYPE_VALID);
            newCusNumMapExclude = newCusNumDOSExclude.stream().collect(Collectors.toMap(StorePromotionDataDO::getRegionId, StorePromotionDataDO::getNewCusNum, (k1, k2) -> k1));

            cusNumDataDOS = storePromotionDataDOMapper.selectSumCusNumGroupByRegion(storeIds, regionId, null);
            cusNumMap = cusNumDataDOS.stream().collect(Collectors.toMap(StorePromotionDataDO::getRegionId, s -> s, (k1, k2) -> k1));

            cusNumDataDOSExclude = storePromotionDataDOMapper.selectSumCusNumGroupByRegion(storeIds, regionId, Constants.STORE_SELLER_CUS_RELATION_TYPE_VALID);
            cusNumMapExclude = cusNumDataDOSExclude.stream().collect(Collectors.toMap(StorePromotionDataDO::getRegionId, s -> s, (k1, k2) -> k1));

            wxCusInfoDO = storePromotionDataDOMapper.selectWxCusInfoByRegionId(startDate, endDate);
            delCusNumMap = wxCusInfoDO.stream().collect(Collectors.toMap(StorePromotionDataDO::getRegionId, StorePromotionDataDO::getDelCusNum, (k1, k2) -> k1));
        } else if (Constants.STORE_DATA_TYPE_STORE.equals(type)) {
            PageHelper.startPage(pageNum, pageSize);
            promotionDataDOS = storePromotionDataDOMapper.selectPromotionDataGroupByStore(storeIds, storeId, regionId, startDate, endDate, null);

            newCusNumDOSExclude = storePromotionDataDOMapper.selectPromotionDataGroupByStore(storeIds, storeId, regionId, startDate, endDate, Constants.STORE_SELLER_CUS_RELATION_TYPE_VALID);
            newCusNumMapExclude = newCusNumDOSExclude.stream().collect(Collectors.toMap(StorePromotionDataDO::getStoreId, StorePromotionDataDO::getNewCusNum, (k1, k2) -> k1));

            cusNumDataDOS = storePromotionDataDOMapper.selectSumCusNumGroupByStore(storeIds, storeId, regionId, null);
            cusNumMap = cusNumDataDOS.stream().collect(Collectors.toMap(StorePromotionDataDO::getStoreId, s -> s, (k1, k2) -> k1));

            cusNumDataDOSExclude = storePromotionDataDOMapper.selectSumCusNumGroupByStore(storeIds, storeId, regionId, Constants.STORE_SELLER_CUS_RELATION_TYPE_VALID);
            cusNumMapExclude = cusNumDataDOSExclude.stream().collect(Collectors.toMap(StorePromotionDataDO::getStoreId, s -> s, (k1, k2) -> k1));

            wxCusInfoDO = storePromotionDataDOMapper.selectWxCusInfoByStoreId(startDate, endDate);
            delCusNumMap = wxCusInfoDO.stream().collect(Collectors.toMap(StorePromotionDataDO::getStoreId, StorePromotionDataDO::getDelCusNum, (k1, k2) -> k1));
        } else {
            PageHelper.startPage(pageNum, pageSize);
            promotionDataDOS = storePromotionDataDOMapper.selectPromotionDataGroupBySeller(storeIds, storeId, regionId, sellerId, startDate, endDate, null);

            newCusNumDOSExclude = storePromotionDataDOMapper.selectPromotionDataGroupBySeller(storeIds, storeId, regionId, sellerId, startDate, endDate, Constants.STORE_SELLER_CUS_RELATION_TYPE_VALID);
            newCusNumMapExclude = newCusNumDOSExclude.stream().collect(Collectors.toMap(StorePromotionDataDO::getStoreId, StorePromotionDataDO::getNewCusNum, (k1, k2) -> k1));

            cusNumDataDOS = storePromotionDataDOMapper.selectSumCusNumGroupBySeller(storeIds, storeId, regionId, sellerId, null);
            cusNumMap = cusNumDataDOS.stream().collect(Collectors.toMap(StorePromotionDataDO::getSellerId, s -> s, (k1, k2) -> k1));

            cusNumDataDOSExclude = storePromotionDataDOMapper.selectSumCusNumGroupBySeller(storeIds, storeId, regionId, sellerId, Constants.STORE_SELLER_CUS_RELATION_TYPE_VALID);
            cusNumMapExclude = cusNumDataDOSExclude.stream().collect(Collectors.toMap(StorePromotionDataDO::getStoreId, s -> s, (k1, k2) -> k1));
        }


        Map<Long, StorePromotionDataDO> finalCusNumMap = cusNumMap;
        Map<Long, Integer> finalDelCusNumMap = delCusNumMap;
        promotionDataDOS.forEach(promotionDataDO -> {
            Long storeIdKey = promotionDataDO.getStoreId();
            Long regionIdKey = promotionDataDO.getRegionId();
            Long sellerIdKey = promotionDataDO.getSellerId();
            //填充门店数据
            if (Constants.STORE_DATA_TYPE_REGION.equals(type)) {
                addPromotionData(promotionDataDO, regionIdKey, newCusNumMapExclude, finalCusNumMap,
                        cusNumMapExclude, finalDelCusNumMap, type);
            } else if (Constants.STORE_DATA_TYPE_STORE.equals(type)) {
                addPromotionData(promotionDataDO, storeIdKey, newCusNumMapExclude, finalCusNumMap,
                        cusNumMapExclude, finalDelCusNumMap, type);
            } else {
                addPromotionData(promotionDataDO, sellerIdKey, newCusNumMapExclude, finalCusNumMap,
                        cusNumMapExclude, finalDelCusNumMap, type);
            }
        });
        return new PageInfo<>(promotionDataDOS);
    }

    /**
     * 填充门店数据
     *
     * @param promotionDataDO       数据对象
     * @param keyId                 数据keyId regionId/storeId/sellerId
     * @param newCusNumMapExclude   新增客户Map
     * @param finalCusNumMap        总客户Map
     * @param finalCusNumMapExclude 总客户剔除完Map
     * @param finalDelCusNumMap     拉黑客户数Map
     * @param type                  数据查询类型
     */
    private void addPromotionData(StorePromotionDataDO promotionDataDO,
                                  Long keyId, Map<Long, Integer> newCusNumMapExclude,
                                  Map<Long, StorePromotionDataDO> finalCusNumMap,
                                  Map<Long, StorePromotionDataDO> finalCusNumMapExclude,
                                  Map<Long, Integer> finalDelCusNumMap, String type) {
        // 新增客户数量 (去重完)
        Integer newCusNumExclude = newCusNumMapExclude == null || newCusNumMapExclude.get(keyId) == null ? null : newCusNumMapExclude.get(keyId);
        // 客户总数
        Integer cusNum = finalCusNumMap == null || finalCusNumMap.get(keyId) == null ? null : finalCusNumMap.get(keyId).getCusNum();
        // 客户总数 (去重完)
        Integer cusNumExclude = finalCusNumMapExclude == null || finalCusNumMapExclude.get(keyId) == null ? null : finalCusNumMapExclude.get(keyId).getCusNum();
        // 最小日期
        Date minDate = finalCusNumMap == null || finalCusNumMap.get(keyId) == null ? null : finalCusNumMap.get(keyId).getMinDate();
        // 最大日期
        Date maxDate = finalCusNumMap == null || finalCusNumMap.get(keyId) == null ? null : finalCusNumMap.get(keyId).getMaxDate();
        // 最小日期 (去重完)
        Date minDateExclude = finalCusNumMapExclude == null || finalCusNumMapExclude.get(keyId) == null ? null : finalCusNumMapExclude.get(keyId).getMinDate();
        // 最大日期 (去重完)
        Date maxDateExclude = finalCusNumMapExclude == null || finalCusNumMapExclude.get(keyId) == null ? null : finalCusNumMapExclude.get(keyId).getMaxDate();
        // 被拉黑客户数
        Integer delCusNum = finalDelCusNumMap == null || finalDelCusNumMap.get(keyId) == null ? null : finalDelCusNumMap.get(keyId);
        // 新增客户数 (去重完)
        if (newCusNumExclude != null) {
            promotionDataDO.setNewCusNumExclude(newCusNumExclude);
        }
        // 客户总数 (去重完)
        if (cusNumExclude != null) {
            promotionDataDO.setCusNumExclude(cusNumExclude);
        }
        // 拉黑数 拉黑率 拉黑/总客户
        if (!Constants.STORE_DATA_TYPE_SELLER.equals(type)) {
            if (null != delCusNum) {
                promotionDataDO.setDelCusNum(delCusNum);
                promotionDataDO.setDelCusRate(cusNum == null || cusNum == Constants.CONTACT_COUNT_ZERO ?
                        0 : delCusNum * 1f / promotionDataDO.getCusNum());
            }
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            // 日增好友平均 总客户/天
            if (minDate != null && maxDate != null) {
                Date minDateF = sdf.parse(sdf.format(minDate));
                Date maxDateF = sdf.parse(sdf.format(minDate));
                int nDay = maxDateF.getTime() - minDateF.getTime() == 0 ? 1 : (int) ((maxDateF.getTime() - minDateF.getTime()) / (24 * 60 * 60 * 1000));
                if (cusNum != null) {
                    promotionDataDO.setAvgNewCusNum(cusNum / nDay);
                }
            }
            // 日增好友平均 (去重完)
            if (minDateExclude != null && maxDateExclude != null) {
                Date minDateFExclude = sdf.parse(sdf.format(minDateExclude));
                Date maxDateFExclude = sdf.parse(sdf.format(maxDateExclude));
                int nDay = maxDateFExclude.getTime() - minDateFExclude.getTime() == 0 ? 1 : (int) ((maxDateFExclude.getTime() - minDateFExclude.getTime()) / (24 * 60 * 60 * 1000));
                if (cusNumExclude != null) {
                    promotionDataDO.setAvgNewCusNumExclude(cusNumExclude / nDay);
                }
            }
        } catch (ParseException e) {
            log.error("查询门店推广数据列表日期转换出错！", e);
        }
    }


    public PageInfo<PoiCustomerContactDataStat> listUserBehaviorData(Long userId,Long companyId,Long shopId,Date startDate, Date endDate,Integer pageNum,Integer pageSize){
        Set<Long> shopIds = new HashSet<>();

        if (shopId != null) {
            //如果有店铺则查店铺
            shopIds.add(shopId);
        } else if (companyId != null) {
            //如果有公司则查公司店铺
            Set<Long> sp = customerViewService.getCompanyShop(companyId, userId);
            shopIds.addAll(sp);
        } else {
            //查询用户权限店铺
            shopIds = new HashSet<>(privilageDomainService.listUserDatePermission(userId));
        }

        AtomicInteger number = new AtomicInteger(1 + ((pageNum - 1) * pageSize));

        PageHelper.startPage(pageNum, pageSize);
        List<PoiCustomerContactDataStat> results = poiCustomerContactDataStatMapper.selectSumDataByShopIds(shopIds,startDate,endDate);
        if (CollectionUtils.isNotEmpty(results)){
            results.forEach(result -> {
                Long storeId = result.getStoreId();
                PoiStore poiStore = poiStoreDOMapper.selectById(storeId);
                if (poiStore == null){
                    return;
                }
                result.setStoreName(poiStore.getName());
                result.setStoreCode(poiStore.getCode());
                result.setAddress(poiStore.getAddress());
                result.setNumber(number.get());
                number.incrementAndGet();

                //客户orgId
                Long customerId = privilageDomainEntityDOMapper.selectDomainIdByShopEntity(storeId);

                if (customerId != null){
                    PrivilageOrganizational customer = retailCompanyMapper.selectById(customerId);
                    PrivilageOrganizational company = retailCompanyMapper.selectById(customer.getParentId());
                    result.setCompanyName(company.getName());
                }
            });
        }
        return new PageInfo<>(results);
    }

    public void translateDate(String cpUserIds){
        String[] split = cpUserIds.split(",");
        List<String> cpUserIdList = Arrays.asList(split);
        for (String cpUserId : cpUserIdList) {
            QueryWrapper<PrivilageCpUserDO> cpUserDOQueryWrapper = new QueryWrapper<>();
            cpUserDOQueryWrapper.eq("cp_user_id",cpUserId).last("limit 1");
            PrivilageCpUserDO privilageCpUserDO = privilageCpUserDOMapper.selectOne(cpUserDOQueryWrapper);
            if (privilageCpUserDO == null){
                continue;
            }
            Long storeId = privilageCpUserStoreDOMapper.selectOneByCpUserId(cpUserId);
            if (storeId == null){
                continue;
            }
            //删除原有的数据
            QueryWrapper<PoiCustomerContactDataStat> poiCustomerContactDataStatQueryWrapper = new QueryWrapper<>();
            poiCustomerContactDataStatQueryWrapper.isNull("store_id").eq("region_id",privilageCpUserDO.getId());
            List<PoiCustomerContactDataStat> poiCustomerContactDataStats = poiCustomerContactDataStatMapper.selectList(poiCustomerContactDataStatQueryWrapper);
            if (CollectionUtils.isNotEmpty(poiCustomerContactDataStats)){
                poiCustomerContactDataStats.forEach(poiCustomerContactDataStat -> {
                    poiCustomerContactDataStat.setRegionId(null);
                    poiCustomerContactDataStat.setStoreId(storeId);
                    poiCustomerContactDataStatMapper.updateById(poiCustomerContactDataStat);
                });
            }
        }
    }

    public void downloadUserBehaviorDataExcel(Long userId, Long companyId, Long shopId, Date startDate, Date endDate, HttpServletResponse response) throws IOException {
        Set<Long> shopIds = new HashSet<>();

        if (shopId != null) {
            //如果有店铺则查店铺
            shopIds.add(shopId);
        } else if (companyId != null) {
            //如果有公司则查公司店铺
            Set<Long> sp = customerViewService.getCompanyShop(companyId, userId);
            shopIds.addAll(sp);
        } else {
            //查询用户权限店铺
            shopIds = new HashSet<>(privilageDomainService.listUserDatePermission(userId));
        }


        List<PoiCustomerContactDataStat> results = poiCustomerContactDataStatMapper.selectSumDataByShopIds(shopIds,startDate,endDate);
        if (CollectionUtils.isNotEmpty(results)){
            results.forEach(result -> {
                Long storeId = result.getStoreId();
                PoiStore poiStore = poiStoreDOMapper.selectById(storeId);
                if (poiStore == null){
                    return;
                }
                result.setStoreName(poiStore.getName());
                result.setStoreCode(poiStore.getCode());
                result.setAddress(poiStore.getAddress());

                //客户orgId
                Long customerId = privilageDomainEntityDOMapper.selectDomainIdByShopEntity(storeId);

                if (customerId != null){
                    PrivilageOrganizational customer = retailCompanyMapper.selectById(customerId);
                    PrivilageOrganizational company = retailCompanyMapper.selectById(customer.getParentId());
                    result.setCompanyName(company.getName());
                }
            });
        }

        String[] headNames = new String[]{"序号","店铺名","店铺编号","所属零售公司","新增客户数","聊天总数","发消息数","已回复聊天占比","平均回复时长","删除/拉黑成员客户数"};
        HSSFWorkbook ws = new HSSFWorkbook();
        Sheet hssfSheet = ws.createSheet("店铺号数据");
        HSSFCellStyle cellStyle = ws.createCellStyle();
        cellStyle.setWrapText(true);//设置自动换行
        int isAdd = 0;
        //设置列名
        if (null != headNames && headNames.length > 0) {

            Row row = hssfSheet.createRow(isAdd++);
            for (int i = 0; i < headNames.length; i++) {

                String name = headNames[i];
                Cell cell = row.createCell(i);
                cell.setCellValue(name);
            }
            isAdd++;
        }

        for (int i = 0; i < results.size(); i++) {
            //创造行
            Row row = hssfSheet.createRow(isAdd++);
            PoiCustomerContactDataStat poiCustomerContactDataStat = results.get(i);
            Cell orderCell = row.createCell(0);
            orderCell.setCellValue(i + 1 +"");
            Cell storeCell = row.createCell(1);
            storeCell.setCellValue(poiCustomerContactDataStat.getStoreName());
            Cell storeCodeCell = row.createCell(2);
            storeCodeCell.setCellValue(poiCustomerContactDataStat.getStoreCode());
            Cell companyNameCell = row.createCell(3);
            companyNameCell.setCellValue(poiCustomerContactDataStat.getCompanyName());
            Cell newContactCntCell = row.createCell(4);
            newContactCntCell.setCellValue(poiCustomerContactDataStat.getNewContactCnt());
            Cell chatCntCell = row.createCell(5);
            chatCntCell.setCellValue(poiCustomerContactDataStat.getChatCnt());
            Cell messageCntCell = row.createCell(6);
            messageCntCell.setCellValue(poiCustomerContactDataStat.getMessageCnt());
            Cell replyPercentage = row.createCell(7);
            replyPercentage.setCellValue(poiCustomerContactDataStat.getReplyPercentage());
            Cell avgReplyTime = row.createCell(8);
            avgReplyTime.setCellValue(poiCustomerContactDataStat.getAvgReplyTime());
            Cell negativeFeedbackCnt = row.createCell(9);
            negativeFeedbackCnt.setCellValue(poiCustomerContactDataStat.getNegativeFeedbackCnt());
        }
        OutputStream output = response.getOutputStream();
        response.setHeader("Content-disposition", "attachment; filename=store.xls");
        response.setContentType("application/vnd.ms-excel");
        ws.write(output);
        ws.close();
    }


    /**
     * 获取联系客户统计数据
     *
     * @param wxCusInfoReqDO
     * @return
     * @throws WxErrorException
     */
    public WxCusInfoRespDO getWxCusInfoBSD(WxCusInfoReqDO wxCusInfoReqDO) throws Exception {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Map<String, Object> params = new HashMap<>();
        params.put("start_time", wxCusInfoReqDO.getStart_time());
        params.put("end_time", wxCusInfoReqDO.getEnd_time());
        params.put("userid", wxCusInfoReqDO.getUserid());
        HttpResult httpResult = HttpClientUtil.httpPost(userBehavior + MD5FileUtil.getMD5String("BOSIDENG" + sdf.format(new Date())), JSONObject.toJSONString(params));
        String message = httpResult.getMessage();
        if (StringUtils.isBlank(message)) {
            return null;
        }
        JSONObject qrCodeJson = JSONObject.parseObject(message);
        BsdShareCodeResponse bsdResponse = qrCodeJson.toJavaObject(BsdShareCodeResponse.class);

//        JSONObject parseObject = JSON.parseObject(result);
//        String[] behavior_data = JSONObject.parseObject(parseObject.getString("behavior_data"), String[].class);
        return null;
    }

    /**
     * 查询门店推广数据列表 手机端
     *
     * @param userId
     * @param roleCode
     * @param startDate
     * @param endDate
     * @return
     */
    public StorePromotionDataDO listStorePromotionDataWx(Long userId, String roleCode,
                                                         Date startDate, Date endDate, Date lastStartDate, Date lastEndDate) {
        StorePromotionDataDO storePromotionDataDO = new StorePromotionDataDO();
        Integer cusNum = null;
        Integer newCusNum = null;
        Integer newCusNumLast = null;
        Integer rankNo = null;
        Integer differFromChampion = null;
        Long storeId = storePromotionDataDOMapper.selectStoreIdByUserId(userId);
        if (storeId == null) {
            return storePromotionDataDO;
        }
        switch (roleCode) {
            // 店长
            case Constants.WX_USER_ROLE_SHOP_MANAGER:
                cusNum = storePromotionDataDOMapper.selectWxSumCusNumByConditionShopManager(storeId, null, null);
                newCusNum = storePromotionDataDOMapper.selectWxSumCusNumByConditionShopManager(storeId, startDate, endDate);
                newCusNumLast = storePromotionDataDOMapper.selectWxSumCusNumByConditionShopManager(storeId, lastStartDate, lastEndDate);
                // 店铺排名
                List<StorePromotionDataDO> storeRankNoList = storePromotionDataDOMapper.selectStoreRankNo(startDate, endDate);
                if (CollectionUtils.isNotEmpty(storeRankNoList)) {
                    for (int i = 0; i < storeRankNoList.size(); i++) {
                        if (storeRankNoList.get(i).getStoreId().equals(storeId)) {
                            rankNo = storeRankNoList.get(i).getRankNo();
                            Integer curNewCusNum = storeRankNoList.get(i).getNewCusNum();
                            Integer championNewCusNum = storeRankNoList.get(0).getNewCusNum();
                            differFromChampion = championNewCusNum - curNewCusNum;
                            break;
                        }
                    }
                }
                // 导购列表
                List<StaffDO> staffDOList = storePromotionDataDOMapper.selectWxValidStaffNameList(storeId);
                // 导购新增客户数列表
                List<StaffDO> staffNewCusNumList = storePromotionDataDOMapper.selectWxStaffDOList(storeId, startDate, endDate);
                Map<Long, Integer> staffNewCusNumMap = staffNewCusNumList.stream().collect(Collectors.toMap(StaffDO::getId, StaffDO::getCusNum, (k1, k2) -> k1));
                // 导购总客户数
                List<StaffDO> staffCusNumList = storePromotionDataDOMapper.selectWxStaffDOList(storeId, null, null);
                Map<Long, Integer> staffCusNumMap = staffCusNumList.stream().collect(Collectors.toMap(StaffDO::getId, StaffDO::getCusNum, (k1, k2) -> k1));
                staffDOList.forEach(storeDO -> {
                    Long id = storeDO.getId();
                    if (null != staffCusNumMap && staffCusNumMap.get(id) != null) {
                        storeDO.setCusNum(staffCusNumMap.get(id));
                    } else {
                        storeDO.setCusNum(Constants.CUS_NUM_ZERO);
                    }
                    if (null != staffNewCusNumMap && staffNewCusNumMap.get(id) != null) {
                        storeDO.setNewCusNum(staffNewCusNumMap.get(id));
                    } else {
                        storeDO.setNewCusNum(Constants.CUS_NUM_ZERO);
                    }
                });
                if (CollectionUtils.isNotEmpty(staffDOList)) {
                    // 总客户数降序
                    List<StaffDO> staffFinalList = staffDOList.stream().sorted(Comparator.comparing(StaffDO::getCusNum, Comparator.nullsFirst(Integer::compareTo)).reversed()).collect(Collectors.toList());
                    storePromotionDataDO.setStaffDOList(staffFinalList);
                }
                break;
            // 导购
            case Constants.WX_USER_ROLE_STAFF:
                cusNum = storePromotionDataDOMapper.selectWxSumCusNumByConditionStaff(userId, null, null);
                newCusNum = storePromotionDataDOMapper.selectWxSumCusNumByConditionStaff(userId, startDate, endDate);
                newCusNumLast = storePromotionDataDOMapper.selectWxSumCusNumByConditionStaff(userId, lastStartDate, lastEndDate);
                // 店铺排名
                List<StorePromotionDataDO> staffRankNoList = storePromotionDataDOMapper.selectStaffRankNo(startDate, endDate, storeId);
                if (CollectionUtils.isNotEmpty(staffRankNoList)) {
                    for (int i = 0; i < staffRankNoList.size(); i++) {
                        if (staffRankNoList.get(i).getUserId().equals(userId.toString())) {
                            rankNo = staffRankNoList.get(i).getRankNo();
                            Integer curNewCusNum = staffRankNoList.get(i).getNewCusNum();
                            Integer championNewCusNum = staffRankNoList.get(0).getNewCusNum();
                            differFromChampion = championNewCusNum - curNewCusNum;
                            break;
                        }
                    }
                }
                Date latestUpdate = storePromotionDataDOMapper.selectLatestUpdateTime(storeId);
                if (null != latestUpdate) {
                    storePromotionDataDO.setLatestUpdate(latestUpdate);
                }
                break;
            default:
                break;
        }
        if (null != cusNum) {
            storePromotionDataDO.setCusNum(cusNum);
        }
        if (null != newCusNum) {
            storePromotionDataDO.setNewCusNum(newCusNum);
        }
        if (null != newCusNumLast) {
            storePromotionDataDO.setNewCusNumLast(newCusNumLast);
        }
        if (null != rankNo) {
            storePromotionDataDO.setRankNo(rankNo);
        }
        if (null != differFromChampion) {
            storePromotionDataDO.setDifferFromChampion(differFromChampion);
        }
        return storePromotionDataDO;
    }
}
