package com.pcloud.book.group.set;

import com.pcloud.analysisengine.browse.dto.GroupBrowseStatisticVO;
import com.pcloud.appcenter.app.dto.AppDto;
import com.pcloud.appcenter.assist.dto.AssistTempletDTO;
import com.pcloud.appcenter.base.dto.AppPriceCacheDTO;
import com.pcloud.appcenter.cache.service.AppPriceCacheService;
import com.pcloud.book.consumer.analysisengine.BrowseRecordConsr;
import com.pcloud.book.consumer.app.AppConsr;
import com.pcloud.book.consumer.app.AssistTempletConsr;
import com.pcloud.book.consumer.common.ExportConsr;
import com.pcloud.book.consumer.label.LabelConsr;
import com.pcloud.book.consumer.resource.ProductConsr;
import com.pcloud.book.consumer.trade.TradeConsr;
import com.pcloud.book.consumer.user.AdviserConsr;
import com.pcloud.book.consumer.user.AgentConsr;
import com.pcloud.book.consumer.user.ChannelConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.dao.BookGroupCipherUserDao;
import com.pcloud.book.group.dao.BookGroupClassifyDao;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dto.AgentStatisticsInfoDTO;
import com.pcloud.book.group.dto.BookGroupStatisticDTO;
import com.pcloud.book.group.dto.CountAndTimeDTO;
import com.pcloud.book.group.dto.GroupTopicDTO;
import com.pcloud.book.group.entity.BookGroupServe;
import com.pcloud.book.group.vo.BookGroupAnalysisVO;
import com.pcloud.book.group.vo.UserBookInfoItemVO;
import com.pcloud.book.group.vo.UserBookInfoVO;
import com.pcloud.book.keywords.dao.BookKeywordDao;
import com.pcloud.book.keywords.dto.KeywordResourceDTO;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.book.keywords.vo.ListKeywordVO;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.constant.MQTopicProducer;
import com.pcloud.common.enums.AppTypeEnum;
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.GroupIncomeSearchDto;
import com.pcloud.facade.tradecenter.dto.GroupMoneyDto;
import com.pcloud.facade.tradecenter.dto.ProductSaleDetailDto;
import com.pcloud.resourcecenter.product.dto.ProductDto;
import com.pcloud.resourcecenter.product.dto.SpecificationDto;
import com.pcloud.usercenter.party.adviser.dto.AdviserBaseInfoDto;
import com.pcloud.wechatgroup.group.dto.GroupUserCountDTO;
import com.pcloud.wechatgroup.group.dto.GroupUserDTO;

import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

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

/**
 * @描述：
 * @作者：zhuyajie
 * @创建时间：16:26 2019/7/16
 * @版本：1.0
 */
@Component("groupSet")
public class GroupSet {

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

    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private AssistTempletConsr assistTempletConsr;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private ChannelConsr channelConsr;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private BookGroupClassifyDao bookGroupClassifyDao;
    @Autowired
    private BookKeywordDao bookKeywordDao;
    @Autowired
    private ExportConsr exportConsr;
    @Autowired
    private TradeConsr tradeConsr;
    @Autowired
    private BookGroupCipherUserDao bookGroupCipherUserDao;
    @Autowired
    private BrowseRecordConsr browseRecordConsr;
    @Autowired
    private AgentConsr agentConsr;
    @Autowired
    private BookGroupDao bookGroupDao;
    @Autowired
    private LabelConsr labelConsr;
    @Autowired
    private AppConsr appConsr;
    @Autowired
    private ProductConsr productConsr;
    @Autowired
    private AppPriceCacheService appPriceCacheService;

    /**
     * 群分类删除topic
     * @param classifyId
     */
    public void sendGroupClassifyDeleteTopic(Long classifyId) {
        LOGGER.info("【社群书】发送群分类删除topic,<START>classifyId:{}", classifyId);
        GroupTopicDTO groupTopicDTO = new GroupTopicDTO();
        groupTopicDTO.setClassifyId(classifyId);
        try {
            amqpTemplate.convertAndSend(MQTopicProducer.EXCHAGE, MQTopicProducer.GROUP_CLASSIFY_DELETE, groupTopicDTO);
        } catch (Exception e) {
            LOGGER.error("【社群书】发送群分类删除topic,<ERROR>", e);
        }
    }

