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

import com.pcloud.analysisengine.browse.dto.GroupBrowseStatisticVO;
import com.pcloud.appcenter.app.dto.AppDto;
import com.pcloud.appcenter.base.dto.AppPriceCacheDTO;
import com.pcloud.appcenter.cache.service.AppPriceCacheService;
import com.pcloud.audioapp.audioLesson.service.AudioLessonService;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.analysisengine.BrowseRecordConsr;
import com.pcloud.book.consumer.app.AppConsr;
import com.pcloud.book.consumer.common.ExportConsr;
import com.pcloud.book.consumer.message.MessageConsr;
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.MerchantConsr;
import com.pcloud.book.group.biz.BookGroupAppBiz;
import com.pcloud.book.group.dao.AppClickRecordDao;
import com.pcloud.book.group.dao.BookGroupAppDao;
import com.pcloud.book.group.dao.BookGroupClassifyDao;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dao.BookGroupServeDao;
import com.pcloud.book.group.dto.BookGroupAppDTO;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.dto.GroupClassifyQrcodeDTO;
import com.pcloud.book.group.entity.BookGroupApp;
import com.pcloud.book.group.entity.BookGroupServe;
import com.pcloud.book.group.enums.AppAndProductTypeEnum;
import com.pcloud.book.group.enums.BookGroupAppOriginTypeEnum;
import com.pcloud.book.keywords.dao.BookGuideDao;
import com.pcloud.book.keywords.dao.BookKeywordDao;
import com.pcloud.book.keywords.entity.BookGuide;
import com.pcloud.book.keywords.entity.BookGuideReply;
import com.pcloud.book.keywords.entity.BookKeyword;
import com.pcloud.book.keywords.entity.SelfRobotKeyword;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.book.push.dao.PushGroupDao;
import com.pcloud.book.push.entity.PushGroup;
import com.pcloud.book.push.entity.PushItem;
import com.pcloud.book.push.enums.ItemTypeEnum;
import com.pcloud.book.util.common.ThreadPoolUtils;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.enums.NotifyOriginTypeEnum;
import com.pcloud.common.enums.AppTypeEnum;
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.facade.tradecenter.dto.GroupMoneyDto;
import com.pcloud.facade.tradecenter.dto.WechatGroupDto;
import com.pcloud.liveapp.live.dto.ProductIdSearchDto;
import com.pcloud.liveapp.live.service.TimeTableService;
import com.pcloud.resourcecenter.product.dto.ProductDto;
import com.pcloud.resourcecenter.product.dto.ProductTypeDto;
import com.pcloud.resourcecenter.product.dto.SpecificationDto;
import com.pcloud.videolesson.schedule.service.ScheduleService;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * @Description
 * @Author ruansiyuan
 * @Date 2019/11/14 10:29
 **/
@Component("bookGroupAppBiz")
public class BookGroupAppBizImpl implements BookGroupAppBiz {

    private static final Logger log = LoggerFactory.getLogger(BookGroupAppBizImpl.class);

    @Autowired
    private BookGroupAppDao bookGroupAppDao;
    @Autowired
    private BookGroupClassifyDao bookGroupClassifyDao;
    @Autowired
    private AppClickRecordDao appClickRecordDao;
    @Autowired
    private AppConsr appConsr;
    @Autowired
    private ProductConsr productConsr;
    @Autowired
    private AppPriceCacheService appPriceCacheService;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private MerchantConsr merchantConsr;
    @Autowired
    private BrowseRecordConsr browseRecordConsr;
    @Autowired
    private TradeConsr tradeConsr;
    @Autowired
    private BookGroupDao bookGroupDao;
    @Autowired
    private ScheduleService scheduleService;
    @Autowired
    private AudioLessonService audioLessonService;
    @Autowired
    private TimeTableService timeTableService;
    @Autowired
    private ExportConsr exportConsr;
    @Autowired
    private MessageConsr messageConsr;
    @Autowired
    private BookGuideDao bookGuideDao;
    @Autowired
    private BookKeywordDao bookKeywordDao;
    @Autowired
    private PushGroupDao pushGroupDao;
    @Autowired
    private BookGroupServeDao bookGroupServeDao;

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("将作品应用关键词加到社群书应用")
    @Override
    public void addAppKeywordToBookGroupApp(List<BookKeyword> bookKeywords) {
        if (ListUtils.isEmpty(bookKeywords)) {
            return;
        }
        List<BookGroupApp> bookGroupApps = new ArrayList<>();
        for (BookKeyword bookKeyword : bookKeywords) {
            if (bookKeyword.getKeyword() != null && ReplyTypeEnum.APP.value.equals(bookKeyword.getKeyword().getReplyType())) {
                BookGroupApp bookGroupApp = new BookGroupApp();
                bookGroupApp.setBookGroupId(bookKeyword.getBookGroupId());
                bookGroupApp.setClassifyId(bookKeyword.getClassifyId());
                bookGroupApp.setServeId(bookKeyword.getKeyword().getServeId());
                bookGroupApp.setServeType(bookKeyword.getKeyword().getServeType());
                bookGroupApp.setCreateUser(bookKeyword.getCreateUser());
                bookGroupApp.setOriginType(BookGroupAppOriginTypeEnum.KEYWORD.code);
                //判断是否已经添加过
                BookGroupApp bookGroupAppOld = bookGroupAppDao.getByCondition(bookGroupApp);
                if (bookGroupAppOld != null) {
                    continue;
                }
                bookGroupApps.add(bookGroupApp);
            }
        }
        if (ListUtils.isEmpty(bookGroupApps)){
            return;
        }
        bookGroupAppDao.batchInsert(bookGroupApps);
        log.info("将作品应用关键词加到社群书应用数据库插入"+bookGroupApps.toString());
    }


