package com.pcloud.book.group.biz.impl;

import com.alibaba.fastjson.JSONObject;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.common.ExportConsr;
import com.pcloud.book.consumer.message.MessageConsr;
import com.pcloud.book.consumer.promotion.PromotionConsr;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.consumer.resource.ProductConsr;
import com.pcloud.book.consumer.settlement.SettlementConsr;
import com.pcloud.book.consumer.trade.TradeConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.copyright.biz.BookAuthUserBiz;
import com.pcloud.book.group.biz.BookGroupBiz;
import com.pcloud.book.group.biz.BookGroupClassifyBiz;
import com.pcloud.book.group.biz.GroupAnnouncementBiz;
import com.pcloud.book.group.biz.GroupQrcodeBiz;
import com.pcloud.book.group.biz.WeixinQrcodeBiz;
import com.pcloud.book.group.dao.BookClassifyBuyRecordDao;
import com.pcloud.book.group.dao.BookGroupClassifyDao;
import com.pcloud.book.group.dao.BookQrcodeUserDao;
import com.pcloud.book.group.dao.JoinGroupCipherDao;
import com.pcloud.book.group.dao.LearningReportBrowseRecordDao;
import com.pcloud.book.group.dao.LearningReportTouchRecordDao;
import com.pcloud.book.group.dto.BookClassifyDTO;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.dto.BookGroupStatisticDTO;
import com.pcloud.book.group.dto.BookWxQrcodeDTO;
import com.pcloud.book.group.dto.ClassifyDTO;
import com.pcloud.book.group.dto.ClassifyLearningCountDto;
import com.pcloud.book.group.dto.ClassifyLearningReportDto;
import com.pcloud.book.group.dto.GroupAndUserNumberDTO;
import com.pcloud.book.group.dto.GroupClassifyQrcodeDTO;
import com.pcloud.book.group.dto.GroupNameAndMaxSeqDTO;
import com.pcloud.book.group.dto.GroupQrcodeBaseDTO;
import com.pcloud.book.group.dto.GroupQrcodeInfoDTO;
import com.pcloud.book.group.dto.ProAssocGroupAndUserNumberDTO;
import com.pcloud.book.group.dto.QrcodeNameAndProIdDTO;
import com.pcloud.book.group.dto.WeixinQrcodeDTO;
import com.pcloud.book.group.entity.BookGroupClassify;
import com.pcloud.book.group.entity.BookQrcodeUser;
import com.pcloud.book.group.entity.GroupQrcode;
import com.pcloud.book.group.enums.RankTypeEnum;
import com.pcloud.book.group.set.GroupSet;
import com.pcloud.book.group.tools.SendWeixinRequestTools;
import com.pcloud.book.group.vo.AddClassifyVO;
import com.pcloud.book.group.vo.AdviserClassifyParam;
import com.pcloud.book.group.vo.AdviserClassifyVO;
import com.pcloud.book.group.vo.BookGroupClassifyVO;
import com.pcloud.book.group.vo.BookGroupQrcodeStatisticVO;
import com.pcloud.book.group.vo.ClassifyAndGroupCountVO;
import com.pcloud.book.group.vo.ClassifyAndUserCountVO;
import com.pcloud.book.group.vo.ClassifyNameVO;
import com.pcloud.book.group.vo.ClassifyVO;
import com.pcloud.book.group.vo.GroupQrcode4ClassifyVO;
import com.pcloud.book.group.vo.GroupQrcodeBaseInfoVO;
import com.pcloud.book.group.vo.ListBookGroupQrcodeParamVO;
import com.pcloud.book.group.vo.ListClassify4WechatVO;
import com.pcloud.book.group.vo.ListClassifyVO;
import com.pcloud.book.group.vo.ListGroupClassifyParam;
import com.pcloud.book.group.vo.StatisticVO;
import com.pcloud.book.group.vo.SyncKeyworsVO;
import com.pcloud.book.group.vo.UpdateClassifyVO;
import com.pcloud.book.group.vo.UpdateRankVO;
import com.pcloud.book.keywords.dao.BookKeywordDao;
import com.pcloud.book.keywords.entity.BookKeyword;
import com.pcloud.book.util.common.ThreadPoolUtils;
import com.pcloud.book.util.properties.BookProps;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.constant.SystemCode;
import com.pcloud.common.core.enums.NotifyOriginTypeEnum;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.facade.tradecenter.dto.QrGroupBuyDetailDto;
import com.pcloud.labelcenter.label.service.LabelService;
import com.pcloud.readercenter.wechat.dto.WechatUserRobotDto;
import com.pcloud.resourcecenter.product.dto.UpdateAppProductParamDTO;
import com.pcloud.resourcecenter.product.entity.Product;
import com.pcloud.resourcecenter.product.entity.Specification;
import com.pcloud.wechatgroup.group.dto.GroupMemberStatisDTO;
import com.pcloud.wechatgroup.message.dto.GroupChatCountDTO;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lily
 * @date 2019/4/17 11:20
 */
@Slf4j
@Component("bookGroupClassifyBiz")
public class BookGroupClassifyBizImpl implements BookGroupClassifyBiz {

    private static final Logger LOGGER = LoggerFactory.getLogger(BookGroupClassifyBizImpl.class);

    @Autowired
    private WeixinQrcodeBiz weixinQrcodeBiz;
    @Autowired
    private BookGroupClassifyDao bookGroupClassifyDao;
    @Autowired
    private BookGroupBiz bookGroupBiz;
    @Autowired
    private ProductConsr productConsr;
    @Autowired
    private GroupQrcodeBiz groupQrcodeBiz;
    @Autowired
    private ReaderConsr readerConsr;
    @Autowired
    private BookClassifyBuyRecordDao bookClassifyBuyRecordDao;
    @Autowired
    private BookQrcodeUserDao bookQrcodeUserDao;
    @Autowired
    private PromotionConsr promotionConsr;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private SettlementConsr settlementConsr;
    @Autowired
    private ExportConsr exportConsr;
    @Autowired
    private MessageConsr messageConsr;
    @Autowired
    private TradeConsr tradeConsr;
    @Autowired
    private GroupAnnouncementBiz groupAnnouncementBiz;
    @Autowired
    private LabelService labelService;
    @Autowired
    private BookKeywordDao bookKeywordDao;
    @Autowired
    private GroupSet groupSet;
    @Autowired
    private BookGroupClassifyBiz bookGroupClassifyBiz;
    @Autowired
    private LearningReportBrowseRecordDao learningReportBrowseRecordDao;
    @Autowired
    private LearningReportTouchRecordDao learningReportTouchRecordDao;
    @Autowired
    private JoinGroupCipherDao joinGroupCipherDao;

    @Autowired
    private BookAuthUserBiz bookAuthUserBiz;


