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

import com.pcloud.appcenter.app.dto.AppDto;
import com.pcloud.book.applet.biz.AppletBooklistBiz;
import com.pcloud.book.applet.biz.AppletThirdResourcesBiz;
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.applet.enums.AppletRecordTypeEnum;
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.vo.BookLinkVO;
import com.pcloud.book.consumer.app.AppConsr;
import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
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.wechatgroup.WechatGroupConsr;
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.ResourcePageColumnDao;
import com.pcloud.book.group.dao.ResourcePageDao;
import com.pcloud.book.group.dao.ResourcePageItemDao;
import com.pcloud.book.group.dto.BookGroupDTO;
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.ResourcePageColumn;
import com.pcloud.book.group.entity.ResourcePageItem;
import com.pcloud.book.group.enums.QrcodeJumpType;
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.ResourcePageVO;
import com.pcloud.book.group.vo.UpdateResourceColumnVO;
import com.pcloud.book.group.vo.UpdateResourcePageVO;
import com.pcloud.book.rightsSetting.biz.RightsSettingBannerBiz;
import com.pcloud.book.rightsSetting.biz.RightsSettingBiz;
import com.pcloud.book.rightsSetting.constants.RightsSettingConstant;
import com.pcloud.book.rightsSetting.dto.RightsSettingDto;
import com.pcloud.book.rightsSetting.dto.RightsSettingQueryDTO;
import com.pcloud.book.rightsSetting.entity.RightsNowItem;
import com.pcloud.book.rightsSetting.entity.RightsSetting;
import com.pcloud.book.rightsSetting.entity.RightsSettingBanner;
import com.pcloud.book.rightsSetting.entity.RightsSettingTitle;
import com.pcloud.book.skill.biz.PcloudGroupActivityBiz;
import com.pcloud.book.util.common.ThreadPoolUtils;
import com.pcloud.book.util.properties.BookProps;
import com.pcloud.channelcenter.qrcode.dto.GroupQrcodeVO;
import com.pcloud.channelcenter.qrcode.dto.QrcodeSceneDto;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
import com.pcloud.common.core.aspect.ParamLog;
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.QrcodeUtils;
import com.pcloud.common.utils.UUIDUitl;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.resourcecenter.product.dto.ProductDto;
import com.pcloud.usercenter.party.adviser.dto.AdviserBaseInfoDto;

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.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.stream.Collectors;

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 RightsSettingBannerBiz rightsSettingBannerBiz;
    @Autowired
    private AgentConsr agentConsr;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private BookAppletSceneDao bookAppletSceneDao;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;

    @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 Long updatePageBySceneId(UpdateResourcePageVO updateResourcePageVO){
        Long sceneId = updateResourcePageVO.getSceneId();
        ResourcePage resourcePage = resourcePageDao.getBySceneId(sceneId);
        updateResourcePageVO.setOpenRays(updateResourcePageVO.getOpenRays() == null ? 0 : updateResourcePageVO.getOpenRays());
        if (null == resourcePage) {
            resourcePage = new ResourcePage();
            BeanUtils.copyProperties(updateResourcePageVO, resourcePage);
            //预览二维码
            String qrcodeLink = "https://wechat666.raysgo.com/rayh5/book?sceneId="+sceneId;
            String qrcodeUrl = QrcodeUtils.createWithMargin(qrcodeLink, 1);
            resourcePage.setQrcodeUrl(qrcodeUrl);
            resourcePageDao.insert(resourcePage);
        } else {
            resourcePage.setStyle(updateResourcePageVO.getStyle());
            resourcePage.setOpenRays(updateResourcePageVO.getOpenRays());
            resourcePage.setShowBook(updateResourcePageVO.getShowBook());
            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);
            }
        }
        return resourcePage.getId();
    }

    private Long updatePageByBookGroupId(UpdateResourcePageVO updateResourcePageVO) {
        Long bookGroupId = updateResourcePageVO.getBookGroupId();
        ResourcePage resourcePage = resourcePageDao.getByBookGroupId(bookGroupId);
        updateResourcePageVO.setOpenRays(updateResourcePageVO.getOpenRays() == null ? 0 : updateResourcePageVO.getOpenRays());
        if (null == resourcePage) {
            resourcePage = new ResourcePage();
            BeanUtils.copyProperties(updateResourcePageVO, resourcePage);
            //预览二维码
            String qrcodeLink = "https://wechat666.raysgo.com/rayh5/book?bookGroupId="+bookGroupId;
            String qrcodeUrl = QrcodeUtils.createWithMargin(qrcodeLink, 1);
            resourcePage.setQrcodeUrl(qrcodeUrl);
            resourcePageDao.insert(resourcePage);
        } else {
            resourcePage.setStyle(updateResourcePageVO.getStyle());
            resourcePage.setOpenRays(updateResourcePageVO.getOpenRays());
            resourcePage.setShowBook(updateResourcePageVO.getShowBook());
            resourcePageDao.update(resourcePage);
        }
        if (updateResourcePageVO.getOpenRays() == 1) {
            //同一本书其他码下关闭小睿流程
            BookGroupDTO bookGroupDTO = bookGroupDao.getDTOById(bookGroupId);
            if (null != bookGroupDTO) {
                Map<String, Object> paramMap = new HashMap<>();
                paramMap.put("bookId", bookGroupDTO.getBookId());
                paramMap.put("adviserId", bookGroupDTO.getCreateUser());
                paramMap.put("channelId", bookGroupDTO.getChannelId());
                paramMap.put("bookGroupId", bookGroupId);
                resourcePageDao.setRaysCloseByBook(paramMap);
            }
            //小程序码
            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);
            }
        }
        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);
        //预览二维码
        String qrcodeLink;
        if (null != bookGroupId) {
            qrcodeLink = "https://wechat666.raysgo.com/rayh5/book?bookGroupId="+bookGroupId;
        } else {
            qrcodeLink = "https://wechat666.raysgo.com/rayh5/book?sceneId="+sceneId;
        }
        resourcePageDao.insert(resourcePage);
        ThreadPoolUtils.OTHER_POOL.execute(()->{
            String qrcodeUrl = QrcodeUtils.createWithMargin(qrcodeLink, 1);
            resourcePage.setQrcodeUrl(qrcodeUrl);
            resourcePageDao.update(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;
        }
        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);
        }
    }

    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()+"缺少资源");
        }
        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或类型");
            }
        }
    }

    @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) {
        ResourcePageItemVO itemVO = updateResourceColumnVO.getItemVOList().get(0);
        ResourcePage resourcePage = resourcePageDao.getById(updateResourceColumnVO.getResourcePageId());
        if (null == resourcePage) {
            return;
        }
        Long officialSceneId = resourcePage.getOfficialSceneId();
        if (null == officialSceneId) {
            CompletableFuture<Long> sceneIdFuture = CompletableFuture.supplyAsync(() ->
                    this.createOfficialScene(resourcePage.getBookGroupId(), resourcePage.getSceneId()));
            try {
                officialSceneId = sceneIdFuture.get();
            } catch (InterruptedException |ExecutionException e) {
                throw new BookBizException(BookBizException.ERROR, "二维码生成失败！");
            }
            if (null == officialSceneId) {
                throw new BookBizException(BookBizException.ERROR, "二维码生成失败！");
            }
            resourcePage.setOfficialSceneId(officialSceneId);
            resourcePageDao.update(resourcePage);
        }
        QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(officialSceneId);
        String qrcodeUrl = qrcodeSceneDto.getQrcodeUrl();
        String url = qrcodeSceneDto.getUrl();

        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);
        if (!StringUtil.isEmpty(itemVO.getLogoUrl())) {
            //生成黑白logo二维码
            CompletableFuture<String> qrcodeFuture = CompletableFuture.supplyAsync(()->
               QrcodeUtils.createLogoQr(url, itemVO.getLogoUrl(), 0xFF000000, 1));
            try {
                qrcodeUrl = qrcodeFuture.get();
            } catch (InterruptedException |ExecutionException 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;
        BookGroupDTO bookGroupDTO = new BookGroupDTO();
        if (null != bookGroupId) {
            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 != bookGroupDTO) {
                BookGroup group = new BookGroup();
                group.setId(bookGroupDTO.getId());
                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);
            resourcePageVO.setBookImg(bookGroupDTO.getBookImg());
            resourcePageVO.setBookName(bookGroupDTO.getBookName());
        } 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.setBookName(qrcodeSceneDto.getBook().getBookName());
        }
        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) {
        List<ResourceColumnAndServeVO> serveVOS = resourcePageColumnDao.getColumnListByPageId(resourcePageId);
        if (ListUtils.isEmpty(serveVOS)) {
            return new ArrayList<>();
        }
        List<ResourcePageItemVO> itemVOList;
        if (isWechat) {
            itemVOList = resourcePageItemDao.getResourcePageItemByPageId(resourcePageId, true);
        } else {
            itemVOList = resourcePageItemDao.getResourcePageItemByPageId(resourcePageId, null);
        }
        if (ListUtils.isEmpty(itemVOList)) {
            return serveVOS;
        }
        Map<String, List<ResourcePageItemVO>> listMap = itemVOList.stream().collect(Collectors.groupingBy(ResourcePageItemVO::getServeType));
        for (Map.Entry<String, List<ResourcePageItemVO>> entry : listMap.entrySet()) {
            this.fillResourceByType(entry.getValue(), isWechat, entry.getKey());
        }
        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());
            }
        }
        return serveVOS;
    }

    @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);
        }
    }

    @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());
            //原始二维码
            QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(itemVO.getServeId());
            itemVO.setLinkUrl(qrcodeSceneDto.getQrcodeUrl());
            itemVO.setTypeName("公众号");
        }
    }

    @ParamLog("填充应用作品")
    private void fillAppProductServe(List<ResourcePageItemVO> itemVOS, Boolean isWechat) {
        log.info("填充应用作品");
        if (ListUtils.isEmpty(itemVOS)) {
            return;
        }
        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> accountSettingDtoMap = new HashMap<>();
        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());
                itemVO.setTransverseImg(productDto.getPicture1());
                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.setHasThirdLink(!StringUtil.isEmpty(productDto.getSkipUrl())?true:false);
            } else {
                continue;
            }
            Long channelId = getChannelIdFromUrl(itemVO.getLinkUrl());
            if (null == channelId) {
                throw new BookBizException(BookBizException.ERROR, itemVO.getServeName() + "无运营平台");
            }
            itemVO.setChannelId(channelId);
            if (isWechat) {
                //客户端处理链接
                if (itemVO.getLinkUrl().startsWith("http")) {
                    itemVO.setResultUrl(itemVO.getLinkUrl());
                    continue;
                }
                AccountSettingDto accountSettingDto = accountSettingDtoMap.get(channelId);
                if (accountSettingDto == null) {
                    accountSettingDto = qrcodeSceneConsr.getWechatInfo(channelId);
                    accountSettingDtoMap.put(channelId, accountSettingDto);
                }
                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)) {
                channelId = Long.valueOf(url);
            }
        }
        return channelId;
    }

    @ParamLog("填充社群")
    private void fillGroupServe(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, GroupActivity4AppletDTO> groupDtoMap = pcloudGroupActivityBiz.getGroupActivityMap(serveIds);
        if (MapUtils.isEmpty(groupDtoMap)) {
            return;
        }
        for (ResourcePageItemVO itemVO : itemVOS) {
            if (groupDtoMap.containsKey(itemVO.getServeId())) {
                GroupActivity4AppletDTO groupActivity4AppletDTO = groupDtoMap.get(itemVO.getServeId());
                itemVO.setTypeName("社群");
                itemVO.setActivity4AppletDTO(groupActivity4AppletDTO);
                rightsSettingBiz.fillThirdGroupHeadList(groupActivity4AppletDTO);
            }
        }
    }

    @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.getAdviserBook(bookId, channelId, adviserId, null);
        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());
        }
        return resourcePageVO;
    }


    @Override
    public void dealResource(List<Long> bookGroupIdList, List<Long> sceneIdList) {
        if (!ListUtils.isEmpty(bookGroupIdList)) {
            List<BookGroupDTO> list = bookGroupDao.getDTOByIds(bookGroupIdList);
            if (ListUtils.isEmpty(list)) {
                return;
            }
            for (BookGroupDTO bookGroupDTO : list) {
                Long bookGroupId = bookGroupDTO.getId();
                Long adviserId = bookGroupDTO.getCreateUser();
                Long bookId = bookGroupDTO.getBookId();
                Long channelId = bookGroupDTO.getChannelId();
                //创建资源页
                ResourcePage resourcePage = resourcePageDao.getByBookGroupId(bookGroupId);
                if (null == resourcePage) {
                    Integer openRays = QrcodeJumpType.H5_RESOURCE.getCode().equals(bookGroupDTO.getJumpType())?0:1;
                    resourcePage = this.createDefaultResourcePage(bookGroupId, adviserId, null, openRays);
                }
                Long resourcePageId = resourcePage.getId();
                this.dealResourceByBookId(bookId, adviserId, channelId, resourcePageId, bookGroupDTO.getJumpType());
            }
        }
        if (!ListUtils.isEmpty(sceneIdList)) {
            Map<Long, QrcodeSceneDto> qrcodeSceneDtoMap = qrcodeSceneConsr.listBaseInfoByIds(sceneIdList);
            if (MapUtils.isEmpty(qrcodeSceneDtoMap)) {
                return;
            }
            for (QrcodeSceneDto qrcodeSceneDto : qrcodeSceneDtoMap.values()) {
                Long sceneId = qrcodeSceneDto.getSceneId();
                Long adviserId = qrcodeSceneDto.getCreatedByUserLogin();
                Long bookId = qrcodeSceneDto.getAdviserBookId();
                Long channelId = qrcodeSceneDto.getChannelPartyId();
                //创建资源页
                ResourcePage resourcePage = resourcePageDao.getBySceneId(sceneId);
                if (null == resourcePage) {
                    BookDto bookDto = bookBiz.getAdviserBook(bookId, channelId, adviserId, null);
                    resourcePage = this.createDefaultResourcePage(null, adviserId, sceneId, bookDto.getIsOpenRobotProcess());
                }
                Long resourcePageId = resourcePage.getId();
                this.dealResourceByBookId(bookId, adviserId, channelId, resourcePageId, null);
            }
        }
    }

    private void dealResourceByBookId(Long bookId, Long adviserId, Long channelId, Long resourcePageId, Integer jumpType) {
        //权益
        Long rightsSettingId = null;
        RightsSettingDto rightsSettingDto = rightsSettingBiz.getRightsSettingByBookId4AppletHome(bookId, adviserId, channelId);
        if (null != rightsSettingDto) {
            rightsSettingId = rightsSettingDto.getId();
        }
        //大图banner-图片位
        this.dealBanner(rightsSettingId, adviserId, resourcePageId);
        //资源
        List<ResourceColumnAndServeVO> columns = resourcePageColumnDao.getColumnListByPageId(resourcePageId);
        if (ListUtils.isEmpty(columns) || (columns.size() == 1 && columns.get(0).getColumnType().equals(ResourcePageConstants.ColumnTypeEnum.PICTURE.getCode()))) {
            //1、公众号
            this.dealOfficialAccount(adviserId, resourcePageId, jumpType);
            RightsSettingQueryDTO queryDTO = new RightsSettingQueryDTO();
            queryDTO.setBookId(bookId);
            queryDTO.setAdviserId(adviserId);
            queryDTO.setChannelId(channelId);
            queryDTO.setRightsSettingId(rightsSettingId);
            queryDTO.setRightsSettingTypes(Arrays.asList(RightsSettingConstant.RIGHTSSETTING_TYPES_NEW));
            RightsSetting rightsSetting = rightsSettingBiz.getRightsSettingItemsByTypeListNew(queryDTO);
            for (RightsSettingTitle title : rightsSetting.getRightsSettingNow().getRightsSettingTitles()) {
                if (ListUtils.isEmpty(title.getRightsSettingItemList())) {
                    continue;
                }
                //创建栏目资源
                //2、应用作品
                this.dealAppProduct(title, adviserId, resourcePageId);
                //3、平台书单
                this.dealBooklist(title, adviserId, resourcePageId);
                //4、模板群
                this.dealGroup(title, adviserId, resourcePageId);
                //5、资讯-第三方资源
                this.dealNewsThirdResource(title, adviserId, resourcePageId);
            }
        }
    }

    private void dealBanner(Long rightsSettingId, Long adviserId, Long resourcePageId) {
        List<ResourcePageColumn> columns = resourcePageColumnDao.getByColumnTypeAndPage(resourcePageId, ResourcePageConstants.ColumnTypeEnum.PICTURE.getCode());
        if (!ListUtils.isEmpty(columns)) {
            return;
        }
        List<RightsSettingBanner> banners = rightsSettingBannerBiz.getByRightsSettingId(rightsSettingId);
        if (ListUtils.isEmpty(banners) || banners.size() > 1) {
            //只处理大图
            return;
        }
        RightsSettingBanner banner = banners.get(0);
        Integer bannerServeType = banner.getServeType();
        //资讯
        List<ResourcePageItemVO> itemVOList = new ArrayList<>();
        if (AppletRecordTypeEnum.NEWS.value.equals(bannerServeType)) {
            List<AppletThirdResources> thirdResourcesList = appletThirdResourcesBiz.getThirdResourcesByNewsId(banner.getServeId());
            if (!ListUtils.isEmpty(thirdResourcesList)) {
                for (AppletThirdResources resources : thirdResourcesList) {
                    ResourcePageItemVO vo = new ResourcePageItemVO();
                    vo.setServeId(resources.getId());
                    vo.setServeType(ResourcePageConstants.ServeTypeEnum.THIRD_RESOURCE.getValue());
                    vo.setSeqNum(thirdResourcesList.indexOf(resources));
                    vo.setLogoUrl(banner.getBannerPic());
                    itemVOList.add(vo);
                }
            }
        } else {
            //应用作品/第三方资源
            ResourcePageItemVO vo = new ResourcePageItemVO();
            vo.setServeId(banner.getServeId());
            if (AppletRecordTypeEnum.APP.value.equals(bannerServeType)) {
                vo.setServeType(ResourcePageConstants.ServeTypeEnum.APP.getValue());
                AppDto appDto = appConsr.getBaseById(banner.getServeId());
                vo.setTypeCode(appDto.getTypeCode());
            } else if (AppletRecordTypeEnum.PRODUCT.value.equals(bannerServeType)) {
                vo.setServeType(ResourcePageConstants.ServeTypeEnum.PRODUCT.getValue());
                ProductDto productDto = productConsr.getProBaseById(banner.getServeId());
                vo.setTypeCode(productDto.getProductTypeDto().getTypeCode());
            } else if (AppletRecordTypeEnum.THIRD_RESOURCE.value.equals(bannerServeType)) {
                vo.setServeType(ResourcePageConstants.ServeTypeEnum.THIRD_RESOURCE.getValue());
            } else {
                return;
            }
            vo.setLinkUrl(banner.getJumpUrl());
            vo.setSeqNum(1);
            vo.setLogoUrl(banner.getBannerPic());
            itemVOList.add(vo);
        }
        if (!ListUtils.isEmpty(itemVOList)) {
            UpdateResourceColumnVO columnVO = new UpdateResourceColumnVO();
            columnVO.setColumnFormat(1);
            columnVO.setColumnType(ResourcePageConstants.ColumnTypeEnum.PICTURE.getCode());
            columnVO.setCreateUser(adviserId);
            columnVO.setColumnName(banner.getBannerTitle());
            columnVO.setItemVOList(itemVOList);
            columnVO.setResourcePageId(resourcePageId);
            columnVO.setLogoUrl(banner.getBannerPic());
            this.updateResourceColumn(columnVO);
        }
    }

    private void dealNewsThirdResource(RightsSettingTitle title, Long adviserId, Long resourcePageId) {
        if ("NEWS".equals(title.getServeType())) {
            List<ResourcePageItemVO> itemVOList = new ArrayList<>();
            List<RightsNowItem> itemList = title.getRightsSettingItemList();
            for (RightsNowItem nowItem : itemList) {
                List<AppletThirdResources> thirdResourcesList = appletThirdResourcesBiz.getThirdResourcesByNewsId(nowItem.getServeId());
                if (ListUtils.isEmpty(thirdResourcesList)) {
                    continue;
                }
                for (AppletThirdResources resources : thirdResourcesList) {
                    ResourcePageItemVO vo = new ResourcePageItemVO();
                    vo.setServeId(resources.getId());
                    vo.setServeType(ResourcePageConstants.ServeTypeEnum.THIRD_RESOURCE.getValue());
                    vo.setSeqNum(itemList.indexOf(nowItem));
                    itemVOList.add(vo);
                }
            }
            if (!ListUtils.isEmpty(itemVOList)) {
                UpdateResourceColumnVO columnVO = new UpdateResourceColumnVO();
                columnVO.setColumnFormat(1);
                columnVO.setColumnType(ResourcePageConstants.ColumnTypeEnum.THIRD_RESOURCE.getCode());
                columnVO.setCreateUser(adviserId);
                columnVO.setColumnName(title.getRightsSettingTitle());
                columnVO.setItemVOList(itemVOList);
                columnVO.setResourcePageId(resourcePageId);
                if (itemVOList.size() > 4) {
                    columnVO.setShowMore(true);
                    columnVO.setShowCount(4);
                } else {
                    columnVO.setShowMore(false);
                }
                this.updateResourceColumn(columnVO);
            }
        }
    }

    private void dealGroup(RightsSettingTitle title, Long adviserId, Long resourcePageId) {
        if ("GROUP".equals(title.getServeType())) {
            List<RightsNowItem> itemList = title.getRightsSettingItemList();
            UpdateResourceColumnVO columnVO = new UpdateResourceColumnVO();
            columnVO.setColumnFormat(1);
            columnVO.setColumnType(ResourcePageConstants.ColumnTypeEnum.GROUP.getCode());
            columnVO.setCreateUser(adviserId);
            columnVO.setColumnName(title.getRightsSettingTitle());
            List<ResourcePageItemVO> itemVOList = new ArrayList<>();
            for (RightsNowItem nowItem : itemList) {
                //只处理第三方群
                if (!"1".equals(nowItem.getGroupType())) {
                    continue;
                }
                ResourcePageItemVO vo = new ResourcePageItemVO();
                vo.setServeId(nowItem.getServeId());
                vo.setServeType(ResourcePageConstants.ServeTypeEnum.GROUP_ACTIVITY.getValue());
                vo.setSeqNum(itemList.indexOf(nowItem));
                itemVOList.add(vo);
            }
            columnVO.setItemVOList(itemVOList);
            columnVO.setResourcePageId(resourcePageId);
            if (itemVOList.size() > 4) {
                columnVO.setShowMore(true);
                columnVO.setShowCount(4);
            } else {
                columnVO.setShowMore(false);
            }
            if (!ListUtils.isEmpty(itemVOList)) {
                this.updateResourceColumn(columnVO);
            }
        }
    }

    private void dealBooklist(RightsSettingTitle title, Long adviserId, Long resourcePageId) {
        if ("BOOKLIST".equals(title.getServeType())) {
            List<RightsNowItem> itemList = title.getRightsSettingItemList();
            UpdateResourceColumnVO columnVO = new UpdateResourceColumnVO();
            columnVO.setColumnFormat(1);
            columnVO.setColumnType(ResourcePageConstants.ColumnTypeEnum.BOOKLIST.getCode());
            columnVO.setCreateUser(adviserId);
            columnVO.setColumnName(title.getRightsSettingTitle());
            List<ResourcePageItemVO> itemVOList = new ArrayList<>();
            for (RightsNowItem nowItem : itemList) {
                ResourcePageItemVO vo = new ResourcePageItemVO();
                vo.setServeId(nowItem.getServeId());
                vo.setServeType(ResourcePageConstants.ServeTypeEnum.BOOKLIST.getValue());
                vo.setSeqNum(itemList.indexOf(nowItem));
                itemVOList.add(vo);
            }
            columnVO.setItemVOList(itemVOList);
            columnVO.setResourcePageId(resourcePageId);
            if (itemVOList.size() > 4) {
                columnVO.setShowMore(true);
                columnVO.setShowCount(4);
            } else {
                columnVO.setShowMore(false);
            }
            if (!ListUtils.isEmpty(itemVOList)) {
                this.updateResourceColumn(columnVO);
            }
        }
    }

    private void dealOfficialAccount(Long adviserId, Long resourcePageId, Integer jumpType) {
        if (null == jumpType) {
            return;
        }
        if (QrcodeJumpType.H5_OFFICIAL_ACCOUNTS.getCode().equals(jumpType)) {
            UpdateResourceColumnVO columnVO = new UpdateResourceColumnVO();
            columnVO.setColumnFormat(1);
            columnVO.setColumnType(ResourcePageConstants.ColumnTypeEnum.OFFICIAL_ACCOUNT.getCode());
            columnVO.setCreateUser(adviserId);
            columnVO.setColumnName("公众号");
            columnVO.setShowMore(false);
            columnVO.setResourcePageId(resourcePageId);
            columnVO.setColumnSeq(1);

            ResourcePageItemVO item = new ResourcePageItemVO();
            item.setCreateUser(adviserId);
            item.setGuideContent("关注公众号，第一时间获取本书更新动态");
            item.setServeType(ResourcePageConstants.ServeTypeEnum.OFFICIAL_ACCOUNT.getValue());
            item.setSeqNum(1);
            columnVO.setItemVOList(Arrays.asList(item));
            this.updateResourceColumn(columnVO);
        }
    }

    private void dealAppProduct(RightsSettingTitle title, Long adviserId, Long resourcePageId) {
        List<Integer> rightsSettingNowTypes = Arrays.asList(17,18,19);
        if ("APP/PRODUCT".equals(title.getServeType()) || rightsSettingNowTypes.contains(title.getRightsSettingNowType())) {
            List<RightsNowItem> itemList = title.getRightsSettingItemList();
            UpdateResourceColumnVO columnVO = new UpdateResourceColumnVO();
            columnVO.setColumnFormat(1);
            columnVO.setColumnType(ResourcePageConstants.ColumnTypeEnum.APP_PRODUCT.getCode());
            columnVO.setCreateUser(adviserId);
            columnVO.setColumnName(title.getRightsSettingTitle());
            List<ResourcePageItemVO> itemVOList = new ArrayList<>();
            for (RightsNowItem nowItem : itemList) {
                ResourcePageItemVO vo = new ResourcePageItemVO();
                vo.setLinkUrl(nowItem.getLinkUrl());
                vo.setServeId(nowItem.getServeId());
                vo.setServeType(nowItem.getServeType());
                vo.setTypeCode(nowItem.getServeTypeCode());
                vo.setSeqNum(itemList.indexOf(nowItem));
                itemVOList.add(vo);
            }
            columnVO.setItemVOList(itemVOList);
            columnVO.setResourcePageId(resourcePageId);
            if (itemVOList.size() > 4) {
                columnVO.setShowMore(true);
                columnVO.setShowCount(4);
            } else {
                columnVO.setShowMore(false);
            }
            if (!ListUtils.isEmpty(itemVOList)) {
                this.updateResourceColumn(columnVO);
            }
        }
    }

    @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);
    }

    @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());
    }

    @Override
    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);
            }
        }
        return resourcePageId;
    }

    @Override
    public ResourcePageVO getResourcePageByBookGroupIdOrSceneId4Wechat(Long bookGroupId, Long wechatUserId, Long sceneId) {
        if (null == bookGroupId && null == sceneId) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"参数缺失");
        }
        if (null != bookGroupId) {
            return getResourcePageByBookGroupId4Wechat(bookGroupId, wechatUserId);
        } else if (null != sceneId) {
            return getResourcePageBySceneId4Wechat(sceneId);
        }
        return new ResourcePageVO();
    }

    @ParamLog("根据bookGroupId查资源页信息")
    private ResourcePageVO getResourcePageByBookGroupId4Wechat(Long bookGroupId, Long wechatUserId) {
        ResourcePageVO resourcePageVO = new ResourcePageVO();
        ResourcePage resourcePage = resourcePageDao.getByBookGroupId(bookGroupId);
        if (null == resourcePage) {
            return resourcePageVO;
        }
        BeanUtils.copyProperties(resourcePage, resourcePageVO);
        BookGroupDTO bookGroupDTO = bookGroupDao.getDTOById(bookGroupId);
        if (null != bookGroupDTO) {
            resourcePageVO.setBookId(bookGroupDTO.getBookId());
            resourcePageVO.setAdviserId(bookGroupDTO.getCreateUser());
            resourcePageVO.setChannelId(bookGroupDTO.getChannelId());
            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());
        return resourcePageVO;
    }

    @ParamLog("根据SceneId查资源页信息")
    private ResourcePageVO getResourcePageBySceneId4Wechat(Long sceneId) {
        ResourcePageVO resourcePageVO = new ResourcePageVO();
        ResourcePage resourcePage = resourcePageDao.getBySceneId(sceneId);
        if (null == resourcePage) {
            return resourcePageVO;
        }
        BeanUtils.copyProperties(resourcePage, 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());
            Long adviserId = qrcodeSceneDto.getCreatedByUserLogin();
            Map<Long, AdviserBaseInfoDto> agentMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(Arrays.asList(adviserId));
            if (!MapUtils.isEmpty(agentMap)) {
                resourcePageVO.setAgentName(agentMap.get(adviserId).getAgentName());
            }
        }
        //小程序
        BookAppletScene bookAppletScene = bookAppletSceneDao.getBySceneId(sceneId);
        resourcePageVO.setAppletId(null == bookAppletScene?null:bookAppletScene.getAppletId());
        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);
    }

}