    @Transactional(rollbackFor = Exception.class)
    @ParamLog("将作品应用欢迎语加到社群书应用")
    @Override
    public void addBookGuideToBookGroupApp(BookGuide bookGuide, List<BookGuideReply> bookGuideReplies) {
        if (ListUtils.isEmpty(bookGuideReplies)) {
            return;
        }
        if (bookGuide == null) {
            return;
        }
        List<BookGroupApp> bookGroupApps = new ArrayList<>();
        for (BookGuideReply bookGuideReply : bookGuideReplies) {
            if (ReplyTypeEnum.APP.value.equals(bookGuideReply.getReplyType())) {
                BookGroupApp bookGroupApp = new BookGroupApp();
                bookGroupApp.setOriginType(BookGroupAppOriginTypeEnum.GUIDE.code);
                bookGroupApp.setServeId(bookGuideReply.getServeId());
                bookGroupApp.setServeType(bookGuideReply.getServeType());
                bookGroupApp.setClassifyId(bookGuide.getClassifyId());
                bookGroupApp.setBookGroupId(bookGuide.getBookGroupId());
                bookGroupApp.setCreateUser(bookGuide.getCreateUser());
                //判断是否已经添加过
                BookGroupApp bookGroupAppOld = bookGroupAppDao.getByCondition(bookGroupApp);
                if (bookGroupAppOld != null) {
                    continue;
                }
                bookGroupApps.add(bookGroupApp);
            }
        }
        if (ListUtils.isEmpty(bookGroupApps)) {
            return;
        }
        bookGroupAppDao.batchInsert(bookGroupApps);
        log.info("将作品应用欢迎语加到社群书应用数据库插入" + bookGroupApps.toString());
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("将作品应用群发加到社群书应用")
    @Override
    public void addPushToBookGroupApp(List<PushGroup> pushGroups, List<PushItem> pushItems) {
        if (ListUtils.isEmpty(pushGroups) || ListUtils.isEmpty(pushItems)) {
            return;
        }
        List<Long> classifyIds = pushGroups.stream().filter(s -> s.getClassifyId() != null).map(PushGroup::getClassifyId).collect(Collectors.toList());
        if (ListUtils.isEmpty(classifyIds)) {
            return;
        }
        List<PushItem> pushItemsNew = pushItems.stream().filter(s -> ItemTypeEnum.APP.value.equals(s.getItemType())).collect(Collectors.toList());
        if (ListUtils.isEmpty(pushItemsNew)) {
            return;
        }
        List<GroupClassifyQrcodeDTO> dtos = bookGroupClassifyDao.listClassifyQrcodeInfo(classifyIds);
        List<BookGroupApp> pushGroupApps = new ArrayList<>();
        for (PushItem pushItem : pushItemsNew) {
            for (GroupClassifyQrcodeDTO dto : dtos) {
                BookGroupApp bookGroupApp = new BookGroupApp();
                if (pushItem.getAppId() != null) {
                    bookGroupApp.setServeId(pushItem.getAppId());
                    bookGroupApp.setServeType(AppAndProductTypeEnum.APP.value);
                }
                if (pushItem.getProductId() != null) {
                    bookGroupApp.setServeId(pushItem.getProductId());
                    bookGroupApp.setServeType(AppAndProductTypeEnum.PRODUCT.value);
                }
                bookGroupApp.setBookGroupId(dto.getBookGroupId());
                bookGroupApp.setClassifyId(dto.getClassifyId());
                bookGroupApp.setOriginType(BookGroupAppOriginTypeEnum.PUSH.code);
                bookGroupApp.setCreateUser(pushItem.getCreateUser());
                //判断是否已经添加过
                BookGroupApp bookGroupAppOld = bookGroupAppDao.getByCondition(bookGroupApp);
                if (bookGroupAppOld != null) {
                    continue;
                }
                pushGroupApps.add(bookGroupApp);
            }
        }
        if (ListUtils.isEmpty(pushGroupApps)){
            return;
        }
        bookGroupAppDao.batchInsert(pushGroupApps);
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("将作品应用关键词加到社群书应用")
    @Override
    public void addServeToBookGroupApp(List<BookGroupServe> bookGroupServes) {
        if (ListUtils.isEmpty(bookGroupServes)) {
            return;
        }
        List<BookGroupApp> bookGroupApps = new ArrayList<>();
        for (BookGroupServe bookGroupServe : bookGroupServes) {
            BookGroupApp bookGroupApp = new BookGroupApp();
            bookGroupApp.setBookGroupId(bookGroupServe.getBookGroupId());
            bookGroupApp.setClassifyId(0L);
            bookGroupApp.setServeId(bookGroupServe.getServeId());
            bookGroupApp.setServeType(bookGroupServe.getServeType());
            bookGroupApp.setCreateUser(bookGroupServe.getCreateUser());
            bookGroupApp.setOriginType(BookGroupAppOriginTypeEnum.SERVE.code);
            //判断是否已经添加过
            BookGroupApp bookGroupAppOld = bookGroupAppDao.getByCondition(bookGroupApp);
            if (bookGroupAppOld != null) {
                continue;
            }
            bookGroupApps.add(bookGroupApp);
        }
        if (ListUtils.isEmpty(bookGroupApps)) {
            return;
        }
        bookGroupAppDao.batchInsert(bookGroupApps);
    }

    @ParamLog("根据社群码id查询所挂资源统计")
    @Override
    public PageBeanNew<BookGroupAppDTO> getBookGroupAppDTOSByBookGroupId(Long bookGroupId, Integer currentPage, Integer numPerPage) {
        if (bookGroupId == null || currentPage == null || numPerPage == null || currentPage < 0 || numPerPage <= 0) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数有误");
        }
        PageParam pageParam = new PageParam(currentPage, numPerPage);
        Map<String, Object> map = new HashMap<>();
        map.put("bookGroupId", bookGroupId);
        PageBeanNew<BookGroupAppDTO> pageBeanNew = bookGroupAppDao.listPageNew(pageParam, map, "getBookGroupAppDTOSByBookGroupId");
        List<BookGroupAppDTO> list = pageBeanNew.getRecordList();
        fillBookGroupAppDTOS(list, bookGroupId);
        return pageBeanNew;
    }

    @ParamLog("根据社群码id导出所挂资源统计")
    @Override
    public void exportBookGroupAppDTOSByBookGroupId(Long bookGroupId, String systemCode, Long partyId) {
        if (bookGroupId == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数有误");
        }

        List<BookGroupAppDTO> list = bookGroupAppDao.getBookGroupAppDTOSByBookGroupId(bookGroupId);
        fillBookGroupAppDTOS(list, bookGroupId);
        ThreadPoolUtils.EXPORT_THREAD_POOL.execute(() -> {
            try {
                //导出数据
                exportDTOS(list,bookGroupId, systemCode, partyId);
            } catch (Exception e) {
                log.error("导出失败exportBookGroupAppDTOSByBookGroupId+++bookGroupId=" + bookGroupId + "systemCode=" + systemCode + "partyId=" + partyId);
            }
        });
    }

    @ParamLog("补充社群书旧的作品应用到新的表")
    @Override
    public void addOldBookGroupAppToNew() {
        //1欢迎语,2关键词,3群发,4配置资源
        //先查询现有的所有bookGroupId避免重复
        List<Long> hasBookGroupIds = bookGroupAppDao.getAllBookGroupId();
        if (ListUtils.isEmpty(hasBookGroupIds)) {
            hasBookGroupIds = new ArrayList<>();
        }
        //查询所有欢迎语
        List<BookGroupApp> guideApps = bookGuideDao.getAllAppGuide();
        //查询所有关键词
        List<BookGroupApp> keywordApps = bookKeywordDao.getAllAppKeyword();
        //查询所有群发
        List<BookGroupApp> pushApps = pushGroupDao.getAllAppPush();
        //查询所有的配置资源
        List<BookGroupApp> serveApps=bookGroupServeDao.getAllAppServe();
        List<BookGroupApp> list=new ArrayList<>();
        if (!ListUtils.isEmpty(guideApps)){
            list.addAll(guideApps);
        }
        if (!ListUtils.isEmpty(keywordApps)){
            list.addAll(keywordApps);
        }
        if (!ListUtils.isEmpty(pushApps)){
            list.addAll(pushApps);
        }
        if (!ListUtils.isEmpty(serveApps)){
            list.addAll(serveApps);
        }
        List<BookGroupApp> bookGroupApps=new ArrayList<>();
        List<Long> bookGroupIds=new ArrayList<>();
        for (BookGroupApp bookGroupApp:list){
            if (!hasBookGroupIds.contains(bookGroupApp.getBookGroupId())){
                bookGroupApps.add(bookGroupApp);
                if (!bookGroupIds.contains(bookGroupApp.getBookGroupId())){
                    bookGroupIds.add(bookGroupApp.getBookGroupId());
                }
            }
        }
        //插入数据
        if (!ListUtils.isEmpty(bookGroupApps)) {
            Map<Long, List<BookGroupApp>> map = bookGroupApps.stream().collect(Collectors.groupingBy(BookGroupApp::getBookGroupId));
            for (Long bookGroupId : bookGroupIds) {
                List<BookGroupApp> bookGroupAppList = map.get(bookGroupId);
                if (!ListUtils.isEmpty(bookGroupAppList)) {
                    bookGroupAppDao.batchInsert(bookGroupAppList);
                }
            }
        }

    }

    @ParamLog("将个人号应用关键词插入到社群书应用")
    @Override
    public void addSelfKeywordToBookGroupApp(List<SelfRobotKeyword> selfRobotKeywords) {
        if (ListUtils.isEmpty(selfRobotKeywords)) {
            return;
        }
        List<BookGroupApp> bookGroupApps = new ArrayList<>();
        for (SelfRobotKeyword selfRobotKeyword : selfRobotKeywords) {
            if (ReplyTypeEnum.APP.value.equals(selfRobotKeyword.getType())) {
                BookGroupApp bookGroupApp = new BookGroupApp();
                bookGroupApp.setOriginType(BookGroupAppOriginTypeEnum.SELF_KEYWORD.code);
                bookGroupApp.setServeId(selfRobotKeyword.getServeId());
                bookGroupApp.setServeType(selfRobotKeyword.getServeType());
                bookGroupApp.setClassifyId(0L);
                bookGroupApp.setBookGroupId(selfRobotKeyword.getBookGroupId());
                bookGroupApp.setCreateUser(selfRobotKeyword.getCreateUser());
                //判断是否已经添加过
                BookGroupApp bookGroupAppOld = bookGroupAppDao.getByCondition(bookGroupApp);
                if (bookGroupAppOld != null) {
                    continue;
                }
                bookGroupApps.add(bookGroupApp);
            }
        }
        if (ListUtils.isEmpty(bookGroupApps)) {
            return;
        }
        bookGroupAppDao.batchInsert(bookGroupApps);
    }

    @ParamLog("导出")
    private void exportDTOS(List<BookGroupAppDTO> list, Long bookGroupId, String systemCode, Long partyId) {
        if (ListUtils.isEmpty(list)) {
            return;
        }
        BookGroupDTO bookGroupDTO = bookGroupDao.getDTOById(bookGroupId);
        if (bookGroupDTO == null) {
            log.error("没有找到改社群码");
            return;
        }
        List<Object[]> dataList = new ArrayList<>();
        for (int i = 0, size = list.size(); i < size; i++) {
            BookGroupAppDTO bookGroupAppDTO = list.get(i);
            Object[] obj = new Object[12];
            obj[0] = i + 1;
            obj[1] = bookGroupAppDTO.getServeName();
            if (AppAndProductTypeEnum.APP.value.equalsIgnoreCase(bookGroupAppDTO.getServeType())) {
                obj[2] = "应用";
            } else {
                obj[2] = "作品";
            }
            obj[3] = bookGroupAppDTO.getTypeName();
            obj[4] = bookGroupAppDTO.getServeCreateUserName();
            obj[5] = bookGroupAppDTO.getDealPrice();
            obj[6] = bookGroupAppDTO.getRetailPrice();
            obj[7] = bookGroupAppDTO.getClickPeopleCount();
            obj[8] = bookGroupAppDTO.getClickCount();
            obj[9] = bookGroupAppDTO.getAvgBrowseTime();
            obj[10] = bookGroupAppDTO.getBuyPeopleCount();
            obj[11] = bookGroupAppDTO.getSaleAmount();
            dataList.add(obj);
        }
        Date date = new Date();
        String[] rowsName = {"序号", "应用或作品名称", "应用/作品", "类型", "编辑/作者名称", "协议价", "销售价",
                "点击人数", "点击次数", "平均浏览时长（秒/人）", "购买人数", "销售额"};
        String fileName = "社群码应用作品统计--" + bookGroupDTO.getGroupQrcodeName() + "--" + DateUtils.getStrFormTime("yyyyMMdd", date);
        String fileUrl = exportConsr.exportExcel(fileName, rowsName, dataList);
        String letterType = "pcloud_book_group_serve";
        String content = String.format("{\"commitTime\":\"%s\",\"type\":\"%s\"}", DateUtils.formatDate(date), fileName);
        messageConsr.sendLetter(partyId, partyId, content, systemCode, letterType, fileUrl, fileName, NotifyOriginTypeEnum.BOOK_GROUP.value, bookGroupDTO.getId().toString());
    }

    @ParamLog("填充统计列表一些信息")
    private void fillBookGroupAppDTOS(List<BookGroupAppDTO> list, Long bookGroupId) {
        if (ListUtils.isEmpty(list)) {
            return;
        }
        List<Long> appIds = new ArrayList<>();
        List<Long> productIds = new ArrayList<>();
        for (BookGroupAppDTO bookGroupAppDTO : list) {
            if (AppAndProductTypeEnum.APP.value.equalsIgnoreCase(bookGroupAppDTO.getServeType())) {
                appIds.add(bookGroupAppDTO.getServeId());
            }
            if (AppAndProductTypeEnum.PRODUCT.value.equalsIgnoreCase(bookGroupAppDTO.getServeType())) {
                productIds.add(bookGroupAppDTO.getServeId());
            }
        }
        fillServeClick(appIds, productIds, bookGroupId, list);
        //填充应用作品信息相关
        fillServeInfo(appIds, productIds, bookGroupId, list);
        //填充创建者名称
        fillCreateUserName(list);
        //填充浏览时长
        fillServeBrowse(appIds, productIds, bookGroupId, list);
        //填充销售额购买人数
        fillSaleInfo(appIds, productIds, bookGroupId, list);
    }

    @ParamLog("填充销售额购买人数")
    private void fillSaleInfo(List<Long> appIds, List<Long> productIds, Long bookGroupId, List<BookGroupAppDTO> list) {
        BookGroupDTO bookGroupDTO = bookGroupDao.getDTOById(bookGroupId);
        WechatGroupDto wechatGroupDtoP = new WechatGroupDto();
        wechatGroupDtoP.setBookGroupId(bookGroupId);
        wechatGroupDtoP.setIds(productIds);
        wechatGroupDtoP.setType("PRODUCT");
        WechatGroupDto wechatGroupDtoA = new WechatGroupDto();
        wechatGroupDtoA.setBookGroupId(bookGroupId);
        wechatGroupDtoA.setIds(appIds);
        wechatGroupDtoA.setType("APP");
        if (bookGroupDTO!=null){
            wechatGroupDtoP.setPartyId(bookGroupDTO.getCreateUser());
            wechatGroupDtoA.setPartyId(bookGroupDTO.getCreateUser());
        }
        Map<Long, GroupMoneyDto> productSaleMap = tradeConsr.getQrGroupSaleMoney(wechatGroupDtoP);
        Map<Long, GroupMoneyDto> appSaleMap = tradeConsr.getQrGroupSaleMoney(wechatGroupDtoA);
        String[] videoTypes = {"VIDEO_COURSE", "VIDEO_SCHEDULE"};
        String[] audioTypes = {"AUDIOAPP", "AUDIO_RESOURCE", "AUDIO_SCHEDULE", "AUDIO_COURSE"};
        String[] liveTypes = {"LIVE", "SCHEDULE"};
        //视频课，音频课，直播课特殊处理
        List<Long> videoProductIds = new ArrayList<>();
        List<Long> audioProductIds = new ArrayList<>();
        List<Long> liveProductIds = new ArrayList<>();
        for (BookGroupAppDTO bookGroupAppDTO:list){
            Long serveId = bookGroupAppDTO.getServeId();
            String serveType = bookGroupAppDTO.getServeType();
            if (AppAndProductTypeEnum.APP.value.equalsIgnoreCase(serveType)) {
                GroupMoneyDto groupMoneyDto=appSaleMap.get(serveId);
                if (groupMoneyDto!=null){
                    bookGroupAppDTO.setBuyPeopleCount(groupMoneyDto.getPayUserCount().intValue());
                    bookGroupAppDTO.setSaleAmount(groupMoneyDto.getSaleMoney());
                }
            }
            if (AppAndProductTypeEnum.PRODUCT.value.equalsIgnoreCase(serveType)) {
                GroupMoneyDto groupMoneyDto=productSaleMap.get(serveId);
                if (groupMoneyDto!=null){
                    bookGroupAppDTO.setBuyPeopleCount(groupMoneyDto.getPayUserCount().intValue());
                    bookGroupAppDTO.setSaleAmount(groupMoneyDto.getSaleMoney());
                }
                String typeCode = bookGroupAppDTO.getTypeCode();
                if (Arrays.asList(videoTypes).contains(typeCode)) {
                    videoProductIds.add(serveId);
                }
                if (Arrays.asList(audioTypes).contains(typeCode)) {
                    audioProductIds.add(serveId);
                }
                if (Arrays.asList(liveTypes).contains(typeCode)) {
                    liveProductIds.add(serveId);
                }
            }
            if (bookGroupAppDTO.getBuyPeopleCount() == null) {
                bookGroupAppDTO.setBuyPeopleCount(0);
            }
            if (bookGroupAppDTO.getSaleAmount() == null) {
                bookGroupAppDTO.setSaleAmount(0D);
            }
        }
        List<Long> specialProductIds=new ArrayList<>();
        Map<Long, List<Long>> videoPProductMapIds=new HashMap<>();
        //视频课
        if (ListUtils.isEmpty(videoProductIds)){
            videoPProductMapIds = ResponseHandleUtil.parseMapList(scheduleService.getCourseProductIdByIds(videoProductIds, "PRODUCT"), Long.class, Long.class);
            if (!MapUtils.isEmpty(videoPProductMapIds)){
                List<Long> keys = new ArrayList<>(videoPProductMapIds.keySet());
                for (Long key : keys) {
                    specialProductIds.addAll(videoPProductMapIds.get(key));
                }
            }
        }
        Map<Long, List<Long>> audioPProductMapIds=new HashMap<>();
        //音频课
        if (ListUtils.isEmpty(audioProductIds)){
            audioPProductMapIds = ResponseHandleUtil.parseMapList(audioLessonService.getProIdsByIds(audioProductIds, "PRODUCT"), Long.class, Long.class);
            if (!MapUtils.isEmpty(audioPProductMapIds)){
                List<Long> keys = new ArrayList<>(audioPProductMapIds.keySet());
                for (Long key : keys) {
                    specialProductIds.addAll(audioPProductMapIds.get(key));
                }
            }
        }
        Map<Long, List<Long>> livePProductMapIds=new HashMap<>();
        //直播课
        if (ListUtils.isEmpty(liveProductIds)){
            ProductIdSearchDto productIdSearchDto = new ProductIdSearchDto();
            productIdSearchDto.setIds(liveProductIds);
            productIdSearchDto.setType(AppAndProductTypeEnum.PRODUCT.value);
            livePProductMapIds = ResponseHandleUtil.parseMapList(timeTableService.getCoursePidsUnderTable(productIdSearchDto), Long.class, Long.class);
            if (!MapUtils.isEmpty(livePProductMapIds)){
                List<Long> keys = new ArrayList<>(livePProductMapIds.keySet());
                for (Long key : keys) {
                    specialProductIds.addAll(livePProductMapIds.get(key));
                }
            }
        }
        if (ListUtils.isEmpty(specialProductIds)){
            return;
        }
        WechatGroupDto specialWechatGroupDtoP = new WechatGroupDto();
        specialWechatGroupDtoP.setBookGroupId(bookGroupId);
        specialWechatGroupDtoP.setIds(productIds);
        specialWechatGroupDtoP.setType("PRODUCT");
        if (bookGroupDTO!=null){
            specialWechatGroupDtoP.setPartyId(bookGroupDTO.getCreateUser());
        }
        Map<Long, GroupMoneyDto> specialProductSaleMap = tradeConsr.getQrGroupSaleMoney(specialWechatGroupDtoP);
        for (BookGroupAppDTO bookGroupAppDTO:list){
            Long serveId = bookGroupAppDTO.getServeId();
            String serveType = bookGroupAppDTO.getServeType();
            if (AppAndProductTypeEnum.PRODUCT.value.equalsIgnoreCase(serveType)) {
                String typeCode = bookGroupAppDTO.getTypeCode();
                List<Long> ids=new ArrayList<>();
                if (Arrays.asList(videoTypes).contains(typeCode)) {
                    ids = videoPProductMapIds.get(serveId);
                }
                if (Arrays.asList(audioTypes).contains(typeCode)) {
                    ids = audioPProductMapIds.get(serveId);
                }
                if (Arrays.asList(liveTypes).contains(typeCode)) {
                    ids = livePProductMapIds.get(serveId);
                }
                if (!ListUtils.isEmpty(list)){
                    for (Long id : ids) {
                        GroupMoneyDto groupMoneyDto=specialProductSaleMap.get(id);
                        if (groupMoneyDto!=null){
                            if (bookGroupAppDTO.getBuyPeopleCount()==null){
                                bookGroupAppDTO.setBuyPeopleCount(0);
                            }
                            if (groupMoneyDto.getSaleCount()!=null){
                                bookGroupAppDTO.setBuyPeopleCount(bookGroupAppDTO.getBuyPeopleCount()+groupMoneyDto.getPayUserCount().intValue());
                            }
                            if (bookGroupAppDTO.getSaleAmount()==null){
                                bookGroupAppDTO.setSaleAmount(0D);
                            }
                            if (groupMoneyDto.getSaleMoney()!=null){
                                bookGroupAppDTO.setSaleAmount(bookGroupAppDTO.getSaleAmount()+groupMoneyDto.getSaleMoney());
                            }
                        }
                    }
                }

            }
        }

    }

    @ParamLog("填充浏览时长相关")
    private void fillServeBrowse(List<Long> appIds, List<Long> productIds, Long bookGroupId, List<BookGroupAppDTO> list) {
        Map<Long, GroupBrowseStatisticVO> appBrowseMap = browseRecordConsr.mapServeBrowseStatistic(appIds, AppAndProductTypeEnum.APP.value, bookGroupId);
        Map<Long, GroupBrowseStatisticVO> proBrowseMap = browseRecordConsr.mapServeBrowseStatistic(productIds, AppAndProductTypeEnum.PRODUCT.value, bookGroupId);
        for (BookGroupAppDTO bookGroupAppDTO : list) {
            Long serveId = bookGroupAppDTO.getServeId();
            String serveType = bookGroupAppDTO.getServeType();
            if (AppAndProductTypeEnum.APP.value.equalsIgnoreCase(serveType)) {
                if (appBrowseMap != null && appBrowseMap.get(serveId) != null) {
                    GroupBrowseStatisticVO vo = appBrowseMap.get(serveId);
                    if (vo.getBrowseTimes() != null && vo.getBrowserCount() != null) {
                        bookGroupAppDTO.setAvgBrowseTime(vo.getBrowseTimes().intValue() / vo.getBrowserCount());
                    }
                }
            }
            if (AppAndProductTypeEnum.PRODUCT.value.equalsIgnoreCase(serveType)) {
                if (proBrowseMap != null && proBrowseMap.get(serveId) != null) {
                    GroupBrowseStatisticVO vo = proBrowseMap.get(serveId);
                    if (vo.getBrowseTimes() != null && vo.getBrowserCount() != null) {
                        bookGroupAppDTO.setAvgBrowseTime(vo.getBrowseTimes().intValue() / vo.getBrowserCount());
                    }
                }
            }
            if (bookGroupAppDTO.getAvgBrowseTime() == null) {
                bookGroupAppDTO.setAvgBrowseTime(0);
            }
        }
    }

    @ParamLog("填充应用作品信息相关")
    private void fillServeInfo(List<Long> appIds, List<Long> productIds, Long bookGroupId, List<BookGroupAppDTO> list) {
        Map<Long, AppDto> appDtoMap = new HashMap<>();
        Map<Long, ProductDto> productDtoMap = new HashMap<>();
        Map<Long, BigDecimal> appPriceMap=new HashMap<>();
        Map<Long, String> sceneNameMap=new HashMap<>();
        if (!ListUtils.isEmpty(appIds)) {
            //获取详情
            appDtoMap = appConsr.mapByIds(appIds);
            sceneNameMap = appConsr.listSceneNameByIds(appIds);
            List<AppPriceCacheDTO> appPriceCacheDTOS = new ArrayList<>();
            for (Long appId : appIds) {
                if (appDtoMap.get(appId) != null && appDtoMap.get(appId).getTypeCode() != 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);
        }
        if (!ListUtils.isEmpty(productIds)) {
            productDtoMap = productConsr.getProBasesByIds(productIds);
        }
        List<Long> adviserIds=new ArrayList<>();
        List<Long> merchantIds=new ArrayList<>();
        for (BookGroupAppDTO bookGroupAppDTO : list){
            Long serveId = bookGroupAppDTO.getServeId();
            String serveType = bookGroupAppDTO.getServeType();
            if(AppAndProductTypeEnum.APP.value.equalsIgnoreCase(serveType)){
                if (appDtoMap != null && appDtoMap.get(serveId)!=null) {
                    AppDto appDto=appDtoMap.get(serveId);
                    bookGroupAppDTO.setServeName(appDto.getTitle());
                    bookGroupAppDTO.setServeCreateUserId(appDto.getCreatedUser());
                    bookGroupAppDTO.setTypeName(appDto.getTypeName());
                    bookGroupAppDTO.setTypeCode(appDto.getTypeCode());
                    adviserIds.add(appDto.getCreatedUser());
                }
                bookGroupAppDTO.setSceneName(sceneNameMap.get(serveId));
                if (appPriceMap!=null&& appPriceMap.get(serveId)!=null){
                    bookGroupAppDTO.setRetailPrice(appPriceMap.get(serveId).doubleValue());
                }
            }
            if (AppAndProductTypeEnum.PRODUCT.value.equalsIgnoreCase(serveType)){
                if (productDtoMap!=null&& productDtoMap.get(serveId)!=null){
                    ProductDto productDto=productDtoMap.get(serveId);
                    bookGroupAppDTO.setServeName(productDto.getProductName());
                    bookGroupAppDTO.setServeCreateUserId(productDto.getCreatedUser());
                    merchantIds.add(productDto.getCreatedUser());
                    ProductTypeDto productTypeDto = productDto.getProductTypeDto();
                    if (productTypeDto != null) {
                        bookGroupAppDTO.setTypeName(productTypeDto.getTypeName());
                        bookGroupAppDTO.setTypeCode(productTypeDto.getTypeCode());
                    }
                    List<SpecificationDto> specificationDtos = productDto.getSpecification();
                    if (!ListUtils.isEmpty(specificationDtos)) {
                        SpecificationDto specificationDto = specificationDtos.get(0);
                        if (specificationDto != null) {
                            bookGroupAppDTO.setDealPrice(specificationDto.getDealPrice());
                            bookGroupAppDTO.setRetailPrice(specificationDto.getAdvisePrice());
                        }
                    }
                }
            }
        }
    }

    @ParamLog("填充点击相关")
    private void fillServeClick(List<Long> appIds, List<Long> productIds, Long bookGroupId, List<BookGroupAppDTO> list) {
        Map<Long,Integer> appClickCountMap = new HashMap<>();
        Map<Long,Integer> appClickPeopleCountMap = new HashMap<>();
        Map<Long,Integer> proClickCountMap = new HashMap<>();
        Map<Long,Integer> proClickPeopleCountMap  = new HashMap<>();
        if (!ListUtils.isEmpty(appIds)) {
            //获取应用点击次数
            List<BookGroupAppDTO> appClickCountList = appClickRecordDao.getClickCountByServe(bookGroupId, AppAndProductTypeEnum.APP.value, appIds);
            if (!ListUtils.isEmpty(appClickCountList)){
                for (BookGroupAppDTO appClickCount:appClickCountList){
                    appClickCountMap.put(appClickCount.getServeId(),appClickCount.getClickCount());
                }
            }
            //获取应用点击人数
            List<BookGroupAppDTO> appClickPeopleCountList = appClickRecordDao.getClickPeopleCountByServe(bookGroupId, AppAndProductTypeEnum.APP.value, appIds);
            if (!ListUtils.isEmpty(appClickPeopleCountList)){
                for (BookGroupAppDTO appClickPeopleCount:appClickPeopleCountList){
                    appClickPeopleCountMap.put(appClickPeopleCount.getServeId(),appClickPeopleCount.getClickPeopleCount());
                }
            }
        }
        if (!ListUtils.isEmpty(productIds)) {
            //获取作品点击次数
            List<BookGroupAppDTO> proClickCountList = appClickRecordDao.getClickCountByServe(bookGroupId, AppAndProductTypeEnum.PRODUCT.value, productIds);
            if (!ListUtils.isEmpty(proClickCountList)){
                for (BookGroupAppDTO proClickCount:proClickCountList){
                    proClickCountMap.put(proClickCount.getServeId(),proClickCount.getClickCount());
                }
            }
            //获取作品点击人数
            List<BookGroupAppDTO> proClickPeopleCountList = appClickRecordDao.getClickPeopleCountByServe(bookGroupId, AppAndProductTypeEnum.PRODUCT.value, productIds);
            if (!ListUtils.isEmpty(proClickPeopleCountList)){
                for (BookGroupAppDTO proClickPeopleCount:proClickPeopleCountList){
                    proClickPeopleCountMap.put(proClickPeopleCount.getServeId(),proClickPeopleCount.getClickPeopleCount());
                }
            }
        }
        for (BookGroupAppDTO bookGroupAppDTO : list){
            Long serveId = bookGroupAppDTO.getServeId();
            String serveType = bookGroupAppDTO.getServeType();
            if(AppAndProductTypeEnum.APP.value.equalsIgnoreCase(serveType)){
                bookGroupAppDTO.setClickCount(appClickCountMap.get(serveId)==null?0:appClickCountMap.get(serveId));
                bookGroupAppDTO.setClickPeopleCount(appClickPeopleCountMap.get(serveId)==null?0:appClickPeopleCountMap.get(serveId));
            }
            if (AppAndProductTypeEnum.PRODUCT.value.equalsIgnoreCase(serveType)){
                bookGroupAppDTO.setClickCount(proClickCountMap.get(serveId)==null?0:proClickCountMap.get(serveId));
                bookGroupAppDTO.setClickPeopleCount(proClickPeopleCountMap.get(serveId)==null?0:proClickPeopleCountMap.get(serveId));
            }
        }
    }

    @ParamLog("填充创建者名称")
    private void fillCreateUserName(List<BookGroupAppDTO> list) {
        List<Long> adviserIds = new ArrayList<>();
        List<Long> merchantIds = new ArrayList<>();
        for (BookGroupAppDTO bookGroupAppDTO:list){
            if (AppAndProductTypeEnum.APP.value.equalsIgnoreCase(bookGroupAppDTO.getServeType())){
                adviserIds.add(bookGroupAppDTO.getServeCreateUserId());
            }
            if (AppAndProductTypeEnum.PRODUCT.value.equalsIgnoreCase(bookGroupAppDTO.getServeType())){
                merchantIds.add(bookGroupAppDTO.getServeCreateUserId());
            }
        }
        Map<Long, String> adviserNameMap = new HashMap<>();
        Map<Long, String> merchantNameMap = new HashMap<>();
        List<Long> merchentIds = new ArrayList<>();
        if (!ListUtils.isEmpty(adviserIds)) {
            adviserNameMap = adviserConsr.getNames(adviserIds);
        }
        if (!ListUtils.isEmpty(merchantIds)) {
            merchantNameMap = merchantConsr.getNamesByIdList(merchantIds);
            Map<Long, Long> superMerchantMap = merchantConsr.getSuperMerchantList();
            if (superMerchantMap!=null){
                merchentIds.addAll(superMerchantMap.keySet());
            }
        }
        //填充创建者名称
        for (BookGroupAppDTO bookGroupAppDTO : list) {
            Long userId = bookGroupAppDTO.getServeCreateUserId();
            String serveType = bookGroupAppDTO.getServeType();
            if(AppAndProductTypeEnum.APP.value.equalsIgnoreCase(serveType)){
                if (adviserNameMap!=null){
                    bookGroupAppDTO.setServeCreateUserName(adviserNameMap.get(userId));
                }
            }
            if (AppAndProductTypeEnum.PRODUCT.value.equalsIgnoreCase(serveType)){
                if (merchantNameMap!=null){
                    bookGroupAppDTO.setServeCreateUserName(merchantNameMap.get(userId));
                }
                if (merchentIds.contains(userId)){
                    bookGroupAppDTO.setIsSuper(true);
                }else {
                    bookGroupAppDTO.setIsSuper(false);
                }
            }
        }

    }
}
