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

import com.pcloud.advertising.advertising.dto.AdvertisingSpaceDTO;
import com.pcloud.advertising.advertising.dto.AdvertisingSpaceItemDTO;
import com.pcloud.analysisengine.browse.dto.BrowseRecordStatisticDTO;
import com.pcloud.appcenter.app.dto.AppDto;
import com.pcloud.book.applet.biz.AppletBooklistBiz;
import com.pcloud.book.applet.biz.AppletGroupSearchRecordBiz;
import com.pcloud.book.applet.biz.AppletRecordAggrStatisBiz;
import com.pcloud.book.applet.biz.AppletThirdResourcesBiz;
import com.pcloud.book.applet.dto.AppletGroupStatementDTO;
import com.pcloud.book.applet.dto.AppletOuterBooklistDTO;
import com.pcloud.book.applet.dto.GroupActivity4AppletDTO;
import com.pcloud.book.applet.entity.AppletThirdResources;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.biz.BookBiz;
import com.pcloud.book.book.dto.BookDto;
import com.pcloud.book.book.dto.RaysSceneCatalogDto;
import com.pcloud.book.book.entity.Book;
import com.pcloud.book.book.enums.WxworkQrcodeType;
import com.pcloud.book.book.vo.BookLinkVO;
import com.pcloud.book.book.vo.response.BookQrcodeWxworkResponseVO;
import com.pcloud.book.consumer.advsertising.AdvertisingConsr;
import com.pcloud.book.consumer.analysisengine.BrowseRecordConsr;
import com.pcloud.book.consumer.app.AppConsr;
import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.label.LabelConsr;
import com.pcloud.book.consumer.raystask.AdviserTaskConsr;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.consumer.resource.ProductConsr;
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.user.MerchantConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.es.biz.ESBookAndAdviserBiz;
import com.pcloud.book.group.biz.BookGroupBiz;
import com.pcloud.book.group.biz.ResourcePageBiz;
import com.pcloud.book.group.constant.ResourcePageConstants;
import com.pcloud.book.group.dao.BookAppletSceneDao;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dao.ResourcePageCollectDao;
import com.pcloud.book.group.dao.ResourcePageColumnDao;
import com.pcloud.book.group.dao.ResourcePageCourseDao;
import com.pcloud.book.group.dao.ResourcePageDao;
import com.pcloud.book.group.dao.ResourcePageItemDao;
import com.pcloud.book.group.dao.ResourcePageToolDao;
import com.pcloud.book.group.dao.ResourceRecomManageDao;
import com.pcloud.book.group.dto.AddBookGroupServeDTO;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.dto.BookGroupServeCountDTO;
import com.pcloud.book.group.dto.BookGroupServeDTO;
import com.pcloud.book.group.dto.BookServeDTO;
import com.pcloud.book.group.dto.ResourcePageCourseDTO;
import com.pcloud.book.group.dto.ResourcePageUrlDTO;
import com.pcloud.book.group.entity.BookAppletScene;
import com.pcloud.book.group.entity.BookGroup;
import com.pcloud.book.group.entity.BookGroupServe;
import com.pcloud.book.group.entity.ResourcePage;
import com.pcloud.book.group.entity.ResourcePageCollect;
import com.pcloud.book.group.entity.ResourcePageColumn;
import com.pcloud.book.group.entity.ResourcePageCourse;
import com.pcloud.book.group.entity.ResourcePageItem;
import com.pcloud.book.group.entity.ResourcePageTool;
import com.pcloud.book.group.entity.ResourceRecomManage;
import com.pcloud.book.group.tools.SendWeixinRequestTools;
import com.pcloud.book.group.vo.ResourceColumnAndServeVO;
import com.pcloud.book.group.vo.ResourcePageItemVO;
import com.pcloud.book.group.vo.ResourcePageOneServe;
import com.pcloud.book.group.vo.ResourcePageVO;
import com.pcloud.book.group.vo.UpdateResourceColumnVO;
import com.pcloud.book.group.vo.UpdateResourcePageVO;
import com.pcloud.book.rightsSetting.biz.RightsSettingBiz;
import com.pcloud.book.skill.biz.PcloudGroupActivityBiz;
import com.pcloud.book.util.common.ThreadPoolUtils;
import com.pcloud.book.util.common.YesOrNoEnums;
import com.pcloud.book.util.properties.BookProps;
import com.pcloud.channelcenter.qrcode.dto.BookSceneIdListDTO;
import com.pcloud.channelcenter.qrcode.dto.GroupQrcodeVO;
import com.pcloud.channelcenter.qrcode.dto.OwnMessageDTO;
import com.pcloud.channelcenter.qrcode.dto.QrcodeSceneDto;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
import com.pcloud.channelcenter.wechat.entity.AccountSetting;
import com.pcloud.channelcenter.wechat.entity.Message;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.constant.AdviserTaskConstants;
import com.pcloud.common.core.constant.ProductTypeConstant;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.BeanUtils;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.NumberUtil;
import com.pcloud.common.utils.QrcodeUtils;
import com.pcloud.common.utils.ServeLinkUtils;
import com.pcloud.common.utils.UUIDUitl;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.message.common.enums.YesNoEnums;
import com.pcloud.readercenter.userlabel.dto.UserGradeLabelIdDTO;
import com.pcloud.resourcecenter.product.dto.ProductDto;
import com.pcloud.resourcecenter.product.dto.ProductLabelDto;
import com.pcloud.usercenter.party.adviser.dto.AdviserBaseInfoDto;
import com.pcloud.wechatgroup.wxwork.dto.WxworkGroupQrcodeBaseDTO;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
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;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.qrcode.QrCodeException;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName com.pcloud.book.group.biz.impl.ResourcePageBizImpl
 * @Author zhuyajie
 * @Description 自有码H5页面
 * @Date 2021/3/26 15:57
 * @Version 1.0
 **/
@Component
@Slf4j
public class ResourcePageBizImpl implements ResourcePageBiz {

    @Autowired
    private ResourcePageDao resourcePageDao;
    @Autowired
    private ResourcePageColumnDao resourcePageColumnDao;
    @Autowired
    private ResourcePageItemDao resourcePageItemDao;
    @Autowired
    private BookGroupBiz bookGroupBiz;
    @Autowired
    private AppConsr appConsr;
    @Autowired
    private ProductConsr productConsr;
    @Autowired
    private PcloudGroupActivityBiz pcloudGroupActivityBiz;
    @Autowired
    private AppletBooklistBiz appletBooklistBiz;
    @Autowired
    private RightsSettingBiz rightsSettingBiz;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;
    @Autowired
    private BookGroupDao bookGroupDao;
    @Autowired
    private AppletThirdResourcesBiz appletThirdResourcesBiz;
    @Autowired
    private BookBiz bookBiz;
    @Autowired
    private AgentConsr agentConsr;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private BookAppletSceneDao bookAppletSceneDao;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private ResourcePageCollectDao resourcePageCollectDao;
    @Autowired
    private AdviserTaskConsr adviserTaskConsr;
    @Autowired
    private AdvertisingConsr advertisingConsr;
    @Autowired
    private ESBookAndAdviserBiz esBookAndAdviserBiz;
    @Autowired
    private ResourcePageToolDao resourcePageToolDao;
    @Autowired
    private ReaderConsr readerConsr;
    @Autowired
    private ResourcePageCourseDao resourcePageCourseDao;
    @Autowired
    private BrowseRecordConsr browseRecordConsr;
    @Autowired
    private ChannelConsr channelConsr;
    @Autowired
    private AppletGroupSearchRecordBiz appletGroupSearchRecordBiz;
    @Autowired
    private MerchantConsr merchantConsr;
    @Autowired
    private AppletRecordAggrStatisBiz appletRecordAggrStatisBiz;
    @Autowired
    private ResourceRecomManageDao resourceRecomManageDao;