    @Override
    @ParamLog("新增分类")
    @Transactional(rollbackFor = Exception.class)
    public void addClassify(AddClassifyVO addClassifyVO, Long partyId) {
        checkClassifyIsExist(addClassifyVO.getClassify(), null, addClassifyVO.getBookGroupId());
        final Map<Long, BookGroupStatisticDTO> statistic = bookGroupClassifyBiz.getBookGroupStatistic(Collections.singletonList(addClassifyVO.getBookGroupId()));
        Integer classifyCount = 0;
        if (!CollectionUtils.isEmpty(statistic) && null != statistic.get(addClassifyVO.getBookGroupId())) {
            classifyCount = statistic.get(addClassifyVO.getBookGroupId()).getClassifyCount();
        }
        if (classifyCount >= 40) {
            throw new BookBizException(BookBizException.ERROR, "分类数量超出限制");
        }
        if (addClassifyVO.getPrice() == null) {
            addClassifyVO.setPrice(BigDecimal.ZERO);
        }
        BookGroupClassify bookGroupClassify = new BookGroupClassify();
        BeanUtils.copyProperties(addClassifyVO, bookGroupClassify);
        QrcodeNameAndProIdDTO qrcodeNameAndProId = bookGroupBiz.getQrcodeNameAndProId(addClassifyVO.getBookGroupId());
        if (qrcodeNameAndProId == null) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "请先填写社群码信息！");
        }
        bookGroupClassify.setProductId(qrcodeNameAndProId.getProductId());
        bookGroupClassify.setCreateUser(partyId);
        Integer rank = bookGroupClassifyDao.getMaxRank(addClassifyVO.getBookGroupId());
        bookGroupClassify.setRank(rank);
        bookGroupClassifyDao.insert(bookGroupClassify);
        final Long wechatGroupNum = weixinQrcodeBiz.countWechatGroup();
        // 只有生产环境才有30个限制
        if ("pro".equalsIgnoreCase(BookProps.getSystemEnv())) {
            if(null == wechatGroupNum || wechatGroupNum <= 30) {
                log.info("[新增分类] : 可用微信群数量：{}个", wechatGroupNum);
                throw new BookBizException(BookBizException.PARAM_IS_NULL, "群二维码数量不足，您可以明天再创建群。");
            }
        }
        Integer generation = null;
        if (new Integer(2).equals(qrcodeNameAndProId.getJoinGroupType())) {
            generation = 3;
        }
        WeixinQrcodeDTO oneQrcode = weixinQrcodeBiz.getOneQrcode(generation);
        if (oneQrcode == null) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "系统二维码数量不足，请联系客服人员补充二维码数量！");
        }
        GroupQrcode groupQrcode = new GroupQrcode();
        groupQrcode.setWeixinGroupId(oneQrcode.getWeixinGroupId());
        groupQrcode.setQrcodeUrl(oneQrcode.getQrcodeUrl());
        groupQrcode.setCreateUser(partyId);
        groupQrcode.setWeixinQrcodeId(oneQrcode.getId());
        groupQrcode.setUserNumber(oneQrcode.getUserNumber());
        groupQrcode.setGroupSeq(1);
        // 群长度超过16部分会被截取，导致群名称重复
        final String s = "1群";
        String groupName = qrcodeNameAndProId.getGroupQrcodeName() + addClassifyVO.getClassify() + s;
        if (groupName.length() > 15) {
            groupName = addClassifyVO.getClassify() + s;
            if (groupName.length() > 15) {
                groupName = addClassifyVO.getClassify().substring(0, 16 - s.length()) + s;
            }
        }
        groupQrcode.setGroupName(groupName);
        groupQrcode.setClassifyId(bookGroupClassify.getId());
        groupQrcode.setQrcodeHeadUrl(readerConsr.getNineHeadUrl());
        groupQrcodeBiz.insert(groupQrcode);
        //获取该社群书下是否有群公告
        groupAnnouncementBiz.setAnForGroup(addClassifyVO.getBookGroupId(), null, oneQrcode.getWeixinGroupId());
        //新增一个规格
        Long specId = addSpecification(bookGroupClassify.getPrice(), qrcodeNameAndProId.getProductId(), addClassifyVO.getChannelId(), bookGroupClassify.getClassify());
        bookGroupClassify.setProductSpecId(specId);
        //更新规格
        bookGroupClassifyDao.updateSpecId(bookGroupClassify.getId(), bookGroupClassify.getProductSpecId());
        //发送更新群名称请求
