package com.kiisoo.ic.customer;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.kiisoo.ic.constants.Constants;
import com.kiisoo.ic.customer.bean.CustomerDTO;
import com.kiisoo.ic.customer.bean.CustomerModifyDTO;
import com.kiisoo.ic.customer.bean.FriendDTO;
import com.kiisoo.ic.customer.bean.OpCustomerDTO;
import com.kiisoo.ic.customer.entity.OpCustomer;
import com.kiisoo.ic.customer.entity.OpSellerCustomerRelation;
import com.kiisoo.ic.customer.entity.OpVip;
import com.kiisoo.ic.customer.mapper.OpCustomerDOMapper;
import com.kiisoo.ic.customer.mapper.OpSellerCustomerRelationDOMapper;
import com.kiisoo.ic.customer.mapper.OpVipDOMapper;
import com.kiisoo.ic.customer.service.CustomerViewService;
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.employee.service.EmployeeService;
import com.kiisoo.ic.generalize.service.RetailCompanyService;
import com.kiisoo.ic.ls.controller.WebSocketController;
import com.kiisoo.ic.store.entity.PoiStore;
import com.kiisoo.ic.store.entity.PoiStoreStaff;
import com.kiisoo.ic.store.entity.PrivilageCpUserStoreDO;
import com.kiisoo.ic.store.mapper.PoiStoreDOMapper;
import com.kiisoo.ic.store.mapper.PoiStoreStaffDOMapper;
import com.kiisoo.ic.store.mapper.PrivilageCpUserStoreDOMapper;
import com.kiisoo.ic.store.service.PoiStoreService;
import com.kiisoo.ic.synchronous.entity.TurnBackDTO;
import com.kiisoo.ic.system.entity.PrivilageUserDO;
import com.kiisoo.ic.system.enums.RoleEnum;
import com.kiisoo.ic.system.mapper.PrivilageUserDOMapper;
import com.kiisoo.ic.webappmy.vo.StafferInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @ClassName: CustomerService
 * @Description: 客户业务类
 * @Auther: Caps
 * @Date: 2020/4/2 0002 17:06
 * @Version: v1
 */
@Service
@Slf4j
public class CustomerService {

    @Autowired
    private OpCustomerDOMapper opCustomerDOMapper;

    @Autowired
    private OpSellerCustomerRelationDOMapper opSellerCustomerRelationDOMapper;

    @Autowired
    private PrivilageCpUserDOMapper privilageCpUserDOMapper;

    @Autowired
    private OpVipDOMapper opVipDOMapper;

    @Autowired
    private PoiStoreDOMapper poiStoreDOMapper;

    @Autowired
    private PoiStoreStaffDOMapper poiStoreStaffDOMapper;

    @Autowired
    private PrivilageCpUserStoreDOMapper privilageCpUserStoreDOMapper;

    @Autowired
    private PoiStoreService poiStoreService;

    @Autowired
    private PrivilageDomainService privilageDomainService;

    @Autowired
    private RetailCompanyService retailCompanyService;

    @Autowired
    private CustomerViewService customerViewService;


    @Autowired
    public PrivilageUserDOMapper privilageUserDOMapper;

    /**
     * token
     */
    private final static String TOKEN = "BOSIDENG";