    /**
     * 设置书刊分类名称
     * @param recordList
     */
    @ParamLog("设置书刊分类名称")
    public void setTempletName(List<BookGroupAnalysisVO> recordList) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        List<Long> templetIds = new ArrayList<>();
        recordList.forEach(bookGroupAnalysisVO -> {
            if (Objects.nonNull(bookGroupAnalysisVO.getTempletId())) {
                templetIds.add(bookGroupAnalysisVO.getTempletId());
            }
            if (Objects.nonNull(bookGroupAnalysisVO.getSecondTempletId())) {
                templetIds.add(bookGroupAnalysisVO.getSecondTempletId());
            }
        });
        final Map<Long, AssistTempletDTO> assistTempletIds = assistTempletConsr.mapByIds(templetIds);
        if (MapUtils.isEmpty(assistTempletIds)) {
            return;
        }
        recordList.forEach(analysisVO -> {
            Long secondTempletId = analysisVO.getSecondTempletId();
            Long templetId = analysisVO.getTempletId();
            if (Objects.nonNull(secondTempletId)) {
                AssistTempletDTO templetDTO = assistTempletIds.get(secondTempletId);
                analysisVO.setSecondTempletName(Optional.ofNullable(templetDTO).map(AssistTempletDTO::getTempletName).orElse(null));
            }
            if (Objects.nonNull(templetId)) {
                AssistTempletDTO templetDTO = assistTempletIds.get(templetId);
                analysisVO.setTempletName(Optional.ofNullable(templetDTO).map(AssistTempletDTO::getTempletName).orElse(null));
            }
        });
    }


    /**
     * 设置出版运营编辑名称
     * @param recordList
     */
    @ParamLog("设置出版运营编辑名称")
    public void setPartyInfo(List<BookGroupAnalysisVO> recordList) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        List<Long> adviserIds = recordList.stream().filter(s -> s.getAdviserId() != null).map(BookGroupAnalysisVO::getAdviserId).distinct().collect(Collectors.toList());
        List<Long> channelIds = recordList.stream().filter(s -> s.getChannelId() != null).map(BookGroupAnalysisVO::getChannelId).distinct().collect(Collectors.toList());
        Map<Long, AdviserBaseInfoDto> adviserBaseInfoDtoMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(adviserIds);
        Map<Long, String> channelNameMap = channelConsr.getNamesByIdList(channelIds);
        recordList.forEach(bookGroupAnalysisVO -> {
            if (!MapUtils.isEmpty(adviserBaseInfoDtoMap) && adviserBaseInfoDtoMap.containsKey(bookGroupAnalysisVO.getAdviserId())) {
                AdviserBaseInfoDto adviserBaseInfoDto = adviserBaseInfoDtoMap.get(bookGroupAnalysisVO.getAdviserId());
                if (null != adviserBaseInfoDto) {
                    bookGroupAnalysisVO.setAdviserName(adviserBaseInfoDto.getPartyName());
                    bookGroupAnalysisVO.setAgentId(adviserBaseInfoDto.getAgentId());
                    bookGroupAnalysisVO.setAgentName(adviserBaseInfoDto.getAgentName());
                }
            }
            if (!MapUtils.isEmpty(channelNameMap) && channelNameMap.containsKey(bookGroupAnalysisVO.getChannelId())) {
                bookGroupAnalysisVO.setChannelName(channelNameMap.get(bookGroupAnalysisVO.getChannelId()));
            }
        });
    }

    /**
     * 设置社群码扫码量
     * @param recordList
     * @param monthDate
     */
    @ParamLog("设置社群码扫码量")
    public void setGroupScanCount(List<BookGroupAnalysisVO> recordList, String monthDate) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        List<Long> bookGroupIds = recordList.stream().filter(s -> s.getBookGroupId() != null).map(BookGroupAnalysisVO::getBookGroupId).distinct().collect(Collectors.toList());
        Map<Long, GroupUserCountDTO> userCountDTOMap = wechatGroupConsr.getScanCountByGroup(bookGroupIds, monthDate);
        if (MapUtils.isEmpty(userCountDTOMap)) {
            return;
        }
        recordList.forEach(bookGroupAnalysisVO -> {
            GroupUserCountDTO groupUserCountDTO = userCountDTOMap.get(bookGroupAnalysisVO.getBookGroupId());
            if (null != groupUserCountDTO) {
                bookGroupAnalysisVO.setScanCount(groupUserCountDTO.getCount());
                bookGroupAnalysisVO.setScanUserCount(groupUserCountDTO.getUserCount());
            }
        });
    }

    /**
     * 设置微信群数据（分类数，群数，群人数，累计进群人数，好友数，资源数）
     * @param recordList
     * @param monthDate
     */
    public void setGroupStatistic(List<BookGroupAnalysisVO> recordList, String monthDate) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        List<Long> bookGroupIds = recordList.stream().filter(s -> s.getBookGroupId() != null).map(BookGroupAnalysisVO::getBookGroupId).distinct().collect(Collectors.toList());
        if (ListUtils.isEmpty(bookGroupIds)) {
            return;
        }
        String startTime = null;
        String endTime = null;
        if (!StringUtil.isEmpty(monthDate)) {
            startTime = monthDate + "-01";
            endTime = DateUtils.formatDate(DateUtils.getMonthEnd(DateUtils.getDateByStr(startTime)), DateUtils.DATE_FORMAT_DATEONLY);
        }
        //分类数，群数，群人数
        Map<Long, BookGroupStatisticDTO> bookGroupStatisticDTOMap = bookGroupClassifyDao.getClassifyCountAbout(bookGroupIds);
        //社群码下资源数量（关键词及1v1配置资源）
        Map<Long, KeywordResourceDTO> keywordResourceDTOMap = bookKeywordDao.getBookGroupResourceCount(bookGroupIds);
        //累计进群人数-按月
        Map<Long, GroupUserCountDTO> userCountDTOMap = wechatGroupConsr.mapBookGroupJoinUserCount(bookGroupIds, monthDate);
        for (BookGroupAnalysisVO bookGroupAnalysisVO : recordList) {
            if (!MapUtils.isEmpty(bookGroupStatisticDTOMap)) {
                BookGroupStatisticDTO bookGroupStatisticDTO = bookGroupStatisticDTOMap.get(bookGroupAnalysisVO.getBookGroupId());
                if (null != bookGroupStatisticDTO) {
                    bookGroupAnalysisVO.setClassifyCount(bookGroupStatisticDTO.getClassifyCount());
                    bookGroupAnalysisVO.setGroupCount(bookGroupStatisticDTO.getGroupNumber());
                    bookGroupAnalysisVO.setUserNumber(bookGroupStatisticDTO.getUserNumber());
                }
            }
            if (!MapUtils.isEmpty(keywordResourceDTOMap)) {
                KeywordResourceDTO resourceDTO = keywordResourceDTOMap.get(bookGroupAnalysisVO.getBookGroupId());
                if (null != resourceDTO) {
                    bookGroupAnalysisVO.setResourceCount(resourceDTO.getCount());
                }
            }
            if (!MapUtils.isEmpty(userCountDTOMap)) {
                GroupUserCountDTO userCountDTO = userCountDTOMap.get(bookGroupAnalysisVO.getBookGroupId());
                bookGroupAnalysisVO.setJoinUserCount(null == userCountDTO ? 0 : userCountDTO.getUserCount());
            }
            //好友数量-按月
            Integer friendsCount = bookGroupCipherUserDao.getFriendsCountByBookGroupByTime(bookGroupAnalysisVO.getBookGroupId(), startTime, endTime);
            bookGroupAnalysisVO.setFriendsCount(friendsCount);
        }
    }

    /**
     * 设置资源数据(浏览量，读者量，销售额，支付率，客单价)
     * @param recordList
     * @param monthDate
     */
    public void setResourceStatistic(List<BookGroupAnalysisVO> recordList, String monthDate) {
        List<Long> bookGroupIds = recordList.stream().filter(s -> s.getBookGroupId() != null).map(BookGroupAnalysisVO::getBookGroupId).distinct().collect(Collectors.toList());
        if (ListUtils.isEmpty(bookGroupIds)) {
            return;
        }
        Map<Long, GroupBrowseStatisticVO> browseStatisticVOMap = browseRecordConsr.mapGroupBrowseStatistic(bookGroupIds,monthDate);
        Map<Long, ProductSaleDetailDto> saleDetailDtoMap = tradeConsr.getSaleInfo4Group(bookGroupIds, monthDate);
        for (BookGroupAnalysisVO bookGroupAnalysisVO : recordList) {
            Integer browserCount = 0;//读者量
            Long payCount = 0L;//购买人数
            //浏览量，读者量
            if (!MapUtils.isEmpty(browseStatisticVOMap)) {
                GroupBrowseStatisticVO statisticVO = browseStatisticVOMap.get(bookGroupAnalysisVO.getBookGroupId());
                bookGroupAnalysisVO.setBrowseCount(null == statisticVO ? 0 : statisticVO.getBrowseCount());
                browserCount = null == statisticVO ? 0 : statisticVO.getBrowserCount();
                bookGroupAnalysisVO.setBrowserCount(browserCount);
            }
            //销售额，客单价
            if (!MapUtils.isEmpty(saleDetailDtoMap)) {
                ProductSaleDetailDto saleDetailDto = saleDetailDtoMap.get(bookGroupAnalysisVO.getBookGroupId());
                payCount = (null == saleDetailDto || null == saleDetailDto.getPayCount()) ? 0L : saleDetailDto.getPayCount();
                //销售额
                BigDecimal saleMoney = (null == saleDetailDto || null == saleDetailDto.getSaleMoney()) ? BigDecimal.ZERO : BigDecimal.valueOf(saleDetailDto.getSaleMoney());
                //购买次数
                Long saleCount = (null == saleDetailDto || null == saleDetailDto.getSaleCount()) ? 0L : saleDetailDto.getSaleCount();
                BigDecimal avgSaleAmount = saleCount.equals(0L) ? BigDecimal.ZERO : new BigDecimal(saleMoney.doubleValue() / saleCount).
                        setScale(2, BigDecimal.ROUND_HALF_UP);
                bookGroupAnalysisVO.setSaleAmount(saleMoney);
                bookGroupAnalysisVO.setAvgSaleAmount(avgSaleAmount);
            }
            //支付率(支付人数/读者量)
            bookGroupAnalysisVO.setPayRate(browserCount.equals(0) ? BigDecimal.ZERO : new BigDecimal(payCount.doubleValue() / browserCount).
                    setScale(4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100)));
        }
    }

    /**
     * 社群书分析-导出表格
     * @param list
     * @param fileName
     * @return
     */
    public String fillBookGroupExcel(List<BookGroupAnalysisVO> list, String fileName) {
        String[] rowsName = {"序号", "图书名称", "ISBN", "书刊分类", "创建时间", "出版社名称", "运营平台", "编辑名称", "是否基金书", "扫码次数", "扫码人数",
                "获取资源方式", "群分类数", "添加客服好友数", "微信群数", "累计进群人数", "资源数", "浏览量", "读者量", "支付率", "销售额", "客单价", "是否版权保护", "社群码"};
        List<Object[]> dataList = new ArrayList<>();
        Object[] objs;
        for (int i = 0; i < list.size(); i++) {
            BookGroupAnalysisVO analysisVO = list.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = analysisVO.getBookName();
            objs[2] = analysisVO.getIsbn();
            String templetName = "";
            if (!StringUtil.isEmpty(analysisVO.getTempletName())) {
                templetName = analysisVO.getTempletName();
                if (!StringUtil.isEmpty(analysisVO.getSecondTempletName())) {
                    templetName = templetName + "-" + analysisVO.getSecondTempletName();
                }
            } else if (!StringUtil.isEmpty(analysisVO.getSecondTempletName())) {
                templetName = analysisVO.getSecondTempletName();
            }
            objs[3] = templetName;
            objs[4] = DateUtils.formatDate(analysisVO.getCreateTime(), DateUtils.DATE_FORMAT_DATETIME);
            objs[5] = analysisVO.getAgentName();
            objs[6] = analysisVO.getChannelName();
            objs[7] = analysisVO.getAdviserName();
            objs[8] = analysisVO.getIsFundSupport() ? "是" : "否";
            objs[9] = analysisVO.getScanCount() == null ? 0 : analysisVO.getScanCount();
            objs[10] = analysisVO.getScanUserCount() == null ? 0 : analysisVO.getScanUserCount();
            objs[11] = analysisVO.getJoinGroupType() == 2 ? "1V1客服机器人" : "普通微信群";
            objs[12] = analysisVO.getClassifyCount() == null ? 0 : analysisVO.getClassifyCount();
            objs[13] = analysisVO.getFriendsCount() == null ? 0 : analysisVO.getFriendsCount();
            objs[14] = analysisVO.getGroupCount() == null ? 0 : analysisVO.getGroupCount();
            objs[15] = analysisVO.getJoinUserCount() == null ? 0 : analysisVO.getJoinUserCount();
            objs[16] = analysisVO.getResourceCount() == null ? 0 : analysisVO.getResourceCount();
            objs[17] = analysisVO.getBrowseCount() == null ? 0 : analysisVO.getBrowseCount();
            objs[18] = analysisVO.getBrowserCount() == null ? 0 : analysisVO.getBrowserCount();
            objs[19] = analysisVO.getPayRate() + "%";
            objs[20] = analysisVO.getSaleAmount();
            objs[21] = analysisVO.getAvgSaleAmount();
            objs[22] = analysisVO.getIsCopyright() ? "是" : "否";
            objs[23] = analysisVO.getGroupQrcodeUrl().replace("//oss", "//file");
            dataList.add(objs);
        }
        String fileUrl = exportConsr.exportExcel(fileName, rowsName, dataList);
        return fileUrl;
    }

    @ParamLog("填充空缺的时间")
    public void fillEmptyTime(List<CountAndTimeDTO> list, Integer timeType, String startTime, String endTime) {
        Date flag = DateUtils.getDateByStr(startTime);
        Date end = DateUtils.getDateByStr(endTime);
        List<String> times = list.stream().map(CountAndTimeDTO::getTime).collect(Collectors.toList());
        //按天
        if (timeType == 1) {
            while (flag.before(end)) {
                if (!times.contains(DateUtils.getStrFormTime("yyyy-MM-dd", flag))) {
                    CountAndTimeDTO countAndTimeDTO = new CountAndTimeDTO();
                    countAndTimeDTO.setTime(DateUtils.getStrFormTime("yyyy-MM-dd", flag));
                    countAndTimeDTO.setCount(0);
                    list.add(countAndTimeDTO);
                }
                flag = DateUtils.addDay(flag, 1);
            }
        }
        //按小时
        if (timeType == 2) {
            while (flag.before(end)) {
                String strForm = DateUtils.getStrFormTime("yyyy-MM-dd HH:mm:ss", flag);
                strForm = strForm.substring(0, 13);
                if (!times.contains(strForm)) {
                    CountAndTimeDTO countAndTimeDTO = new CountAndTimeDTO();
                    countAndTimeDTO.setTime(strForm);
                    countAndTimeDTO.setCount(0);
                    list.add(countAndTimeDTO);
                }
                flag = DateUtils.addHour(flag, 1);
            }
        }
    }

    public void setAgentStatisticsDetailInfo(List<AgentStatisticsInfoDTO> agentStatisticsInfoDTOS) {
        List<Long> agentIds = agentStatisticsInfoDTOS.stream().filter(s -> s.getAgentId() != null).map(AgentStatisticsInfoDTO::getAgentId).collect(Collectors.toList());
        Map<Long, String> agentNameMap = agentConsr.getNames(agentIds);
        //出版社定制小号数量
        Map<Long, Integer> agentRobotCountMap = wechatGroupConsr.mapSpecialAgentRobotCount(agentIds);
        //出版社关联小号发送消息数量
        Map<Long, List<String>> agentRobotParamMap = new HashMap<>();
        for(Long agId :agentIds) {
            List<String> robotWxids = bookGroupDao.getRobotWxidsByAgent(agId);
            agentRobotParamMap.put(agId, robotWxids);
        }
        Map<Long, Integer> agentRobotMsgCountMap = wechatGroupConsr.mapAgentMsgCountByRobotIdList(agentRobotParamMap);
        for(AgentStatisticsInfoDTO statisticsInfoDTO : agentStatisticsInfoDTOS) {
            Long statisticsAgentId = statisticsInfoDTO.getAgentId();
            //出版社名称
            if(!CollectionUtils.isEmpty(agentNameMap)) {
                statisticsInfoDTO.setAgentName(agentNameMap.get(statisticsAgentId) == null ? "" : agentNameMap.get(statisticsAgentId));
            } else {
                statisticsInfoDTO.setAgentName("");
            }
            //定制个人号数量
            if(!CollectionUtils.isEmpty(agentRobotCountMap)) {
                statisticsInfoDTO.setRobotCount(agentRobotCountMap.get(statisticsAgentId) == null ? 0 : agentRobotCountMap.get(statisticsAgentId));
            } else {
                statisticsInfoDTO.setRobotCount(0);
            }
            //出版社个人号已发消息数量
            if(!CollectionUtils.isEmpty(agentRobotMsgCountMap)) {
                statisticsInfoDTO.setSendMsgCount(agentRobotMsgCountMap.get(statisticsAgentId) == null ? 0 : agentRobotMsgCountMap.get(statisticsAgentId));
            } else {
                statisticsInfoDTO.setSendMsgCount(0);
            }
        }
    }


    /**
     * 填充个人号群发用户信息、扫码书刊信息
     * @param list
     */
    public void setUserBookInfo4SelfPush(List<UserBookInfoVO> list) {
        List<String> wxUserIds = list.stream().filter(s -> s.getWxUserId() != null).map(UserBookInfoVO::getWxUserId).distinct().collect(Collectors.toList());
        Map<String, GroupUserDTO> userDTOMap = wechatGroupConsr.mapWxUserInfoByWxIdList(wxUserIds);
        List<Long> labelIds = new ArrayList<>();
        for (UserBookInfoVO userBookInfoVO : list) {
            //用户信息
            if (!MapUtils.isEmpty(userDTOMap) && userDTOMap.containsKey(userBookInfoVO.getWxUserId())) {
                GroupUserDTO userDTO = userDTOMap.get(userBookInfoVO.getWxUserId());
                userBookInfoVO.setHeadPic(userDTO.getHeadPic());
                userBookInfoVO.setNickName(userDTO.getNickName());
                userBookInfoVO.setSex(userDTO.getSex());
            }
            //扫码书刊
            List<UserBookInfoItemVO> bookList = bookGroupCipherUserDao.getScanBookInfoByUser(userBookInfoVO.getWxUserId(), userBookInfoVO.getAltId());
            userBookInfoVO.setBookInfoItemVOS(bookList);
            List<Long> bookProLabelIds = bookList.stream().filter(s -> s.getProLabelId() != null).map(UserBookInfoItemVO::getProLabelId).distinct().collect(Collectors.toList());
            List<Long> bookDepLabelIds = bookList.stream().filter(s -> s.getDepLabelId() != null).map(UserBookInfoItemVO::getDepLabelId).distinct().collect(Collectors.toList());
            if (!ListUtils.isEmpty(bookProLabelIds)) {
                labelIds.addAll(bookProLabelIds);
            }
            if (!ListUtils.isEmpty(bookDepLabelIds)) {
                labelIds.addAll(bookDepLabelIds);
            }
        }
        //标签
        Map<Long, String> bookLabelMap = labelConsr.getLabelName(labelIds);
        if (!MapUtils.isEmpty(bookLabelMap)) {
            list.forEach(userBookInfoVO -> {
                for (UserBookInfoItemVO bookInfoItemVO : userBookInfoVO.getBookInfoItemVOS()) {
                    if (null != bookInfoItemVO.getProLabelId() && bookLabelMap.containsKey(bookInfoItemVO.getProLabelId())) {
                        bookInfoItemVO.setProLabelName(bookLabelMap.get(bookInfoItemVO.getProLabelId()));
                    }
                    if (null != bookInfoItemVO.getDepLabelId() && bookLabelMap.containsKey(bookInfoItemVO.getDepLabelId())) {
                        bookInfoItemVO.setDepLabelName(bookLabelMap.get(bookInfoItemVO.getDepLabelId()));
                    }
                }
            });
        }
    }

    /**
     * 填充关键词信息
     */
    public void setKeyWordStatistic(Long classifyId, Long bookGroupId, List<ListKeywordVO> listKeywordVOS) {
        if (ListUtils.isEmpty(listKeywordVOS)) {
            return;
        }
        List<Long> appIds = listKeywordVOS.stream().filter(s -> "APP".equalsIgnoreCase(s.getServeType())).map(ListKeywordVO::getServeId).collect(Collectors.toList());
        List<Long> productIds = listKeywordVOS.stream().filter(s -> "PRODUCT".equalsIgnoreCase(s.getServeType())).map(ListKeywordVO::getServeId).collect(Collectors.toList());
        //应用商品信息
        Map<Long, AppDto> appDtoMap = new HashMap<>();
        Map<Long, BigDecimal> appPriceMap = new HashMap<>();
        Map<Long, ProductDto> productDtoMap = new HashMap<>();
        Map<Long, Boolean> isSuperMap = new HashMap<>();
        //浏览量浏览时长
        Map<Long, GroupBrowseStatisticVO> appBrowseMap = new HashMap<>();
        Map<Long, GroupBrowseStatisticVO> productBrowseMap = new HashMap<>();
        //购买次数
        Map<Long, GroupMoneyDto> appSaleDetail4Group = new HashMap<>();
        Map<Long, GroupMoneyDto> productSaleDetail4Group = new HashMap<>();
        if (!ListUtils.isEmpty(appIds)) {
            appDtoMap = appConsr.mapByIds(appIds);
            List<AppPriceCacheDTO> appPriceCacheDTOS = new ArrayList<>();
            for (Long appId : appIds) {
                if (appDtoMap.get(appId) != null) {
                    AppPriceCacheDTO appPriceCacheDTO = new AppPriceCacheDTO();
                    appPriceCacheDTO.setAppId(appId);
                    appPriceCacheDTO.setAppTypeEnum(AppTypeEnum.APP_TYPE_MAP.get(appDtoMap.get(appId).getTypeCode()));
                    appPriceCacheDTOS.add(appPriceCacheDTO);
                }
            }
            appPriceMap = ResponseHandleUtil.parseMapResponse(appPriceCacheService.getCaches(appPriceCacheDTOS), Long.class, BigDecimal.class);
            appBrowseMap = browseRecordConsr.mapServeBrowseStatisticByClassify(appIds, "APP", classifyId);
            GroupIncomeSearchDto groupIncomeSearchDto = new GroupIncomeSearchDto();
            groupIncomeSearchDto.setBookGroupId(bookGroupId);
            groupIncomeSearchDto.setClassifyId(classifyId);
            groupIncomeSearchDto.setIds(appIds);
            groupIncomeSearchDto.setTypeCode("APP");
            appSaleDetail4Group = tradeConsr.getSaleDetail4Group(groupIncomeSearchDto);
        }
        if (!ListUtils.isEmpty(productIds)) {
            productDtoMap = productConsr.getProBasesByIds(productIds);
            isSuperMap = productConsr.getIsSuperByProductIdList(productIds);
            productBrowseMap = browseRecordConsr.mapServeBrowseStatisticByClassify(productIds, "PRODUCT", classifyId);
            GroupIncomeSearchDto groupIncomeSearchDto = new GroupIncomeSearchDto();
            groupIncomeSearchDto.setBookGroupId(bookGroupId);
            groupIncomeSearchDto.setIds(productIds);
            groupIncomeSearchDto.setClassifyId(classifyId);
            groupIncomeSearchDto.setTypeCode("PRODUCT");
            productSaleDetail4Group = tradeConsr.getSaleDetail4Group(groupIncomeSearchDto);
        }
        //数据填充
        for (ListKeywordVO listKeywordVO : listKeywordVOS) {
            if (ReplyTypeEnum.APP.value.equals(listKeywordVO.getReplyType())) {
                listKeywordVO.setSaleCount(0);
                if ("APP".equalsIgnoreCase(listKeywordVO.getServeType())) {
                    Long appId = listKeywordVO.getServeId();
                    if (!MapUtils.isEmpty(appDtoMap)) {
                        AppDto appDto = appDtoMap.get(appId);
                        if (appDto != null) {
                            listKeywordVO.setTypeCode(appDto.getTypeCode());
                            listKeywordVO.setContent(appDto.getTitle());
                        }
                    }
                    if (!MapUtils.isEmpty(appPriceMap)) {
                        if (appPriceMap.get(appId) != null) {
                            listKeywordVO.setRetailPrice(appPriceMap.get(appId).doubleValue());
                            listKeywordVO.setDealPrice(0D);
                        }
                    }
                    listKeywordVO.setApSource("APP");
                    if (!MapUtils.isEmpty(appBrowseMap) && appBrowseMap.containsKey(appId)) {
                        GroupBrowseStatisticVO appBrowse = appBrowseMap.get(appId);
                        listKeywordVO.setBrowseCount(appBrowse.getBrowseCount());
                        listKeywordVO.setBrowserCount(appBrowse.getBrowserCount());
                        listKeywordVO.setAvgbrowseTimes(appBrowse.getBrowserCount() == 0 ? 0 : appBrowse.getBrowseTimes() / appBrowse.getBrowserCount());
                    }
                    if (!MapUtils.isEmpty(appSaleDetail4Group) && appSaleDetail4Group.containsKey(appId)) {
                        GroupMoneyDto groupMoneyDto = appSaleDetail4Group.get(appId);
                        if (null != groupMoneyDto && null != groupMoneyDto.getSaleCount()) {
                            listKeywordVO.setSaleCount(groupMoneyDto.getSaleCount().intValue());
                        }
                    }
                } else if ("PRODUCT".equalsIgnoreCase(listKeywordVO.getServeType())) {
                    Long productId = listKeywordVO.getServeId();
                    if (!MapUtils.isEmpty(productDtoMap)) {
                        ProductDto productDto = productDtoMap.get(productId);
                        if (productDto != null) {
                            listKeywordVO.setTypeCode(productDto.getProductTypeCode());
                            listKeywordVO.setContent(productDto.getProductName());
                            List<SpecificationDto> specificationDtos = productDto.getSpecification();
                            if (!ListUtils.isEmpty(specificationDtos)) {
                                SpecificationDto specificationDto = specificationDtos.get(0);
                                if (specificationDto != null) {
                                    listKeywordVO.setRetailPrice(specificationDto.getAdvisePrice());
                                    listKeywordVO.setDealPrice(specificationDto.getDealPrice());
                                }
                            }
                        }
                    }
                    //判断是否为超级作者作品
                    if (!MapUtils.isEmpty(isSuperMap) && isSuperMap.get(productId) != null && isSuperMap.get(productId)) {
                        listKeywordVO.setApSource("SUPER_PRODUCT");
                    } else {
                        listKeywordVO.setApSource("PRODUCT");
                    }
                    if (!MapUtils.isEmpty(productBrowseMap) && productBrowseMap.containsKey(productId)) {
                        GroupBrowseStatisticVO productBrowse = productBrowseMap.get(productId);
                        listKeywordVO.setBrowseCount(productBrowse.getBrowseCount());
                        listKeywordVO.setBrowserCount(productBrowse.getBrowserCount());
                        listKeywordVO.setAvgbrowseTimes(productBrowse.getBrowserCount() == 0 ? 0 : productBrowse.getBrowseTimes() / productBrowse.getBrowserCount());
                    }
                    if (!MapUtils.isEmpty(productSaleDetail4Group) && productSaleDetail4Group.containsKey(productId)) {
                        GroupMoneyDto groupMoneyDto = productSaleDetail4Group.get(productId);
                        if (null != groupMoneyDto && null != groupMoneyDto.getSaleCount()) {
                            listKeywordVO.setSaleCount(groupMoneyDto.getSaleCount().intValue());
                        }
                    }
                }
            }
        }
    }

    /**
     * 个人号资源配置统计数据
     * @param bookGroupServeList
     * @param bookGroupId
     */
    public void setBookGroupServeStatistic(List<BookGroupServe> bookGroupServeList, Long bookGroupId) {
        if (ListUtils.isEmpty(bookGroupServeList)) {
            return;
        }
        List<Long> appIds = bookGroupServeList.stream().filter(s -> "APP".equalsIgnoreCase(s.getServeType())).map(BookGroupServe::getServeId).collect(Collectors.toList());
        List<Long> productIds = bookGroupServeList.stream().filter(s -> "PRODUCT".equalsIgnoreCase(s.getServeType())).map(BookGroupServe::getServeId).collect(Collectors.toList());
        Map<Long, ProductDto> productDtoMap = new HashMap<>();
        Map<Long, AppDto> appDtoMap = new HashMap<>();
        //浏览量浏览时长
        Map<Long, GroupBrowseStatisticVO> appBrowseStatisticMap = new HashMap<>();
        Map<Long, GroupBrowseStatisticVO> productBrowseStatisticMap = new HashMap<>();
        //购买次数
        Map<Long, GroupMoneyDto> appSaleDetail4Group = new HashMap<>();
        Map<Long, GroupMoneyDto> productSaleDetail4Group = new HashMap<>();
        //销售价协议价
        Map<Long, BigDecimal> appPriceMap = new HashMap<>();
        if (!ListUtils.isEmpty(productIds)) {
            productDtoMap = productConsr.getProBasesByIds(productIds);
            productBrowseStatisticMap = browseRecordConsr.mapServeBrowseStatistic(productIds, "PRODUCT", bookGroupId);
            GroupIncomeSearchDto groupIncomeSearchDto = new GroupIncomeSearchDto();
            groupIncomeSearchDto.setBookGroupId(bookGroupId);
            groupIncomeSearchDto.setIds(productIds);
            groupIncomeSearchDto.setTypeCode("PRODUCT");
            productSaleDetail4Group = tradeConsr.getSaleDetail4Group(groupIncomeSearchDto);
        }
        if (!ListUtils.isEmpty(appIds)) {
            appDtoMap = appConsr.mapByIds(appIds);
            appBrowseStatisticMap = browseRecordConsr.mapServeBrowseStatistic(appIds, "APP", bookGroupId);
            List<AppPriceCacheDTO> appPriceCacheDTOS = new ArrayList<>();
            for (Long appId : appIds) {
                if (null != appDtoMap.get(appId)) {
                    AppPriceCacheDTO appPriceCacheDTO = new AppPriceCacheDTO();
                    appPriceCacheDTO.setAppId(appId);
                    appPriceCacheDTO.setAppTypeEnum(AppTypeEnum.APP_TYPE_MAP.get(appDtoMap.get(appId).getTypeCode()));
                    appPriceCacheDTOS.add(appPriceCacheDTO);
                }
            }
            appPriceMap = ResponseHandleUtil.parseMapResponse(appPriceCacheService.getCaches(appPriceCacheDTOS), Long.class, BigDecimal.class);
            GroupIncomeSearchDto groupIncomeSearchDto = new GroupIncomeSearchDto();
            groupIncomeSearchDto.setBookGroupId(bookGroupId);
            groupIncomeSearchDto.setIds(appIds);
            groupIncomeSearchDto.setTypeCode("APP");
            appSaleDetail4Group = tradeConsr.getSaleDetail4Group(groupIncomeSearchDto);
        }
        for (BookGroupServe bookGroupServe : bookGroupServeList) {
            Long serveId = bookGroupServe.getServeId();
            GroupBrowseStatisticVO statisticVO = new GroupBrowseStatisticVO();
            GroupMoneyDto groupMoneyDto = new GroupMoneyDto();
            if ("PRODUCT".equals(bookGroupServe.getServeType())) {
                if (!MapUtils.isEmpty(productDtoMap) && productDtoMap.containsKey(serveId)) {
                    ProductDto productDto = productDtoMap.get(serveId);
                    if (productDto != null) {
                        bookGroupServe.setServeName(productDto.getProductName());
                        if (productDto.getProductTypeDto() != null) {
                            bookGroupServe.setFromType(productDto.getProductTypeDto().getTypeCode());
                            bookGroupServe.setDescription(productDto.getProductTypeDto().getTypeName());
                            bookGroupServe.setPicUrl(productDto.getCoverImg());
                        }
                        List<SpecificationDto> specificationDtos = productDto.getSpecification();
                        if (!ListUtils.isEmpty(specificationDtos)) {
                            SpecificationDto specificationDto = specificationDtos.get(0);
                            if (null != specificationDto) {
                                bookGroupServe.setRetailPrice(specificationDto.getAdvisePrice());
                                bookGroupServe.setDealPrice(specificationDto.getDealPrice());
                            }
                        }
                    }
                }
                if (!MapUtils.isEmpty(productBrowseStatisticMap) && productBrowseStatisticMap.containsKey(serveId)) {
                    statisticVO = productBrowseStatisticMap.get(serveId);
                }
                if (!MapUtils.isEmpty(productSaleDetail4Group) && productSaleDetail4Group.containsKey(serveId)) {
                    groupMoneyDto = productSaleDetail4Group.get(serveId);
                }
            } else if ("APP".equals(bookGroupServe.getServeType())) {
                if (!MapUtils.isEmpty(appDtoMap) && appDtoMap.containsKey(serveId)) {
                    AppDto appDto = appDtoMap.get(serveId);
                    if (appDto != null) {
                        bookGroupServe.setServeName(appDto.getTitle());
                        bookGroupServe.setFromType(appDto.getTypeCode());
                        bookGroupServe.setDescription(appDto.getTypeName());
                        bookGroupServe.setPicUrl(appDto.getSquareImg());
                    }
                }
                if (!MapUtils.isEmpty(appBrowseStatisticMap) && appBrowseStatisticMap.containsKey(serveId)) {
                    statisticVO = appBrowseStatisticMap.get(serveId);
                }
                if (!MapUtils.isEmpty(appPriceMap)) {
                    if (appPriceMap.get(serveId) != null) {
                        bookGroupServe.setRetailPrice(appPriceMap.get(serveId).doubleValue());
                        bookGroupServe.setDealPrice(0D);
                    }
                }
                if (!MapUtils.isEmpty(appSaleDetail4Group) && appSaleDetail4Group.containsKey(serveId)) {
                    groupMoneyDto = appSaleDetail4Group.get(serveId);
                }
            }
            if (null != statisticVO && null != statisticVO.getBrowseCount()) {
                bookGroupServe.setBrowseCount(statisticVO.getBrowseCount());
                bookGroupServe.setBrowserCount(statisticVO.getBrowserCount());
                bookGroupServe.setAvgbrowseTimes(statisticVO.getBrowserCount() == 0 ? 0 : statisticVO.getBrowseTimes() / statisticVO.getBrowserCount());
            }
            if (null != groupMoneyDto && null != groupMoneyDto.getSaleCount()) {
                bookGroupServe.setSaleCount(groupMoneyDto.getSaleCount().intValue());
            }
        }
    }
}