//        String robotId = wechatGroupConsr.getRobotIdByGroupId(oneQrcode.getWeixinGroupId());

        //同步关键词
        List<BookKeyword> bookKeywords = new ArrayList<>();
        List<SyncKeyworsVO> syncKeyworsVOS = bookKeywordDao.getKeywordsIdsByBookGroupId(addClassifyVO.getBookGroupId(),0L);
        syncKeyworsVOS.forEach(e -> {
            BookKeyword bookKeyword = new BookKeyword();
            bookKeyword.setBookGroupId(addClassifyVO.getBookGroupId());
            bookKeyword.setClassifyId(bookGroupClassify.getId());
            bookKeyword.setKeywordId(e.getKeywordsId());
            bookKeyword.setBookId(addClassifyVO.getBookId());
            bookKeyword.setChannelId(addClassifyVO.getChannelId());
            bookKeyword.setSetType(0);
            //获取最大排序值
            Integer seq = bookKeywordDao.getMaxRank(addClassifyVO.getBookGroupId(), bookKeyword.getClassifyId());
            bookKeyword.setRank(seq + 1);
            bookKeyword.setCreateUser(partyId);
            bookKeyword.setWarehouseId(e.getWarehouseId());
            bookKeyword.setIsWarehouse(e.getIsWarehouse());
            bookKeyword.setIsEdit(0);
            bookKeywords.add(bookKeyword);
        });
        bookKeywordDao.insert(bookKeywords);
        final String wechatGroupId = oneQrcode.getWeixinGroupId();
        Map<String, BookWxQrcodeDTO> groupVersion = weixinQrcodeBiz.getGroupVersion(Collections.singletonList(wechatGroupId));
        String ip = Optional.ofNullable(groupVersion.get(wechatGroupId)).orElse(new BookWxQrcodeDTO()).getWechatGroupIp();
        SendWeixinRequestTools.changeGroupName(oneQrcode.getRobotWxId(), oneQrcode.getWeixinGroupId(), groupQrcode.getGroupName(), ip);
    }

    @ParamLog("新增商品对应规格")
    private Long addSpecification(BigDecimal price, Long productId, Long channelId, String classify) {
        UpdateAppProductParamDTO updateAppProductParamDTO = new UpdateAppProductParamDTO();
        updateAppProductParamDTO.setProductId(productId);
        updateAppProductParamDTO.setChannelId(channelId);
        List<Specification> specificationList = new ArrayList<>();
        Specification specification = new Specification();
        specification.setRetailPrice(price.doubleValue());
        specification.setSpecificationName(classify);
        specificationList.add(specification);
        updateAppProductParamDTO.setSpecificationList(specificationList);
        Product product = productConsr.postUpdateBookGroupProduct(updateAppProductParamDTO);
        if (product == null) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "新增分类对应商品失败");
        }
        List<Specification> spec = product.getSpecification();
        if (spec != null) {
            return spec.get(0).getSpecificationId();
        } else {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "新增分类对应商品失败");
        }
    }

    @ParamLog("新增商品对应规格")
    private void deleteSpecification(Long productId, Long channelId, Long specId) {
        UpdateAppProductParamDTO updateAppProductParamDTO = new UpdateAppProductParamDTO();
        updateAppProductParamDTO.setProductId(productId);
        updateAppProductParamDTO.setChannelId(channelId);
        List<Long> specIds = new ArrayList<>();
        specIds.add(specId);
        updateAppProductParamDTO.setDelSpecificationIds(specIds);
        productConsr.postUpdateBookGroupProduct(updateAppProductParamDTO);
    }


    @ParamLog("校验分类是否存在")
    private void checkClassifyIsExist(String classify, Long classfiyId, Long bookGroupId) {
        Boolean isHaveThisClassify = bookGroupClassifyDao.isHaveThisClassify(classify, classfiyId, bookGroupId);
        if (isHaveThisClassify) {
            throw new BookBizException(BookBizException.ERROR, "已存在该分类!");
        }
        if (classify != null && classify.contains("#")) {
            throw new BookBizException(BookBizException.ERROR, "名称不能包含#!");
        }
    }

    @ParamLog("获取社群下有多少分类")
    private Integer getClassifyCount(Long bookGroupId) {
        Integer count = bookGroupClassifyDao.getClassifyCount(bookGroupId);
        return count;
    }

    @Override
    @ParamLog("更新分类")
    public void updateClassify(UpdateClassifyVO updateClassifyVO, Long partyId) {
        checkClassifyIsExist(updateClassifyVO.getClassify(), updateClassifyVO.getId(), updateClassifyVO.getBookGroupId());
        if (updateClassifyVO.getPrice() == null) {
            updateClassifyVO.setPrice(BigDecimal.ZERO);
        }
        //获取分类基本信息
        ClassifyDTO oldClassify = bookGroupClassifyDao.getById(updateClassifyVO.getId());
        BookGroupClassify bookGroupClassify = new BookGroupClassify();
        BeanUtils.copyProperties(updateClassifyVO, bookGroupClassify);
        bookGroupClassifyDao.update(bookGroupClassify);
        //修改规格信息
        updateSpec(oldClassify, updateClassifyVO);
    }

    @ParamLog("更新规格信息")
    private void updateSpec(ClassifyDTO oldClassify, UpdateClassifyVO updateClassifyVO) {
        BigDecimal oldPrice = oldClassify.getPrice() == null ? BigDecimal.ZERO : oldClassify.getPrice();
        BigDecimal newPrice = updateClassifyVO.getPrice() == null ? BigDecimal.ZERO : updateClassifyVO.getPrice();
        if (oldPrice.equals(newPrice) && oldClassify.getClassify().equalsIgnoreCase(updateClassifyVO.getClassify())) {
            return;
        }
        UpdateAppProductParamDTO updateAppProductParamDTO = new UpdateAppProductParamDTO();
        updateAppProductParamDTO.setProductId(oldClassify.getProductId());
        updateAppProductParamDTO.setChannelId(oldClassify.getChannelId());
        List<Specification> specificationList = new ArrayList<>();
        Specification specification = new Specification();
        specification.setRetailPrice(newPrice.doubleValue());
        specification.setSpecificationName(updateClassifyVO.getClassify());
        specification.setSpecificationId(oldClassify.getProductSpecId());
        specificationList.add(specification);
        updateAppProductParamDTO.setSpecificationList(specificationList);
        productConsr.postUpdateBookGroupProduct(updateAppProductParamDTO);
    }

    @Override
    @ParamLog("分类列表")
    public List<ListClassifyVO> listAllClassify(Long bookGroupId) {
        //获取排序方式
        Integer rankType = bookGroupBiz.getRankType(bookGroupId);
        List<ListClassifyVO> classifys;
        if (RankTypeEnum.BY_RANK.value.equals(rankType)) {
            classifys = bookGroupClassifyDao.listAllClassifyByRank(bookGroupId);
            //设置群总人数与群总数
            setGroupNumberAndUserNumber(classifys);
        } else {
            classifys = bookGroupClassifyDao.listAllClassifyByUser(bookGroupId);
        }
        if (ListUtils.isEmpty(classifys)) {
            return new ArrayList<>();
        }
        return classifys;
    }

    @ParamLog("设置群数量与群总人数")
    private void setGroupNumberAndUserNumber(List<ListClassifyVO> classifys) {
        if (ListUtils.isEmpty(classifys)) {
            return;
        }
        List<Long> classifyIds = new ArrayList<>();
        for (ListClassifyVO listClassifyVO : classifys) {
            classifyIds.add(listClassifyVO.getId());
        }
        Map<Long, GroupAndUserNumberDTO> groupAndUserNumberMap = groupQrcodeBiz.listGroupAndUserNumber(classifyIds);
        for (ListClassifyVO listClassifyVO : classifys) {
            if (groupAndUserNumberMap != null) {
                GroupAndUserNumberDTO groupAndUserNumberDTO = groupAndUserNumberMap.get(listClassifyVO.getId());
                listClassifyVO.setQrcodeNumber(groupAndUserNumberDTO == null ? 0 : groupAndUserNumberDTO.getGroupCount());
                listClassifyVO.setUserNumberTotal(groupAndUserNumberDTO == null ? 0 : groupAndUserNumberDTO.getUserCount());
            } else {
                listClassifyVO.setQrcodeNumber(0);
                listClassifyVO.setUserNumberTotal(0);
            }
        }
    }

    @Override
    @ParamLog("删除分类")
    @Transactional(rollbackFor = Exception.class)
    public void deleteClassify(Long classifyId, Long partyId) {
        //获取分类基本信息
        ClassifyDTO classifyDTO = bookGroupClassifyDao.getById(classifyId);
        if (classifyDTO == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "该分类不存在");
        }
        bookGroupClassifyDao.deleteClassify(classifyId, partyId);
        groupQrcodeBiz.deleteByClassifyId(classifyId);
        //删除此商品对应规格
        deleteSpecification(classifyDTO.getProductId(), classifyDTO.getChannelId(), classifyDTO.getProductSpecId());
        //发送topic
        groupSet.sendGroupClassifyDeleteTopic(classifyId);
    }

    @Override
    @ParamLog("获取分类基本信息")
    public ClassifyVO getClassify(Long classifyId) {
        ClassifyVO classifyVO = bookGroupClassifyDao.getClassify(classifyId);
        return classifyVO;
    }

    @Override
    @ParamLog("根据主键id获取群分类")
    public  Map<Long, String> getClassifyByIds(List<Long> weixinGroupClassifyPrimaryIds) {
        if (ListUtils.isEmpty(weixinGroupClassifyPrimaryIds)) {
            return new HashMap<>();
        }
        List<BookGroupClassify> bookGroupClassifyList = bookGroupClassifyDao.getClassifyByIds(weixinGroupClassifyPrimaryIds);
        Map<Long, String> classifyMap = new HashMap<>();
        bookGroupClassifyList.stream().forEach(eachBookGroupClassify ->{
            Long key = eachBookGroupClassify.getId();
            String value = eachBookGroupClassify.getClassify();
            classifyMap.put(key, value);
        });
        return classifyMap;
    }

    @Override
    @ParamLog("根据规格获取分类基本信息（图书，运营，二维码，分类）")
    public ClassifyDTO getBaseInfoBySpecId(Long productSpecId) {
        ClassifyDTO classifyDTO = bookGroupClassifyDao.getBaseInfoBySpecId(productSpecId);
        return classifyDTO;
    }


    @Override
    @ParamLog("修改排序值")
    public void updateClassifyRank(UpdateRankVO updateRankVO, Long partyId) {
        BookGroupClassify bookGroupClassify = new BookGroupClassify();
        bookGroupClassify.setId(updateRankVO.getClassifyId());
        bookGroupClassify.setRank(updateRankVO.getRank());
        bookGroupClassify.setUpdateUser(partyId);
        bookGroupClassifyDao.updateClassifyRank(bookGroupClassify);
    }

    @Override
    @ParamLog("获取所有分类名")
    public List<ClassifyNameVO> listClassify(Long bookGroupId) {
        //获取排序方式
        Integer rankType = bookGroupBiz.getRankType(bookGroupId);
        List<ClassifyNameVO> classifys;
        if (RankTypeEnum.BY_RANK.value.equals(rankType)) {
            classifys = bookGroupClassifyDao.listClassifyByRank(bookGroupId);
        } else {
            classifys = bookGroupClassifyDao.listClassifyByUser(bookGroupId);
        }
        return classifys;
    }

    @Override
    @ParamLog("获取分类与群数量")
    public ClassifyAndGroupCountVO getClassifyAndGroupCount(Long bookGroupId) {
        ClassifyAndGroupCountVO classifyAndGroupCountVO = new ClassifyAndGroupCountVO();
        Integer groupCount = bookGroupClassifyDao.getGroupCount(bookGroupId);
        //获取分类数量
        final Map<Long, BookGroupStatisticDTO> statistic = bookGroupClassifyBiz.getBookGroupStatistic(Collections.singletonList(bookGroupId));
        if (CollectionUtils.isEmpty(statistic) || null == statistic.get(bookGroupId)) {
            classifyAndGroupCountVO.setClassifyCount(0);
        } else {
            classifyAndGroupCountVO.setClassifyCount(statistic.get(bookGroupId).getClassifyCount());
        }
        classifyAndGroupCountVO.setGroupCount(groupCount);
        return classifyAndGroupCountVO;
    }

    @Override
    @ParamLog("获取分类数与用户总数")
    public ClassifyAndUserCountVO getClassifyAndUserCount(Long bookGroupId) {
        ClassifyAndUserCountVO classifyAndUserCountVO = new ClassifyAndUserCountVO();
        final Map<Long, BookGroupStatisticDTO> statistic = bookGroupClassifyBiz.getBookGroupStatistic(Collections.singletonList(bookGroupId));
        if (CollectionUtils.isEmpty(statistic) || null == statistic.get(bookGroupId)) {
            classifyAndUserCountVO.setClassifyCount(0);
        } else {
            classifyAndUserCountVO.setClassifyCount(statistic.get(bookGroupId).getClassifyCount());
        }
        Integer userCount = bookGroupClassifyDao.getUserNumberCount(bookGroupId);
        classifyAndUserCountVO.setUserCount(userCount);
        return classifyAndUserCountVO;
    }

    @Override
    @ParamLog("获取分类社群码名称以及最大群数量")
    public GroupNameAndMaxSeqDTO getGroupNameAndMaxSeq(Long classifyId) {
        return bookGroupClassifyDao.getGroupNameAndMaxSeq(classifyId);
    }

    @Override
    @ParamLog("获取分类二维码相关标识")
    public GroupClassifyQrcodeDTO getClassifyQrcodeInfo(String weixinGroupId) {
        return bookGroupClassifyDao.getClassifyQrcodeInfo(weixinGroupId);
    }

    @Override
    @ParamLog("获取分类二维码相关标识")
    public List<GroupClassifyQrcodeDTO> listClassifyQrcodeInfo(List<Long> classifyIds) {
        return bookGroupClassifyDao.listClassifyQrcodeInfo(classifyIds);
    }

    @Override
    @ParamLog("客户端获取分类信息")
    public List<ListClassify4WechatVO> listClassify4Wechat(Long bookGroupId, Long wechatUserId) {
        //获取排序方式
        Integer rankType = bookGroupBiz.getRankType(bookGroupId);
        List<ListClassify4WechatVO> listClassify4WechatVOS = bookGroupClassifyDao.listClassify4Wechat(bookGroupId, rankType);
        if (listClassify4WechatVOS == null) {
            return new ArrayList<>();
        }
        //设置二维码信息
        setGroupQrcodeInfo(listClassify4WechatVOS);
        //获取头像信息
        //setUserHeader(listClassify4WechatVOS);
        //设置是否购买
        setIsBuy(listClassify4WechatVOS, wechatUserId);
        return listClassify4WechatVOS;
    }

    @ParamLog(value = "设置是否购买", isBefore = false)
    private void setIsBuy(List<ListClassify4WechatVO> listClassify4Wechats, Long wechatUserId) {
        if (ListUtils.isEmpty(listClassify4Wechats)) {
            return;
        }
        List<Long> classifyIds = new ArrayList<>();
        for (ListClassify4WechatVO listClassify4WechatVO : listClassify4Wechats) {
            classifyIds.add(listClassify4WechatVO.getClassifyId());
        }
        //根据二维码获取二维码基本信息
        List<Long> buyClassifyIds = bookClassifyBuyRecordDao.checkUsersBuy(classifyIds, wechatUserId);
        if (ListUtils.isEmpty(buyClassifyIds)) {
            return;
        }
        for (ListClassify4WechatVO listClassify4WechatVO : listClassify4Wechats) {
            if (buyClassifyIds.contains(listClassify4WechatVO.getClassifyId())) {
                listClassify4WechatVO.setBuy(true);
            }
        }
    }

    @Override
    @ParamLog("客户端根据群分类获取二维码")
    public GroupQrcode4ClassifyVO getGroupQrcode4ClassifyWechat(Long classifyId, Long wechatUserId) {
        //获取分类基本信息
        ClassifyVO classify = bookGroupClassifyDao.getClassify(classifyId);
        if (classify == null) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "社群码不存在，请刷新后重试");
        }
        if (new BigDecimal(0).compareTo(classify.getPrice()) < 0) {
            //校验用户是否正版授权
            Boolean isAuth = bookAuthUserBiz.checkIsHaveAuth(classify.getBookId(), classify.getChannelId(), classify.getCreateUser(), wechatUserId, 1);
            if(!isAuth) {
                //校验用户是否购买
                Boolean isBuy = bookClassifyBuyRecordDao.checkUserBuy(wechatUserId, classifyId);
                if (!isBuy) {
                    throw new BookBizException(BookBizException.PARAM_IS_NULL, "您还未购买，请购买后使用！");
                }
            }
        }

        //获取用户是否分配过二维码
        GroupQrcode4ClassifyVO groupQrcode4ClassifyVO = bookQrcodeUserDao.getUserQrcode(classifyId, wechatUserId);
        if (groupQrcode4ClassifyVO == null) {
            //获取分类对应的二维码
            groupQrcode4ClassifyVO = bookGroupClassifyDao.getClassifyQrcode(classifyId, classify.getChangeNumber());
            if (groupQrcode4ClassifyVO == null) {
                groupQrcode4ClassifyVO = new GroupQrcode4ClassifyVO();
                groupQrcode4ClassifyVO.setClassifyId(classifyId);
            } else {
                BookQrcodeUser bookQrcodeUser = new BookQrcodeUser();
                bookQrcodeUser.setClassifyId(classifyId);
                bookQrcodeUser.setGroupQrcodeId(groupQrcode4ClassifyVO.getGroupQrcodeId());
                bookQrcodeUser.setWechatUserId(wechatUserId);
                bookQrcodeUser.setCreateUser(wechatUserId);
                try {
                    bookQrcodeUserDao.insert(bookQrcodeUser);
                } catch (DataIntegrityViolationException e) {
                    LOGGER.error("已存在该用户！");
                }
            }
        }
        String spareQr = getSpareQr(classify.getBookGroupId());
        groupQrcode4ClassifyVO.setSpareQr(spareQr);
        groupQrcode4ClassifyVO.setClassify(classify.getClassify());
        return groupQrcode4ClassifyVO;
    }

    @Override
    @ParamLog("[getWxGroupIdByClassifyIdAndWechatId]")
    public GroupQrcodeBaseInfoVO getWxGroupIdByClassifyIdAndWechatId(Long classifyId, Long wechatUserId) {
        if(null == classifyId || null == wechatUserId) {
            return null;
        }
        final GroupQrcode4ClassifyVO wechat = this.getGroupQrcode4ClassifyWechat(classifyId, wechatUserId);
        if(null == wechat) {
            return null;
        }
        final GroupQrcodeBaseInfoVO baseById = this.groupQrcodeBiz.getBaseById(wechat.getGroupQrcodeId());
        return baseById;
    }

    @ParamLog("获取备用二维码")
    private String getSpareQr(Long bookGroupId) {
        //获取备用二维码
        String spareQr = bookGroupBiz.getSpareQr(bookGroupId);
        if (StringUtil.isEmpty(spareQr)) {
            spareQr = promotionConsr.getSpareQr();
        }
        return spareQr;
    }

    @Override
    @ParamLog("获取编辑所有的分类")
    public PageBeanNew<BookGroupClassifyVO> listGroupClassifyByAdviser(ListGroupClassifyParam listGroupClassifyParam, Long adviserId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("adviserId", adviserId);
        if (!StringUtil.isEmpty(listGroupClassifyParam.getName())) {
            paramMap.put("name", listGroupClassifyParam.getName());
        }
        paramMap.put("bookIds", listGroupClassifyParam.getBookIds());
        paramMap.put("proLabelId",listGroupClassifyParam.getProLabelId());
        paramMap.put("depLabelId",listGroupClassifyParam.getDepLabelId());
        paramMap.put("purLabelId",listGroupClassifyParam.getPurLabelId());
        PageParam pageParam = new PageParam(listGroupClassifyParam.getCurrentPage(), listGroupClassifyParam.getNumPerPage());
        PageBeanNew<BookGroupClassifyVO> pageBeanNew = bookGroupClassifyDao.listPageNew(pageParam, paramMap, "listGroupClassifyByAdviser");
        if (pageBeanNew == null) {
            return new PageBeanNew<>(listGroupClassifyParam.getCurrentPage(), listGroupClassifyParam.getNumPerPage(), new ArrayList<>());
        }
        //遍历填充标签
        List<BookGroupClassifyVO> bookGroupClassifyVOS = pageBeanNew.getRecordList();
        if (!ListUtils.isEmpty(bookGroupClassifyVOS)) {
            List<Long> labelIds = new ArrayList<>();
            List<Long> classifyIds = new ArrayList<>();
            for (BookGroupClassifyVO bookGroupClassifyVO : bookGroupClassifyVOS) {
                classifyIds.add(bookGroupClassifyVO.getClassifyId());
                if (bookGroupClassifyVO.getProLabelId() != null) {
                    labelIds.add(bookGroupClassifyVO.getProLabelId());
                }
                if (bookGroupClassifyVO.getPurLabelId() != null) {
                    labelIds.add(bookGroupClassifyVO.getPurLabelId());
                }
                if (bookGroupClassifyVO.getDepLabelId() != null) {
                    labelIds.add(bookGroupClassifyVO.getDepLabelId());
                }
            }
            Map<Long, Integer> activeCountMap = wechatGroupConsr.get7DayActiveUserCountByClassify(classifyIds);
            Map<Long, String> labelMap = new HashMap<>();
            if (!ListUtils.isEmpty(labelIds)) {
                labelMap = ResponseHandleUtil.parseMap(labelService.getLabelName(labelIds), Long.class, String.class);
            }
            for (BookGroupClassifyVO bookGroupClassifyVO : bookGroupClassifyVOS) {
                if (!MapUtils.isEmpty(labelMap)) {
                    Long proLabelId = bookGroupClassifyVO.getProLabelId();
                    Long purLabelId = bookGroupClassifyVO.getPurLabelId();
                    Long depLabelId = bookGroupClassifyVO.getDepLabelId();
                    if (proLabelId != null) {
                        bookGroupClassifyVO.setProLabelName(labelMap.get(proLabelId));
                    }
                    if (purLabelId != null) {
                        bookGroupClassifyVO.setPurLabelName(labelMap.get(purLabelId));
                    }
                    if (depLabelId != null) {
                        bookGroupClassifyVO.setDepLabelName(labelMap.get(depLabelId));
                    }
                }
                //最近7天活跃人数
                Integer count = activeCountMap.get(bookGroupClassifyVO.getClassifyId());
                if (count == null) {
                    bookGroupClassifyVO.setWeekActiveNumber(0);
                } else {
                    bookGroupClassifyVO.setWeekActiveNumber(count);
                }
            }
        }
        return pageBeanNew;
    }

    @Override
    @ParamLog("获取社群码统计数据（分类数，群总人数，群数量）")
    public Map<Long, BookGroupStatisticDTO> getBookGroupStatistic(List<Long> bookGroupIds) {
        return bookGroupClassifyDao.getBookGroupStatistic(bookGroupIds);
    }

    @Override
    @ParamLog("获取单个群统计")
    public PageBeanNew<BookGroupQrcodeStatisticVO> listBookGroupQrcodeStatistic(ListBookGroupQrcodeParamVO listBookGroupQrcodeParamVO, Long adviserId) {
        PageParam pageParam = new PageParam(listBookGroupQrcodeParamVO.getCurrentPage(), listBookGroupQrcodeParamVO.getNumPerPage());
        Map<String, Object> paramMap = new HashMap<>();
        if (!ListUtils.isEmpty(listBookGroupQrcodeParamVO.getClassifyIds())) {
            paramMap.put("classifyIds", listBookGroupQrcodeParamVO.getClassifyIds());
        }
        paramMap.put("bookGroupId", listBookGroupQrcodeParamVO.getBookGroupId());
        PageBeanNew<BookGroupQrcodeStatisticVO> pageBeanNew = bookGroupClassifyDao.listPageNew(pageParam, paramMap, "listBookGroupQrcodeStatistic");
        if (pageBeanNew == null || pageBeanNew.getRecordList() == null) {
            return new PageBeanNew<>(pageBeanNew.getCurrentPage(), pageBeanNew.getNumPerPage(), new ArrayList<>());
        }
        //设置累计进群人数与今日进群人数
        setJoinUserNumberTotalAndToday(pageBeanNew.getRecordList());
        //设置活跃人数与总发言数
        setActiveNumberAndChatCount(pageBeanNew.getRecordList(), listBookGroupQrcodeParamVO.getBookGroupId());
        //设置收益
        setIncome(pageBeanNew.getRecordList(), adviserId);
        //设置购买次数与用户数
        setBuyUserNumberAndBuyCount(pageBeanNew.getRecordList());
        return pageBeanNew;
    }


    @Override
    @ParamLog("单个群统计导出")
    public void bookGroupQrcodeStatisticExport(List<Long> classifyIds, Long bookGroupId, Long adviserId) {
        ThreadPoolUtils.EXPORT_THREAD_POOL.execute(() -> {
            try {
                BookGroupDTO bookGroupInfo = bookGroupBiz.getBookGroupInfo(bookGroupId);
                if (bookGroupInfo == null) {
                    return;
                }
                Date sendDate = new Date();
                List<BookGroupQrcodeStatisticVO> groupQrcodeStatistics = bookGroupClassifyDao.listBookGroupQrcodeStatistic(classifyIds, bookGroupId);
                if (ListUtils.isEmpty(groupQrcodeStatistics)) {
                    return;
                }
                //设置累计进群人数与今日进群人数
                setJoinUserNumberTotalAndToday(groupQrcodeStatistics);
                //设置活跃人数与总发言数
                setActiveNumberAndChatCount(groupQrcodeStatistics, bookGroupId);
                //设置收益
                setIncome(groupQrcodeStatistics, adviserId);
                //设置购买次数与用户数
                setBuyUserNumberAndBuyCount(groupQrcodeStatistics);
                //导出数据
                exportData(groupQrcodeStatistics, sendDate, adviserId, bookGroupInfo.getGroupQrcodeName());
            } catch (Exception e) {
                LOGGER.error("导出失败classifyIds:" + classifyIds + "bookGroupId" + bookGroupId + "adviserId" + adviserId);
            }
        });
    }

    @Override
    public StatisticVO getStatistic4Adviser(Long adviserId) {
        return bookGroupClassifyDao.getStatistic4Adviser(adviserId);
    }

    @Override
    public Map<String, GroupQrcodeBaseDTO> listGroupQrcodeBaseInfo(List<String> weixinGroupIds) {
        if (ListUtils.isEmpty(weixinGroupIds)) {
            return null;
        }
        return bookGroupClassifyDao.listGroupQrcodeBaseInfo(weixinGroupIds);
    }

    @Override
    @ParamLog("获取商品关联群数量与人数")
    public ProAssocGroupAndUserNumberDTO getProAssocGroupAndUserNumber(Long productId) {
//        //获取商品关联的分类
//        List<Long> classifyIds = bookKeywordBiz.getAssocClassifyIds(productId);
        ProAssocGroupAndUserNumberDTO proAssocGroupAndUserNumberDTO = bookGroupClassifyDao.getProAssocGroupAndUserNumber(productId);
        return proAssocGroupAndUserNumberDTO;
    }

    @ParamLog(value = "设置购买用户数与购买次数", isAfterReturn = false, isBefore = false)
    private void setBuyUserNumberAndBuyCount(List<BookGroupQrcodeStatisticVO> groupQrcodeStatistics) {
        if (ListUtils.isEmpty(groupQrcodeStatistics)) {
            return;
        }
        List<Long> groupQrcodeIds = new ArrayList<>();
        for (BookGroupQrcodeStatisticVO bookGroupQrcodeStatisticVO : groupQrcodeStatistics) {
            if (bookGroupQrcodeStatisticVO.getGroupQrcodeId() != null) {
                groupQrcodeIds.add(bookGroupQrcodeStatisticVO.getGroupQrcodeId());
            }
        }
        Map<Long, QrGroupBuyDetailDto> buyMap = tradeConsr.getQrGroupSaleDetail(groupQrcodeIds);
        for (BookGroupQrcodeStatisticVO bookGroupQrcodeStatisticVO : groupQrcodeStatistics) {
            if (buyMap != null) {
                QrGroupBuyDetailDto qrGroupBuyDetailDto = buyMap.get(bookGroupQrcodeStatisticVO.getGroupQrcodeId());
                bookGroupQrcodeStatisticVO.setBuyCount(qrGroupBuyDetailDto == null ? 0L : qrGroupBuyDetailDto.getBuyCount());
                bookGroupQrcodeStatisticVO.setBuyUserNumber(qrGroupBuyDetailDto == null ? 0L : qrGroupBuyDetailDto.getPayPersonCount());
            } else {
                bookGroupQrcodeStatisticVO.setBuyCount(0L);
                bookGroupQrcodeStatisticVO.setBuyUserNumber(0L);
            }
        }


    }

    @ParamLog(value = "导出数据")
    private void exportData(List<BookGroupQrcodeStatisticVO> groupQrcodeStatistics, Date sendDate, Long adviserId, String bookGroupName) {
        if (ListUtils.isEmpty(groupQrcodeStatistics)) {
            return;
        }
        List<Object[]> dataList = new ArrayList<Object[]>();
        for (int i = 0, size = groupQrcodeStatistics.size(); i < size; i++) {
            BookGroupQrcodeStatisticVO bookGroupQrcodeStatisticVO = groupQrcodeStatistics.get(i);
            Object[] obj = new Object[11];
            obj[0] = i + 1;
            obj[1] = bookGroupQrcodeStatisticVO.getGroupName();
            obj[2] = bookGroupQrcodeStatisticVO.getClassify();
            obj[3] = bookGroupQrcodeStatisticVO.getGroupUserNumber();
            obj[4] = bookGroupQrcodeStatisticVO.getJoinUserNumberToday();
            obj[5] = bookGroupQrcodeStatisticVO.getJoinUserNumberTotal();
            obj[6] = bookGroupQrcodeStatisticVO.getActiveUserCount();
            obj[7] = bookGroupQrcodeStatisticVO.getChatCount();
            obj[8] = bookGroupQrcodeStatisticVO.getBuyCount();
            obj[9] = bookGroupQrcodeStatisticVO.getBuyUserNumber();
            obj[10] = bookGroupQrcodeStatisticVO.getIncome();
            dataList.add(obj);
        }
        String[] rowsName = {"序号", "群名称", "群分类", "当前群总人数", "今日进群人数", "累计进群人数", "活跃人数",
                "总发言数", "购买次数", "购买人数", "收益"};
        String fileName = bookGroupName + "单个群统计-" + DateUtils.getStrFormTime("yyyyMMdd", new Date());
        String fileUrl = exportConsr.exportExcel(fileName, rowsName, dataList);
        String letterType = "pcloud_book_download";
        String content = String.format("{\"commitTime\":\"%s\",\"type\":\"%s\"}", DateUtils.formatDate(sendDate), fileName);
        messageConsr.sendLetter(adviserId, adviserId, content, SystemCode.adviser.code, letterType, fileUrl, fileName, NotifyOriginTypeEnum.BOOK_GROUP.value, null);
    }

    @ParamLog(value = "设置收益", isAfterReturn = false, isBefore = false)
    private void setIncome(List<BookGroupQrcodeStatisticVO> groupQrcodeStatistics, Long adviserId) {
        if (ListUtils.isEmpty(groupQrcodeStatistics)) {
            return;
        }
        List<Long> groupQrcodeIds = new ArrayList<>();
        for (BookGroupQrcodeStatisticVO bookGroupQrcodeStatisticVO : groupQrcodeStatistics) {
            if (bookGroupQrcodeStatisticVO.getGroupQrcodeId() != null) {
                groupQrcodeIds.add(bookGroupQrcodeStatisticVO.getGroupQrcodeId());
            }
        }
        Map<Long, BigDecimal> wxGroupQrcodeIncomeMap = settlementConsr.getWXGroupQrcodeIncomeByAdviser(groupQrcodeIds, adviserId);
        for (BookGroupQrcodeStatisticVO bookGroupQrcodeStatisticVO : groupQrcodeStatistics) {
            if (wxGroupQrcodeIncomeMap != null) {
                bookGroupQrcodeStatisticVO.setIncome(wxGroupQrcodeIncomeMap.get(bookGroupQrcodeStatisticVO.getGroupQrcodeId()) == null ? new BigDecimal(0) : wxGroupQrcodeIncomeMap.get(bookGroupQrcodeStatisticVO.getGroupQrcodeId()));
            } else {
                bookGroupQrcodeStatisticVO.setIncome(new BigDecimal(0));
            }
        }
    }

    @ParamLog(value = "设置活跃人数与总发言数", isAfterReturn = false, isBefore = false)
    private void setActiveNumberAndChatCount(List<BookGroupQrcodeStatisticVO> groupQrcodeStatistics, Long bookGroupId) {
        if (ListUtils.isEmpty(groupQrcodeStatistics)) {
            return;
        }
        List<Long> groupQrcodeIds = new ArrayList<>();
        for (BookGroupQrcodeStatisticVO bookGroupQrcodeStatisticVO : groupQrcodeStatistics) {
            if (bookGroupQrcodeStatisticVO.getGroupQrcodeId() != null) {
                groupQrcodeIds.add(bookGroupQrcodeStatisticVO.getGroupQrcodeId());
            }
        }
        Map<Long, GroupChatCountDTO> groupChatCountMap = wechatGroupConsr.getChatCountByGroup(groupQrcodeIds, bookGroupId);
        for (BookGroupQrcodeStatisticVO bookGroupQrcodeStatisticVO : groupQrcodeStatistics) {
            if (groupChatCountMap != null) {
                GroupChatCountDTO groupChatCountDTO = groupChatCountMap.get(bookGroupQrcodeStatisticVO.getGroupQrcodeId());
                bookGroupQrcodeStatisticVO.setChatCount(groupChatCountDTO == null ? 0 : groupChatCountDTO.getChatCount());
                bookGroupQrcodeStatisticVO.setActiveUserCount(groupChatCountDTO == null ? 0 : groupChatCountDTO.getActiveUserCount());
            } else {
                bookGroupQrcodeStatisticVO.setChatCount(0);
                bookGroupQrcodeStatisticVO.setActiveUserCount(0);
            }
        }
    }


    @ParamLog(value = "设置累计进群人数与今日进群人数", isAfterReturn = false, isBefore = false)
    private void setJoinUserNumberTotalAndToday(List<BookGroupQrcodeStatisticVO> groupQrcodeStatistics) {
        if (ListUtils.isEmpty(groupQrcodeStatistics)) {
            return;
        }
        List<String> weixinGroupIds = new ArrayList<>();
        for (BookGroupQrcodeStatisticVO bookGroupQrcodeStatisticVO : groupQrcodeStatistics) {
            if (!StringUtil.isEmpty(bookGroupQrcodeStatisticVO.getWeixinGroupId())) {
                weixinGroupIds.add(bookGroupQrcodeStatisticVO.getWeixinGroupId());
            }
        }
        Map<String, GroupMemberStatisDTO> groupMemberStatisMap = wechatGroupConsr.listGroupMemberStatisInfo(weixinGroupIds);
        for (BookGroupQrcodeStatisticVO bookGroupQrcodeStatisticVO : groupQrcodeStatistics) {
            if (groupMemberStatisMap != null) {
                GroupMemberStatisDTO groupMemberStatisDTO = groupMemberStatisMap.get(bookGroupQrcodeStatisticVO.getWeixinGroupId());
                bookGroupQrcodeStatisticVO.setJoinUserNumberTotal(groupMemberStatisDTO == null ? 0 : groupMemberStatisDTO.getJoinCount());
                bookGroupQrcodeStatisticVO.setJoinUserNumberToday(groupMemberStatisDTO == null ? 0 : groupMemberStatisDTO.getJoinCountToday());
            } else {
                bookGroupQrcodeStatisticVO.setJoinUserNumberTotal(0);
                bookGroupQrcodeStatisticVO.setJoinUserNumberToday(0);
            }
        }
    }


    @ParamLog("设置用户头像")
    private void setUserHeader(List<ListClassify4WechatVO> listClassify4WechatVOS) {
        if (ListUtils.isEmpty(listClassify4WechatVOS)) {
            return;
        }
        List<WechatUserRobotDto> wechatUserRand = readerConsr.selectRobotsRandom(listClassify4WechatVOS.size() * 9);
        if (ListUtils.isEmpty(wechatUserRand)) {
            return;
        }
        for (int i = 0; i < listClassify4WechatVOS.size(); i++) {
            ListClassify4WechatVO listClassify4WechatVO = listClassify4WechatVOS.get(i);
            List<WechatUserRobotDto> wechatUsers;
            if (wechatUserRand.size() >= (i + 1) * 9) {
                wechatUsers = wechatUserRand.subList(i * 9, (i + 1) * 9);
            } else {
                wechatUsers = wechatUserRand.subList(wechatUserRand.size() - 9 > 0 ? 0 : wechatUserRand.size() - 9, wechatUserRand.size());
            }
            List<String> headUrls = wechatUsers.stream().map(a -> a.getWechatUserHeadUrl()).collect(Collectors.toList());
            listClassify4WechatVO.setHeadUrl(headUrls);
        }
    }

    /**
     * @Author:lili
     * @Desr:设置分类下当前使用二维码
     * @Date:2019/4/29 14:37
     */
    private void setGroupQrcodeInfo(List<ListClassify4WechatVO> listClassify4Wechats) {
        if (ListUtils.isEmpty(listClassify4Wechats)) {
            return;
        }
        List<Long> groupQrcodeIds = new ArrayList<>();
        for (ListClassify4WechatVO listClassify4WechatVO : listClassify4Wechats) {
            groupQrcodeIds.add(listClassify4WechatVO.getGroupQrcodeId());
        }
        //根据二维码获取二维码基本信息
        Map<Long, GroupQrcodeInfoDTO> groupQrcodeMap = groupQrcodeBiz.listQrcodeInfoByIds(groupQrcodeIds);
        if (MapUtils.isEmpty(groupQrcodeMap)) {
            return;
        }
        for (ListClassify4WechatVO listClassify4WechatVO : listClassify4Wechats) {
            GroupQrcodeInfoDTO groupQrcodeInfoDTO = groupQrcodeMap.get(listClassify4WechatVO.getGroupQrcodeId());
            if (groupQrcodeInfoDTO != null) {
                listClassify4WechatVO.setUserNumber(groupQrcodeInfoDTO.getUserNumber());
                listClassify4WechatVO.setGroupSeq(groupQrcodeInfoDTO.getGroupSeq());
                listClassify4WechatVO.setHeadUrl(JSONObject.parseArray(groupQrcodeInfoDTO.getQrcodeHeadUrl(), String.class));
            }
        }
    }

    /**
     * 获取社群书分类列表(编辑)
     * @param adviserId
     * @param bookGroupClassify
     * @return
     */
    @Override
    @ParamLog("获取社群书分类列表(编辑)")
    public PageBeanNew<ClassifyDTO> listSimpleBookGroupClassify4Adviser(Long adviserId, BookGroupClassify bookGroupClassify,PageParam pageParam) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("adviserId",adviserId);
        if(!StringUtil.isEmpty(bookGroupClassify.getClassify())){
            paramMap.put("classify",bookGroupClassify.getClassify());
        }
        if(!ListUtils.isEmpty(bookGroupClassify.getBookGroupIds())){
            paramMap.put("bookGroupIds",bookGroupClassify.getBookGroupIds());
        }
        return bookGroupClassifyDao.listPageNew(pageParam,paramMap,"listSimpleBookGroupClassify4Adviser");
    }

    @Override
    @ParamLog("获取编辑的分类")
    public PageBeanNew<AdviserClassifyVO> listAdviserClassify(Long adviserId, AdviserClassifyParam adviserClassifyParam) {
        PageParam pageParam = new PageParam(adviserClassifyParam.getCurrentPage(), adviserClassifyParam.getNumPerPage());
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("adviserId",adviserId);
        paramMap.put("classify",adviserClassifyParam.getClassify());
        PageBeanNew<AdviserClassifyVO> pageBeanNew = bookGroupClassifyDao.listPageNew(pageParam, paramMap, "listAdviserClassify");
        if(pageBeanNew == null){
            return new PageBeanNew<>(adviserClassifyParam.getCurrentPage(), adviserClassifyParam.getNumPerPage(), new ArrayList<>());
        }
        return pageBeanNew;
    }

    @Override
    public Map<Long, BookClassifyDTO> getGroupClassifyCount(List<Long> bookIds) {
        if (!ListUtils.isEmpty(bookIds)){
            return bookGroupClassifyDao.getGroupClassifyCount(bookIds);
        }else {
            return new HashMap<>();
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("更新是否开启微学习报告")
    @Override
    public void updateHasOpenLearningReport(Long classifyId, Boolean hasOpenLearningReport, Long partyId) {
        bookGroupClassifyDao.updateHasOpenLearningReport(classifyId,hasOpenLearningReport,partyId);
    }

    @ParamLog("获取群分类学习报告相关列表")
    @Override
    public PageBeanNew<ClassifyLearningReportDto> listClassifyForLearningReport(Integer currentPage, Integer numPerPage, String keyword, Long partyId) {
        PageParam pageParam = new PageParam(currentPage, numPerPage);
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("keyword", keyword);
        paramMap.put("partyId", partyId);
        PageBeanNew<ClassifyLearningReportDto> pageBeanNew = bookGroupClassifyDao.listPageNew(pageParam, paramMap, "listClassifyForLearningReport");
        if (pageBeanNew == null) {
            return new PageBeanNew<>(currentPage, numPerPage, new ArrayList<>());
        }
        //遍历填充标签
        List<ClassifyLearningReportDto> list = pageBeanNew.getRecordList();
        if (!ListUtils.isEmpty(list)) {
            List<Long> labelIds = new ArrayList<>();
            List<Long> classifyIds = new ArrayList<>();
            for (ClassifyLearningReportDto classifyLearningReportDto : list) {
                classifyIds.add(classifyLearningReportDto.getClassifyId());
                if (classifyLearningReportDto.getProLabelId() != null) {
                    labelIds.add(classifyLearningReportDto.getProLabelId());
                }
                if (classifyLearningReportDto.getPurLabelId() != null) {
                    labelIds.add(classifyLearningReportDto.getPurLabelId());
                }
                if (classifyLearningReportDto.getDepLabelId() != null) {
                    labelIds.add(classifyLearningReportDto.getDepLabelId());
                }
            }
            Map<Long, Integer> browseCountMap = new HashMap<>();
            Map<Long, Integer> touchCountMap = new HashMap<>();
            if (!ListUtils.isEmpty(classifyIds)) {
                List<ClassifyLearningCountDto> browseCountList = learningReportBrowseRecordDao.getCountGroupByClassifyId(classifyIds);
                List<ClassifyLearningCountDto> touchCountList = learningReportTouchRecordDao.getCountGroupByClassifyId(classifyIds);
                for (ClassifyLearningCountDto classifyLearningCountDto:browseCountList){
                    browseCountMap.put(classifyLearningCountDto.getClassifyId(),classifyLearningCountDto.getCount());
                }
                for (ClassifyLearningCountDto classifyLearningCountDto:touchCountList){
                    touchCountMap.put(classifyLearningCountDto.getClassifyId(),classifyLearningCountDto.getCount());
                }
            }
            Map<Long, String> labelMap = new HashMap<>();
            if (!ListUtils.isEmpty(labelIds)) {
                labelMap = ResponseHandleUtil.parseMap(labelService.getLabelName(labelIds), Long.class, String.class);
            }
            for (ClassifyLearningReportDto classifyLearningReportDto : list) {
                if (!MapUtils.isEmpty(labelMap)) {
                    Long proLabelId = classifyLearningReportDto.getProLabelId();
                    if (proLabelId != null) {
                        classifyLearningReportDto.setProLabelName(labelMap.get(proLabelId));
                    }
                    Long purLabelId = classifyLearningReportDto.getPurLabelId();
                    if (purLabelId != null) {
                        classifyLearningReportDto.setPurLabelName(labelMap.get(purLabelId));
                    }
                    Long depLabelId = classifyLearningReportDto.getDepLabelId();
                    if (depLabelId != null) {
                        classifyLearningReportDto.setDepLabelName(labelMap.get(depLabelId));
                    }
                }
                Integer browseCount = browseCountMap.get(classifyLearningReportDto.getClassifyId());
                if (browseCount == null) {
                    browseCount = 0;
                }
                Integer touchCount = touchCountMap.get(classifyLearningReportDto.getClassifyId());
                if (touchCount == null) {
                    touchCount = 0;
                }
                classifyLearningReportDto.setLearningReportBrowseCount(browseCount);
                classifyLearningReportDto.setLearningReportTouchCount(touchCount);
            }
        }
        return pageBeanNew;

    }


    @ParamLog("拖动排序")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void dragSortClassify(List<Long> classifyIds) {
        if (ListUtils.isEmpty(classifyIds)) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数为空！");
        }
        bookGroupClassifyDao.dragSortClassify(classifyIds);
    }

    @Override
    public BigDecimal getPayPrice(Long qrcodeId, String wxId) {
        return joinGroupCipherDao.getPayPrice(wxId, qrcodeId);
    }

    @Override
    public void clickClassify(Long wechatUserId, Long bookGroupId, Long classifyId) {
        bookGroupClassifyDao.addClickClassify(wechatUserId,bookGroupId,classifyId);
    }


    @Override
    public List<ListClassifyVO> getClassifyIngoreDelete(Long bookGroupId) {
        List<ListClassifyVO> classifyVOS = bookGroupClassifyDao.getClassifyIngoreDelete(bookGroupId);
        if (ListUtils.isEmpty(classifyVOS)){
            return new ArrayList<>();
        }
        return classifyVOS;
    }


}