    /**
     * 绑定客户的关系
     *
     * @param customerDTO 传输实体
     * @Description: 根据客户联系方式查询客户id 1.判断客户是否存在，不存在就添加，存在就进行下一步 2.判断客户id和导购是否绑定了关系如果绑定了就直接下一步，如果没有就绑定 3.判断客户id和vip是否绑定了关系如果绑定了就直接下一步，如果没有就绑定
     */
    @Transactional(rollbackFor = Exception.class)
    public Long customerRelation(CustomerDTO customerDTO) {
        //客户信息
        QueryWrapper<OpCustomer> customerWrapper = new QueryWrapper<>();
        customerWrapper.eq("external_userid", customerDTO.getExternalUserid()).last("limit 1");
        OpCustomer opCustomer = opCustomerDOMapper.selectOne(customerWrapper);
        //店铺信息
        QueryWrapper<PoiStore> poiWrapper = new QueryWrapper<>();
        poiWrapper.eq("code", customerDTO.getShopCode()).last("limit 1");
        PoiStore poiStore = poiStoreDOMapper.selectOne(poiWrapper);

        //导购信息
        QueryWrapper<PoiStoreStaff> wrapper = new QueryWrapper<>();
        wrapper.eq("staff_code", customerDTO.getStaffCode()).eq("store_code", customerDTO.getShopCode()).last("limit 1");
        PoiStoreStaff poiStoreStaff = poiStoreStaffDOMapper.selectOne(wrapper);
        if (poiStoreStaff == null || poiStore == null) {
            return null;
        }

        //做插入使用
        OpCustomer insertCustomer = new OpCustomer();
        insertCustomer.setExternalUserid(customerDTO.getExternalUserid());
//        String customerName = EmployeeService.filterEmoji(customerDTO.getName());
        insertCustomer.setName(customerDTO.getName());
        insertCustomer.setCreateTime(opCustomer.getCreateTime());
        if (null != opCustomer) {
            //存在--1.处理客户导购关系。
            sellerCustomerRelation(opCustomer, opCustomer.getCreateTime(), poiStore.getId(), poiStoreStaff.getUserId());
            return opCustomer.getId();
        } else {
            insertCustomer.setCreateBy(Constants.SYS_OPERATION);
            //不存在
            opCustomerDOMapper.insert(insertCustomer);
            //添加关系
            sellerCustomerRelation(insertCustomer, insertCustomer.getCreateTime(), poiStore.getId(), poiStoreStaff.getUserId());
            return insertCustomer.getId();
        }
    }

    /**
     * 录入客户信息/绑定客户vip关系（如果是VIP的话）
     *
     * @param customerModifyDTO 更新实体
     */
    @Transactional(rollbackFor = Exception.class)
    public void customerVipRelation(CustomerModifyDTO customerModifyDTO) {
        OpCustomer opCustomer = new OpCustomer(customerModifyDTO.getName(), customerModifyDTO.getPhone());
        opCustomer.setUpdateBy(Constants.SYS_OPERATION);
        QueryWrapper<OpVip> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", customerModifyDTO.getPhone()).last("limit 1");
        OpVip opVip = opVipDOMapper.selectOne(wrapper);
        if (null != opVip) {
            //有vip信息就绑定信息
            opCustomer.setMemberId(opVip.getId());
        }
        QueryWrapper<OpCustomer> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("wechat_uni_id", customerModifyDTO.getUniId());
        opCustomerDOMapper.update(opCustomer, wrapper1);
    }