    @Override
    public Long updateResourcePage(UpdateResourcePageVO updateResourcePageVO) {
        if (null == updateResourcePageVO.getBookGroupId() && null == updateResourcePageVO.getSceneId()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"参数缺失");
        }
        if (null != updateResourcePageVO.getBookGroupId()) {
           return this.updatePageByBookGroupId(updateResourcePageVO);
        } else if (null != updateResourcePageVO.getSceneId()) {
            return this.updatePageBySceneId(updateResourcePageVO);
        }
        return null;
    }

    private void checkOpenRays(Long bookId, Integer openRaysState) {
        if (openRaysState != 1) {
            return;
        }
        if (null == bookId || bookId == 0) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "二维码未关联书刊， 不能开启小睿流程");
        }
    }

    private Long updatePageBySceneId(UpdateResourcePageVO updateResourcePageVO){
        Long sceneId = updateResourcePageVO.getSceneId();
        ResourcePage resourcePage = resourcePageDao.getBySceneId(sceneId);
        updateResourcePageVO.setOpenRays(updateResourcePageVO.getOpenRays() == null ? 0 : updateResourcePageVO.getOpenRays());
        QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(sceneId);
        if (null == resourcePage) {
            resourcePage = new ResourcePage();
            BeanUtils.copyProperties(updateResourcePageVO, resourcePage);
            resourcePage.setQrcodeUrl(null == qrcodeSceneDto?null:qrcodeSceneDto.getQrcodeUrl());
            //同步bookGroupId
            if (null == resourcePage.getBookGroupId()) {
                resourcePage.setBookGroupId(getBookGroupIdBySceneId(sceneId));
            }
            resourcePage.setBookId(null == qrcodeSceneDto?null:qrcodeSceneDto.getAdviserBookId());
            resourcePage.setChannelId(null == qrcodeSceneDto?null:qrcodeSceneDto.getChannelPartyId());
            //校验能否开启小睿
            this.checkOpenRays(resourcePage.getBookId(), updateResourcePageVO.getOpenRays());
            resourcePageDao.insert(resourcePage);
        } else {
            resourcePage.setStyle(updateResourcePageVO.getStyle());
            resourcePage.setOpenRays(updateResourcePageVO.getOpenRays());
            resourcePage.setOpenFood(updateResourcePageVO.getOpenFood());
            resourcePage.setShowBook(updateResourcePageVO.getShowBook());
            resourcePage.setBookCover(updateResourcePageVO.getBookCover());
            resourcePage.setBookId(null == qrcodeSceneDto?null:qrcodeSceneDto.getAdviserBookId());
            resourcePage.setChannelId(null == qrcodeSceneDto?null:qrcodeSceneDto.getChannelPartyId());
            //同步bookGroupId
            if (null == resourcePage.getBookGroupId()) {
                resourcePage.setBookGroupId(getBookGroupIdBySceneId(sceneId));
            }
            //校验能否开启小睿
            this.checkOpenRays(resourcePage.getBookId(), updateResourcePageVO.getOpenRays());
            resourcePage.setBackgroundImg(updateResourcePageVO.getBackgroundImg());
            resourcePageDao.update(resourcePage);
        }
        if (updateResourcePageVO.getOpenRays() == 1) {
            //小程序码
            BookAppletScene appletScene = bookAppletSceneDao.getBySceneId(sceneId);
            if (null == appletScene) {
                BookAppletScene bookAppletScene = new BookAppletScene();
                bookAppletScene.setSceneId(sceneId);
                bookAppletScene.setAppletId(UUIDUitl.generateString(20));
                bookAppletScene.setAccountSettingId(BookProps.getMiniOfficialAccountsId());
                bookAppletSceneDao.insert(bookAppletScene);
            }
            //同一本书其他码下关闭小睿流程
            resourcePageDao.setOtherPageRaysClose(resourcePage.getBookId(), resourcePage.getChannelId(), resourcePage.getCreateUser(), sceneId, null);

        }
        esBookAndAdviserBiz.updateBookAndAdviserToES(Collections.singletonList(resourcePage.getBookId()));
        return resourcePage.getId();
    }

    private Long getBookGroupIdBySceneId(Long sceneId) {
        QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(sceneId);
        if (null == qrcodeSceneDto || StringUtil.isEmpty(qrcodeSceneDto.getQrcodeType())
                || StringUtil.isEmpty(qrcodeSceneDto.getSceneCode())) {
            return null;
        }
        if ("own".equalsIgnoreCase(qrcodeSceneDto.getQrcodeType())) {
            String bookGroupId = qrcodeSceneDto.getSceneCode().replace("own","").replace("OWN","");
            if (NumberUtil.isNumber(bookGroupId)) {
                return Long.valueOf(bookGroupId);
            }
        }
        return null;
    }

    private Long updatePageByBookGroupId(UpdateResourcePageVO updateResourcePageVO) {
        Long bookGroupId = updateResourcePageVO.getBookGroupId();
        ResourcePage resourcePage = resourcePageDao.getByBookGroupId(bookGroupId);
        updateResourcePageVO.setOpenRays(updateResourcePageVO.getOpenRays() == null ? 0 : updateResourcePageVO.getOpenRays());
        BookGroupDTO dto = bookGroupDao.getDTOById(bookGroupId);
        if (null == resourcePage) {
            resourcePage = new ResourcePage();
            BeanUtils.copyProperties(updateResourcePageVO, resourcePage);
            resourcePage.setQrcodeUrl(null == dto? null: dto.getGroupQrcodeUrl());
            resourcePage.setBookId(null == dto?null:dto.getBookId());
            resourcePage.setChannelId(null == dto?null:dto.getChannelId());
            //校验能否开启小睿
            this.checkOpenRays(resourcePage.getBookId(), updateResourcePageVO.getOpenRays());
            resourcePageDao.insert(resourcePage);
        } else {
            resourcePage.setStyle(updateResourcePageVO.getStyle());
            resourcePage.setOpenRays(updateResourcePageVO.getOpenRays());
            resourcePage.setShowBook(updateResourcePageVO.getShowBook());
            //校验能否开启小睿
            this.checkOpenRays(resourcePage.getBookId(), updateResourcePageVO.getOpenRays());
            resourcePage.setBookCover(updateResourcePageVO.getBookCover());
            resourcePage.setBackgroundImg(updateResourcePageVO.getBackgroundImg());
            resourcePage.setBookId(null == dto?null:dto.getBookId());
            resourcePage.setChannelId(null == dto?null:dto.getChannelId());
            resourcePageDao.update(resourcePage);
        }
        if (updateResourcePageVO.getOpenRays() == 1) {
            //小程序码
            BookAppletScene appletScene = bookAppletSceneDao.getByBookGroupId(bookGroupId);
            if (null == appletScene) {
                BookAppletScene bookAppletScene = new BookAppletScene();
                bookAppletScene.setBookGroupId(bookGroupId);
                bookAppletScene.setAppletId(UUIDUitl.generateString(20));
                bookAppletScene.setAccountSettingId(BookProps.getMiniOfficialAccountsId());
                bookAppletSceneDao.insert(bookAppletScene);
            }
            //同一本书其他码下关闭小睿流程
            resourcePageDao.setOtherPageRaysClose(resourcePage.getBookId(), resourcePage.getChannelId(), resourcePage.getCreateUser(), null, bookGroupId);
        }
        esBookAndAdviserBiz.updateBookAndAdviserToES(Collections.singletonList(resourcePage.getBookId()));
        return resourcePage.getId();
    }


    private ResourcePage createDefaultResourcePage(Long bookGroupId, Long adviserId, Long sceneId, Integer openRays) {
        ResourcePage resourcePage = new ResourcePage();
        resourcePage.setBookGroupId(bookGroupId);
        resourcePage.setStyle(1);
        resourcePage.setOpenRays(openRays);
        resourcePage.setShowBook(1);
        resourcePage.setCreateUser(adviserId);
        resourcePage.setSceneId(sceneId);
        //预览二维码,取原有二维码
        if (null != bookGroupId) {
            BookGroupDTO dto = bookGroupDao.getDTOById(bookGroupId);
            resourcePage.setQrcodeUrl(null == dto?null:dto.getGroupQrcodeUrl());
            resourcePage.setBookId(null == dto?null:dto.getBookId());
            resourcePage.setChannelId(null == dto?null:dto.getChannelId());
        } else if (null != sceneId) {
            QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(sceneId);
            resourcePage.setQrcodeUrl(null == qrcodeSceneDto?null:qrcodeSceneDto.getQrcodeUrl());
            //同步bookGroupId
            resourcePage.setBookGroupId(getBookGroupIdBySceneId(sceneId));
            resourcePage.setBookId(null == qrcodeSceneDto?null:qrcodeSceneDto.getAdviserBookId());
            resourcePage.setChannelId(null == qrcodeSceneDto?null:qrcodeSceneDto.getChannelPartyId());
        }
        resourcePageDao.insert(resourcePage);
        return resourcePage;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateResourceColumn(UpdateResourceColumnVO updateResourceColumnVO) throws BizException {
        updateResourceColumnVO.setShowMore(updateResourceColumnVO.getShowMore() == null ? false : updateResourceColumnVO.getShowMore());
        //栏目校验
        this.checkResourceColumn(updateResourceColumnVO);
        //新增修改栏目
        Long resourcePageColumnId = this.createOrUpdateColumn(updateResourceColumnVO);
        //栏目资源
        resourcePageItemDao.deleteByPageColumnId(resourcePageColumnId);
        if (ResourcePageConstants.ColumnTypeEnum.OFFICIAL_ACCOUNT.getCode().equals(updateResourceColumnVO.getColumnType())) {
            //公众号栏目
            createOfficialAccountUrl(resourcePageColumnId, updateResourceColumnVO);
            return;
        }
        //作品id
        List<Long> productIds4Shelve = updateResourceColumnVO.getItemVOList().stream().filter(s->s.getServeType().equals(ResourcePageConstants.ServeTypeEnum.PRODUCT.getValue())).map(ResourcePageItemVO::getServeId).distinct().collect(Collectors.toList());
        if (!ListUtils.isEmpty(updateResourceColumnVO.getItemVOList())) {
            List<ResourcePageItemVO> itemVOList = updateResourceColumnVO.getItemVOList();
            List<ResourcePageItem> itemList = new ArrayList<>();
            for (ResourcePageItemVO itemVO : itemVOList) {
                ResourcePageItem item = new ResourcePageItem();
                BeanUtils.copyProperties(itemVO, item);
                item.setResourcePageColumnId(resourcePageColumnId);
                item.setResourcePageId(updateResourceColumnVO.getResourcePageId());
                item.setCreateUser(updateResourceColumnVO.getCreateUser());
                //根据展示数量设置是否展示
                item.setIsShow(true);
                if (updateResourceColumnVO.getShowMore() && itemList.indexOf(item) + 1 > updateResourceColumnVO.getShowCount()) {
                    item.setIsShow(false);
                }
                //编辑书刊链接
                if (ResourcePageConstants.ServeTypeEnum.ADVISER_BOOK.getValue().equals(itemVO.getServeType())) {
                    BookLinkVO linkVO = new BookLinkVO();
                    linkVO.setBookId(itemVO.getServeId());
                    linkVO.setLinkFrom(itemVO.getLinkFrom());
                    linkVO.setLinkUrl(itemVO.getLinkUrl());
                    bookBiz.updateBookLink(linkVO, updateResourceColumnVO.getCreateUser());
                }
                //图片位
                if (ResourcePageConstants.ColumnTypeEnum.PICTURE.getCode().equals(updateResourceColumnVO.getColumnType())) {
                    item.setLogoUrl(updateResourceColumnVO.getLogoUrl());
                }
                itemList.add(item);
            }
            resourcePageItemDao.insert(itemList);
        }
        if (!ListUtils.isEmpty(productIds4Shelve)){
            //作品自动上架
            List<Long> productIds = productIds4Shelve;
            ThreadPoolUtils.OTHER_POOL.execute(()->{
               Long channelId = getChannelIdFromUrl(updateResourceColumnVO.getItemVOList().get(0).getLinkUrl());
                productConsr.productAutoOnShelves(channelId, productIds);
            });
        }
    }

    private void checkResourceColumn(UpdateResourceColumnVO updateResourceColumnVO) throws BizException {
        if (null != updateResourceColumnVO.getShowMore() && updateResourceColumnVO.getShowMore() && null == updateResourceColumnVO.getShowCount()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少展示更多数量");
        }
        if (ListUtils.isEmpty(updateResourceColumnVO.getItemVOList())) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, updateResourceColumnVO.getColumnName()+"缺少资源");
        }
        List<String> typeCodes = Arrays.asList(ResourcePageConstants.ServeTypeEnum.APP.getValue(),ResourcePageConstants.ServeTypeEnum.PRODUCT.getValue());
        for (ResourcePageItemVO itemVO : updateResourceColumnVO.getItemVOList()) {
            if (ResourcePageConstants.ServeTypeEnum.ADVISER_BOOK.getValue().equals(itemVO.getServeType()) &&
                    (null == itemVO.getLinkFrom() || StringUtil.isEmpty(itemVO.getLinkUrl()))) {
                throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少书刊链接来源");
            }
            if (!ResourcePageConstants.ServeTypeEnum.OFFICIAL_ACCOUNT.getValue().equals(itemVO.getServeType())
                    && (null == itemVO.getServeId() || StringUtil.isEmpty(itemVO.getServeType()))) {
                throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少资源id或类型");
            }
            if (typeCodes.contains(itemVO.getServeType()) && StringUtil.isEmpty(itemVO.getLinkUrl())) {
                throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少资源链接");
            }
        }
    }

    @ParamLog("新增/修改栏目")
    private Long createOrUpdateColumn(UpdateResourceColumnVO updateResourceColumnVO) {
        ResourcePageColumn resourcePageColumn = new ResourcePageColumn();
        BeanUtils.copyProperties(updateResourceColumnVO, resourcePageColumn);
        if (null == updateResourceColumnVO.getResourcePageColumnId()) {
            if (null == resourcePageColumn.getColumnSeq()) {
                Integer maxSeq = resourcePageColumnDao.getMaxSeq(updateResourceColumnVO.getResourcePageId());
                resourcePageColumn.setColumnSeq(maxSeq + 1);
            }
            resourcePageColumnDao.insert(resourcePageColumn);
        } else {
            resourcePageColumn.setId(updateResourceColumnVO.getResourcePageColumnId());
            resourcePageColumnDao.update(resourcePageColumn);
        }
        return resourcePageColumn.getId();
    }

    @ParamLog("生成公众号码")
    private void createOfficialAccountUrl(Long resourcePageColumnId, UpdateResourceColumnVO updateResourceColumnVO) {
        String qrcodeUrl;
        String url = null;
        ResourcePageItemVO itemVO = updateResourceColumnVO.getItemVOList().get(0);
        ResourcePage resourcePage = resourcePageDao.getById(updateResourceColumnVO.getResourcePageId());
        if (null == resourcePage) {
            return;
        }
        Long officialSceneId = resourcePage.getOfficialSceneId();
        if(ResourcePageConstants.QrcodeSourceEnum.OFFICIAL_ACCOUNT.value.equals(itemVO.getQrcodeSource())){
            if (null == officialSceneId) {
                officialSceneId = this.createOfficialScene(resourcePage.getBookGroupId(), resourcePage.getSceneId());
                if (null == officialSceneId) {
                    throw new BookBizException(BookBizException.ERROR, "二维码生成失败！");
                }
                resourcePage.setOfficialSceneId(officialSceneId);
                resourcePageDao.update(resourcePage);
            }
            QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(officialSceneId);
            qrcodeUrl = qrcodeSceneDto.getQrcodeUrl();
            url = qrcodeSceneDto.getUrl();
        } else {
            qrcodeUrl = itemVO.getLinkUrl();
            String tmpDirPath = FileUtil.getTmpDirPath();
            if (!tmpDirPath.endsWith(File.separator)) {
                tmpDirPath = tmpDirPath + File.separator;
            }
            File file = FileUtil.touch(tmpDirPath + UUIDUitl.generateShort() + ".png");
            HttpUtil.downloadFile(qrcodeUrl, file);
            try {
                url = QrCodeUtil.decode(file);
            } catch (QrCodeException e){
                log.info("解析二维码图片失败，qrcodeUrl：{}", qrcodeUrl);
            }
        }

        ResourcePageItem item = new ResourcePageItem();
        item.setResourcePageColumnId(resourcePageColumnId);
        item.setResourcePageId(updateResourceColumnVO.getResourcePageId());
        item.setCreateUser(updateResourceColumnVO.getCreateUser());
        item.setLogoUrl(itemVO.getLogoUrl());
        item.setGuideContent(itemVO.getGuideContent());
        item.setServeType(ResourcePageConstants.ServeTypeEnum.OFFICIAL_ACCOUNT.getValue());
        item.setSeqNum(1);
        item.setIsShow(true);
        item.setServeId(officialSceneId);
        item.setQrcodeSource(itemVO.getQrcodeSource() == null ? ResourcePageConstants.QrcodeSourceEnum.OFFICIAL_ACCOUNT.value : itemVO.getQrcodeSource());
        if (!StringUtil.isEmpty(itemVO.getLogoUrl())) {
            //生成黑白logo二维码
            try {
                qrcodeUrl = QrcodeUtils.createLogoQr(url, itemVO.getLogoUrl(), 0xFF000000, 1);
            } catch (BizException e) {
                log.error("生成黑白logo二维码失败"+e.getMessage(), e);
            }
        }
        item.setLinkUrl(qrcodeUrl);
        resourcePageItemDao.insert(item);
    }

    /**
     * 生成公众号二维码
     * @author：zhuyajie
     * @date：2021/4/13 10:14
     *  * @param null
     */
    private Long createOfficialScene(Long bookGroupId, Long sceneId) {
        if (null == bookGroupId && null == sceneId) {
            return null;
        }
        Long bookId = null;
        Long channelId = null;
        Long adviserId = null;
        if (null != bookGroupId) {
            BookGroupDTO bookGroupDTO = bookGroupDao.getDTOById(bookGroupId);
            if (null == bookGroupDTO) {
                throw new BookBizException(BookBizException.ERROR,"RAYS码不存在");
            }
            //是否创建过公众号码
            if (null != bookGroupDTO.getSceneId()) {
                return bookGroupDTO.getSceneId();
            }
            bookId = bookGroupDTO.getBookId();
            channelId = bookGroupDTO.getChannelId();
            adviserId = bookGroupDTO.getCreateUser();
        } else if (null != sceneId) {
            QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(sceneId);
            if (null == qrcodeSceneDto) {
                throw new BookBizException(BookBizException.ERROR,"自建码不存在");
            }
            bookId = qrcodeSceneDto.getAdviserBookId();
            channelId = qrcodeSceneDto.getChannelPartyId();
            adviserId = qrcodeSceneDto.getCreatedByUserLogin();
        }
        if (null != bookId && null != channelId && null != adviserId) {
            GroupQrcodeVO groupQrcodeVO = qrcodeSceneConsr.createWxGroupQrcode(bookId, channelId, adviserId);
            if (groupQrcodeVO == null) {
                throw new BookBizException(BookBizException.ERROR, "二维码生成失败！");
            }
            if (null != bookGroupId) {
                BookGroup group = new BookGroup();
                group.setId(bookGroupId);
                group.setSceneId(groupQrcodeVO.getSceneId());
                bookGroupDao.update(group);
            }
            return groupQrcodeVO.getSceneId();
        }
        return null;
    }

    @Override
    public ResourcePageVO getResourcePageByBookGroupIdOrSceneId(Long bookGroupId, Long adviserId, Long sceneId) {
        if (null == bookGroupId && null == sceneId) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"参数缺失");
        }
        ResourcePageVO resourcePageVO = new ResourcePageVO();
        if (null != bookGroupId) {
            ResourcePage resourcePage = resourcePageDao.getByBookGroupId(bookGroupId);
            if (null == resourcePage) {
                resourcePage = this.createDefaultResourcePage(bookGroupId, adviserId, null, 0);
            }
            BeanUtils.copyProperties(resourcePage, resourcePageVO);
            BookGroupDTO bookGroupDTO = bookGroupBiz.getBookInfo(bookGroupId);
            if (null != bookGroupDTO) {
                resourcePageVO.setBookImg(bookGroupDTO.getBookImg());
                resourcePageVO.setBookName(bookGroupDTO.getBookName());
                resourcePageVO.setBookCover(bookGroupDTO.getBookImg());
            }
            BookGroupDTO dto = bookGroupDao.getDTOById(bookGroupId);
            if (null != dto) {
                resourcePageVO.setBookId(dto.getBookId());
                resourcePageVO.setAdviserId(dto.getCreateUser());
                resourcePageVO.setChannelId(dto.getChannelId());
                //预览码放原有的二维码
                resourcePageVO.setQrcodeUrl(dto.getGroupQrcodeUrl());
                resourcePageVO.setQrcodeLink(dto.getGroupQrcodeLink());
            }
        } else {
            ResourcePage resourcePage = resourcePageDao.getBySceneId(sceneId);
            if (null == resourcePage) {
                resourcePage = this.createDefaultResourcePage(null, adviserId, sceneId, 0);
            }
            BeanUtils.copyProperties(resourcePage, resourcePageVO);
            QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(sceneId);
            resourcePageVO.setBookImg(qrcodeSceneDto.getBook().getCoverImg());
            resourcePageVO.setBookCover(qrcodeSceneDto.getBook().getCoverImg());
            resourcePageVO.setBookName(qrcodeSceneDto.getBook().getBookName());
            resourcePageVO.setBookId(qrcodeSceneDto.getAdviserBookId());
            resourcePageVO.setAdviserId(qrcodeSceneDto.getCreatedByUserLogin());
            resourcePageVO.setChannelId(qrcodeSceneDto.getChannelPartyId());
            //预览取原有二维码
            resourcePageVO.setQrcodeUrl(qrcodeSceneDto.getQrcodeUrl());
            resourcePageVO.setQrcodeLink(qrcodeSceneDto.getUrl());
        }
        Map<Long, AdviserBaseInfoDto> agentMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(Arrays.asList(adviserId));
        if (!MapUtils.isEmpty(agentMap)) {
            resourcePageVO.setAgentName(agentMap.get(adviserId).getAgentName());
        }
        return resourcePageVO;
    }

    @Override
    public List<ResourceColumnAndServeVO> getColumnAndServeListByPageId(Long resourcePageId, Boolean isWechat, Long bookId, Long adviserId, Long channelId, Integer enableAdverting) {
        List<ResourceColumnAndServeVO> serveVOS = resourcePageColumnDao.getColumnListByPageId(resourcePageId);
        if (CollUtil.isNotEmpty(serveVOS)) {
            List<ResourcePageItemVO> itemVOList;
            if (isWechat) {
                itemVOList = resourcePageItemDao.getResourcePageItemByPageId(resourcePageId, true);
            } else {
                itemVOList = resourcePageItemDao.getResourcePageItemByPageId(resourcePageId, null);
            }
            if (CollUtil.isNotEmpty(itemVOList)) {
                //二维码类型
                fillQrcodeType(resourcePageId, itemVOList);
                Map<String, List<ResourcePageItemVO>> listMap = itemVOList.stream().collect(Collectors.groupingBy(ResourcePageItemVO::getServeType));
                itemVOList = new ArrayList<>();
                //过滤一些资源,重新排序
                for (Map.Entry<String, List<ResourcePageItemVO>> entry : listMap.entrySet()) {
                    this.fillResourceByType(entry.getValue(), isWechat, entry.getKey());
                    itemVOList.addAll(entry.getValue());
                }
                itemVOList.sort(Comparator.comparing(ResourcePageItemVO::getId));
                Map<Long, List<ResourcePageItemVO>> columnMap = itemVOList.stream().collect(Collectors.groupingBy(ResourcePageItemVO::getResourcePageColumnId));
                for (ResourceColumnAndServeVO columnAndServeVO : serveVOS) {
                    List<ResourcePageItemVO> itemVOS = columnMap.get(columnAndServeVO.getResourcePageColumnId());
                    if (ListUtils.isEmpty(itemVOS)) {
                        continue;
                    }
                    columnAndServeVO.setItemVOList(itemVOS);
                    String serveType = itemVOS.get(0).getServeType();
                    if (ResourcePageConstants.ServeTypeEnum.APP.getValue().equals(serveType) ||
                            (ResourcePageConstants.ServeTypeEnum.PRODUCT.getValue().equals(serveType))) {
                        serveType = "APP/PRODUCT";
                    }
                    columnAndServeVO.setServeType(serveType);
                    //图片位
                    if (ResourcePageConstants.ColumnTypeEnum.PICTURE.getCode().equals(columnAndServeVO.getColumnType())) {
                        columnAndServeVO.setLogoUrl(itemVOS.get(0).getLogoUrl());
                    }
                }
            }
        }
        if(CollUtil.isEmpty(serveVOS)){
            serveVOS = CollUtil.toList();
        }
        // 填充广告
        this.fillAdvertising(serveVOS, bookId, adviserId, channelId, enableAdverting);
        return serveVOS;
    }

    /**
     * 二维码类型
     */
    private void fillQrcodeType(Long resourcePageId, List<ResourcePageItemVO> itemVOList) {
        String qrcodeType = "";
        ResourcePage resourcePage = resourcePageDao.getById(resourcePageId);
        if (null == resourcePage || ListUtils.isEmpty(itemVOList)) {
           return;
        }
        Integer jumpType = null;
        if (null != resourcePage.getBookGroupId()) {
            qrcodeType = "own";
            BookGroupDTO bookGroupDTO = bookGroupDao.getDTOById(resourcePage.getBookGroupId());
            jumpType = null == bookGroupDTO? null:bookGroupDTO.getJumpType();
        } else if (null != resourcePage.getSceneId()) {
            QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(resourcePage.getSceneId());
            qrcodeType = null == qrcodeSceneDto?"ali":qrcodeSceneDto.getQrcodeType();
        }
        for (ResourcePageItemVO itemVO:itemVOList) {
            itemVO.setQrcodeType(qrcodeType);
            itemVO.setJumpType(jumpType);
        }
    }
    /**
     * 填充广告
     */
    private void fillAdvertising(List<ResourceColumnAndServeVO> serveVOS, Long bookId, Long adviserId, Long channelId, Integer enableAdverting) {
        if(serveVOS == null || bookId == null || adviserId == null || channelId == null || !YesOrNoEnums.YES.getValue().equals(enableAdverting)){
            return;
        }
        try {
            List<AdvertisingSpaceDTO> h5Advertising = advertisingConsr.getH5Advertising(bookId, adviserId, channelId);
            if(CollUtil.isEmpty(h5Advertising)){
                return;
            }
            for (AdvertisingSpaceDTO adDto : h5Advertising) {
                List<AdvertisingSpaceItemDTO> itemList = adDto.getAdvertisingSpaceItemList();
                if(CollUtil.isEmpty(itemList)){
                    continue;
                }
                ResourceColumnAndServeVO serveVO = new ResourceColumnAndServeVO();
                serveVO.setIsAdvertising(true);
                serveVO.setColumnFormat(2); // 宽图
                serveVO.setColumnSeq(0);
                serveVO.setShowMore(YesNoEnums.NO.code);
                serveVO.setThemeStyle(adDto.getThemeStyle());
                serveVO.setAdPosition(adDto.getAdPosition());
                serveVO.setMasterId(adDto.getMasterId());
                serveVO.setAdvertisingSpaceId(adDto.getId());
                serveVO.setAdvertisingItemList(itemList);
                AdvertisingSpaceItemDTO item = itemList.get(0);
                if("H5_SERVE_RESOURCE".equalsIgnoreCase(adDto.getAdPosition())){
                    serveVO.setColumnName(item.getColumnTitle());
                    serveVO.setColumnMarker(item.getColumnMarker());
                    serveVO.setColumnSeq(getColumnSeq(item.getColumnSeq()));
                } else {
                    serveVO.setColumnName(item.getAdTitle());
                }
                serveVOS.add(serveVO);
            }
        }  catch (Exception e){
            log.error("[fillAdvertising] H5 填充广告失败，err：{}", e.getMessage(), e);
        }
    }

    private Integer getColumnSeq(Integer columnSeq) {
        if(columnSeq == null){
            return 0;
        }
        if(columnSeq == -1){
            return 9999;
        }
        return columnSeq;
    }

    @ParamLog("按类型填充资源")
    private void fillResourceByType(List<ResourcePageItemVO> itemVOS, Boolean isWechat, String serveType) {
        if (ListUtils.isEmpty(itemVOS)) {
            return;
        }
        if (ResourcePageConstants.ServeTypeEnum.APP.getValue().equals(serveType)) {
            fillAppProductServe(itemVOS, isWechat);
        } else if (ResourcePageConstants.ServeTypeEnum.PRODUCT.getValue().equals(serveType)) {
            fillAppProductServe(itemVOS, isWechat);
        } else if (ResourcePageConstants.ServeTypeEnum.OFFICIAL_ACCOUNT.getValue().equals(serveType)) {
            fillOfficialAccount(itemVOS, isWechat);
        } else if (ResourcePageConstants.ServeTypeEnum.BOOKLIST.getValue().equals(serveType)) {
            fillBooklistServe(itemVOS, isWechat);
        } else if (ResourcePageConstants.ServeTypeEnum.ADVISER_BOOK.getValue().equals(serveType)) {
            fillAdviserBook(itemVOS, isWechat);
        } else if (ResourcePageConstants.ServeTypeEnum.GROUP_ACTIVITY.getValue().equals(serveType)) {
            fillGroupServe(itemVOS, isWechat);
        } else if (ResourcePageConstants.ServeTypeEnum.THIRD_RESOURCE.getValue().equals(serveType)) {
            fillThirdResource(itemVOS, isWechat);
        } else if (ResourcePageConstants.ServeTypeEnum.WXWORK_GROUP.getValue().equals(serveType)) {
            fillWxworkGroup(itemVOS);
        }
    }

    @ParamLog("填充企业微信群")
    private void fillWxworkGroup(List<ResourcePageItemVO> itemVOS) {
        log.info("填充企业微信群");
        if (ListUtils.isEmpty(itemVOS)) {
            return;
        }
        List<Long> serveIds = itemVOS.stream().map(ResourcePageItemVO::getServeId).distinct().collect(Collectors.toList());
        Map<Long, WxworkGroupQrcodeBaseDTO> groupDtoMap = wechatGroupConsr.mapWxworkGroupQrcode(serveIds);
        List<ResourcePageItemVO> removeList = new ArrayList<>();
        for (ResourcePageItemVO itemVO : itemVOS) {
            if (MapUtils.isEmpty(groupDtoMap) || !groupDtoMap.containsKey(itemVO.getServeId())) {
                removeList.add(itemVO);
                continue;
            }
            WxworkGroupQrcodeBaseDTO wxworkGroupQrcodeBaseDTO = groupDtoMap.get(itemVO.getServeId());
            if (null == wxworkGroupQrcodeBaseDTO) {
                continue;
            }
            BookQrcodeWxworkResponseVO responseVO = new BookQrcodeWxworkResponseVO();
            responseVO.setWxworkQrcodeId(itemVO.getServeId());
            responseVO.setWxworkQrcodeType(WxworkQrcodeType.GROUP_QRCODE.getCode());
            responseVO.setWxworkQrcodeName(wxworkGroupQrcodeBaseDTO.getGroupQrcodeName());
            responseVO.setInvitationRays(wxworkGroupQrcodeBaseDTO.getInvitationRays());
            responseVO.setWxworkQrcodeUrl(wxworkGroupQrcodeBaseDTO.getGroupQrcodeUrl());
            responseVO.setGroupName(wxworkGroupQrcodeBaseDTO.getGroupQrcodeName());
            responseVO.setGroupDesc(wxworkGroupQrcodeBaseDTO.getInvitationRays());
            responseVO.setUrl(wxworkGroupQrcodeBaseDTO.getUrl());
            responseVO.setClassifyName(wxworkGroupQrcodeBaseDTO.getClassifyName());
            //头像列表从缓存里取
            List<String> headUrlList = appletGroupSearchRecordBiz.getHeadUrlList(9, itemVO.getServeId());
            responseVO.setHeadUrlList(headUrlList);
            List<AppletGroupStatementDTO> statementDTOList = appletGroupSearchRecordBiz
                    .getStatementList(9, headUrlList, itemVO.getServeId());
            responseVO.setStatementDTOList(statementDTOList);

            itemVO.setTypeName("社群");
            itemVO.setBookQrcodeWxworkResponseVO(responseVO);
        }
        itemVOS.removeAll(removeList);
    }

    @ParamLog("填充第三方资源")
    private void fillThirdResource(List<ResourcePageItemVO> itemVOS, Boolean isWechat) {
        log.info("填充第三方资源");
        if (ListUtils.isEmpty(itemVOS)) {
            return;
        }
        List<Long> serveIds = itemVOS.stream().map(ResourcePageItemVO::getServeId).distinct().collect(Collectors.toList());
        Map<Long, AppletThirdResources> resourcesMap = appletThirdResourcesBiz.getAppletMapByIds(serveIds);
        if (MapUtils.isEmpty(resourcesMap)) {
            return;
        }
        for (ResourcePageItemVO itemVO : itemVOS) {
            AppletThirdResources resources = resourcesMap.get(itemVO.getServeId());
            if (null != resources) {
                itemVO.setTypeName("第三方资源");
                itemVO.setAppletThirdResources(resources);
            }
        }
    }

    @ParamLog("填充编辑书刊链接")
    private void fillAdviserBook(List<ResourcePageItemVO> itemVOS, Boolean isWechat) {
        log.info("填充编辑书刊链接");
        if (ListUtils.isEmpty(itemVOS)) {
            return;
        }
        Long adviserId = itemVOS.get(0).getCreateUser();
        List<Long> serveIds = itemVOS.stream().map(ResourcePageItemVO::getServeId).distinct().collect(Collectors.toList());
        Map<Long, BookLinkVO> bookLinkMap = bookBiz.getBookLinkMap(adviserId, serveIds);
        if (MapUtils.isEmpty(bookLinkMap)) {
            return;
        }
        for (ResourcePageItemVO itemVO : itemVOS) {
            BookLinkVO bookLinkVO = bookLinkMap.get(itemVO.getServeId());
            if (null != bookLinkVO) {
                itemVO.setTypeName("编辑书刊");
                itemVO.setBookName(bookLinkVO.getBookName());
                itemVO.setLinkFrom(bookLinkVO.getLinkFrom());
                itemVO.setCoverImg(bookLinkVO.getCoverImg());
                itemVO.setIsbn(bookLinkVO.getIsbn());
                itemVO.setUniqueNumber(bookLinkVO.getUniqueNumber());
                itemVO.setPublish(bookLinkVO.getPublish());
            }
        }
    }

    @ParamLog("填充公众号二维码")
    private void fillOfficialAccount(List<ResourcePageItemVO> itemVOS, Boolean isWechat) {
        log.info("填充公众号二维码");
        if (ListUtils.isEmpty(itemVOS)) {
            return;
        }
        for (ResourcePageItemVO itemVO : itemVOS) {
            //带logo的二维码
            itemVO.setResultUrl(itemVO.getLinkUrl());
            itemVO.setTypeName("公众号");
            //原始二维码
            if(ResourcePageConstants.QrcodeSourceEnum.OFFICIAL_ACCOUNT.value.equals(itemVO.getQrcodeSource())){
                QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(itemVO.getServeId());
                itemVO.setLinkUrl(qrcodeSceneDto.getQrcodeUrl());
            }
        }
    }

    @ParamLog("填充应用作品")
    private void fillAppProductServe(List<ResourcePageItemVO> itemVOS, Boolean isWechat) {
        log.info("填充应用作品");
        if (ListUtils.isEmpty(itemVOS)) {
            return;
        }
        Long adviserId = itemVOS.get(0).getCreateUser();
        List<Long> appIds = new ArrayList<>();
        List<Long> productIds = new ArrayList<>();
        for (ResourcePageItemVO vo : itemVOS) {
            Long serveId = vo.getServeId();
            if (ResourcePageConstants.ServeTypeEnum.APP.getValue().equals(vo.getServeType()) && !appIds.contains(serveId)) {
                appIds.add(serveId);
            } else if (ResourcePageConstants.ServeTypeEnum.PRODUCT.getValue().equals(vo.getServeType()) && !productIds.contains(serveId)) {
                productIds.add(serveId);
            }
        }
        Map<Long, AppDto> appDtoMap = appConsr.mapBaseByIds(appIds);
        Map<Long, ProductDto> productDtoMap = productConsr.getProBasesByIds(productIds);
        Map<Long, AccountSettingDto> channelAccountSettingDtoMap = new HashMap<>();
        Map<Long, AccountSetting> accountSettingMap = new HashMap<>();
        //应用配置公众号工具
        Map<Long, Long> appOfficialAccountToolMap = new HashMap<>();
        if (isWechat) {
            appOfficialAccountToolMap = appConsr.getPayOfficialAccountsToolByAppIds(appIds);
        }
        for (ResourcePageItemVO itemVO : itemVOS) {
            Long serveId = itemVO.getServeId();
            String serveType = itemVO.getServeType();
            if (ResourcePageConstants.ServeTypeEnum.APP.getValue().equals(serveType)
                    && !MapUtils.isEmpty(appDtoMap) && appDtoMap.containsKey(serveId)) {
                AppDto appDto = appDtoMap.get(itemVO.getServeId());
                itemVO.setServeName(appDto.getTitle());
                itemVO.setServePic(appDto.getSquareImg());
                itemVO.setTypeCode(appDto.getTypeCode());
                itemVO.setTypeName(appDto.getTypeName());
                itemVO.setTransverseImg(appDto.getTransverseImg());
                itemVO.setPrice(appDto.getPrice());
                itemVO.setHasThirdLink(!StringUtil.isEmpty(appDto.getTurnUrl())?true:false);
            } else if (ResourcePageConstants.ServeTypeEnum.PRODUCT.getValue().equals(serveType)
                    && !MapUtils.isEmpty(productDtoMap) && productDtoMap.containsKey(serveId)) {
                ProductDto productDto = productDtoMap.get(itemVO.getServeId());
                itemVO.setServeName(productDto.getProductName());
                itemVO.setServePic(productDto.getCoverImg());
                if (productDto.getProductTypeDto() != null) {
                    itemVO.setTypeCode(productDto.getProductTypeDto().getTypeCode());
                    itemVO.setTypeName(productDto.getProductTypeDto().getTypeName());
                }
                if (!ListUtils.isEmpty(productDto.getSpecification())) {
                    itemVO.setPrice(productDto.getSpecification().get(0).getAdvisePrice());
                }
                itemVO.setTransverseImg(StringUtil.isEmpty(productDto.getPicture1())?
                        getDefaultBigPic(itemVO.getTypeCode()): productDto.getPicture1());
                itemVO.setHasThirdLink(!StringUtil.isEmpty(productDto.getSkipUrl())?true:false);
            } else {
                continue;
            }
            Long channelId = getChannelIdFromUrl(itemVO.getLinkUrl());
            if (null == channelId) {
                log.info(itemVO.getServeName() + "无运营平台, serveId=" + itemVO.getServeId());
                channelId = adviserConsr.getDefaultChannel(adviserId);
            }
            itemVO.setChannelId(channelId);
            if (isWechat) {
                setResourceLink4Wechat(itemVO, channelAccountSettingDtoMap, appOfficialAccountToolMap, accountSettingMap);
            }
        }
    }

    /**
     * 客户端处理链接
     * @author：zhuyajie
     * @date：2021/6/10 11:20
     *  * @param null
     */
    private void setResourceLink4Wechat(ResourcePageItemVO itemVO, Map<Long, AccountSettingDto> channelAccountSettingDtoMap,
                                        Map<Long, Long> appOfficialAccountToolMap, Map<Long, AccountSetting> accountSettingMap) {
        if (itemVO.getLinkUrl().startsWith("http")) {
            itemVO.setResultUrl(itemVO.getLinkUrl());
            return;
        }
        AccountSettingDto accountSettingDto = new AccountSettingDto();
        //有应用配了付费公众号工具,取公众号工具的公众号域名， 没有就根据渠道id取
        if (!MapUtils.isEmpty(appOfficialAccountToolMap) && appOfficialAccountToolMap.containsKey(itemVO.getServeId())) {
            Long accountSettingId = appOfficialAccountToolMap.get(itemVO.getServeId());
            AccountSetting accountSetting = accountSettingMap.get(accountSettingId);
            if (null == accountSetting) {
                accountSetting = qrcodeSceneConsr.getAppInfo(accountSettingId);
                accountSettingMap.put(accountSettingId, accountSetting);
            }
            BeanUtils.copyProperties(accountSetting, accountSettingDto);
            itemVO.setHasOfficialAccountsTool(true);

        } else {
            Long channelId = itemVO.getChannelId();
            accountSettingDto = channelAccountSettingDtoMap.get(channelId);
            if (accountSettingDto == null) {
                accountSettingDto = qrcodeSceneConsr.getWechatInfo(channelId);
                channelAccountSettingDtoMap.put(channelId, accountSettingDto);
            }
            itemVO.setHasOfficialAccountsTool(false);
        }
        if (null == accountSettingDto) {
            throw new BookBizException(BookBizException.ERROR, itemVO.getServeName() + "未设置公众号");
        }
        String resultLinkUrl = SendWeixinRequestTools.splitUrl(accountSettingDto, itemVO.getLinkUrl());
        itemVO.setResultUrl(resultLinkUrl);
    }


    private Long getChannelIdFromUrl(String url) {
        Long channelId = null;
        if (url.contains("/C")) {
            url = url.substring(url.indexOf("/C") + 2);
            url = url.substring(0, url.indexOf("/"));
            if (!StringUtil.isEmpty(url) && NumberUtil.isNumber(url)) {
                channelId = Long.valueOf(url);
            }
        }
        return channelId;
    }

    @ParamLog("填充社群")
    private void fillGroupServe(List<ResourcePageItemVO> itemVOS, Boolean isWechat) {
        log.info("填充社群");
        if (ListUtils.isEmpty(itemVOS)) {
            return;
        }
        List<ResourcePageItemVO> removeList = new ArrayList<>();
        List<Long> serveIds = itemVOS.stream().map(ResourcePageItemVO::getServeId).distinct().collect(Collectors.toList());
        Map<Long, GroupActivity4AppletDTO> groupDtoMap = pcloudGroupActivityBiz.getGroupActivityMap(serveIds);
        for (ResourcePageItemVO itemVO : itemVOS) {
            if (MapUtils.isEmpty(groupDtoMap) || !groupDtoMap.containsKey(itemVO.getServeId())) {
                removeList.add(itemVO);
                continue;
            }
            GroupActivity4AppletDTO groupActivity4AppletDTO = groupDtoMap.get(itemVO.getServeId());
            if (null == groupActivity4AppletDTO) {
                continue;
            }
            itemVO.setTypeName("社群");
            groupActivity4AppletDTO.setGroupName(groupActivity4AppletDTO.getName());
            groupActivity4AppletDTO.setGroupDesc(groupActivity4AppletDTO.getCutDesc());
            itemVO.setActivity4AppletDTO(groupActivity4AppletDTO);
            rightsSettingBiz.fillThirdGroupHeadList(groupActivity4AppletDTO);
        }
        itemVOS.removeAll(removeList);
    }

    @ParamLog("填充平台书单")
    private void fillBooklistServe(List<ResourcePageItemVO> itemVOS, Boolean isWechat) {
        log.info("填充平台书单");
        if (ListUtils.isEmpty(itemVOS)) {
            return;
        }
        List<Long> serveIds = itemVOS.stream().map(ResourcePageItemVO::getServeId).distinct().collect(Collectors.toList());
        Map<Long, AppletOuterBooklistDTO> outerBooklistDTOMap = appletBooklistBiz.getByIds(serveIds);
        if (MapUtils.isEmpty(outerBooklistDTOMap)) {
            return;
        }
        for (ResourcePageItemVO itemVO : itemVOS) {
            AppletOuterBooklistDTO outerBooklistDTO = outerBooklistDTOMap.get(itemVO.getServeId());
            if (null != outerBooklistDTO) {
                itemVO.setTypeName("平台书单");
                itemVO.setAppletOuterBooklistDTO(outerBooklistDTO);
            }
        }
    }

    @Override
    public ResourcePageVO getResourcePageByBookId(Long bookId, Long channelId, Long adviserId, Long wechatUserId) {
        ResourcePageVO resourcePageVO = new ResourcePageVO();
        ResourcePage resourcePage = resourcePageDao.getByBookId(bookId, channelId, adviserId);
        if (null != resourcePage) {
            BeanUtils.copyProperties(resourcePage, resourcePageVO);
        }
        BookDto bookDto = bookBiz.getBaseById(bookId);
        if (null != bookDto) {
            resourcePageVO.setBookImg(bookDto.getCoverImg());
            resourcePageVO.setBookName(bookDto.getBookName());
        }
        Map<Long, AdviserBaseInfoDto> agentMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(Arrays.asList(adviserId));
        if (!MapUtils.isEmpty(agentMap)) {
            resourcePageVO.setAgentName(agentMap.get(adviserId).getAgentName());
        }
        if (null != wechatUserId) {
            //查收藏状态
            Integer collectState = 0;
            if (null != resourcePageVO && null != resourcePageVO.getId()) {
                ResourcePageCollect collect = resourcePageCollectDao.getCollectRecordByUser(wechatUserId, resourcePageVO.getId());
                collectState = null == collect ? 0 : 1;
            }
            resourcePageVO.setCollectState(collectState);
        }
        if(resourcePageVO != null){
            AccountSettingDto accountSettingDto = qrcodeSceneConsr.getWechatInfo(channelId);
            if(accountSettingDto != null){
                resourcePageVO.setAccountSettingId(accountSettingDto.getAccountSettingId());
            }
            resourcePageVO.setChannelId(channelId);
        }
        return resourcePageVO;
    }


    @Override
    public PageBeanNew<ResourcePageItemVO> listPageResourcePageItem(Integer currentPage, Integer numPerPage, Long resourcePageColumnId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("resourcePageColumnId", resourcePageColumnId);
        PageBeanNew<ResourcePageItemVO> pageBeanNew = resourcePageItemDao.listPageNew(new PageParam(currentPage, numPerPage), paramMap, "getResourcePageItemByColumnId");
        if (ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, pageBeanNew.getTotalCount(), new ArrayList<>());
        }
        Map<String, List<ResourcePageItemVO>> listMap = pageBeanNew.getRecordList().stream().collect(Collectors.groupingBy(ResourcePageItemVO::getServeType));
        for (Map.Entry<String, List<ResourcePageItemVO>> entry : listMap.entrySet()) {
            fillResourceByType(entry.getValue(), true, entry.getKey());
        }
        return pageBeanNew;
    }

    @Override
    public ResourcePage getPageByBookGroupId(Long bookGroupId) {
        return resourcePageDao.getByBookGroupId(bookGroupId);
    }

    @Override
    public List<Map<String, Object>> getColumnAndServeTypeList() {
        List<Map<String, Object>> list = new ArrayList<>();
        for (ResourcePageConstants.ColumnTypeEnum columnTypeEnum : ResourcePageConstants.ColumnTypeEnum.values()) {
            Map<String, Object> map = new HashMap<>();
            map.put("code", columnTypeEnum.getCode());
            map.put("name", columnTypeEnum.getName());
            List<Map<String, Object>> serveTypeList = new ArrayList<>();
            for (String serveType : columnTypeEnum.getServes()) {
                Map<String, Object> serveTypeMap = new HashMap<>();
                serveTypeMap.put("code", serveType);
                serveTypeMap.put("name", ResourcePageConstants.ServeTypeEnum.getNameByValue(serveType));
                serveTypeList.add(serveTypeMap);
            }
            map.put("serveTypeList", serveTypeList);
            list.add(map);
        }
        return list;
    }

    @Override
    public void updateColumnSeq(Long resourcePageColumnId, String moveType) {
        ResourcePageColumn resourcePageColumn = resourcePageColumnDao.getById(resourcePageColumnId);
        if (null == resourcePageColumn) {
            throw new BookBizException(BookBizException.ERROR, "该栏目不存在！");
        }
        Long resourcePageId = resourcePageColumn.getResourcePageId();
        Integer columnSeq = resourcePageColumn.getColumnSeq();
        //获取要调换的栏目
        ResourcePageColumn column = resourcePageColumnDao.getColumByMoveType(moveType, resourcePageId, columnSeq);
        if (null == column) {
            return;
        }
        //调换序号
        resourcePageColumnDao.updateColumnSeqNum(resourcePageColumnId, column.getColumnSeq());
        resourcePageColumnDao.updateColumnSeqNum(column.getId(), columnSeq);
        // 修改该单页面的更新时间
        resourcePageDao.updatePageUpdateTime(resourcePageId);
        //同步RAYS码资源配置
        ThreadPoolUtils.OTHER_POOL.execute(()->{
            ResourcePage resourcePage = resourcePageDao.getById(resourcePageId);
            this.updateOwnMessage4Qr(null == resourcePage? null : resourcePage.getSceneId());
        });
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteColumnById(Long resourcePageColumnId) {
        ResourcePageColumn column = resourcePageColumnDao.getById(resourcePageColumnId);
        if (null == column) {
            return;
        }
        //删除资源配置
        resourcePageItemDao.deleteByPageColumnId(resourcePageColumnId);
        //删除栏目
        resourcePageColumnDao.deleteById(resourcePageColumnId);
        //栏目重新排序
        this.updateSeq4Batch(column.getResourcePageId());
        //同步RAYS码资源配置
        ThreadPoolUtils.OTHER_POOL.execute(()->{
            ResourcePage resourcePage = resourcePageDao.getPageByColumnId(resourcePageColumnId);
            this.updateOwnMessage4Qr(null == resourcePage? null : resourcePage.getSceneId());
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long updateResourcePageAndColumn(UpdateResourcePageVO updateResourcePageVO) {
        Long resourcePageId = this.updateResourcePage(updateResourcePageVO);
        if (!ListUtils.isEmpty(updateResourcePageVO.getColumnVOS())) {
            List<UpdateResourceColumnVO> list = updateResourcePageVO.getColumnVOS();
            for (UpdateResourceColumnVO columnVO : list) {
                columnVO.setResourcePageId(resourcePageId);
                columnVO.setCreateUser(updateResourcePageVO.getCreateUser());
                //栏目校验
                this.checkResourceColumn(columnVO);
            }
            for (UpdateResourceColumnVO columnVO : list) {
                this.updateResourceColumn(columnVO);
            }
        }

        // 更新图书封面
        ResourcePage page = resourcePageDao.getById(resourcePageId);
        if (StrUtil.isNotBlank(updateResourcePageVO.getBookCover()) && Objects.nonNull(page)) {
            Long bookId;
            if (Objects.nonNull(page.getBookGroupId())) {
                BookGroupDTO bookGroupDto = bookGroupDao.getDTOById(page.getBookGroupId());
                bookId = bookGroupDto.getBookId();
            } else {
                bookId = channelConsr.getBookId4SceneId(page.getSceneId());
            }
            if (bookId != null) {
                Book book = new Book();
                book.setBookId(bookId);
                book.setLastModifiedUser(updateResourcePageVO.getCreateUser());
                book.setCoverImg(updateResourcePageVO.getBookCover());
                bookBiz.updateCoverImg(book);
            }
        }

        //发送编辑任务queue
        adviserTaskConsr.sendAdviserTaskQueue(updateResourcePageVO.getCreateUser(), AdviserTaskConstants.TargetTypeEnum.QRCODE.getValue(),
                page.getBookGroupId() == null ? page.getSceneId() : page.getBookGroupId(),
                AdviserTaskConstants.OperateTypeEnum.CONFIGURE_RESOURCE.getValue());
        //同步RAYS码资源配置
        ThreadPoolUtils.OTHER_POOL.execute(()->{
            this.updateOwnMessage4Qr(updateResourcePageVO.getSceneId());
        });
        return resourcePageId;
    }

    @Override
    public ResourcePageVO getResourcePageByBookGroupIdOrSceneId4Wechat(Long bookGroupId, Long wechatUserId, Long sceneId) {
        if (null == bookGroupId && null == sceneId) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"参数缺失");
        }
        ResourcePageVO resourcePageVO = new ResourcePageVO();
        if (null != bookGroupId) {
            resourcePageVO = getResourcePageByBookGroupId4Wechat(bookGroupId, wechatUserId);
        } else if (null != sceneId) {
            resourcePageVO = getResourcePageBySceneId4Wechat(sceneId);
        }
        if (null != resourcePageVO.getId()) {
            //查收藏状态
            ResourcePageCollect collect = resourcePageCollectDao.getCollectRecordByUser(wechatUserId, resourcePageVO.getId());
            resourcePageVO.setCollectState(null == collect ? 0 : 1);
        }
        if (null != resourcePageVO.getAdviserId()) {
            resourcePageVO.setPushTextOpenStatus(qrcodeSceneConsr.getPushTextOpenStatus(resourcePageVO.getAdviserId()));
        }
        return resourcePageVO;
    }

    @ParamLog("根据bookGroupId查资源页信息")
    private ResourcePageVO getResourcePageByBookGroupId4Wechat(Long bookGroupId, Long wechatUserId) {
        ResourcePageVO resourcePageVO = new ResourcePageVO();
        resourcePageVO.setBookGroupId(bookGroupId);
        BookGroupDTO bookGroupDTO = bookGroupDao.getDTOById(bookGroupId);
        if (null != bookGroupDTO) {
            resourcePageVO.setBookId(bookGroupDTO.getBookId());
            resourcePageVO.setAdviserId(bookGroupDTO.getCreateUser());
            resourcePageVO.setChannelId(bookGroupDTO.getChannelId());
            resourcePageVO.setQrcodeName(bookGroupDTO.getGroupQrcodeName());
            resourcePageVO.setAgentName(agentConsr.getNameById(bookGroupDTO.getAgentId()));
            BookDto bookDto = bookBiz.getBaseById(bookGroupDTO.getBookId());
            if (null != bookDto) {
                resourcePageVO.setBookImg(bookDto.getCoverImg());
                resourcePageVO.setBookName(bookDto.getBookName());
            }
        }
        //上次阅读时间
        String lastTime = wechatGroupConsr.getUserLastTime(bookGroupId, wechatUserId);
        resourcePageVO.setLastReadTime(StringUtil.isEmpty(lastTime) ? DateUtils.formatDate(new Date()) : lastTime);
        //小程序
        BookAppletScene bookAppletScene = bookAppletSceneDao.getByBookGroupId(bookGroupId);
        resourcePageVO.setAppletId(null == bookAppletScene ? null : bookAppletScene.getAppletId());
        ResourcePage resourcePage = resourcePageDao.getByBookGroupId(bookGroupId);
        if (null != resourcePage) {
            resourcePageVO.setShowBook(resourcePage.getShowBook());
            resourcePageVO.setOpenRays(resourcePage.getOpenRays());
            resourcePageVO.setStyle(resourcePage.getStyle());
            resourcePageVO.setQrcodeUrl(resourcePage.getQrcodeUrl());
            resourcePageVO.setId(resourcePage.getId());
            resourcePageVO.setBookCover(resourcePage.getBookCover());
            resourcePageVO.setBackgroundImg(resourcePage.getBackgroundImg());
        }
        return resourcePageVO;
    }

    @ParamLog("根据SceneId查资源页信息")
    private ResourcePageVO getResourcePageBySceneId4Wechat(Long sceneId) {
        ResourcePageVO resourcePageVO = new ResourcePageVO();
        resourcePageVO.setSceneId(sceneId);
        QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(sceneId);
        if (null != qrcodeSceneDto) {
            resourcePageVO.setBookId(qrcodeSceneDto.getAdviserBookId());
            resourcePageVO.setAdviserId(qrcodeSceneDto.getCreatedByUserLogin());
            resourcePageVO.setChannelId(qrcodeSceneDto.getChannelPartyId());
            resourcePageVO.setBookImg(qrcodeSceneDto.getBook().getCoverImg());
            resourcePageVO.setBookName(qrcodeSceneDto.getBook().getBookName());
            resourcePageVO.setQrcodeName(qrcodeSceneDto.getSceneName());
            Long adviserId = qrcodeSceneDto.getCreatedByUserLogin();
            Map<Long, AdviserBaseInfoDto> agentMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(Arrays.asList(adviserId));
            if (!MapUtils.isEmpty(agentMap)) {
                resourcePageVO.setAgentName(agentMap.get(adviserId).getAgentName());
            }
            AccountSettingDto accountSettingDto = qrcodeSceneConsr.getWechatInfo(qrcodeSceneDto.getChannelPartyId());
            if(accountSettingDto != null){
                resourcePageVO.setAccountSettingId(accountSettingDto.getAccountSettingId());
            }
        }
        //小程序
        BookAppletScene bookAppletScene = bookAppletSceneDao.getBySceneId(sceneId);
        resourcePageVO.setAppletId(null == bookAppletScene?null:bookAppletScene.getAppletId());
        ResourcePage resourcePage = resourcePageDao.getBySceneId(sceneId);
        if (null != resourcePage) {
            resourcePageVO.setShowBook(resourcePage.getShowBook());
            resourcePageVO.setOpenRays(resourcePage.getOpenRays());
            resourcePageVO.setOpenFood(resourcePage.getOpenFood());
            resourcePageVO.setStyle(resourcePage.getStyle());
            resourcePageVO.setQrcodeUrl(resourcePage.getQrcodeUrl());
            resourcePageVO.setId(resourcePage.getId());
            resourcePageVO.setBookCover(resourcePage.getBookCover());
            resourcePageVO.setBackgroundImg(resourcePage.getBackgroundImg());
        }
        return resourcePageVO;
    }

    /**
     * 栏目重新排序
     * @author：zhuyajie
     * @date：2021/4/14 10:37
     *  * @param null
     */
    private void updateSeq4Batch(Long resourcePageId) {
        List<ResourceColumnAndServeVO> serveVOS = resourcePageColumnDao.getColumnListByPageId(resourcePageId);
        if (ListUtils.isEmpty(serveVOS)) {
            return;
        }
        for (ResourceColumnAndServeVO serveVO : serveVOS) {
            serveVO.setColumnSeq(serveVOS.indexOf(serveVO) + 1);
        }
        resourcePageColumnDao.updateSeq4Batch(serveVOS);
    }

    @Override
    public Integer getResourceCounts(Long bookId, Long adviserId, Long channelId) {
        ResourcePage resourcePage = resourcePageDao.getByBookId(bookId, channelId, adviserId);
        if (null == resourcePage) {
            return 0;
        }
        Integer count = resourcePageItemDao.getResourceCounts(resourcePage.getId());
        return count;
    }

    @Override
    public List<BookGroupServe> getServeListByBookGroupId(Long bookGroupId) {
        return resourcePageItemDao.getServeListByBookGroupId(bookGroupId);
    }

    @Override
    public void batchUpdateResourceUrl(List<Long> sceneIdList) {
        if (ListUtils.isEmpty(sceneIdList)) {
            return;
        }
        List<ResourcePageUrlDTO> itemList = resourcePageItemDao.getServeUrl4Update(sceneIdList);
        if (ListUtils.isEmpty(itemList)) {
            return;
        }
        List<ResourcePageUrlDTO> updateList = new ArrayList<>();
        for (ResourcePageUrlDTO dto : itemList) {
            if (StringUtil.isEmpty(dto.getLinkUrl())) {
                continue;
            }
            String url = dto.getLinkUrl();
            //sceneId参数不对
            if (url.contains("sceneId")) {
                String sceneParam = url.substring(url.indexOf("sceneId"));
                if (sceneParam.contains("&")) {
                    sceneParam = sceneParam.substring(0, sceneParam.indexOf("&"));
                }
                if (!StringUtil.isEmpty(sceneParam)) {
                    String newParam = "sceneId=" + dto.getSceneId();
                    url = url.replace(sceneParam, newParam);
                }
            } else {
                //不含sceneId
                if (url.contains("?")) {
                    url = url + "&sceneId=" + dto.getSceneId();
                } else {
                    url = url + "?sceneId=" + dto.getSceneId();
                }
            }
            dto.setLinkUrl(url);
            updateList.add(dto);
        }
        if (!ListUtils.isEmpty(updateList)) {
            resourcePageItemDao.batchUpdateServeUrlById(updateList);
        }
    }

    @Override
    public ResourcePageVO getResourcePageByBookIdAndChannelId(Long bookId, Long channelId) {
        ResourcePageVO resourcePageVO = new ResourcePageVO();
        ResourcePage resourcePage = resourcePageDao.getByBookId(bookId, channelId, null);
        if (null != resourcePage) {
            BeanUtils.copyProperties(resourcePage, resourcePageVO);
        }
        return resourcePageVO;
    }


    private String getDefaultBigPic(String productTypeCode) {
       if (StringUtil.isEmpty(productTypeCode)) {
           return null;
       }
       if (ProductTypeConstant.ATTENDANCE_TASK.equalsIgnoreCase(productTypeCode)) {
           return "https://oss.5rs.me/oss/uploadfe/jpg/439fc2ce08a39581591f0d51784cf1ce.jpg";
       } else if (ProductTypeConstant.QANEWS.equalsIgnoreCase(productTypeCode)) {
           return "https://file.5rs.me/oss/uploadfe/jpg/9476eaf59a23eef05e67b10fb8c3e987.jpg";
       } else if (ProductTypeConstant.SUBJECTNOTE_APP.equalsIgnoreCase(productTypeCode)) {
           return "https://oss.5rs.me/oss/uploadfe/png/7828df80a6f236f5c5534152a2371075.png";
       } else if (ProductTypeConstant.LIVE.equalsIgnoreCase(productTypeCode)) {
           return "https://oss.5rs.me/oss/uploadfe/jpg/675e741e5a40e01b9fc4dd22de6f6bc4.jpg";
       }
       return null;
    }

    @Override
    public List<BookGroupServe> getServeListByBookGroupAndSceneIds(List<Long> bookGroupIds, List<Long> sceneIds) {
        List<BookGroupServe> list = new ArrayList<>();
        List<BookGroupServe> bookGroupServeList = new ArrayList<>();
        if (!ListUtils.isEmpty(bookGroupIds)) {
            bookGroupServeList = resourcePageItemDao.getServeListByBookGroupIds(bookGroupIds);
        }
        List<BookGroupServe> sceneServeList = new ArrayList<>();
        if (!ListUtils.isEmpty(sceneIds)) {
            sceneServeList = resourcePageItemDao.getServeListBySceneIds(sceneIds);
        }
        list.addAll(ListUtils.isEmpty(bookGroupServeList) ? new ArrayList<>() : bookGroupServeList);
        list.addAll(ListUtils.isEmpty(sceneServeList) ? new ArrayList<>() : sceneServeList);
        return list;
    }

    @Override
    public ResourcePageOneServe hasOneResource(Long bookGroupId, Long sceneId) {
        ResourcePageOneServe pageOneServe = new ResourcePageOneServe();
        pageOneServe.setBookGroupId(bookGroupId);
        pageOneServe.setSceneId(sceneId);
        pageOneServe.setOneServe(false);
        ResourcePage resourcePage = null;
        if (null != bookGroupId) {
            resourcePage = resourcePageDao.getByBookGroupId(bookGroupId);
            BookGroupDTO bookGroupDTO = bookGroupDao.getDTOById(bookGroupId);
            pageOneServe.setJumpType(null == bookGroupDTO? null:bookGroupDTO.getJumpType());
            pageOneServe.setQrcodeType("own");
        } else if (null != sceneId) {
            resourcePage = resourcePageDao.getBySceneId(sceneId);
            QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(sceneId);
            pageOneServe.setQrcodeType(null == qrcodeSceneDto?"ali":qrcodeSceneDto.getQrcodeType());
        }
        if (null != resourcePage) {
            Long resourcePageId = resourcePage.getId();
            pageOneServe.setResourcePageId(resourcePageId);
            //只配置了1个应用作品，且不开启小睿
            ResourcePageItemVO itemVO = resourcePageItemDao.checkOneServeItemByPageId(resourcePageId);
            if (null != itemVO) {
                pageOneServe.setOneServe(true);
                fillAppProductServe(Arrays.asList(itemVO), true);
                pageOneServe.setServeId(itemVO.getServeId());
                pageOneServe.setServeType(itemVO.getServeType());
                pageOneServe.setLinkUrl(itemVO.getLinkUrl());
                pageOneServe.setTypeCode(itemVO.getTypeCode());
                pageOneServe.setResultUrl(itemVO.getResultUrl());
                pageOneServe.setHasThirdLink(itemVO.getHasThirdLink());
                pageOneServe.setServeName(itemVO.getServeName());
                pageOneServe.setPrice(itemVO.getPrice());
                pageOneServe.setHasOfficialAccountsTool(itemVO.getHasOfficialAccountsTool());
            }
        }
        return pageOneServe;
    }

    @Override
    public Map<Long, List<BookGroupServeDTO>> mapSceneServeList(List<Long> sceneIds) {
        Map<Long, List<BookGroupServeDTO>> map = new HashMap<>();
        if (ListUtils.isEmpty(sceneIds)) {
            return map;
        }
        List<BookGroupServe> sceneServeList = resourcePageItemDao.getServeListBySceneIds(sceneIds);
        if (ListUtils.isEmpty(sceneServeList)) {
            return map;
        }
        List<ResourcePageItemVO> itemVOS = new ArrayList<>();
        sceneServeList.stream().forEach(s->{
            ResourcePageItemVO itemVO = new ResourcePageItemVO();
            itemVO.setServeId(s.getServeId());
            itemVO.setServeType(s.getServeType());
            itemVO.setLinkUrl(s.getServeUrl());
            itemVO.setTypeCode(s.getTypeCode());
            itemVO.setSceneId(s.getSceneId());
            itemVOS.add(itemVO);
        });
        fillAppProductServe(itemVOS, false);
        List<BookGroupServeDTO> serveDTOS = new ArrayList<>();
        for (ResourcePageItemVO itemVO: itemVOS) {
            BookGroupServeDTO serveDTO = new BookGroupServeDTO();
            serveDTO.setServeId(itemVO.getServeId());
            serveDTO.setServeType(itemVO.getServeType());
            serveDTO.setServeUrl(itemVO.getLinkUrl());
            serveDTO.setTypeCode(itemVO.getTypeCode());
            serveDTO.setServeName(itemVO.getServeName());
            serveDTO.setPicUrl(itemVO.getServePic());
            serveDTO.setTransverseImg(itemVO.getTransverseImg());
            serveDTO.setTypeName(itemVO.getTypeName());
            serveDTO.setSceneId(itemVO.getSceneId());
            serveDTOS.add(serveDTO);
        }
        map = serveDTOS.stream().collect(Collectors.groupingBy(BookGroupServeDTO::getSceneId));
        return map;
    }

    @Override
    public ResourcePage getPageByOfficialScene(Long officialSceneId) {
        return resourcePageDao.getPageByOfficialScene(officialSceneId);
    }

    @Override
    public void addCollectRecord(ResourcePageCollect resourcePageCollect) {
        if (null == resourcePageCollect.getResourcePageId() || null == resourcePageCollect.getCollectState()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"缺少参数");
        }
        resourcePageCollectDao.insert(resourcePageCollect);
    }

    /**
     * 同步RAYS码资源配置
     * @author：zhuyajie
     * @date：2021/4/28 10:42
     *  * @param null
     */
    private void updateOwnMessage4Qr(Long sceneId) {
        log.info("同步RAYS码资源配置，sceneId=" + sceneId);
        if (null == sceneId) {
            return;
        }
        QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(sceneId);
        if (null == qrcodeSceneDto) {
            log.error("二维码不存在，sceneId=" + sceneId);
            return;
        }
        OwnMessageDTO ownMessageDTO = new OwnMessageDTO();
        ownMessageDTO.setAdviserId(qrcodeSceneDto.getCreatedByUserLogin());
        ownMessageDTO.setBookId(qrcodeSceneDto.getAdviserBookId());
        ownMessageDTO.setChannelId(qrcodeSceneDto.getChannelPartyId());
        ownMessageDTO.setSceneId(sceneId);
        //配置的资源
        Map<Long, List<BookGroupServeDTO>> serveList = this.mapSceneServeList(Arrays.asList(sceneId));
        List<Message> messages = new ArrayList<>();
        if (!MapUtils.isEmpty(serveList)) {
            for (BookGroupServeDTO serveDTO : serveList.get(sceneId)) {
                Message message = new Message();
                message.setFromId(serveDTO.getServeId());
                message.setFromType(serveDTO.getTypeCode());
                message.setUrl(serveDTO.getServeUrl());
                message.setCoverImg(serveDTO.getPicUrl());
                message.setPosterPicUrl(serveDTO.getTransverseImg());
                message.setTitle(serveDTO.getServeName());
                message.setShortTitle(serveDTO.getTypeName());
                message.setTypeCode(serveDTO.getServeType());
                messages.add(message);
            }
        }
        ownMessageDTO.setMessages(messages);
        qrcodeSceneConsr.updateOwnMessage4Qr(ownMessageDTO);
    }

    @Override
    public void batchAddResource(List<AddBookGroupServeDTO> list, Long adviserId) {
        if (ListUtils.isEmpty(list) || null == adviserId) {
            return;
        }
        for (AddBookGroupServeDTO bookGroupServeDTO : list) {
            this.addResource(bookGroupServeDTO, adviserId);
        }
    }

    private void addResource(AddBookGroupServeDTO addBookGroupServeDTO, Long adviserId) {
        if (null == addBookGroupServeDTO || null == addBookGroupServeDTO.getSceneId()) {
            return;
        }
        Long sceneId = addBookGroupServeDTO.getSceneId();
        ResourcePage resourcePage = resourcePageDao.getBySceneId(sceneId);
        if (null == resourcePage) {
            resourcePage = this.createDefaultResourcePage(null, adviserId, sceneId, 0);
        }
        Long resourcePageId = resourcePage.getId();
        //是否有应用栏目
        List<ResourcePageColumn> columns = resourcePageColumnDao.getByColumnTypeAndPage(resourcePageId, ResourcePageConstants.ColumnTypeEnum.APP_PRODUCT.getCode());
        ResourcePageColumn column = null;
        List<ResourcePageItemVO> itemVOS = new ArrayList<>();
        if (!ListUtils.isEmpty(columns)) {
            column = columns.get(0);
            itemVOS = resourcePageItemDao.getResourcePageItemByColumnId(column.getId());
        }
        //资源
        ResourcePageItemVO vo = new ResourcePageItemVO();
        BeanUtils.copyProperties(addBookGroupServeDTO, vo);
        vo.setLinkUrl(addBookGroupServeDTO.getServeUrl());
        vo.setSeqNum(itemVOS.size() + 1);
        itemVOS.add(vo);
        //更新栏目
        UpdateResourceColumnVO columnVO = new UpdateResourceColumnVO();
        columnVO.setColumnFormat(null == column ? 1 : column.getColumnFormat());
        columnVO.setColumnType(ResourcePageConstants.ColumnTypeEnum.APP_PRODUCT.getCode());
        columnVO.setCreateUser(adviserId);
        columnVO.setColumnName(null == column ? "本书配套资源服务" : column.getColumnName());
        columnVO.setResourcePageColumnId(null == column ? null : column.getId());
        columnVO.setItemVOList(itemVOS);
        columnVO.setResourcePageId(resourcePageId);
        columnVO.setShowMore(null == column ? false : column.getShowMore());
        columnVO.setShowCount(null == column ? null : column.getShowCount());
        this.updateResourceColumn(columnVO);
    }

    @Override
    public List<Long> getOpenRaysSceneIds(List<Long> sceneIds) {
        if (ListUtils.isEmpty(sceneIds)) {
            return new ArrayList<>();
        }
        return resourcePageDao.getOpenRaysSceneIds(sceneIds);
    }

    @Override
    public void batchUpdateSceneIdByBookGroup(List<AddBookGroupServeDTO> list) {
        if(ListUtils.isEmpty(list)) {
            return;
        }
        resourcePageDao.batchUpdateSceneIdByBookGroup(list);
    }

    @Override
    public List<Long> getSceneIdsByResourceId(Long resourceId) {
        //慎用。这个接口是给删除作品的时候用的
        //获取的同时。会删掉配置的资源。
        List<Long> result=resourcePageDao.getSceneIdsByResourceId(resourceId);
        if(CollectionUtil.isNotEmpty(result)){
            //删除配置的资源
            resourcePageItemDao.deleteByServeId(resourceId);
        }
        return result;
    }

    @Override
    public void batchUpdateBookId(List<BookSceneIdListDTO> requestDto) {
        if (ListUtils.isEmpty(requestDto)) {
            return;
        }
        List<BookSceneIdListDTO> sceneIdListDTOS = qrcodeSceneConsr.listSceneIds4Book(requestDto);
        if (ListUtils.isEmpty(sceneIdListDTOS)) {
            return;
        }
        for (BookSceneIdListDTO dto : sceneIdListDTOS) {
            List<Long> sceneIds = dto.getSceneIds();
            if (!ListUtils.isEmpty(sceneIds)) {
                resourcePageDao.updateBookBySceneIds(sceneIds, dto.getBookId(), dto.getChannelId());
            }
        }
    }

    @Override
    public List<BookServeDTO> getBookAndBookGroupServeIds(Long adviserId, Long bookId, Long channelId) {
        ResourcePage resourcePage = resourcePageDao.getByBookId(bookId, channelId, adviserId);
        if (null == resourcePage) {
            return new ArrayList<>();
        }
        List<BookServeDTO> itemVOS = resourcePageItemDao.getAppServeByPage(resourcePage.getId());
        return itemVOS;
    }

    @Override
    public List<ResourcePageTool> getToolListByUser(Long wechatUserId, Long officialAccountsId) {
        Long gradeLabel = getUserGrade(wechatUserId, officialAccountsId);
        return resourcePageToolDao.getByUserLabel(gradeLabel);
    }

    @Override
    public List<Map<String, Object>> getResourceSourceTypeList(Long wechatUserId, Long officialAccountsId) {
        Long gradeLabel = getUserGrade(wechatUserId, officialAccountsId);
        for (ResourcePageConstants.CrowdSourceEnum crowdSourceEnum : ResourcePageConstants.CrowdSourceEnum.values()) {
            List<Integer> crowdTypes = Arrays.asList(crowdSourceEnum.getCrowdTypes());
            if (crowdTypes.contains(gradeLabel.intValue())) {
                List<Map<String, Object>> list = new ArrayList<>();
                for (ResourcePageConstants.ResourceSourceTypeEnum sourceTypeEnum : crowdSourceEnum.getSourceTypes()) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("sourceType", sourceTypeEnum.getCode());
                    map.put("sourceName", sourceTypeEnum.getName());
                    list.add(map);
                }
                return list;
            }
        }
        return new ArrayList<>();
    }

    @Override
    public Long getUserGrade(Long wechatUserId, Long officialAccountsId) {
        UserGradeLabelIdDTO userGradeLabelIdDTO = readerConsr.getUserGrade(wechatUserId, officialAccountsId);
        Long gradeLabel = 1L;
        if (null != userGradeLabelIdDTO && null != userGradeLabelIdDTO.getLabelId()) {
            gradeLabel = (null == userGradeLabelIdDTO.getParentId() ||
                    userGradeLabelIdDTO.getParentId() == 0) ? userGradeLabelIdDTO.getLabelId() : userGradeLabelIdDTO.getParentId();
        }
        return gradeLabel;
    }

    @Override
    public void insertCourseStatistic() {
        List<String> typeCodes = Arrays.asList("SCHEDUE", "VIDEO_SCHEDULE", "VIDEO", "LIVE_TIMETABLE");
        List<BrowseRecordStatisticDTO> statisticDTOS = browseRecordConsr.getResourceTopIn7Day4H5(typeCodes);
        if (ListUtils.isEmpty(statisticDTOS)) {
            return;
        }
        resourcePageCourseDao.deleteAll();
        List<ResourcePageCourse> courses = new ArrayList<>();
        for (BrowseRecordStatisticDTO dto:statisticDTOS) {
            ResourcePageCourse course = new ResourcePageCourse();
            course.setServeId(dto.getBrowseId());
            course.setServeName(dto.getBrowseName());
            course.setServeType(dto.getType());
            course.setTypeCode(dto.getTypeCode());
            course.setTypeName(dto.getTypeName());
            course.setAgentId(dto.getAgencyId());
            course.setChannelId(dto.getChannelId());
            course.setProLabelId(dto.getProLableId());
            course.setDepLableId(dto.getDepLableId());
            course.setPurLabelId(dto.getPurLableId());
            course.setBrowseCount(dto.getBrowseCount());
            courses.add(course);
        }
        resourcePageCourseDao.insert(courses);
    }

    @Override
    public PageBeanNew<ResourcePageCourseDTO> listCourseByUser(Long wechatUserId, Long officialAccountsId, Integer currentPage, Integer numPerPage) {
        UserGradeLabelIdDTO userGradeLabelIdDTO = readerConsr.getUserGrade(wechatUserId, officialAccountsId);
        Long gradeLabel = null == userGradeLabelIdDTO? 11L : userGradeLabelIdDTO.getLabelId();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("userGradeLabelId", gradeLabel);
        paramMap.put("sourceFrom", ResourcePageConstants.RecommendResourceFromEnum.HOT_COURSE.getCode());
        PageBeanNew<ResourcePageCourseDTO> pageBeanNew = resourcePageCourseDao.listPageNew(new PageParam(currentPage,numPerPage), paramMap,"listCourseByGradeLabelId");
        if (ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage,numPerPage,pageBeanNew.getTotalCount(),new ArrayList<>());
        }
        List<ResourcePageCourseDTO> dtos = pageBeanNew.getRecordList();
        List<Long> appIds = new ArrayList<>();
        List<Long> productIds = new ArrayList<>();
        for (ResourcePageCourseDTO dto : dtos) {
            Long serveId = dto.getServeId();
            if (ResourcePageConstants.ServeTypeEnum.APP.getValue().equals(dto.getServeType()) && !appIds.contains(serveId)) {
                appIds.add(serveId);
            }
            if (ResourcePageConstants.ServeTypeEnum.PRODUCT.getValue().equals(dto.getServeType()) && !productIds.contains(serveId)) {
                productIds.add(serveId);
            }
        }
        Map<Long, AppDto> appDtoMap = appConsr.mapBaseByIds(appIds);
        Map<Long, ProductDto> productDtoMap = productConsr.getProBasesByIds(productIds);
        Long accountSettingId = BookProps.getOperateOfficalId();
        AccountSetting accountSetting = channelConsr.getAppInfo(accountSettingId);
        for (ResourcePageCourseDTO courseDTO : dtos) {
            Long serveId = courseDTO.getServeId();
            String serveType = courseDTO.getServeType();
            if (ResourcePageConstants.ServeTypeEnum.APP.getValue().equals(serveType)
                    && !MapUtils.isEmpty(appDtoMap) && appDtoMap.containsKey(serveId)) {
                AppDto appDto = appDtoMap.get(courseDTO.getServeId());
                if (StringUtil.isEmpty(courseDTO.getServePic())) {
                    courseDTO.setServePic(appDto.getSquareImg());
                }
                courseDTO.setTransverseImg(appDto.getTransverseImg());
                courseDTO.setProLabelName(appDto.getProLabelName());
                courseDTO.setDepLabelName(appDto.getDepLabelName());
                courseDTO.setPurLabelName(appDto.getPurLabelName());
                //跳转链接
                String turnUrl = ServeLinkUtils.getCompleteLink("APP", appDto.getTypeCode(),  appDto.getAppId().toString(),
                        appDto.getSceneCode(), appDto.getChannelId().toString(), appDto.getCreatedUser().toString(), null, accountSettingId.toString(),
                        accountSetting.getProtocol(), accountSetting.getDomain(), accountSetting.getFirstDomain(),
                        null != accountSetting.getRandom() ? accountSetting.getRandom().toString() : null);
                courseDTO.setResultUrl(turnUrl);

            } else if (ResourcePageConstants.ServeTypeEnum.PRODUCT.getValue().equals(serveType)
                    && !MapUtils.isEmpty(productDtoMap) && productDtoMap.containsKey(serveId)) {
                ProductDto productDto = productDtoMap.get(courseDTO.getServeId());
                if (StringUtil.isEmpty(courseDTO.getServePic())) {
                    courseDTO.setServePic(productDto.getCoverImg());
                }
                courseDTO.setTransverseImg(StringUtil.isEmpty(productDto.getPicture1())?
                        getDefaultBigPic(courseDTO.getTypeCode()): productDto.getPicture1());
                List<ProductLabelDto> labelDtos = productDto.getProductLabels();
                if (!ListUtils.isEmpty(labelDtos)) {
                    courseDTO.setProLabelName(labelDtos.get(0).getProLabelName());
                    courseDTO.setDepLabelName(labelDtos.get(0).getDepLabelName());
                    courseDTO.setPurLabelName(labelDtos.get(0).getPurLabelName());
                }
                //跳转链接
                String turnUrl = ServeLinkUtils.getCompleteLink("PRODUCT", courseDTO.getTypeCode(), productDto.getProductId().toString(),
                        productDto.getProductSceneCode(), courseDTO.getChannelId().toString(), null, null, accountSettingId.toString(),
                        accountSetting.getProtocol(), accountSetting.getDomain(), accountSetting.getFirstDomain(),
                        null != accountSetting.getRandom() ? accountSetting.getRandom().toString() : null);
                courseDTO.setResultUrl(turnUrl);
            }
        }
        return pageBeanNew;
    }

    @Override
    public Long getGradeByGradeLabelId(Long graLabelId) {
        return resourcePageCourseDao.getGradeByGradeLabelId(graLabelId);
    }

    @Override
    public Long getGradeByDepLabelId(Long depLabelId) {
        return resourcePageCourseDao.getGradeByDepLabelId(depLabelId);
    }

    @Override
    public Boolean isOpenRaysBook(Long bookId, Long channelId, Long adviserId) {
        return resourcePageDao.isOpenRaysBook(bookId, channelId, adviserId);
    }

    @Override
    public Map<String, Object> getUserNewState(Long wechatUserId) {
        Integer notNew = resourcePageCollectDao.getUserIsNotNew(wechatUserId);
        Boolean isNew = notNew > 0 ? false : true;
        Map<String, Object> map = new HashMap<>();
        map.put("isNew", isNew);
        return map;
    }

    @Override
    public void addNewUserRecord(ResourcePageCollect resourcePageCollect) {
        if (null == resourcePageCollect.getIsNew()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"缺少用户状态");
        }
        resourcePageCollectDao.insert(resourcePageCollect);
    }

    @Override
    public Boolean isOpenRaysScene(Long sceneId, Long bookGroupId) {
        ResourcePage resourcePage;
        if (null != sceneId) {
            resourcePage = resourcePageDao.getBySceneId(sceneId);
        } else if (null != bookGroupId) {
            resourcePage = resourcePageDao.getByBookGroupId(bookGroupId);
        } else {
            return false;
        }
        Integer openRays = (null == resourcePage || null == resourcePage.getOpenRays()) ? 0 : resourcePage.getOpenRays();
        return openRays > 0 ? true : false;
    }

    @Override
    public List<String> mapCatalogBook(List<Long> bookIds, Long adviserId) {
        List<Long> sceneIds = bookGroupDao.mapCatalogBook(bookIds,adviserId);
        if (CollUtil.isEmpty(sceneIds)) {
            return new ArrayList<>();
        }
        return channelConsr.getCatalog4SceneIds(sceneIds);
    }

    @Override
    public List<RaysSceneCatalogDto> listRaysSceneCatalogDto(List<Long> sceneIds) {
        return Optional.ofNullable(bookGroupDao.listRaysSceneCatalogDto(sceneIds)).orElse(new ArrayList<>());
    }


    @Override
    public Map<String, BookGroupServeCountDTO> mapRaysCodeServeCount(List<Long> adviserIds, List<Long> bookIds, List<Long> channelIds) {
        if(CollectionUtils.isEmpty(adviserIds) || CollectionUtils.isEmpty(bookIds) || CollectionUtils.isEmpty(channelIds)){
            return new HashMap<>();
        }
        return resourcePageDao.mapRaysCodeServeCount(adviserIds, bookIds, channelIds);
    }
    @Override
    public List<ResourcePageVO> getAllBook4OpenFood() {
        List<ResourcePageVO> resourcePageList = resourcePageDao.getAllBook4OpenFood();
        if(CollUtil.isEmpty(resourcePageList)){
            return CollUtil.toList();
        }
        List<Long> bookIds = resourcePageList.stream().map(x -> x.getBookId()).collect(Collectors.toList());
        if(CollUtil.isEmpty(bookIds)){
            return CollUtil.toList();
        }
        Map<Long, BookDto> mapBook = bookBiz.getListByIds(bookIds);
        for (ResourcePageVO vo : resourcePageList) {
            Long bookId = vo.getBookId();
            BookDto bookDto = mapBook.get(bookId);
            if(bookDto == null){
                continue;
            }
            vo.setBookName(bookDto.getBookName());
            vo.setBookImg(bookDto.getCoverImg());
        }
        return resourcePageList;
    }


    @Override
    public  Map<String, Object> hasOfficialAccountsTool(Long resourcePageId) {
        //是否有应用配了付费公众号工具
        List<Long> appIds = resourcePageItemDao.getAppIdsByPageId(resourcePageId);
        Boolean hasOfficialAccountsTool = false;
        Map<Long, Long> map = appConsr.getPayOfficialAccountsToolByAppIds(appIds);
        if (!MapUtils.isEmpty(map)) {
            hasOfficialAccountsTool = true;
        }
        Map<String, Object> result = new HashMap<>();
        result.put("hasOfficialAccountsTool", hasOfficialAccountsTool);
        return result;
    }

    @Override
    public void updateBookId(Long bookId, Long sceneId) {
        ResourcePage resourcePage = resourcePageDao.getBySceneId(sceneId);
        if (null != resourcePage) {
            resourcePageDao.updateBookIdBySceneId(bookId, sceneId);
        }
        Long bookGroupId = this.getBookGroupIdBySceneId(sceneId);
        if (null != bookGroupId) {
            bookGroupDao.updateBookIdById(bookGroupId, bookId);
        }
    }


    @Override
    public PageBeanNew listRecommendCourse4Pcloud(Integer currentPage, Integer numPerPage, String query) {
        //热门课程
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("query", query);
        paramMap.put("sourceFrom", ResourcePageConstants.RecommendResourceFromEnum.HOT_COURSE.getCode());
        PageBeanNew<ResourcePageCourseDTO> pageBeanNew = resourcePageCourseDao.listPageNew(new PageParam(currentPage,numPerPage), paramMap,"listCourse4Pcloud");
        if (ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return pageBeanNew;
        }
        fillHotCourse4Pcloud(pageBeanNew.getRecordList());
        return pageBeanNew;
    }

    @Override
    public PageBeanNew listRecommendResource4Pcloud(Integer currentPage, Integer numPerPage, String query, Integer sourceFrom) {
        if (null == sourceFrom) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"参数缺失");
        }
        if (ListUtils.isEmpty(ResourcePageConstants.RecommendResourceFromEnum.getSourceTypesByCode(sourceFrom))) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"参数有误");
        }
        //育儿宝库/搜教辅资料
        PageBeanNew  pageBeanNew = appletRecordAggrStatisBiz.getResource4H54Pcloud(currentPage, numPerPage, query, sourceFrom);
        return pageBeanNew;
    }

    @Override
    public void updateRecommendResource4Pcloud(ResourceRecomManage resourceRecomManage) {
        if (null == resourceRecomManage || null == resourceRecomManage.getSourceFrom()
                || null == resourceRecomManage.getServeId()
                || StringUtil.isEmpty(resourceRecomManage.getServeType())
                || null == resourceRecomManage.getTypeCode()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"参数缺失");
        }
        resourceRecomManageDao.deleteByServe(resourceRecomManage.getServeId(), resourceRecomManage.getServeType(),
                resourceRecomManage.getSourceFrom());
        if (null == resourceRecomManage.getShowState()) {
            resourceRecomManage.setShowState(1);
        }
        resourceRecomManageDao.insert(resourceRecomManage);
    }

    @Override
    public Map<Long, ResourceRecomManage> mapResourceRecomManage(List<Long> serveIds, String serveType, Integer sourceFrom) {
        if (ListUtils.isEmpty(serveIds) || StringUtil.isEmpty(serveType) || null == sourceFrom) {
            return new HashMap<>();
        }
        Map<Long, ResourceRecomManage> manageMap = resourceRecomManageDao.mapResourceRecomManage(serveIds, serveType, sourceFrom);
        return manageMap;
    }

    /**
     * 热门课程
     * @author：zhuyajie
     * @date：2021/7/9 15:30
     *  * @param null
     */
    private void fillHotCourse4Pcloud(List<ResourcePageCourseDTO> recordList) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        List<Long> appIds = new ArrayList<>();
        List<Long> productIds = new ArrayList<>();
        for (ResourcePageCourseDTO dto : recordList) {
            Long serveId = dto.getServeId();
            if (ResourcePageConstants.ServeTypeEnum.APP.getValue().equals(dto.getServeType()) && !appIds.contains(serveId)) {
                appIds.add(serveId);
            }
            if (ResourcePageConstants.ServeTypeEnum.PRODUCT.getValue().equals(dto.getServeType()) && !productIds.contains(serveId)) {
                productIds.add(serveId);
            }
        }
        Map<Long, AppDto> appDtoMap = appConsr.mapBaseByIds(appIds);
        List<Long> adviserIds = MapUtils.isEmpty(appDtoMap)?new ArrayList<>():appDtoMap.values().stream().map(AppDto::getCreatedUser).distinct().collect(Collectors.toList());
        Map<Long, String> adviserMap = adviserConsr.getNames(adviserIds);
        Map<Long, ProductDto> productDtoMap = productConsr.getProBasesByIds(productIds);
        List<Long> merchantIds = MapUtils.isEmpty(productDtoMap)?new ArrayList<>():productDtoMap.values().stream().map(ProductDto::getCreatedUser).distinct().collect(Collectors.toList());
        Map<Long, String> merchantMap = merchantConsr.getNamesByIdList(merchantIds);
        for (ResourcePageCourseDTO courseDTO : recordList) {
            Long serveId = courseDTO.getServeId();
            String serveType = courseDTO.getServeType();
            if (ResourcePageConstants.ServeTypeEnum.APP.getValue().equals(serveType)
                    && !MapUtils.isEmpty(appDtoMap) && appDtoMap.containsKey(serveId)) {
                AppDto appDto = appDtoMap.get(serveId);
                //平台端没给封面，取原有封面
                if (StringUtil.isEmpty(courseDTO.getServePic())) {
                    courseDTO.setServePic(appDto.getSquareImg());
                }
                courseDTO.setProLabelName(appDto.getProLabelName());
                courseDTO.setDepLabelName(appDto.getDepLabelName());
                courseDTO.setPurLabelName(appDto.getPurLabelName());
                courseDTO.setServeCreateUserId(appDto.getCreatedUser());
                //应用创建人名称
                if (!MapUtils.isEmpty(adviserMap) && adviserMap.containsKey(appDto.getCreatedUser())) {
                    courseDTO.setServeCreateUserName(adviserMap.get(appDto.getCreatedUser()));
                }
            } else if (ResourcePageConstants.ServeTypeEnum.PRODUCT.getValue().equals(serveType)
                    && !MapUtils.isEmpty(productDtoMap) && productDtoMap.containsKey(serveId)) {
                ProductDto productDto = productDtoMap.get(serveId);
                if (StringUtil.isEmpty(courseDTO.getServePic())) {
                    courseDTO.setServePic(productDto.getCoverImg());
                }
                List<ProductLabelDto> labelDtos = productDto.getProductLabels();
                if (!ListUtils.isEmpty(labelDtos)) {
                    courseDTO.setProLabelName(labelDtos.get(0).getProLabelName());
                    courseDTO.setDepLabelName(labelDtos.get(0).getDepLabelName());
                    courseDTO.setPurLabelName(labelDtos.get(0).getPurLabelName());
                }
                courseDTO.setServeCreateUserId(productDto.getCreatedUser());
                if (!MapUtils.isEmpty(merchantMap) && merchantMap.containsKey(productDto.getCreatedUser())) {
                    courseDTO.setServeCreateUserName(merchantMap.get(productDto.getCreatedUser()));
                }
            }
        }
    }
}