    /**
     * 好友添加回调通知
     *
     * @param turnBackDTOS 数据实体
     * @return 是否成功
     */
    public void turnBack(TurnBackDTO turnBackDTOS) throws Exception {
        OpCustomer opCustomer = null;
        if (turnBackDTOS.getWxData().getUnionId() == null && turnBackDTOS.getWxData().getUserId() != null) {
            //此时说明是企业微信扫码添加
            QueryWrapper<OpCustomer> customerWrapper = new QueryWrapper<>();
            customerWrapper.eq("wechat_uni_id", null).eq("external_userid", turnBackDTOS.getWxData().getUserId()).last("limit 1");
            opCustomer = opCustomerDOMapper.selectOne(customerWrapper);
        }else if (turnBackDTOS.getWxData().getUnionId() != null && turnBackDTOS.getUserId() != null){
            //客户信息
            QueryWrapper<OpCustomer> customerWrapper = new QueryWrapper<>();
            customerWrapper.eq("wechat_uni_id", turnBackDTOS.getWxData().getUnionId()).last("limit 1");
            opCustomer = opCustomerDOMapper.selectOne(customerWrapper);
        }else{
            return;
        }

        //店铺信息
        PrivilageCpUserStoreDO poiStore = privilageCpUserStoreDOMapper.selectOneCpUser(turnBackDTOS.getUserId());
        if (poiStore == null) {
            //无店铺数据处理
            poiStore = new PrivilageCpUserStoreDO();
            poiStore.setStoreId(0L);
        }
        PoiStore shop = poiStoreDOMapper.selectById(poiStore.getStoreId());
        PoiStoreStaff poiStoreStaff = null;
        if (!turnBackDTOS.getEaCode().equals("") && !turnBackDTOS.getEaCode().equals("0")) {
            //导购信息
            QueryWrapper<PoiStoreStaff> wrapper = new QueryWrapper<>();
            if (turnBackDTOS.getEaCode().matches("导购(.*)")){
                wrapper.eq("staff_code", turnBackDTOS.getEaCode()).eq("status","1").last("limit 1");
            }else{
                wrapper.eq("staff_code", turnBackDTOS.getEaCode()).eq("status","1").eq("store_id", poiStore.getStoreId()).last("limit 1");
            }
            poiStoreStaff = poiStoreStaffDOMapper.selectOne(wrapper);
        }

        //做插入使用 --如果没有客户信息就先创建客户信息如果有就判断是否有客户导购得关系，如果没有就添加有就不管
        OpCustomer insertCustomer = new OpCustomer();
        insertCustomer.setWechatUniId(turnBackDTOS.getWxData().getUnionId());
        insertCustomer.setName(turnBackDTOS.getName());
        insertCustomer.setType(new Long(turnBackDTOS.getType()));
        insertCustomer.setAvatarUrl(turnBackDTOS.getWxData().getAvatarUrl());
        insertCustomer.setExternalUserid(turnBackDTOS.getWxData().getUserId());
        insertCustomer.setCpUserId(turnBackDTOS.getUserId());
        insertCustomer.setPhone(turnBackDTOS.getPhone());
        if (shop != null && StringUtils.isNotBlank(shop.getName())){
            insertCustomer.setShopName(shop.getName());
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (turnBackDTOS.getJoinTime() != null){
            insertCustomer.setCreateTime(sdf.parse(turnBackDTOS.getJoinTime()));
        }
        if (null != opCustomer) {
            //更新一下
            insertCustomer.setId(opCustomer.getId());
            try {
                opCustomerDOMapper.updateById(insertCustomer);
            }catch (Exception e) {
                log.error(insertCustomer.toString(),e);
                return;
            }
            if (poiStoreStaff != null) {
                //存在--1.处理客户导购关系。
                try {
                    sellerCustomerRelation(insertCustomer, sdf.parse(turnBackDTOS.getJoinTime()), poiStore.getStoreId(), poiStoreStaff.getId());
                }catch (Exception e) {
                    log.error(insertCustomer.toString(),e);
                    return;
                }
            } else {
                try {
                    storeCustomerRelation(insertCustomer,sdf.parse(turnBackDTOS.getJoinTime()), poiStore.getStoreId());
                }catch (Exception e) {
                    log.error(insertCustomer.toString(),e);
                    return;
                }
            }
        } else {
            insertCustomer.setCreateBy(Constants.SYS_OPERATION);
            //不存在
            try {
                opCustomerDOMapper.insert(insertCustomer);
            }catch (Exception e) {
                log.error(insertCustomer.toString(),e);
                return;
            }

            if (poiStoreStaff != null) {
                //添加关系
                try {
                    sellerCustomerRelation(insertCustomer, sdf.parse(turnBackDTOS.getJoinTime()), poiStore.getStoreId(), poiStoreStaff.getId());
                }catch (Exception e) {
                    log.error(insertCustomer.toString(),e);
                    return;
                }
            } else {
                try {
                    storeCustomerRelation(insertCustomer, sdf.parse(turnBackDTOS.getJoinTime()),poiStore.getStoreId());
                }catch (Exception e) {
                    log.error(insertCustomer.toString(),e);
                    return;
                }
            }
        }

        //处理客户vip的关系
        if (turnBackDTOS.getVipData() != null && !turnBackDTOS.getVipData().getPhone().equals("")) {
            //有vip数据就不需要重新请求bsd的vip接口
            vipCheck(turnBackDTOS);
        }
        //todo 发送websocket放开
//        WebSocketController.sendInfo(new Gson().toJson(insertCustomer));
    }

    /**
     * vip数据检验
     *
     * @param turnBackDTO vip数据
     */
    private void vipCheck(TurnBackDTO turnBackDTO) throws Exception {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        OpCustomer opCustomer = new OpCustomer(turnBackDTO.getName(), turnBackDTO.getPhone());
        opCustomer.setUpdateBy(Constants.SYS_OPERATION);

        // 根据手机号码去重
        QueryWrapper<OpVip> wrapper = new QueryWrapper<>();
        wrapper.eq("phone", turnBackDTO.getVipData().getPhone());
        OpVip opVip = opVipDOMapper.selectOne(wrapper);
        OpVip opVip1 = new OpVip();
        opVip1.setStatus(1L);
        opVip1.setLevel(turnBackDTO.getVipData().getLevel());
        opVip1.setPhone(turnBackDTO.getVipData().getPhone());
        opVip1.setName(turnBackDTO.getVipData().getName());
        opVip1.setBirthday(turnBackDTO.getVipData().getBirthday());
        opVip1.setRegisterTime(turnBackDTO.getVipData().getRegisterTime().equals("") ? new Date() : simpleDateFormat.parse(turnBackDTO.getVipData().getRegisterTime()));
        if (opVip == null) {
            //数据库没有这个数据--新建数据
            opVip1.setCreateBy(Constants.SYS_OPERATION);
            opVip1.setCreateTime(new Date());
            opVipDOMapper.insert(opVip1);
            //有vip信息就绑定信息
            opCustomer.setMemberId(opVip1.getId());
        } else {
            opVip1.setId(opVip.getId());
            opVip1.setUpdateTime(new Date());
            opVip1.setUpdateBy(Constants.SYS_OPERATION);
            opVipDOMapper.updateById(opVip1);
            //有vip信息就绑定信息
            opCustomer.setMemberId(opVip.getId());
        }
        QueryWrapper<OpCustomer> wrapper1 = new QueryWrapper<>();
        if (turnBackDTO.getType() == 1){
            wrapper1.eq("wechat_uni_id", turnBackDTO.getWxData().getUnionId());
        }else{
            wrapper1.eq("external_userid", turnBackDTO.getWxData().getUserId());
        }
        opCustomerDOMapper.update(opCustomer, wrapper1);
    }

    /**
     * 处理客户和导购的关系
     * @param opCustomer
     * @param joinTime
     * @param shopId
     * @param sellerId
     */
    @Transactional(rollbackFor = Exception.class)
    public void sellerCustomerRelation(OpCustomer opCustomer, Date joinTime, long shopId, long sellerId) {
        QueryWrapper<OpSellerCustomerRelation> wrapper1 = new QueryWrapper<>();
        //一个客户只能添加一个店的店长微信，所以根据店铺判断即可
        wrapper1.eq("customer_id", opCustomer.getId()).eq("store_id", shopId).last("limit 1");
        OpSellerCustomerRelation opSellerCustomerRelation = opSellerCustomerRelationDOMapper.selectOne(wrapper1);
        if (null == opSellerCustomerRelation) {
            //不存在就添加
            OpSellerCustomerRelation insertRelation = new OpSellerCustomerRelation();
            insertRelation.setCreateTime(joinTime);
            insertRelation.setUpdateTime(new Date());
            insertRelation.setCustomerId(opCustomer.getId());
            insertRelation.setStoreId(shopId);
            insertRelation.setUserId(sellerId);
            insertRelation.setCreateBy(Constants.SYS_OPERATION);
            insertRelation.setUpdateBy(Constants.SYS_OPERATION);

            //判断是否有效
            QueryWrapper<OpSellerCustomerRelation> wrapper = new QueryWrapper<>();
            wrapper.eq("customer_id", opCustomer.getId()).last("limit 1");
            OpSellerCustomerRelation op = opSellerCustomerRelationDOMapper.selectOne(wrapper);
            if (op == null) {
                //有效
                insertRelation.setType(1);
            } else {
                //无效
                insertRelation.setType(2);
            }
            opSellerCustomerRelationDOMapper.insert(insertRelation);
        }else{
            //可能是同步过来的数据，此时已经存在的话，用有导购的代替
            opSellerCustomerRelation.setCreateTime(joinTime);
            opSellerCustomerRelation.setUpdateTime(new Date());
            opSellerCustomerRelation.setCustomerId(opCustomer.getId());
            opSellerCustomerRelation.setStoreId(shopId);
            opSellerCustomerRelation.setUserId(sellerId);
            opSellerCustomerRelation.setCreateBy(Constants.SYS_OPERATION);
            opSellerCustomerRelation.setUpdateBy(Constants.SYS_OPERATION);
            opSellerCustomerRelationDOMapper.updateById(opSellerCustomerRelation);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void storeCustomerRelation(OpCustomer opCustomer, Date joinTime,long shopId) {
        QueryWrapper<OpSellerCustomerRelation> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("customer_id", opCustomer.getId()).eq("store_id", shopId).last("limit 1");
        OpSellerCustomerRelation opSellerCustomerRelation = opSellerCustomerRelationDOMapper.selectOne(wrapper1);
        if (null == opSellerCustomerRelation) {
            //不存在就添加
            OpSellerCustomerRelation insertRelation = new OpSellerCustomerRelation();
            insertRelation.setCreateTime(joinTime);
            insertRelation.setUpdateTime(new Date());
            insertRelation.setCustomerId(opCustomer.getId());
            insertRelation.setStoreId(shopId);
            insertRelation.setUserId(0L);
            insertRelation.setCreateBy(Constants.SYS_OPERATION);
            insertRelation.setUpdateBy(Constants.SYS_OPERATION);

            //判断是否有效
            QueryWrapper<OpSellerCustomerRelation> wrapper = new QueryWrapper<>();
            wrapper.eq("customer_id", opCustomer.getId()).last("limit 1");
            OpSellerCustomerRelation op = opSellerCustomerRelationDOMapper.selectOne(wrapper);
            if (op == null) {
                //有效
                insertRelation.setType(1);
            } else {
                //无效
                insertRelation.setType(2);
            }
            if (shopId == 0L){
                QueryWrapper<PrivilageCpUserDO> cpQw = new QueryWrapper<>();
                cpQw.eq("cp_user_id",opCustomer.getCpUserId()).last("limit 1");
                PrivilageCpUserDO privilageCpUserDO = privilageCpUserDOMapper.selectOne(cpQw);
                if (privilageCpUserDO!=null){
                    insertRelation.setUserId(privilageCpUserDO.getId());
                }else{
                    privilageCpUserDO = new PrivilageCpUserDO();
                    privilageCpUserDO.setCpUserId(opCustomer.getCpUserId());
                    privilageCpUserDO.setStatus(1);
                    privilageCpUserDOMapper.insert(privilageCpUserDO);
                    insertRelation.setUserId(privilageCpUserDO.getId());
                }

                insertRelation.setType(3);
            }
            opSellerCustomerRelationDOMapper.insert(insertRelation);
        }
    }

    /**
     * 根据店铺id找到顾客信息
     *
     * @param shopIds
     */
    public List<OpCustomerDTO> getCustomerInfoByShopIds(Set<Long> shopIds, Date startDate, Date endDate, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<OpCustomerDTO> customers = opCustomerDOMapper.selectCustomerInfoByShopIds(shopIds, startDate, endDate);

        AtomicInteger number = new AtomicInteger(1 + ((pageNum - 1) * pageSize));
        //求分页总数
        Page<OpCustomerDTO> pageList = (Page<OpCustomerDTO>) customers;
        Long totalSize = pageList.getTotal();
        for (OpCustomerDTO m : customers) {
            m.setTotalSize(totalSize);
            m.setNumber(number.get());
            number.incrementAndGet();
            m.setPhone(m.getVipPhone());
        }
        return customers;
    }

    /**
     * 根据导购id找到顾客信息
     *
     * @param sellerId
     */
    public List<OpCustomerDTO> getCustomerInfoBySellerId(long sellerId, Date startDate, Date endDate, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<OpCustomerDTO> customers = opCustomerDOMapper.selectCustomerInfoBySellerId(sellerId, startDate, endDate);

        AtomicInteger number = new AtomicInteger(1 + ((pageNum - 1) * pageSize));
        //求分页总数
        Page<OpCustomerDTO> pageList = (Page<OpCustomerDTO>) customers;
        Long totalSize = pageList.getTotal();
        for (OpCustomerDTO m : customers) {
            m.setTotalSize(totalSize);
            m.setNumber(number.get());
            number.incrementAndGet();
        }
        return customers;
    }

    /**
     * 根据条件查询扫码推广的客户信息
     *
     * @param userId    用户id
     * @param shopId    店铺id
     * @param regionId  区域id
     * @param startDate 开始时间
     * @param endDate   结束时间
     */
    public List<OpCustomerDTO> getCustomerByUserAndDate(long userId, Long shopId, Long regionId, Long sellerId, Long companyId, Date startDate, Date endDate, int pageNum, int pageSize) {
        Set<Long> shopIds = new HashSet<>();

        //根据店铺查询所有扫码客户信息
        List<OpCustomerDTO> opCustomerDTOS;
        if (sellerId != null) {
            opCustomerDTOS = getCustomerInfoBySellerId(sellerId, startDate, endDate, pageNum, pageSize);
            return opCustomerDTOS;
        } else if (shopId != null) {
            //如果有店铺则查店铺
            shopIds.add(shopId);
        } else if (regionId != null) {
            //如果有区域则查区域店铺
            List<PoiStore> shops = poiStoreService.getRegionShop(regionId);
            shopIds = shops.stream().map(p -> p.getId()).collect(Collectors.toSet());
            List<Long> userAllShops = privilageDomainService.listUserDatePermission(userId);
            shopIds.retainAll(userAllShops);
        } else if (companyId != null) {
            //如果有公司则查公司店铺
            Set<Long> sp = customerViewService.getCompanyShop(companyId, userId);
            shopIds.addAll(sp);
        } else {
            //查询用户权限店铺
            shopIds = new HashSet<>(privilageDomainService.listUserDatePermission(userId));
        }

        //根据店铺查询所有扫码客户信息
        opCustomerDTOS = getCustomerInfoByShopIds(shopIds, startDate, endDate, pageNum, pageSize);
        return opCustomerDTOS;
    }

    /**
     * 修改客户信息
     *
     * @param opCustomer
     */
    public void editCustomerInfo(OpCustomer opCustomer) {
        opCustomerDOMapper.updateById(opCustomer);
    }

    /**
     * 查询好友列表，可根据导购、日期、搜索
     * @param userId 用户ID
     * @param sellerId 导购ID
     * @param search 搜索内容
     * @param roleCode 角色编码
     * @param type 会员与非会员类型
     * @param startDate 开始日期
     * @param endDate 结束日期
     * @param flag 0、新增好友  1、累计好友
     * @return 返回数据集合
     * @throws Exception 异常
     * @author dexiang.jiang
     * @date 2020/05/10 21:50
     */
    public Map<String, Object> listCustomerNew(Long userId, Long sellerId, String search, String roleCode, Integer type, Date startDate, Date endDate, int flag, int pageNum, int pageSize) throws Exception {
        Map<String, Object> results = new HashMap<>();
        List<StafferInfoVO> stafferInfoVOS = poiStoreStaffDOMapper.selectInfoById(userId);
        if (CollectionUtils.isEmpty(stafferInfoVOS)) {
            results.put("this", null);
            return results;
        }
        Long shopId = stafferInfoVOS.get(0).getStoreId();
        List<FriendDTO> thisList;
        PageHelper.startPage(pageNum, pageSize);
        if (roleCode.equals(RoleEnum.ROLE_CODE_DZ.getRoleCode())) {
            // 0、新增好友  1、累计好友
            if(flag == 0){
                thisList = opSellerCustomerRelationDOMapper.selectFriendListByShopId(shopId, sellerId, search, startDate, endDate, type);
            }else{
                thisList = opSellerCustomerRelationDOMapper.selectFriendListByShopIdAndDate(shopId, sellerId, search, startDate, endDate, type);
            }

            if(CollectionUtils.isNotEmpty(thisList)){
                for (int i = 0; i < thisList.size(); i++) {
                    // 设置导购名称
                    if(!thisList.get(i).getInviteSellerId().equals(0L)){
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", thisList.get(i).getInviteSellerId());
                        String userName = poiStoreStaffDOMapper.selectUserNameById(thisList.get(i).getInviteSellerId());
                        if(StringUtils.isNotEmpty(userName)){
                            thisList.get(i).setInviteSellerName(userName);
                        }else{
                            thisList.get(i).setInviteSellerName("");
                        }
                    }else{
                        thisList.get(i).setInviteSellerName("");
                    }
                }
            }
        } else {
            // 0、新增好友  1、累计好友
            if(flag == 0){
                thisList = opSellerCustomerRelationDOMapper.selectFriendListBySeller(userId, search, startDate, endDate, type);
            }else{
                thisList = opSellerCustomerRelationDOMapper.selectFriendListBySellerAndDate(userId, search, startDate, endDate, type);
            }
        }

        results.put("this", new PageInfo<>(thisList));
        return results;
    }

    /**
     * @param userId
     * @param sellerId
     * @param search
     * @param roleCode
     */
    public Map<String, Object> listCustomer(Long userId, Long sellerId, String search, String roleCode, Integer type, Date startDate, Date endDate) throws Exception {
        Map<String, Object> results = new HashMap<>();
        Date thisDate = new Date();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.HOUR_OF_DAY, -24);
        Date lastDate = dateFormat.parse(dateFormat.format(calendar.getTime()));
        calendar.set(Calendar.HOUR_OF_DAY, -24);
        Date earlyDate = dateFormat.parse(dateFormat.format(calendar.getTime()));
        List<StafferInfoVO> stafferInfoVOS = poiStoreStaffDOMapper.selectInfoById(userId);
        if (CollectionUtils.isEmpty(stafferInfoVOS)) {
            results.put("this", null);
            results.put("last", null);
            results.put("early", null);
            return results;
        }
        Long shopId = stafferInfoVOS.get(0).getStoreId();
        if (roleCode.equals(RoleEnum.ROLE_CODE_DZ.getRoleCode())) {
            List<FriendDTO> thisList = opSellerCustomerRelationDOMapper.selectFriendListByShopId(shopId, sellerId, search, startDate, endDate, type);
            thisList.forEach(friendDTO -> {
                String inviteSellerName = opSellerCustomerRelationDOMapper.selectStaffName(friendDTO.getInviteSellerId());
                if (StringUtils.isNotBlank(inviteSellerName)) {
                    friendDTO.setInviteSellerName(inviteSellerName);
                }
            });
            List<FriendDTO> lastList = opSellerCustomerRelationDOMapper.selectFriendListByShopId(shopId, sellerId, search, lastDate, lastDate, type);
            lastList.forEach(friendDTO -> {
                String inviteSellerName = opSellerCustomerRelationDOMapper.selectStaffName(friendDTO.getInviteSellerId());
                if (StringUtils.isNotBlank(inviteSellerName)) {
                    friendDTO.setInviteSellerName(inviteSellerName);
                }
            });
            List<FriendDTO> earlyList = opSellerCustomerRelationDOMapper.selectFriendListByShopId(shopId, sellerId, search, null, earlyDate, type);
            earlyList.forEach(friendDTO -> {
                String inviteSellerName = opSellerCustomerRelationDOMapper.selectStaffName(friendDTO.getInviteSellerId());
                if (StringUtils.isNotBlank(inviteSellerName)) {
                    friendDTO.setInviteSellerName(inviteSellerName);
                }
            });
            results.put("this", thisList);
            results.put("last", lastList);
            results.put("early", earlyList);
        } else {
            List<FriendDTO> thisList = opSellerCustomerRelationDOMapper.selectFriendListBySeller(userId, search, startDate, endDate, type);
            results.put("this", thisList);
            List<FriendDTO> lastList = opSellerCustomerRelationDOMapper.selectFriendListBySeller(userId, search, lastDate, lastDate, type);
            results.put("last", lastList);
            List<FriendDTO> earlyList = opSellerCustomerRelationDOMapper.selectFriendListBySeller(userId, search, null, earlyDate, type);
            results.put("early", earlyList);
        }
        return results;
    }

}