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


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;

import com.pcloud.appcenter.app.dto.AppDto;
import com.pcloud.appcenter.app.dto.AppIdTypeDTO;
import com.pcloud.appcenter.assist.dto.AssistTempletDTO;
import com.pcloud.book.applet.biz.AppletBooklistBiz;
import com.pcloud.book.applet.biz.AppletGroupSearchRecordBiz;
import com.pcloud.book.applet.biz.AppletNewsBiz;
import com.pcloud.book.applet.biz.AppletThirdResourcesBiz;
import com.pcloud.book.applet.biz.AppletUserBookcaseBiz;
import com.pcloud.book.applet.biz.ServeCollectBiz;
import com.pcloud.book.applet.dao.AppletNewsDao;
import com.pcloud.book.applet.dao.AppletThirdResourcesDao;
import com.pcloud.book.applet.dao.AppletUserBookcaseDao;
import com.pcloud.book.applet.dto.AppletGroupStatementDTO;
import com.pcloud.book.applet.dto.AppletNewsDTO;
import com.pcloud.book.applet.dto.AppletOuterBooklistDTO;
import com.pcloud.book.applet.dto.ArticleInfoDTO;
import com.pcloud.book.applet.dto.HandleNewsDTO;
import com.pcloud.book.applet.entity.AppletNews;
import com.pcloud.book.applet.entity.AppletThirdResources;
import com.pcloud.book.applet.entity.AppletUserBookcase;
import com.pcloud.book.applet.entity.ServeCollect;
import com.pcloud.book.applet.enums.AppletRecordTypeEnum;
import com.pcloud.book.applet.mapper.AppletThirdResourcesPicMapper;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.biz.BookAdviserBiz;
import com.pcloud.book.book.biz.BookBiz;
import com.pcloud.book.book.biz.BookRaysClassifyBiz;
import com.pcloud.book.book.constant.BookConstant;
import com.pcloud.book.book.dao.BookLabelDao;
import com.pcloud.book.book.dto.BookAdviserDto;
import com.pcloud.book.book.dto.BookDto;
import com.pcloud.book.book.entity.BookLabel;
import com.pcloud.book.consumer.app.AppConsr;
import com.pcloud.book.consumer.app.AssistTempletConsr;
import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.erp.ErpConsr;
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.ChannelConsr;
import com.pcloud.book.consumer.user.PartyConsr;
import com.pcloud.book.cultivate.enums.ReadTypeEnum;
import com.pcloud.book.custom.biz.CustomPlanBiz;
import com.pcloud.book.custom.entity.CustomPlan;
import com.pcloud.book.custom.mapper.CustomPlanMapper;
import com.pcloud.book.giftcoupon.dao.GiftReceiveDao;
import com.pcloud.book.group.biz.BookGroupBiz;
import com.pcloud.book.group.biz.GroupQrcodeBiz;
import com.pcloud.book.group.biz.ResourcePageBiz;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.dto.BookServeDTO;
import com.pcloud.book.group.enums.AppAndProductTypeEnum;
import com.pcloud.book.group.enums.JoinGroupTypeEnum;
import com.pcloud.book.group.enums.QrcodeJumpType;
import com.pcloud.book.group.tools.SendWeixinRequestTools;
import com.pcloud.book.group.vo.ClassifyQrcodeVO;
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.push.dao.PersonalAppletsDao;
import com.pcloud.book.rightsSetting.biz.RightsSettingBannerBiz;
import com.pcloud.book.rightsSetting.biz.RightsSettingBiz;
import com.pcloud.book.rightsSetting.check.RightsSettingCheck;
import com.pcloud.book.rightsSetting.constants.RightsSettingConstant;
import com.pcloud.book.rightsSetting.dao.RightsCustomRelationDao;
import com.pcloud.book.rightsSetting.dao.RightsItemGroupDao;
import com.pcloud.book.rightsSetting.dao.RightsNowItemDao;
import com.pcloud.book.rightsSetting.dao.RightsNowPicDao;
import com.pcloud.book.rightsSetting.dao.RightsNowPopupDao;
import com.pcloud.book.rightsSetting.dao.RightsReadPlanDao;
import com.pcloud.book.rightsSetting.dao.RightsSettingDAO;
import com.pcloud.book.rightsSetting.dao.RightsSettingItemDao;
import com.pcloud.book.rightsSetting.dao.RightsSettingItemDetailDao;
import com.pcloud.book.rightsSetting.dto.FillRightsSettingAppletsDTO;
import com.pcloud.book.rightsSetting.dto.PopupResourceInfoDTO;
import com.pcloud.book.rightsSetting.dto.ReadTypeCountDTO;
import com.pcloud.book.rightsSetting.dto.ResourceList4Answer;
import com.pcloud.book.rightsSetting.dto.RightsSettingDto;
import com.pcloud.book.rightsSetting.dto.RightsSettingQueryDTO;
import com.pcloud.book.rightsSetting.dto.RightsSettingShowStateDTO;
import com.pcloud.book.rightsSetting.dto.ServeIdTypeDTO;
import com.pcloud.book.rightsSetting.entity.BaseTempletClassify;
import com.pcloud.book.rightsSetting.entity.RightsCustomRelation;
import com.pcloud.book.rightsSetting.entity.RightsItemGroup;
import com.pcloud.book.rightsSetting.entity.RightsNowItem;
import com.pcloud.book.rightsSetting.entity.RightsNowPic;
import com.pcloud.book.rightsSetting.entity.RightsNowPopup;
import com.pcloud.book.rightsSetting.entity.RightsReadType;
import com.pcloud.book.rightsSetting.entity.RightsSetting;
import com.pcloud.book.rightsSetting.entity.RightsSettingBanner;
import com.pcloud.book.rightsSetting.entity.RightsSettingBookRelation;
import com.pcloud.book.rightsSetting.entity.RightsSettingClassify;
import com.pcloud.book.rightsSetting.entity.RightsSettingItem;
import com.pcloud.book.rightsSetting.entity.RightsSettingItemDetail;
import com.pcloud.book.rightsSetting.entity.RightsSettingNow;
import com.pcloud.book.rightsSetting.entity.RightsSettingTitle;
import com.pcloud.book.rightsSetting.enums.RightsItemGroupType;
import com.pcloud.book.rightsSetting.enums.RightsNowItemTypeNew;
import com.pcloud.book.rightsSetting.enums.RightsNowPopupType;
import com.pcloud.book.rightsSetting.enums.RightsServeTypeEnum;
import com.pcloud.book.rightsSetting.enums.RightsSettingJumpType;
import com.pcloud.book.rightsSetting.enums.RightsTypeEnum;
import com.pcloud.book.rightsSetting.enums.RightsWeekTypeEnum;
import com.pcloud.book.rightsSetting.mapper.RightsReadTypeMapper;
import com.pcloud.book.rightsSetting.mapper.RightsSettingBookRelationMapper;
import com.pcloud.book.rightsSetting.mapper.RightsSettingTitleMapper;
import com.pcloud.book.rightsSetting.vo.QrcodeMessage4WechatVO;
import com.pcloud.book.rightsSetting.vo.WechatMessageVO;
import com.pcloud.book.skill.biz.PcloudGroupActivityBiz;
import com.pcloud.book.skill.dao.PcloudGroupActivityDao;
import com.pcloud.book.applet.dto.GroupActivity4AppletDTO;
import com.pcloud.book.util.common.YesOrNoEnums;
import com.pcloud.channelcenter.qrcode.dto.QrcodeSceneDto;
import com.pcloud.channelcenter.qrcode.vo.ServeIdTypeVO;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
import com.pcloud.common.constant.CacheConstant;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.constant.ProductTypeConstant;
import com.pcloud.common.core.constant.SystemCode;
import com.pcloud.common.enums.AppTypeEnum;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.BeanUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.NumberUtil;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.common.utils.ServeLinkUtils;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.json.JSONUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.common.utils.string.StringUtilParent;
import com.pcloud.labelcenter.label.service.LabelService;
import com.pcloud.resourcecenter.product.dto.ProductDto;
import com.pcloud.resourcecenter.product.entity.Article;
import com.pcloud.resourcecenter.product.entity.Product;
import com.pcloud.resourcecenter.product.entity.ProductLabel;
import com.pcloud.resourcecenter.product.entity.Specification;
import com.pcloud.usercenter.common.enums.SystemRoleCodeEnum;
import com.pcloud.usercenter.party.adviser.dto.AdviserBaseInfoDto;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

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.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class RightsSettingBizImpl implements RightsSettingBiz {


    @Autowired
    private RightsSettingDAO rightsSettingDAO;
    @Autowired
    private RightsSettingCheck rightsSettingCheck;
    @Autowired
    private BookLabelDao bookLabelDao;
    @Autowired
    private AssistTempletConsr assistTempletConsr;
    @Value("${system.env}")
    private String envStr;
    @Autowired
    private RightsNowItemDao rightsNowItemDao;
    @Autowired
    private RightsReadPlanDao rightsReadPlanDao;
    @Autowired
    private RightsCustomRelationDao rightsCustomRelationDao;
    @Autowired
    private RightsSettingItemDao rightsSettingItemDao;
    @Autowired
    private BookAdviserBiz bookAdviserBiz;
    @Autowired
    private AppletNewsBiz appletNewsBiz;
    @Autowired
    private ProductConsr productConsr;
    @Autowired
    private AppConsr appConsr;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;
    @Autowired
    private GiftReceiveDao giftReceiveDao;
    @Autowired
    private AppletNewsDao appletNewsDao;
    @Autowired
    private BookBiz bookBiz;
    @Autowired
    private RightsSettingTitleMapper rightsSettingTitleMapper;
    @Autowired
    private RightsItemGroupDao rightsItemGroupDao;
    @Autowired
    private BookGroupBiz bookGroupBiz;
    @Autowired
    private CustomPlanMapper customPlanMapper;
    @Autowired
    private CustomPlanBiz customPlanBiz;
    @Autowired
    private PcloudGroupActivityBiz pcloudGroupActivityBiz;
    @Autowired
    private PcloudGroupActivityDao pcloudGroupActivityDao;
    @Autowired
    private ReaderConsr readerConsr;
    @Autowired
    private RightsNowPicDao rightsNowPicDao;

    @Autowired
    private AppletGroupSearchRecordBiz appletGroupSearchRecordBiz;
    @Autowired
    private RightsSettingItemDetailDao rightsSettingItemDetailDao;
    @Autowired
    private RightsReadTypeMapper rightsReadTypeMapper;
    @Autowired
    private AppletUserBookcaseBiz appletUserBookcaseBiz;
    @Autowired
    private RightsSettingBookRelationMapper rightsSettingBookRelationMapper;
    @Autowired
    private GroupQrcodeBiz groupQrcodeBiz;
    @Autowired
    private ErpConsr erpConsr;
    @Autowired
    private BookRaysClassifyBiz bookRaysClassifyBiz;
    @Autowired
    private AppletUserBookcaseDao appletUserBookcaseDao;
    @Autowired
    private RightsSettingBiz rightsSettingBiz;
    @Autowired
    private PersonalAppletsDao personalAppletsDao;
    @Autowired
    private AppletBooklistBiz appletBooklistBiz;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private ServeCollectBiz serveCollectBiz;
    @Autowired
    private RightsNowPopupDao rightsNowPopupDao;
    @Autowired
    private AppletThirdResourcesDao appletThirdResourcesDao;
    @Autowired
    private BookGroupDao bookGroupDao;
    @Autowired
    private LabelService labelService;
    @Autowired
    private PartyConsr partyConsr;
    @Autowired
    private ChannelConsr channelConsr;
    @Autowired
    private RightsSettingBannerBiz rightsSettingBannerBiz;
    @Autowired
    private AppletThirdResourcesBiz appletThirdResourcesBiz;
    @Autowired
    private AppletThirdResourcesPicMapper appletThirdResourcesPicMapper;
    @Autowired
    private ResourcePageBiz resourcePageBiz;

    @Override
    @ParamLog("新增权益设置")
    @Transactional(rollbackFor = Exception.class)
    public Long addRightsSetting(RightsSetting rightsSetting) {
        rightsSettingCheck.rightsSettingCheck4Insert(rightsSetting);
        setClassifyAndLabel(rightsSetting);
        setGuide(rightsSetting);
        if (existCheck(rightsSetting) > 0) {
            throw new BookBizException(BookBizException.ERROR, "已存在相同的权益设置");
        }
        rightsSettingDAO.insert(rightsSetting);
        Long rightsSettingId = rightsSetting.getId();
        if (null == rightsSettingId) {
            throw new BookBizException(BookBizException.DB_DML_FAIL, "新增权益设置失败");
        }
        //新增banner图
        if (!ListUtils.isEmpty(rightsSetting.getRightsSettingBanners())) {
            rightsSetting.getRightsSettingBanners().stream().forEach(e -> e.setRightsSettingId(rightsSettingId));
            rightsSettingBannerBiz.batchInsert(rightsSetting.getRightsSettingBanners());
        }
        //新增关联书刊
        List<RightsSettingBookRelation> rightsSettingBookRelations = rightsSetting.getRightsSettingBookRelations();
        if (ListUtils.isEmpty(rightsSettingBookRelations)) {
            return rightsSettingId;
        }
        rightsSettingBookRelations.forEach(e -> e.setRightsSettingId(rightsSettingId));
        rightsSettingBookRelationMapper.batchInsert(rightsSettingBookRelations);
        return rightsSetting.getId();
    }

    @Override
    public void setClassifyAndLabel(BaseTempletClassify baseTempletClassify) {
      log.info("对于某些特殊分类做处理");
      if (null == baseTempletClassify || null == baseTempletClassify.getFirstClassify()) {
          return;
      }
        Boolean contain4K12 = false;
        if (ArrayUtils.contains(RightsSettingConstant.K12_TEMPLET_ID_NEW, baseTempletClassify.getFirstClassify())) {
            contain4K12 = true;
        }
        if (!contain4K12) {
            baseTempletClassify.setGradeLabelId(null);
            baseTempletClassify.setSubjectLabelId(null);
            baseTempletClassify.setVolLabelId(null);
            baseTempletClassify.setVerLabelId(null);
        }
    }

    /**
     * 校验权益是否存在
     *
     * @param rightsSetting
     */
    public Integer existCheck(RightsSetting rightsSetting) {
        Integer count = 0;
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("rightsSettingType", rightsSetting.getRightsSettingType());
        paramMap.put("exceptId", rightsSetting.getId());
        if (rightsSetting.getRightsSettingType() == 2) {
            List<Long> bookIds = new ArrayList<>();
            if (!ListUtils.isEmpty(rightsSetting.getRightsSettingBookRelations())) {
                bookIds = rightsSetting.getRightsSettingBookRelations().stream().map(e -> e.getBookId()).collect(Collectors.toList());
            }
            if (!ListUtils.isEmpty(bookIds)) {
                paramMap.put("bookIds", bookIds);
            }
        } else if (rightsSetting.getRightsSettingType() == 1) {
            setClassifyAndLabel(rightsSetting);
            paramMap.put("firstClassify", rightsSetting.getFirstClassify());
            paramMap.put("secondClassify", rightsSetting.getSecondClassify());
            paramMap.put("thirdClassify", rightsSetting.getThirdClassify());
            paramMap.put("gradeLabelId", rightsSetting.getGradeLabelId());
            paramMap.put("subjectLabelId", rightsSetting.getSubjectLabelId());
            paramMap.put("volLabelId", rightsSetting.getVolLabelId());
            paramMap.put("verLabelId", rightsSetting.getVerLabelId());
        }
        if (!StringUtil.isEmpty(rightsSetting.getRightsNumber())) {
            RightsSetting exit = rightsSettingDAO.selctByNumber(rightsSetting.getRightsNumber(),rightsSetting.getRightsSettingType());
            if (exit != null && exit.getId() != null) {
                if (rightsSetting.getId() == null || Long.compare(exit.getId(), rightsSetting.getId()) != 0) {
                    throw new BookBizException(BookBizException.ERROR, "编号已存在");
                }
            }
        }
        List<RightsSettingDto> list = rightsSettingDAO.listRightsSettingPage(paramMap);
        count = list.size();
        return count;
    }

    @Override
    @ParamLog("删除权益设置")
    @Transactional(rollbackFor = Exception.class)
    public void deleteRightsSetting(Long id) {
        rightsSettingDAO.deleteByPrimaryKey(id);
        rightsReadTypeMapper.deleteByRightsSettingId(id);
        //删除即享权益项
        rightsNowItemDao.deleteByRightsSettingId(id);
        rightsSettingItemDao.deleteByRightsSettingId(id, null);
        rightsItemGroupDao.deleteByRightsSettingId(id);
        rightsSettingBookRelationMapper.deleteByRightsSettingId(id);
    }

    @Override
    @ParamLog("更新权益设置")
    @Transactional(rollbackFor = Exception.class)
    public void updateRightsSetting(RightsSetting rightsSetting) {
        //处理前端传过来的数据
        handleRightsSetting4Sort(rightsSetting);
        rightsSettingCheck.rightsSettingCheck(rightsSetting);
        if (null == rightsSetting.getId()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少id！");
        }
        Long rightsSettingId = rightsSetting.getId();
        if (Objects.equals(RightsTypeEnum.BASE.code, rightsSetting.getStepType())) {
            //更新基本信息
            updateRightsSettingBase(rightsSetting, rightsSettingId);
        } else if (Objects.equals(RightsTypeEnum.NOW.code, rightsSetting.getStepType())) {
            //更新即享权益
            updateRightNowItemByRightId(rightsSetting);
            rightsSettingDAO.updateUser(rightsSetting);
        } else if (Objects.equals(RightsTypeEnum.WEEK.code, rightsSetting.getStepType())) {
            // 更新每周、长期权益
            updateRightsWeek(rightsSetting);
            rightsSettingDAO.updateUser(rightsSetting);
        } else if (Objects.equals(RightsTypeEnum.LONG_TERM.code, rightsSetting.getStepType())) {
            // 更新每周、长期权益
            updateRightsLongTerm(rightsSetting);
            rightsSettingDAO.updateUser(rightsSetting);
        }else if (Objects.equals(RightsTypeEnum.UP_NUMBER.code, rightsSetting.getStepType())) {
            // 更新每周、长期权益
            updateNumber(rightsSetting);
            rightsSettingDAO.updateUser(rightsSetting);
        }
    }

    private void updateNumber(RightsSetting rightsSetting) {
        if (!StringUtil.isEmpty(rightsSetting.getRightsNumber())){
            RightsSetting exit = rightsSettingDAO.selctByNumber(rightsSetting.getRightsNumber(),rightsSetting.getRightsSettingType());
            if (exit != null && exit.getId() != null) {
                if (rightsSetting.getId() == null || Long.compare(exit.getId(), rightsSetting.getId()) != 0) {
                    throw new BookBizException(BookBizException.ERROR, "编号已存在");
                }
            }
        }
        rightsSettingDAO.updateNumber(rightsSetting.getId(),rightsSetting.getRightsNumber());
    }

    private void handleRightsSetting4Sort(RightsSetting rightsSetting) {
        RightsSettingNow rightsSettingNow = rightsSetting.getRightsSettingNow();
        if(null != rightsSettingNow && !ListUtils.isEmpty(rightsSettingNow.getNewRightsSettingTitles())){
            List<RightsSettingTitle> newRightsSettingTitles= rightsSettingNow.getNewRightsSettingTitles();
            Integer servesTitleType = 1;
            List<RightsSettingTitle> rightsSettingTitles = new ArrayList<>();

            if (!ListUtils.isEmpty(newRightsSettingTitles)){
                newRightsSettingTitles.stream().forEach(
                        rightsSettingTitle -> {
                            if (servesTitleType.intValue() == rightsSettingTitle.getRightsSettingNowType().intValue()) {
                                rightsSettingNow.setServesTitle(rightsSettingTitle);
                            } else {
                                rightsSettingTitles.add(rightsSettingTitle);
                            }
                        }
                );
            }
            rightsSettingNow.setRightsSettingTitles(rightsSettingTitles);
        }
    }

    private void updateRightsSettingBase(RightsSetting rightsSetting, Long rightsSettingId) {
        setClassifyAndLabel(rightsSetting);
        rightsSetting.setUpdateTime(new Date());
        if (existCheck(rightsSetting) > 0) {
            throw new BookBizException(BookBizException.ERROR, "已存在相同的权益设置");
        }
        //设置读书引导
        setGuide(rightsSetting);
        rightsSettingDAO.updateByPrimaryKey(rightsSetting);
        if (!ListUtils.isEmpty(rightsSetting.getRightsSettingBanners())) {
            rightsSetting.getRightsSettingBanners().forEach(e -> e.setRightsSettingId(rightsSettingId));
        }
        rightsSettingBannerBiz.deleteByRightsSettingId(rightsSettingId);
        rightsSettingBannerBiz.batchInsert(rightsSetting.getRightsSettingBanners());
        //更新关联书刊
        updateRelationBook(rightsSetting, rightsSettingId);
    }

    private void setGuide(RightsSetting rightsSetting) {
        if(null != rightsSetting && (RightsServeTypeEnum.APP.name().equals(rightsSetting.getGuideType()) ||
                RightsServeTypeEnum.PRODUCT.name().equals(rightsSetting.getGuideType())) && null != rightsSetting.getGuideAppItem()){
            rightsSetting.setGuideLinkUrl(rightsSetting.getGuideAppItem().getLinkUrl());
        }
    }


    private void updateRightsLongTerm(RightsSetting rightsSetting) {
        // 设置uuid，批量更新使用
        setRightsSettingItemUuid(rightsSetting);
        // 周权益数据入库
        this.batchInsertRightsSettingItem(rightsSetting.getRightsSettingLongTermItems(), rightsSetting.getId(), RightsTypeEnum.LONG_TERM.value);
        // 获取已经生成id的 周/长期 权益数据
        RightsSettingItem rightsSettingItem = new RightsSettingItem();
        rightsSettingItem.setRightsSettingId(rightsSetting.getId());
        rightsSettingItem.setRightsType(RightsTypeEnum.LONG_TERM.value);
        List<RightsSettingItem> list = rightsSettingItemDao.queryAll(rightsSettingItem);
        if (ListUtils.isEmpty(list)) {
            return;
        }
        Map<String, Long> mapRightsSettingItem = list.stream().collect(Collectors.toMap(x -> x.getUuid(), x -> x.getId()));
        // 处理长期权益子对象列表数据
        List<RightsSettingItemDetail> longTermItemDetails = this
                .buildRightsSettingItemDetailList(rightsSetting.getRightsSettingLongTermItems(), mapRightsSettingItem);
        // 整合 长期 权益的子项列表数据
        List<RightsSettingItemDetail> saveItemDetails = Lists.newArrayList();
        if (!ListUtils.isEmpty(longTermItemDetails)) {
            saveItemDetails.addAll(longTermItemDetails);
        }
        // 存储子项列表数据
        rightsSettingItemDetailDao.insert(saveItemDetails);
    }

    private void updateRightsWeek(RightsSetting rightsSetting) {
        // 更新长期权益
        // 设置uuid，批量更新使用
        setRightsSettingItemUuid(rightsSetting);
        // 权益数据入库
        this.batchInsertRightsSettingItem(rightsSetting.getRightsSettingWeekItems(), rightsSetting.getId(),
                RightsTypeEnum.WEEK.value);
        // 获取已经生成id的 周/长期 权益数据
        RightsSettingItem rightsSettingItem = new RightsSettingItem();
        rightsSettingItem.setRightsSettingId(rightsSetting.getId());
        rightsSettingItem.setRightsType(RightsTypeEnum.WEEK.value);
        List<RightsSettingItem> list = rightsSettingItemDao.queryAll(rightsSettingItem);
        if (ListUtils.isEmpty(list)) {
            return;
        }
        Map<String, Long> mapRightsSettingItem = list.stream().collect(Collectors.toMap(x -> x.getUuid(), x -> x.getId()));
        // 处理周权益子对象列表数据
        List<RightsSettingItemDetail> weekItemDetails = this
                .buildRightsSettingItemDetailList(rightsSetting.getRightsSettingWeekItems(), mapRightsSettingItem);
        // 整合 周权益的子项列表数据
        List<RightsSettingItemDetail> saveItemDetails = Lists.newArrayList();
        if (!ListUtils.isEmpty(weekItemDetails)) {
            saveItemDetails.addAll(weekItemDetails);
        }
        // 存储子项列表数据
        rightsSettingItemDetailDao.insert(saveItemDetails);
    }

    private void updateRelationBook(RightsSetting rightsSetting, Long rightsSettingId) {
        rightsSettingBookRelationMapper.deleteByRightsSettingId(rightsSettingId);
        List<RightsSettingBookRelation> rightsSettingBookRelations = rightsSetting.getRightsSettingBookRelations();
        if (!ListUtils.isEmpty(rightsSettingBookRelations)) {
            rightsSettingBookRelations.forEach(e -> e.setRightsSettingId(rightsSettingId));
            rightsSettingBookRelationMapper.batchInsert(rightsSettingBookRelations);
        }
    }

    private void updateRightsWeekOrLongTerm(RightsSetting rightsSetting) {
        // 设置uuid，批量更新使用
        setRightsSettingItemUuid(rightsSetting);
        // 周权益数据入库
        this.batchInsertRightsSettingItem(rightsSetting.getRightsSettingWeekItems(), rightsSetting.getId(), RightsTypeEnum.WEEK.value);
        // 长期权益数据入库
        this.batchInsertRightsSettingItem(rightsSetting.getRightsSettingLongTermItems(), rightsSetting.getId(),
                RightsTypeEnum.LONG_TERM.value);

        // 获取已经生成id的 周/长期 权益数据
        RightsSettingItem rightsSettingItem = new RightsSettingItem();
        rightsSettingItem.setRightsSettingId(rightsSetting.getId());
        List<RightsSettingItem> list = rightsSettingItemDao.queryAll(rightsSettingItem);
        if (ListUtils.isEmpty(list)) {
            return;
        }

        Map<String, Long> mapRightsSettingItem = list.stream().collect(Collectors.toMap(x -> x.getUuid(), x -> x.getId()));
        // 处理周权益子对象列表数据
        List<RightsSettingItemDetail> weekItemDetails = this
                .buildRightsSettingItemDetailList(rightsSetting.getRightsSettingWeekItems(), mapRightsSettingItem);
        // 处理长期权益子对象列表数据
        List<RightsSettingItemDetail> longTermItemDetails = this
                .buildRightsSettingItemDetailList(rightsSetting.getRightsSettingLongTermItems(), mapRightsSettingItem);

        // 整合 周/长期 权益的子项列表数据
        List<RightsSettingItemDetail> saveItemDetails = Lists.newArrayList();
        if (!ListUtils.isEmpty(weekItemDetails)) {
            saveItemDetails.addAll(weekItemDetails);
        }
        if (!ListUtils.isEmpty(longTermItemDetails)) {
            saveItemDetails.addAll(longTermItemDetails);
        }
        // 存储子项列表数据
        rightsSettingItemDetailDao.insert(saveItemDetails);
    }

    /**
     * 将资讯、社群、方案等各种对象列表转为统一数据
     *
     * @param rightsSettingItemList
     * @param mapRightsSettingItem
     */
    private List<RightsSettingItemDetail> buildRightsSettingItemDetailList(List<RightsSettingItem> rightsSettingItemList,
            Map<String, Long> mapRightsSettingItem) {
        if (ListUtils.isEmpty(rightsSettingItemList) || mapRightsSettingItem.isEmpty()) {
            return Lists.newArrayList();
        }
        List<RightsSettingItemDetail> rightsSettingItemDetailList = Lists.newArrayList();
        RightsSettingItemDetail rightsSettingItemDetail;
        List<GroupActivity4AppletDTO> groupActivity4AppletList;
        List<AppletNewsDTO> appletNewsDTOS;
        List<CustomPlan> customPlanList;
        List<AppletOuterBooklistDTO> outerBooklistDTOS;
        List<RightsNowItem> rightsSettingItemList4Serve;
        // 处理资讯、社群等子项列表数据
        for (RightsSettingItem rightsItem : rightsSettingItemList) {
            groupActivity4AppletList = rightsItem.getGroupActivity4AppletList();
            appletNewsDTOS = rightsItem.getAppletNewsDTOS();
            customPlanList = rightsItem.getCustomPlanList();
            outerBooklistDTOS = rightsItem.getOuterBooklistDTOS();
            rightsSettingItemList4Serve =  rightsItem.getRightsSettingItemList4Serve();
            Long rightsSettingItemId = mapRightsSettingItem.get(rightsItem.getUuid());
            if (!NumberUtil.isNumber(rightsSettingItemId)) {
                continue;
            }

            if (rightsItem.getServeType() != null) {
                if (RightsServeTypeEnum.GROUP.name().equalsIgnoreCase(rightsItem.getServeType())) {
                    if (ListUtils.isEmpty(groupActivity4AppletList)) {
                        continue;
                    }
                    for (GroupActivity4AppletDTO group : groupActivity4AppletList) {
                        rightsSettingItemDetail = new RightsSettingItemDetail();
                        rightsSettingItemDetail.setRightsSettingItemId(rightsSettingItemId);
                        rightsSettingItemDetail.setServeType(RightsServeTypeEnum.GROUP.name());
                        rightsSettingItemDetail.setServeId(group.getId());
                        rightsSettingItemDetail.setGroupType(group.getGroupType());
                        rightsSettingItemDetailList.add(rightsSettingItemDetail);
                    }
                } else if (RightsServeTypeEnum.NEWS.name().equalsIgnoreCase(rightsItem.getServeType())) {
                    if (ListUtils.isEmpty(appletNewsDTOS)) {
                        continue;
                    }
                    for (AppletNewsDTO news : appletNewsDTOS) {
                        rightsSettingItemDetail = new RightsSettingItemDetail();
                        rightsSettingItemDetail.setRightsSettingItemId(rightsSettingItemId);
                        rightsSettingItemDetail.setServeType(RightsServeTypeEnum.NEWS.name());
                        rightsSettingItemDetail.setServeId(news.getId());
                        rightsSettingItemDetailList.add(rightsSettingItemDetail);
                    }
                } else if (RightsServeTypeEnum.PLAN.name().equalsIgnoreCase(rightsItem.getServeType())) {
                    if (ListUtils.isEmpty(customPlanList)) {
                        continue;
                    }
                    for (CustomPlan plan : customPlanList) {
                        rightsSettingItemDetail = new RightsSettingItemDetail();
                        rightsSettingItemDetail.setRightsSettingItemId(rightsSettingItemId);
                        rightsSettingItemDetail.setServeType(RightsServeTypeEnum.PLAN.name());
                        rightsSettingItemDetail.setServeId(plan.getId().longValue());
                        rightsSettingItemDetailList.add(rightsSettingItemDetail);
                    }
                } else if (RightsServeTypeEnum.BOOKLIST.name().equalsIgnoreCase(rightsItem.getServeType())){
                    if (ListUtils.isEmpty(outerBooklistDTOS)){
                        continue;
                    }
                    for (AppletOuterBooklistDTO booklistDTO :outerBooklistDTOS){
                        rightsSettingItemDetail = new RightsSettingItemDetail();
                        rightsSettingItemDetail.setRightsSettingItemId(rightsSettingItemId);
                        rightsSettingItemDetail.setServeType(RightsServeTypeEnum.BOOKLIST.name());
                        rightsSettingItemDetail.setServeId(booklistDTO.getId());
                        rightsSettingItemDetailList.add(rightsSettingItemDetail);
                    }
                } else if (BookConstant.APP_PRODUCT.equalsIgnoreCase(rightsItem.getServeType())){
                    if (ListUtils.isEmpty(rightsSettingItemList4Serve)){
                        continue;
                    }
                    for (RightsNowItem rightsNowItem :rightsSettingItemList4Serve){
                        rightsSettingItemDetail = new RightsSettingItemDetail();
                        rightsSettingItemDetail.setRightsSettingItemId(rightsSettingItemId);
                        rightsSettingItemDetail.setServeType(rightsNowItem.getServeType());
                        rightsSettingItemDetail.setServeId(rightsNowItem.getServeId());
                        rightsSettingItemDetail.setLinkUrl(rightsNowItem.getLinkUrl());
                        rightsSettingItemDetailList.add(rightsSettingItemDetail);
                    }
                }
            }
        }
        return rightsSettingItemDetailList;
    }

    private void setRightsSettingItemUuid(RightsSetting rightsSetting) {
        if (!ListUtils.isEmpty(rightsSetting.getRightsSettingWeekItems())) {
            for (RightsSettingItem rightsSettingItem : rightsSetting.getRightsSettingWeekItems()) {
                rightsSettingItem.setUuid(StringUtil.getUUID());
            }
        }
        if (!ListUtils.isEmpty(rightsSetting.getRightsSettingLongTermItems())) {
            for (RightsSettingItem rightsSettingItem : rightsSetting.getRightsSettingLongTermItems()) {
                rightsSettingItem.setUuid(StringUtil.getUUID());
            }
        }
    }

    @ParamLog("更新权益的即享权益项集合")
    private void updateRightNowItemByRightId(RightsSetting rightsSetting) {
        if (rightsSetting == null) {
            return;
        }
        Long rightsSettingId = rightsSetting.getId();
        List<RightsNowItem> items = new ArrayList<>();
        RightsSettingNow rightsSettingNow = rightsSetting.getRightsSettingNow();
        List<RightsSettingTitle> rightsSettingTitleList = new ArrayList<>();
        rightsSettingTitleList.add(rightsSettingNow.getServesTitle());
        if (null == rightsSettingNow) {
            return;
        }
        //根据权益id删除原来的
        rightsSettingTitleMapper.deleteByRightSettingId(rightsSettingId);
        rightsNowItemDao.deleteByRightsSettingId(rightsSettingId);
        //处理权益配套资料分组
        dealItemGroups(rightsSetting, rightsSettingId, items);
        List<RightsSettingTitle> rightsSettingTitles4Other = rightsSettingNow.getRightsSettingTitles();
        if (!ListUtils.isEmpty(rightsSettingTitles4Other)) {
            rightsSettingTitleList.addAll(rightsSettingTitles4Other);
        }
        //校验数量
        rightsSettingCheck.checkRightNowTitles(rightsSettingTitleList);
        //给每个权益设置id
        rightsSettingTitleList.forEach(e -> {
            e.setRightsSettingId(rightsSettingId);
            e.setDisplayType(e.getDisplayType()==null?0:e.getDisplayType());
        });
        if (!ListUtils.isEmpty(rightsSettingTitleList)) {
            rightsSettingTitleMapper.batchInsert(rightsSettingTitleList);
        }
        //设置每个权益详情
        setNowItems(rightsSettingTitleList, rightsSettingId, items);
        //校验itme参数
        rightsSettingCheck.checkRightNowItems(items);
        if (!ListUtils.isEmpty(items)) {
            rightsNowItemDao.batchInsert(items);
        }
    }

    @ParamLog("增加和删除分组")
    private void dealItemGroups(RightsSetting rightsSetting, Long rightsSettingId, List<RightsNowItem> items) {
        //删除之前的
        rightsItemGroupDao.deleteByRightsSettingId(rightsSettingId);
        if (rightsSetting == null || null == rightsSetting.getRightsSettingNow() || ListUtils
                .isEmpty(rightsSetting.getRightsSettingNow().getRightsItemGroups())) {
            return;
        }
        List<RightsItemGroup> rightsItemGroups = rightsSetting.getRightsSettingNow().getRightsItemGroups();
        for (RightsItemGroup group : rightsItemGroups) {
            //集合转化为三个描述
            if (!ListUtils.isEmpty(group.getDescList())) {
                if (group.getDescList().size() > 0) {
                    group.setDesc1(group.getDescList().get(0));
                } else {
                    group.setDesc1(null);
                }
                if (group.getDescList().size() > 1) {
                    group.setDesc2(group.getDescList().get(1));
                } else {
                    group.setDesc2(null);
                }
                if (group.getDescList().size() > 2) {
                    group.setDesc3(group.getDescList().get(2));
                } else {
                    group.setDesc3(null);
                }
            }
            group.setRightsSettingId(rightsSettingId);
        }
        //新增新的
        rightsItemGroupDao.batchInsert(rightsItemGroups);
        for (RightsItemGroup group :rightsItemGroups) {
            if (ListUtils.isEmpty(group.getRightsNowItems())) {
                continue;
            }
            for (RightsNowItem item : group.getRightsNowItems()) {
                item.setType(RightsNowItemTypeNew.SERVES.value);
                item.setRightsItemGroupId(group.getId());
                item.setRightsSettingId(rightsSettingId);
                items.add(item);
            }
        }
    }

    private void setNowItems(List<RightsSettingTitle> rightsSettingTitles, Long rightsSettingId, List<RightsNowItem> items) {
        log.info("填充即享权益具体项目的的基本参数");
        if (ListUtils.isEmpty(rightsSettingTitles)) {
            return;
        }
        rightsSettingTitles.forEach(rightsSettingTitle -> {
            if (Objects.equals(RightsNowItemTypeNew.SERVES.value, rightsSettingTitle.getRightsSettingNowType())) {
                return;
            }
            List<RightsNowItem> rightsNowItemList = rightsSettingTitle.getRightsSettingItemList();
            if (ListUtils.isEmpty(rightsNowItemList)) {
                return;
            }
            if (rightsSettingTitle.getServeType() == null) {
                return;
            }
            //增加社群头图校验
            AtomicInteger showCount = new AtomicInteger(0);
            rightsNowItemList.forEach(rightsNowItem -> {
                if (rightsSettingTitle.getServeType().equalsIgnoreCase(rightsNowItem.getServeType()) || (
                        Objects.equals(BookConstant.APP_PRODUCT, rightsSettingTitle.getServeType()) && ArrayUtils
                                .contains(BookConstant.APPANDPRODUCT, rightsNowItem.getServeType()))) {
                    rightsNowItem.setRightsSettingId(rightsSettingId);
                    rightsNowItem.setRightsSettingTitleId(rightsSettingTitle.getId());
                    rightsNowItem.setType(rightsSettingTitle.getRightsSettingNowType());
                    if (YesOrNoEnums.YES.getValue().equals(rightsNowItem.getIsShow())) {
                        showCount.set(showCount.get() + 1);
                    }
                    items.add(rightsNowItem);
                }
            });
            if (showCount.intValue() > 1) {
                throw new BookBizException(BookBizException.ERROR, "最多只能有一个社群头图可以被开启");
            }
        });
    }

    private void setRightsSettingId(RightsSetting rightsSetting, Long rightsSettingId, List<RightsSettingTitle> rightsSettingTitles) {
        log.info("填充即享权益的基本参数");
        RightsSettingTitle onlineRightsSettingTitle = rightsSetting.getOnlineRightsSettingTitle();
        RightsSettingTitle learningToolTitle = rightsSetting.getLearningToolTitle();
        RightsSettingTitle drawSettingTitle = rightsSetting.getDrawSettingTitle();
        RightsSettingTitle giftCouponPackageTitle = rightsSetting.getGiftCouponPackageTitle();
        RightsSettingTitle groupServiceTitle = rightsSetting.getGroupServiceTitle();
        RightsSettingTitle servesTitle = rightsSetting.getServesTitle();
        if (null != onlineRightsSettingTitle) {
            onlineRightsSettingTitle.setRightsSettingId(rightsSettingId);
            onlineRightsSettingTitle.setRightsSettingNowType(RightsNowItemTypeNew.ONLINE_COURSE.value);
            rightsSettingTitles.add(onlineRightsSettingTitle);
        }
        if (null != learningToolTitle) {
            learningToolTitle.setRightsSettingId(rightsSettingId);
            learningToolTitle.setRightsSettingNowType(RightsNowItemTypeNew.LEARNING_TOOL.value);
            rightsSettingTitles.add(learningToolTitle);
        }
        if (null != drawSettingTitle) {
            drawSettingTitle.setRightsSettingId(rightsSettingId);
            drawSettingTitle.setRightsSettingNowType(RightsNowItemTypeNew.DRAW.value);
            rightsSettingTitles.add(drawSettingTitle);
        }
        if (null != giftCouponPackageTitle) {
            giftCouponPackageTitle.setRightsSettingId(rightsSettingId);
            giftCouponPackageTitle.setRightsSettingNowType(RightsNowItemTypeNew.GIFT_COUPON_PACKAGE.value);
            rightsSettingTitles.add(giftCouponPackageTitle);
        }
        if (null != groupServiceTitle) {
            groupServiceTitle.setRightsSettingId(rightsSettingId);
            groupServiceTitle.setRightsSettingNowType(RightsNowItemTypeNew.GROUP_SERVICE.value);
            rightsSettingTitles.add(groupServiceTitle);
        }
        if (null != servesTitle) {
            servesTitle.setRightsSettingId(rightsSettingId);
            servesTitle.setRightsSettingNowType(RightsNowItemTypeNew.SERVES.value);
            servesTitle.setOpenState(Boolean.TRUE);
            rightsSettingTitles.add(servesTitle);
        }
    }

    @Override
    @ParamLog("获取权益设置")
    public RightsSetting getRightsSetting(Long id) {
        RightsSetting rightsSetting = rightsSettingDAO.selectByPrimaryKey(id);
        if (null == rightsSetting) {
            return new RightsSetting();
        }
        //书刊分类关联书刊
        fillBookName(id, rightsSetting);
        fillRightsNowItems4New(rightsSetting);
        fillRightsWeekAndLongTarm(rightsSetting);
        //设置阅读方式
        setReadType(rightsSetting);
        //设置阅读指引
        fillReadGuide(rightsSetting.getRightsSettingBanners());
        //填充分类及标签
        fillLabelNames(Lists.newArrayList(rightsSetting));
        return rightsSetting;
    }

    private void fillLabelNames(List<RightsSetting> rightsSettingList) {
        if (ListUtils.isEmpty(rightsSettingList)) {
            return;
        }
        List<Long> classifyIds = new ArrayList<>();
        List<Long> bookLabelIds = new ArrayList<>();
        List<Long> labelIds = new ArrayList<>();
        rightsSettingList.stream().forEach(rightsSetting -> {
            if (null == rightsSetting || ListUtils.isEmpty(rightsSetting.getRightsSettingBookRelations())) {
                return;
            }
            List<RightsSettingBookRelation> rightsSettingBookRelations = rightsSetting.getRightsSettingBookRelations();
            rightsSettingBookRelations.stream().forEach(rightsSettingBookRelation -> {
                if (null != rightsSettingBookRelation.getTempletId()) {
                    classifyIds.add(rightsSettingBookRelation.getTempletId());
                }
                if (null != rightsSettingBookRelation.getSecondTempletId()) {
                    classifyIds.add(rightsSettingBookRelation.getSecondTempletId());
                }
                if (null != rightsSettingBookRelation.getThirdTempletId()) {
                    classifyIds.add(rightsSettingBookRelation.getThirdTempletId());
                }
                if (null != rightsSettingBookRelation.getGraLabelId()) {
                    bookLabelIds.add(rightsSettingBookRelation.getGraLabelId());
                }
                if (null != rightsSettingBookRelation.getSubLabelId()) {
                    bookLabelIds.add(rightsSettingBookRelation.getSubLabelId());
                }
                if (null != rightsSettingBookRelation.getVolLabelId()) {
                    bookLabelIds.add(rightsSettingBookRelation.getVolLabelId());
                }
                if (null != rightsSettingBookRelation.getVerLabelId()){
                    bookLabelIds.add(rightsSettingBookRelation.getVerLabelId());
                }
                if (null != rightsSettingBookRelation.getAreaLabelId()) {
                    bookLabelIds.add(rightsSettingBookRelation.getAreaLabelId());
                }
                if (rightsSettingBookRelation.getProLabelId() != null) {
                    labelIds.add(rightsSettingBookRelation.getProLabelId());
                }
                if (rightsSettingBookRelation.getPurLabelId() != null) {
                    labelIds.add(rightsSettingBookRelation.getPurLabelId());
                }
                if (rightsSettingBookRelation.getDepLabelId() != null) {
                    labelIds.add(rightsSettingBookRelation.getDepLabelId());
                }
            });
        });
        Map<Long, AssistTempletDTO> classifyMap = new HashMap<>();
        Map<Long, BookLabel> bookLabelMap = new HashMap<>();
        Map<Long, String> labelMap = new HashMap<>();


        if (!ListUtils.isEmpty(classifyIds)) {
            classifyMap = assistTempletConsr.mapByIds4Classify(classifyIds);
        }
        if (!ListUtils.isEmpty(bookLabelIds)) {
            bookLabelMap = bookLabelDao.getMapByIds(bookLabelIds);
        }
        if (!ListUtils.isEmpty(labelIds)) {
            labelMap = ResponseHandleUtil.parseMap(labelService.getLabelName(labelIds), Long.class, String.class);
        }
        for (RightsSetting rightsSetting : rightsSettingList) {
            if (null == rightsSetting || ListUtils.isEmpty(rightsSetting.getRightsSettingBookRelations())) {
                continue;
            }
            List<RightsSettingBookRelation> rightsSettingBookRelations = rightsSetting.getRightsSettingBookRelations();
            for (RightsSettingBookRelation rightsSettingBookRelation : rightsSettingBookRelations) {

                if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingBookRelation.getTempletId())) {
                    rightsSettingBookRelation.setTempletName(classifyMap.get(rightsSettingBookRelation.getTempletId()).getTempletName());
                }
                if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingBookRelation.getSecondTempletId())) {
                    rightsSettingBookRelation.setSecondTempletName(classifyMap.get(rightsSettingBookRelation.getSecondTempletId()).getTempletName());
                }
                if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingBookRelation.getThirdTempletId())) {
                    rightsSettingBookRelation.setThirdTempletName(classifyMap.get(rightsSettingBookRelation.getThirdTempletId()).getTempletName());
                }
                if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingBookRelation.getGraLabelId())) {
                    rightsSettingBookRelation.setGraLabelName(bookLabelMap.get(rightsSettingBookRelation.getGraLabelId()).getName());
                }
                if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingBookRelation.getSubLabelId())) {
                    rightsSettingBookRelation.setSubLabelName(bookLabelMap.get(rightsSettingBookRelation.getSubLabelId()).getName());
                }
                if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingBookRelation.getVolLabelId())) {
                    rightsSettingBookRelation.setVolLabelName(bookLabelMap.get(rightsSettingBookRelation.getVolLabelId()).getName());
                }
                if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingBookRelation.getVerLabelId())) {
                    rightsSettingBookRelation.setVerLabelName(bookLabelMap.get(rightsSettingBookRelation.getVerLabelId()).getName());
                }
                if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingBookRelation.getAreaLabelId())) {
                    rightsSettingBookRelation.setAreaLabelName(bookLabelMap.get(rightsSettingBookRelation.getAreaLabelId()).getName());
                }
                //设置深度标签
                if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingBookRelation.getDepLabelId())) {
                    rightsSettingBookRelation.setDepLabelName(labelMap.get(rightsSettingBookRelation.getDepLabelId()));
                }
                if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingBookRelation.getPurLabelId())) {
                    rightsSettingBookRelation.setPurLabelName(labelMap.get(rightsSettingBookRelation.getPurLabelId()));
                }
                if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingBookRelation.getProLabelId())) {
                    rightsSettingBookRelation.setProLabelName(labelMap.get(rightsSettingBookRelation.getProLabelId()));
                }
            }
        }
    }

    public void fillReadGuide(List<RightsSettingBanner> rightsSettingBanners){
        if (ListUtils.isEmpty(rightsSettingBanners)) {
            return;
        }
        // 获取资讯信息
        Map<Long, AppletNewsDTO> newsDTOMap = new HashMap<>();
        CompletableFuture<List<Long>> newsBannerFuture = CompletableFuture.supplyAsync(() -> rightsSettingBanners.stream()
                .filter(x -> Objects.nonNull(x) && Objects.equals(x.getJumpType(), 3))
                .map(RightsSettingBanner::getServeId).filter(Objects::nonNull).distinct()
                .collect(Collectors.toList())).whenComplete((list, throwable) -> {
            if (Objects.nonNull(throwable)) {
                log.error("[fillServeInfo] banner 图填充资讯信息失败，err：{}", throwable.getMessage(), throwable);
            } else {
                if (CollUtil.isEmpty(list)){
                    return;
                }
                Map<Long, AppletNewsDTO> dtoMap = appletNewsBiz.getByIds(list);
                newsDTOMap.putAll(Objects.nonNull(dtoMap) ? dtoMap : new HashMap<>());
            }
        });

        // 获取应用信息
        Map<Long, AppDto> appDtoMap = new HashMap<>();
        CompletableFuture<List<Long>> appBannerFuture = CompletableFuture.supplyAsync(() -> rightsSettingBanners.stream()
                .filter(x -> Objects.nonNull(x) && Objects.equals(x.getServeType(), AppletRecordTypeEnum.APP.value))
                .map(RightsSettingBanner::getServeId).collect(Collectors.toList())).whenComplete((list, throwable) -> {
            if (Objects.nonNull(throwable)) {
                log.error("[fillServeInfo] banner 图填充应用信息失败，err：{}", throwable.getMessage(), throwable);
            } else {
                Map<Long, AppDto> dtoMap = !ListUtils.isEmpty(list) ? appConsr.mapByIds4AuditPass(list) : new HashMap<>();
                appDtoMap.putAll(dtoMap);
            }
        });

        // 获取作品信息
        Map<Long, ProductDto> productDtoMap = new HashMap<>();
        CompletableFuture<List<Long>> productBannerFuture = CompletableFuture.supplyAsync(() -> rightsSettingBanners.stream()
                .filter(x -> Objects.nonNull(x) && Objects.equals(x.getServeType(), AppletRecordTypeEnum.PRODUCT.value))
                .map(RightsSettingBanner::getServeId).collect(Collectors.toList())).whenComplete((list, throwable) -> {
            if (Objects.nonNull(throwable)) {
                log.error("[fillServeInfo] banner 图填充作品信息失败，err：{}", throwable.getMessage(), throwable);
            } else {
                Map<Long, ProductDto> dtoMap = !ListUtils.isEmpty(list) ? productConsr.getProBasesByIds(list) : new HashMap<>();
                productDtoMap.putAll(dtoMap);
            }
        });
        //获取第三方资源
        Map<Long, AppletThirdResources> appletThirdResourcesHashMap = new HashMap<>();
        CompletableFuture<List<Long>> appletThirdResourcesFuture = CompletableFuture.supplyAsync(() -> rightsSettingBanners.stream()
                .filter(x -> Objects.nonNull(x) && Objects.equals(x.getJumpType(), RightsSettingJumpType.ThIRD_RESOURCE.code))
                .map(RightsSettingBanner::getServeId).collect(Collectors.toList())).whenComplete((list, throwable) -> {
            if (Objects.nonNull(throwable)) {
                log.error("[fillServeInfo] banner 图填充作品信息失败，err：{}", throwable.getMessage(), throwable);
            } else {
                Map<Long, AppletThirdResources> dtoMap = !ListUtils.isEmpty(list) ? appletThirdResourcesBiz.getAppletMapByIds(list) : new HashMap<>();
                appletThirdResourcesHashMap.putAll(dtoMap);
            }
        });

        try {
            CompletableFuture.allOf(newsBannerFuture, appBannerFuture, productBannerFuture, appletThirdResourcesFuture).get();
        } catch (InterruptedException | ExecutionException e) {
            log.error("[fillServeInfo] banner 填充信息失败，err：{}", e.getMessage(), e);
        }

        // 填充信息
        for (RightsSettingBanner banner : rightsSettingBanners) {
            if (Objects.nonNull(banner) && Objects.nonNull(banner.getServeId()) && Objects.nonNull(banner.getServeType())) {
                Integer serveType = banner.getServeType();
                if (Objects.equals(banner.getJumpType(), 3) && Objects.nonNull(newsDTOMap.get(banner.getServeId()))) {
                    //填充资讯
                    AppletNewsDTO appletNewsDTO = newsDTOMap.get(banner.getServeId());
                    RightsNowItem rightsNowItem = new RightsNowItem();
                    BeanUtils.copyProperties(appletNewsDTO,rightsNowItem);
                    rightsNowItem.setNewsSource(appletNewsDTO.getSource());
                    rightsNowItem.setRightsSettingId(banner.getRightsSettingId());
                    rightsNowItem.setServeName(appletNewsDTO.getNewsName());
                    rightsNowItem.setServePic(appletNewsDTO.getPic1());
                    rightsNowItem.setServeType(RightsServeTypeEnum.NEWS.name());
                    rightsNowItem.setServeName("资讯");
                    rightsNowItem.setSource(appletNewsDTO.getSource());
                    rightsNowItem.setJumpType(appletNewsDTO.getJumpType());
                    banner.setGuideNewsItem(rightsNowItem);
                } else if (Objects.equals(serveType, AppletRecordTypeEnum.APP.value) && Objects.nonNull(appDtoMap.get(banner.getServeId()))) {
                    //填充应用
                    RightsNowItem rightsNowItem = new RightsNowItem();
                    rightsNowItem.setServeId(banner.getServeId());
                    rightsNowItem.setServeType(RightsServeTypeEnum.APP.name());
                    rightsNowItem.setType(RightsNowItemTypeNew.ONLINE_COURSE.value);
                    rightsNowItem.setLinkUrl(banner.getJumpUrl());
                    fillProductAndApp(Lists.newArrayList(rightsNowItem));
                    banner.setGuideAppItem(rightsNowItem);
                } else if (Objects.equals(serveType, AppletRecordTypeEnum.PRODUCT.value) && Objects.nonNull(productDtoMap.get(banner.getServeId()))) {
                    //填充作品
                    RightsNowItem rightsNowItem = new RightsNowItem();
                    rightsNowItem.setServeId(banner.getServeId());
                    rightsNowItem.setServeType(RightsServeTypeEnum.PRODUCT.name());
                    rightsNowItem.setType(RightsNowItemTypeNew.ONLINE_COURSE.value);
                    rightsNowItem.setLinkUrl(banner.getJumpUrl());
                    fillProductAndApp(Lists.newArrayList(rightsNowItem));
                    banner.setGuideAppItem(rightsNowItem);
                } else if (Objects.equals(banner.getJumpType(), RightsSettingJumpType.ThIRD_RESOURCE.code) && Objects.nonNull(appletThirdResourcesHashMap.get(banner.getServeId()))) {
                    //填充第三方资源
                    Long resourceId = banner.getServeId();
                    if (null == resourceId) {
                        return;
                    }
                    AppletThirdResources appletThirdResources= appletThirdResourcesHashMap.get(resourceId);
                    if(appletThirdResources == null){
                        return;
                    }
                    banner.setThirdResource(appletThirdResources);
                }
            }
        }
    }

    @Override
    public Map<String,Object> getBookCardId4Book(Long bookId, Long channelId, Long adviserId, Long rightsSettingId) {
        // 1. 根据图书获取公众号码下的资源中是否包含读书笔记
        CompletableFuture<List<ServeIdTypeVO>> channelServes = CompletableFuture.supplyAsync(() -> channelConsr.listServeIdType4Book(bookId, channelId, adviserId))
                .thenApply(serveIdTypeDTOS -> serveIdTypeDTOS.stream().filter(x->Objects.nonNull(x) && Objects.equals(x.getServeType(),"APP")
                && Objects.equals(x.getTypeCode(),"BOOKCARD")).collect(Collectors.toList()));

        // 2. 根据图书获取社群码下的资源中是否包含读书笔记
        CompletableFuture<List<ServeIdTypeDTO>> groupServes = CompletableFuture.supplyAsync(() -> bookGroupDao.listServeIdAndType4Book(bookId, channelId, adviserId))
                .thenApply(serveIdTypeDTOS -> serveIdTypeDTOS.stream().filter(x->Objects.nonNull(x) && Objects.equals(x.getServeType(),"APP")
                        && Objects.equals(x.getTypeCode(),"BOOKCARD")).collect(Collectors.toList()));

        // 3. 根据权益ID获取权益下配置的资源中是否包含读书笔记
        CompletableFuture<List<ServeIdTypeDTO>> rightsServes = Optional.ofNullable(rightsSettingId).map(tempId -> CompletableFuture.supplyAsync(() -> rightsNowItemDao.listServeIdAndTypeByRightsSettingId(rightsSettingId))
                .thenApply(serveIdTypeDTOS -> {
                    List<Long> appIds = serveIdTypeDTOS.stream().filter(x -> Objects.nonNull(x) && Objects.equals(x.getServeType(), "APP"))
                            .map(ServeIdTypeDTO::getServeId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
                    // 去APP查询APP类型
                    List<Long> targetIds = Optional.ofNullable(appConsr.listAppTypeById(appIds)).map(x -> x.stream()
                            .filter(it -> Objects.nonNull(it) && Objects.equals(it.getTypeCode(), "BOOKCARD"))
                            .map(AppIdTypeDTO::getAppId).filter(Objects::nonNull).distinct().collect(Collectors.toList())).orElse(new ArrayList<>());
                    return serveIdTypeDTOS.stream().filter(x -> Objects.nonNull(x) && targetIds.contains(x.getServeId())).collect(Collectors.toList());
                })).orElse(CompletableFuture.supplyAsync(ArrayList::new));

        try {
            CompletableFuture.allOf(channelServes, groupServes, rightsServes).get();

            List<ServeIdTypeDTO> channel = Optional.ofNullable(channelServes.get()).map(x-> x.stream().map(it->{
                ServeIdTypeDTO serveIdTypeDTO = new ServeIdTypeDTO();
                BeanUtils.copyProperties(it,serveIdTypeDTO);
                return serveIdTypeDTO;
            }).collect(Collectors.toList())).orElse(new ArrayList<>());
            List<ServeIdTypeDTO> group = Optional.ofNullable(groupServes.get()).orElse(new ArrayList<>());
            List<ServeIdTypeDTO> rights = Optional.ofNullable(rightsServes.get()).orElse(new ArrayList<>());
            channel.addAll(group);
            channel.addAll(rights);

            List<Long> appIds = channel.stream().filter(Objects::nonNull).map(ServeIdTypeDTO::getServeId).filter(Objects::nonNull).distinct().collect(Collectors.toList());
            if (CollUtil.isEmpty(appIds)){
                return new HashMap<>();
            }

            Map<Long, AppDto> baseByIds = appConsr.getBaseByIds(appIds);
            if (CollUtil.isEmpty(baseByIds) || CollUtil.isEmpty(baseByIds.values())){
                return new HashMap<>();
            }

            // 应用审核通过并且没有删除
            appIds = new ArrayList<>(baseByIds.values()).stream().filter(x -> Objects.nonNull(x) && StrUtil.equals(x.getAuditState(), "1")
                    && !x.getIsDelete()).map(AppDto::getAppId).collect(Collectors.toList());

            List<Long> finalAppIds = appIds;
            Long serveId = channel.stream().filter(x->Objects.nonNull(x)&& finalAppIds.contains(x.getServeId()))
                    .max(Comparator.comparing(ServeIdTypeDTO::getCreateTime, Comparator.nullsFirst(Date::compareTo)))
                    .orElse(new ServeIdTypeDTO()).getServeId();

            if (Objects.isNull(serveId)) return new HashMap<>();

            Map<String, Object> map = MapUtil.of("serveId", serveId);
            map.put("resultUrl","");
            // 根据serveId获取跳转链接
            AppDto appDto = baseByIds.get(serveId);
            String resultLinkUrl = null;
            if (Objects.nonNull(appDto.getChannelId())) {
                AccountSettingDto accountSettingDto = qrcodeSceneConsr.getWechatInfo(appDto.getChannelId());
                // 根据 APP 拼接 linkUrl
                String linkUrl = ServeLinkUtils.getServeLink("APP", appDto.getTypeCode(), appDto.getAppId().toString(),
                        appDto.getSceneCode(), appDto.getChannelId().toString(), appDto.getCreatedUser().toString(), null);
                if (Objects.nonNull(accountSettingDto)) {
                    resultLinkUrl = SendWeixinRequestTools.splitUrl(accountSettingDto, linkUrl);
                    map.put("resultUrl",resultLinkUrl);
                }
            }
            return map;
        } catch (InterruptedException | ExecutionException e) {
            log.warn("异步任务执行失败！bookId：{} channelId：{} adviserId：{} rightsSettingId：{}", bookId, channelId, adviserId, rightsSettingId);
        }
        return new HashMap<>();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleNews() {
        List<AppletNews> appletNews = rightsSettingDAO.getAllNews();
        if (ListUtils.isEmpty(appletNews)) {
            return;
        }
        Map<Long ,AppletNews> appletNewsMap = appletNews.stream().collect(Collectors.toMap(AppletNews::getId,Function.identity(), (key1, key2) -> key2));
        //获取资讯与作品关系集合
        Map<Long, Long> newsProductMap = getNewsProductMap(appletNews);
        if (MapUtils.isEmpty(newsProductMap)) {
            return;
        }
        //获取所有书刊与资讯的关系
        List<HandleNewsDTO> handleNewsDtos = rightsSettingDAO.getAllBookNews();
        if (ListUtils.isEmpty(handleNewsDtos)) {
            return;
        }
        handleNewsDtos.stream().forEach(bookNews -> {
            //根据bookid 和channel 查询book_groupId 以及对应的编辑端资源 判断是否有应用作品模块 并新增资源
            ResourcePageVO resourcePageVO = resourcePageBiz.getResourcePageByBookIdAndChannelId(bookNews.getBookId(), bookNews.getChannelId());
            if (null == resourcePageVO || null == resourcePageVO.getId()) {
                return;
            }
            List<ResourceColumnAndServeVO> serveVOList = resourcePageBiz.getColumnAndServeListByPageId(resourcePageVO.getId(), false, null, null, null, null);
            UpdateResourceColumnVO columnVO = new UpdateResourceColumnVO();
            columnVO.setColumnFormat(3);
            columnVO.setColumnName("精品资讯");
            Integer serveCount = ListUtils.isEmpty(serveVOList) ? 0 : serveVOList.size();
            columnVO.setColumnSeq(++serveCount);
            columnVO.setColumnType(1);
            columnVO.setResourcePageId(resourcePageVO.getId());
            columnVO.setShowCount(4);
            //新增内容
            if (ListUtils.isEmpty(bookNews.getAppletNewsIds())) {
                return;
            }
            BookAdviserDto  bookAdviserDto = null;
            if (null != bookNews.getBookId() && (null == bookNews.getChannelId() || null == bookNews.getAdviserId())) {
                bookAdviserDto = bookAdviserBiz.getOneMainBook(bookNews.getBookId());
            } else  if (null != bookNews.getBookId() && null != bookNews.getChannelId() && null != bookNews.getAdviserId()) {
                bookAdviserDto = bookAdviserBiz.getBase(bookNews.getBookId(), bookNews.getChannelId(),bookNews.getAdviserId());
            }
            if (null == bookAdviserDto) {
                return;
            }
            List<ResourcePageItemVO> itemVOList = new ArrayList<>();
            BookAdviserDto finalBookAdviserDto = bookAdviserDto;
            bookNews.getAppletNewsIds().stream().forEach(newsId -> {
                ResourcePageItemVO resourcePageItemVO = new ResourcePageItemVO();
                resourcePageItemVO.setServeType("PRODUCT");
                String pic;
                if (MapUtils.isEmpty(newsProductMap) || null == newsProductMap.get(newsId)) {
                    return;
                }
                if (MapUtils.isEmpty(appletNewsMap) || null == appletNewsMap.get(newsId)) {
                    return;
                }
                if (!StringUtil.isEmpty(appletNewsMap.get(newsId).getPic1())){
                    pic = appletNewsMap.get(newsId).getPic1();
                } else {
                    pic = "https://oss.5rs.me/oss/uploadfe/jpg/5b47ff1c2b9a47a7d9fab10ef0990255.jpg";
                }
                resourcePageItemVO.setServePic(pic);
                if (!StringUtil.isEmpty(appletNewsMap.get(newsId).getNewsName())) {
                    resourcePageItemVO.setServeName(appletNewsMap.get(newsId).getNewsName());
                }
                resourcePageItemVO.setServeId(newsProductMap.get(newsId));
                String linkUrl = "/C"+ finalBookAdviserDto.getChannelId()+"/product/display/"+ resourcePageItemVO.getServeId()+
                        "?adviserId="+ finalBookAdviserDto.getAdviserId()+"&proType=ARTICLE&source_type=QRCODE";
                resourcePageItemVO.setLinkUrl(linkUrl);
                itemVOList.add(resourcePageItemVO);
            });
            if (ListUtils.isEmpty(itemVOList)) {
                return;
            }
            columnVO.setItemVOList(itemVOList);
            log.info("columnVO:{}", columnVO);
            resourcePageBiz.updateResourceColumn(columnVO);
            return;
        });
        List<Long> allNewsIds = appletNews.stream().map(e -> e.getId()).collect(Collectors.toList());
        allNewsIds.removeAll(newsProductMap.keySet());
        log.info("没有转成作品的资讯id是：{}", allNewsIds);


    }

    private Map<Long, Long> getNewsProductMap(List<AppletNews> appletNews) {
        String defaultPic1 = "https://oss.5rs.me/oss/uploadfe/jpg/5b47ff1c2b9a47a7d9fab10ef0990255.jpg";
        Long  partyId = null;
        if (envStr.equalsIgnoreCase("test")) {
            partyId = 1404L;
        } else if (envStr.equalsIgnoreCase("uat")) {
            partyId = 12829L;
        } else if (envStr.equalsIgnoreCase("pro")) {
            partyId = 1000022269L;
        }
        String title = "共享教育";
        Map<Long, Long> newsProductMap = new HashMap<>();
        //填充数据
        Long finalPartyId = partyId;
        appletNews.stream().forEach(news -> {
            Product product = new Product();
            product.setCoverImg("https://oss.5rs.me/oss/uploadfe/jpg/03024429744ee9bf16abc728236b7ee7.jpg");
            product.setDetailDesc(StringUtil.isEmpty(news.getDigest()) ? news.getNewsName() : news.getDigest());
            product.setPicture1(StringUtil.isEmpty(news.getPic1()) ? defaultPic1 : news.getPic1());
                ProductLabel productLabel = new ProductLabel();
                productLabel.setProLabelId(null == news.getProLabelId() ? 469L : news.getProLabelId());
                productLabel.setDepLabelId(null == news.getDepLabelId() ? 470L : news.getDepLabelId());
                productLabel.setPurLabelId(null == news.getPurLabelId() ? 245L : news.getPurLabelId());
            product.setProLabelGroup(Lists.newArrayList(productLabel));
            product.setProductName(news.getNewsName());
            product.setProductTypeId(28L);
                Specification specification = new Specification();
                specification.setAdvisePrice(0.00);
                specification.setDealPrice(0.00);
            product.setSpecification(Lists.newArrayList(specification));
            product.setUniqueNumber(news.getUrlNumber());
            //共享教育作者id
            product.setCreatedUser(finalPartyId);
            product.setCreatedUserRole(SystemRoleCodeEnum.MERCHANT.name().toLowerCase());
            Long productId = productConsr.addProductStepOne(product);
            if (null == productId) {
                return;
            }
            product.setProductId(productId);
            Article article = new Article();
            article.setProductId(productId);
            article.setPreReading(20L);
            article.setTitle(StringUtil.isEmpty(news.getSource()) ? title : news.getSource());
            article.setCreatedUser(finalPartyId);
            List<ArticleInfoDTO> articleInfoDTOS = new ArrayList<>();
            ArticleInfoDTO articleInfo4Content = new ArticleInfoDTO();
            articleInfo4Content.setType("text");
            articleInfo4Content.setSeqNum(0);
            articleInfo4Content.setContent(news.getContent());
            articleInfoDTOS.add(articleInfo4Content);
            ArticleInfoDTO articleInfo4Music = new ArticleInfoDTO();
            articleInfo4Music.setType("bgmusic");
            articleInfo4Music.setSeqNum(1);
            articleInfoDTOS.add(articleInfo4Music);
            article.setInfo(JSONUtils.toJsonString(articleInfoDTOS));
            productConsr.addArticle(article);
            productConsr.selfAudit(product);
            if (null != news.getId() && null != productId) {
                newsProductMap.put(news.getId(), productId);
            }
        });
        return newsProductMap;
    }

    private void fillRightsNowItems4New(RightsSetting rightsSetting) {
        log.info("即享权益填充详情");
        List<Integer> types = new ArrayList<>();
        RightsSettingNow rightsSettingNow = new RightsSettingNow();
        types.addAll(Lists.newArrayList(RightsNowItemTypeNew.ONLINE_COURSE.value, RightsNowItemTypeNew.LEARNING_TOOL.value,
                RightsNowItemTypeNew.GIFT_COUPON_PACKAGE.value, RightsNowItemTypeNew.DRAW.value, RightsNowItemTypeNew.GROUP_SERVICE.value,RightsNowItemTypeNew.ONLINE_EXCL_COURSE.value,RightsNowItemTypeNew.COACH.value));
        List<RightsSettingTitle> rightsSettingTitles = rightsSettingTitleMapper.getByRightSettingId(rightsSetting.getId(), null);
        if (ListUtils.isEmpty(rightsSettingTitles)) {
            return;
        }
        List<RightsNowItem> nowItems = rightsNowItemDao.getListByRightsSettingId(rightsSetting.getId(), types);
        RightsSettingTitle servesTitle = new RightsSettingTitle();
        if (!ListUtils.isEmpty(nowItems)) {
            fillProductAndApp(nowItems);
            Map<Long, List<RightsNowItem>> nowItemMap =
                    nowItems.stream().filter(e -> null != e.getRightsSettingTitleId())
                            .collect(Collectors.groupingBy(x -> x.getRightsSettingTitleId()));
            if (!MapUtils.isEmpty(nowItemMap)) {
                // 填充应用、作品、社群、资讯
                for (RightsSettingTitle rightsSettingTitle : rightsSettingTitles) {
                    if (!ListUtils.isEmpty(nowItemMap.get(rightsSettingTitle.getId()))){ //add py pansy 删除的群不显示
                        rightsSettingTitle.setRightsSettingItemList(nowItemMap.get(rightsSettingTitle.getId()));
                    }
                }
            }
          /*  fillProductAndApp(nowItems);*/
        }
        Iterator<RightsSettingTitle> iterator = rightsSettingTitles.iterator();
        while (iterator.hasNext()) {
            RightsSettingTitle rightsSettingTitle = iterator.next();
            if (RightsNowItemTypeNew.SERVES.value.equals(rightsSettingTitle.getRightsSettingNowType())) {
                servesTitle = rightsSettingTitle;
                iterator.remove();
            }
            List<RightsNowItem> giftCouponPackItems = rightsNowItemDao.getGiftCouponListByRightsSettingTitleId(rightsSettingTitle.getId());
            if (RightsNowItemTypeNew.GIFT_COUPON_PACKAGE.value.equals(rightsSettingTitle.getRightsSettingNowType())) {
                rightsSettingTitle.setRightsSettingItemList(giftCouponPackItems);
            }
        }
        rightsSettingNow.setRightsSettingTitles(rightsSettingTitles);
        rightsSettingNow.setRightsItemGroups(getRightsItemGroups(rightsSetting.getId(), null, null, null, false, null, null,false));
        rightsSettingNow.setServesTitle(servesTitle);
        rightsSetting.setRightsSettingNow(rightsSettingNow);
        List<RightsSettingTitle> newRightsSettingTitles =  new ArrayList<> (rightsSettingTitles);
        newRightsSettingTitles.add(servesTitle);

        newRightsSettingTitles = newRightsSettingTitles.stream().sorted(Comparator.comparing(item -> item.getSeqNum(), Comparator.nullsLast(Integer::compareTo)))
                .collect(Collectors.toList());

        rightsSettingNow.setNewRightsSettingTitles(newRightsSettingTitles);
    }

    private void fillBookName(Long id, RightsSetting rightsSetting) {
        if (rightsSetting.getRightsSettingType() != 2) {
            return;
        }
        List<RightsSettingBookRelation> rightsSettingBookRelations = rightsSettingBookRelationMapper.selectByRithsSettingId(id);
        if (ListUtils.isEmpty(rightsSettingBookRelations)) {
            return;
        }
        List<Long> bookIds = rightsSettingBookRelations.stream().map(e -> e.getBookId()).collect(Collectors.toList());
        List<Long> adviserIds = rightsSettingBookRelations.stream().map(e -> e.getAdviserId()).collect(Collectors.toList());
        Map<Long, AdviserBaseInfoDto> infoDtoMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(adviserIds);
        if (MapUtils.isEmpty(infoDtoMap)) {
            return;
        }
        Map<Long, BookDto> bookDtoMap = bookBiz.getListByIds(bookIds);
        if (MapUtils.isEmpty(bookDtoMap)) {
            return;
        }
        for (RightsSettingBookRelation rightsSettingBookRelation : rightsSettingBookRelations) {
            if (bookDtoMap.containsKey(rightsSettingBookRelation.getBookId()) && null != bookDtoMap
                    .get(rightsSettingBookRelation.getBookId())) {
                rightsSettingBookRelation.setBookName(bookDtoMap.get(rightsSettingBookRelation.getBookId()).getBookName());
                rightsSettingBookRelation.setIsbn(bookDtoMap.get(rightsSettingBookRelation.getBookId()).getIsbn());
            }
            if (MapUtils.isNotEmpty(infoDtoMap) && null != infoDtoMap.get(rightsSettingBookRelation.getAdviserId())) {
                if (null != infoDtoMap.get(rightsSettingBookRelation.getAdviserId())) {
                    rightsSettingBookRelation.setAdviserName(infoDtoMap.get(rightsSettingBookRelation.getAdviserId()).getPartyName());
                    rightsSettingBookRelation.setAgentName(infoDtoMap.get(rightsSettingBookRelation.getAdviserId()).getAgentName());
                }
            }
        }
        rightsSetting.setRightsSettingBookRelations(rightsSettingBookRelations);
    }

    private void setReadType(RightsSetting rightsSetting) {
        List<RightsReadType> rightsReadTypes = rightsReadTypeMapper.getByRightsSettingId(rightsSetting.getId());
        rightsSetting.setRightsReadTypes(ListUtils.isEmpty(rightsReadTypes) ? new ArrayList<>() : rightsReadTypes);
    }

    private void fillRightsWeekAndLongTarm(RightsSetting rightsSetting) {
        // 默认值
        rightsSetting.setRightsSettingWeekItems(Lists.newArrayList());
        rightsSetting.setRightsSettingLongTermItems(Lists.newArrayList());
        // 查询周、长期权益
        RightsSettingItem paramItem = new RightsSettingItem();
        paramItem.setRightsSettingId(rightsSetting.getId());
        List<RightsSettingItem> rightsSettingItemList = rightsSettingItemDao.queryAll(paramItem);
        // 加载子项数据
        fillRightsSettingItemDetail(rightsSettingItemList);
        for (RightsSettingItem rightsSettingItem : rightsSettingItemList) {
            if (RightsTypeEnum.WEEK.value.equalsIgnoreCase(rightsSettingItem.getRightsType())) {
                rightsSetting.getRightsSettingWeekItems().add(rightsSettingItem);
            } else if (RightsTypeEnum.LONG_TERM.value.equalsIgnoreCase(rightsSettingItem.getRightsType())) {
                rightsSetting.getRightsSettingLongTermItems().add(rightsSettingItem);
            }
        }
    }

    /**
     * 填充周、长期权益
     *
     * @param rightsSettingItemList
     */
    private void fillRightsSettingItemDetail(List<RightsSettingItem> rightsSettingItemList) {
        if (ListUtils.isEmpty(rightsSettingItemList)) {
            return;
        }
        List<Long> itemIds = rightsSettingItemList.stream().map(RightsSettingItem::getId).collect(Collectors.toList());
        // 查询周、长期权益的列表子项
        List<RightsSettingItemDetail> allItemDetailList = rightsSettingItemDetailDao.getByItemIds(itemIds);
        // 按 rightsSettingItemId 分组
        Map<Long, List<RightsSettingItemDetail>> itemDetailMap = allItemDetailList.stream()
                .collect(Collectors.groupingBy(RightsSettingItemDetail::getRightsSettingItemId));
        //填充应用或作品
        fillProductAndApp4Week(rightsSettingItemList, itemDetailMap);
        List<Long> groupIds = new ArrayList<>();
        List<Long> appletNewsId = new ArrayList<>();
        List<Long> planIds = new ArrayList<>();
        List<Long> booklistIds = new ArrayList<>();

        for (RightsSettingItemDetail item : allItemDetailList) {
            if (item.getServeId() != null && RightsServeTypeEnum.GROUP.name().equals(item.getServeType()) && !groupIds
                    .contains(item.getServeId())) {
                groupIds.add(item.getServeId());
            }
            if (item.getServeId() != null && RightsServeTypeEnum.NEWS.name().equals(item.getServeType()) && !appletNewsId
                    .contains(item.getServeId())) {
                appletNewsId.add(item.getServeId());
            }
            if (item.getServeId() != null && RightsServeTypeEnum.PLAN.name().equals(item.getServeType()) && !planIds
                    .contains(item.getServeId())) {
                planIds.add(item.getServeId());
            }
            if (item.getServeId() != null && RightsServeTypeEnum.BOOKLIST.name().equals(item.getServeType()) && !booklistIds
                    .contains(item.getServeId())){
                booklistIds.add(item.getServeId());
            }
        }

        Map<Long, GroupActivity4AppletDTO> groupDtoMap = new HashMap<>();
        Map<Long, AppletNewsDTO> newsDtoMap = new HashMap<>();
        Map<Long, CustomPlan> planDtoMap = new HashMap<>();
        Map<Long, AppletOuterBooklistDTO> outerBooklistDTOMap = new HashMap<>();
        if (!ListUtils.isEmpty(groupIds)) {
            groupDtoMap = pcloudGroupActivityBiz.getByIds(groupIds);
        }
        if (!ListUtils.isEmpty(appletNewsId)) {
            newsDtoMap = appletNewsBiz.getByIds(appletNewsId);
        }
        if (!ListUtils.isEmpty(planIds)) {
            planDtoMap = customPlanBiz.getByIds(planIds);
        }
        if (!ListUtils.isEmpty(booklistIds)){
            outerBooklistDTOMap = appletBooklistBiz.getByIds(booklistIds);
        }

        List<RightsSettingItemDetail> itemDetailList;
        GroupActivity4AppletDTO groupActivity4AppletDTO;
        AppletNewsDTO appletNewsDTO;
        CustomPlan plan;
        AppletOuterBooklistDTO outerBooklistDTO;
        for (RightsSettingItem rightsSettingItem : rightsSettingItemList) {
            // 默认值
            rightsSettingItem.setGroupActivity4AppletList(Lists.newArrayList());
            rightsSettingItem.setAppletNewsDTOS(Lists.newArrayList());
            rightsSettingItem.setCustomPlanList(Lists.newArrayList());
            rightsSettingItem.setOuterBooklistDTOS(Lists.newArrayList());

            itemDetailList = itemDetailMap.get(rightsSettingItem.getId());
            if (!ListUtils.isEmpty(itemDetailList) && RightsServeTypeEnum.GROUP.name()
                    .equalsIgnoreCase(itemDetailList.get(0).getServeType())) {
                for (RightsSettingItemDetail itemDetail : itemDetailList) {
                    groupActivity4AppletDTO = groupDtoMap.get(itemDetail.getServeId());
                    if (groupActivity4AppletDTO == null) {
                        continue;
                    }
                    if (AppletRecordTypeEnum.ADVISER_GROUP.value.equals(groupActivity4AppletDTO.getGroupType())) {
                        groupActivity4AppletDTO.setGroupActivityId(null);
                    }
                    rightsSettingItem.getGroupActivity4AppletList().add(groupActivity4AppletDTO);
                }
                // 填充头像
                fillGroupActivityHead(rightsSettingItem.getGroupActivity4AppletList());
            } else if (!ListUtils.isEmpty(itemDetailList) && RightsServeTypeEnum.NEWS.name()
                    .equalsIgnoreCase(itemDetailList.get(0).getServeType())) {
                for (RightsSettingItemDetail itemDetail : itemDetailList) {
                    appletNewsDTO = newsDtoMap.get(itemDetail.getServeId());
                    if (appletNewsDTO == null) {
                        continue;
                    }
                    appletNewsDTO.setNewsType(appletNewsDTO.getType());
                    rightsSettingItem.getAppletNewsDTOS().add(appletNewsDTO);
                }
            } else if (!ListUtils.isEmpty(itemDetailList) && RightsServeTypeEnum.PLAN.name()
                    .equalsIgnoreCase(itemDetailList.get(0).getServeType())) {
                for (RightsSettingItemDetail itemDetail : itemDetailList) {
                    plan = planDtoMap.get(itemDetail.getServeId());
                    if (plan == null) {
                        continue;
                    }
                    rightsSettingItem.getCustomPlanList().add(plan);
                }
            } else if (!ListUtils.isEmpty(itemDetailList) && RightsServeTypeEnum.BOOKLIST.name()
                    .equalsIgnoreCase(itemDetailList.get(0).getServeType())){
                for (RightsSettingItemDetail itemDetail : itemDetailList) {
                    outerBooklistDTO = outerBooklistDTOMap.get(itemDetail.getServeId());
                    if (null == outerBooklistDTO){
                        continue;
                    }
                    rightsSettingItem.getOuterBooklistDTOS().add(outerBooklistDTO);
                }
            }
        }
    }

    private void fillProductAndApp4Week(List<RightsSettingItem> rightsSettingItemList, Map<Long, List<RightsSettingItemDetail>> itemDetailMap) {
        if (ListUtils.isEmpty(rightsSettingItemList)) {
            return;
        }
        List<RightsSettingItemDetail> itemDetailList = new ArrayList<>();
        List<RightsNowItem> rightsSettingItemList4Serve = new ArrayList<>();

        for (RightsSettingItem rightsSettingItem : rightsSettingItemList) {
            // 默认值
            rightsSettingItem.setRightsSettingItemList4Serve(Lists.newArrayList());
            itemDetailList = itemDetailMap.get(rightsSettingItem.getId());
            if (!ListUtils.isEmpty(itemDetailList) && (RightsServeTypeEnum.PRODUCT.name().equalsIgnoreCase(itemDetailList.get(0).getServeType()) ||
                    RightsServeTypeEnum.APP.name().equalsIgnoreCase(itemDetailList.get(0).getServeType())
                    )) {
                for (RightsSettingItemDetail itemDetail : itemDetailList) {
                    RightsNowItem rightsNowItem = new RightsNowItem();
                    rightsNowItem.setServeId(itemDetail.getServeId());
                    rightsNowItem.setServeType(itemDetail.getServeType());
                    rightsNowItem.setType(RightsNowItemTypeNew.LEARNING_TOOL.value);
                    rightsNowItem.setLinkUrl(itemDetail.getLinkUrl());
                    rightsSettingItemList4Serve.add(rightsNowItem);
                }
                fillProductAndApp(rightsSettingItemList4Serve);
                rightsSettingItem.setRightsSettingItemList4Serve(rightsSettingItemList4Serve);
            }
        }
    }

    @Override
    public void fillGroupActivityHead(List<GroupActivity4AppletDTO> groupActivity4AppletList) {
        if (!ListUtils.isEmpty(groupActivity4AppletList)) {
            for (GroupActivity4AppletDTO groupActivity4AppletDTO : groupActivity4AppletList) {
                //第三方群获取头像 end  add by Pansy
                Integer integer = 1;
                if(null != groupActivity4AppletDTO.getGroupType() && groupActivity4AppletDTO.getGroupType().intValue() == integer.intValue()){
                    fillThirdGroupHeadList(groupActivity4AppletDTO);
                }
                //第三方群获取头像 end


                String filterStr = StringUtilParent.replaceHtml(groupActivity4AppletDTO.getDesc());
                String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
                groupActivity4AppletDTO.setCutDesc(subStr);
                // 通过群分类ID获取群二维码
                Long classifyId = groupActivity4AppletDTO.getClassifyId();
                if(classifyId != null && classifyId != 0) {
                    String groupQrCode = groupQrcodeBiz.getChangeGroupQrCode(classifyId);
                    // 通过群二维码链接反查群ID 并补充信息
                    if (!StringUtil.isEmpty(groupQrCode)){ //2020/06/30 add by pansy 第三方群为空
                        ClassifyQrcodeVO groupQrcodeInfo = groupQrcodeBiz.getGroupQrcodeInfo(groupQrCode, classifyId);
                        groupActivity4AppletDTO.setBookGroupQrcodeId(groupQrcodeInfo.getId());
                        groupActivity4AppletDTO.setGroupName(groupQrcodeInfo.getGroupName());
                        groupActivity4AppletDTO.setGroupPic(groupQrcodeInfo.getQrcodeUrl());
                        groupActivity4AppletDTO.setUserNumber(groupQrcodeInfo.getUserNumber());

                        //头像列表从缓存里取
                        List<String> headUrlList = appletGroupSearchRecordBiz
                                .getHeadUrlList(groupActivity4AppletDTO.getUserNumber(), groupActivity4AppletDTO.getBookGroupQrcodeId());

                        groupActivity4AppletDTO.setHeadUrlList(headUrlList);

                        List<AppletGroupStatementDTO> statementDTOS = appletGroupSearchRecordBiz
                                .getStatementList(groupActivity4AppletDTO.getUserNumber(), headUrlList,
                                        groupActivity4AppletDTO.getBookGroupQrcodeId());
                        groupActivity4AppletDTO.setStatementDTOList(statementDTOS);
                    }
                }

            }
        }
    }

    @Override
    public void fillThirdGroupHeadList(GroupActivity4AppletDTO groupActivity4AppletDTO) {
        //头像列表从缓存里取
        String key = CacheConstant.BOOK + "THIRD_GROUP:" + groupActivity4AppletDTO.getGroupActivityId();
        Integer userNum;
        if (StringUtil.isEmpty(JedisClusterUtils.get(key))) {
            userNum = RandomUtil.randomInt(10, 30);
            JedisClusterUtils.set(key, userNum.toString(), 3600);
        } else {
            userNum = Integer.valueOf(JedisClusterUtils.get(key));
        }
        List<String> headUrlList = appletGroupSearchRecordBiz
                .getHeadUrlList(userNum, 3L);
        groupActivity4AppletDTO.setHeadUrlList(headUrlList);
        List<AppletGroupStatementDTO> statementDTOS = appletGroupSearchRecordBiz
                .getStatementList(userNum, headUrlList, groupActivity4AppletDTO.getId());
        groupActivity4AppletDTO.setStatementDTOList(statementDTOS);
        groupActivity4AppletDTO.setUserNumber(userNum);
    }

    /**
     * @return void
     * @Author David
     * @Description 设置线上网课
     * @Date 2020/4/24 16:59
     * @Param [rightsSetting, wechatUserId]
     **/
    @ParamLog(value = "填充线上专课", isAfterReturn = false)
    private RightsSetting setOnlineExclCourse(RightsSetting rightsSetting, Long wechatUserId, Integer readType, Long bookId, Integer currentPage, Integer numPerPage, Long officialAccountsId) {
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemTypeNew.ONLINE_EXCL_COURSE, readType);
        boolean hasPage = Objects.nonNull(currentPage) && Objects.nonNull(numPerPage);
        if (null != rightsSettingTitle){
            List<RightsNowItem> nowItems = null;
            if(hasPage){
                Map<String, Object> map = CollUtil.newHashMap(2);
                map.put("rightsSettingTitleId",rightsSettingTitle.getId());
                map.put("types",Collections.singletonList(RightsNowItemTypeNew.ONLINE_EXCL_COURSE.value));
                PageBeanNew<RightsNowItem> pageBeanNew = rightsNowItemDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getListByRightsSettingTitleId");
                nowItems = pageBeanNew.getRecordList();
                rightsSettingTitle.setRightsSettingItemList4Page(pageBeanNew);
            }else {
                nowItems = rightsNowItemDao.getListByRightsSettingTitleId(rightsSettingTitle.getId(), Collections.singletonList(RightsNowItemTypeNew.ONLINE_EXCL_COURSE.value));
            }
            processNowItems(rightsSettingTitle, nowItems, RightsNowItemTypeNew.ONLINE_EXCL_COURSE, rightsSetting.getId(), wechatUserId,
                    Long.valueOf(RightsNowItemTypeNew.ONLINE_EXCL_COURSE.value), BookConstant.MAX_NEWS_COUNT, bookId, currentPage, numPerPage,officialAccountsId);
            rightsSetting.setOnlineRightsSettingTitle(rightsSettingTitle);
        }
        return rightsSetting;
    }

    /**
     * @return void
     * @Author David
     * @Description 设置线上网课
     * @Date 2020/4/24 16:59
     * @Param [rightsSetting, wechatUserId]
     **/
    @ParamLog(value = "填充线上网课", isAfterReturn = false)
    private RightsSetting setOnlineCourse(RightsSetting rightsSetting, Long wechatUserId, Integer readType, Long bookId, Integer currentPage, Integer numPerPage, Long officialAccountsId) {
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemTypeNew.ONLINE_COURSE, readType);
        boolean hasPage = Objects.nonNull(currentPage) && Objects.nonNull(numPerPage);
        if (null != rightsSettingTitle){
            List<RightsNowItem> nowItems = null;
            if (hasPage){
                Map<String, Object> map = CollUtil.newHashMap(2);
                map.put("rightsSettingTitleId",rightsSettingTitle.getId());
                map.put("types",Collections.singletonList(RightsNowItemTypeNew.ONLINE_COURSE.value));
                PageBeanNew<RightsNowItem> pageBeanNew = rightsNowItemDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getListByRightsSettingTitleId");
                nowItems = pageBeanNew.getRecordList();
                rightsSettingTitle.setRightsSettingItemList4Page(pageBeanNew);
            }else {
                nowItems = rightsNowItemDao.getListByRightsSettingTitleId(rightsSettingTitle.getId(), Collections.singletonList(RightsNowItemTypeNew.ONLINE_COURSE.value));
            }
            processNowItems(rightsSettingTitle, nowItems, RightsNowItemTypeNew.ONLINE_COURSE, rightsSetting.getId(), wechatUserId,
                    Long.valueOf(RightsNowItemTypeNew.ONLINE_COURSE.value), BookConstant.MAX_NEWS_COUNT, bookId, currentPage, numPerPage,officialAccountsId);
            rightsSetting.setOnlineRightsSettingTitle(rightsSettingTitle);
        }
        return rightsSetting;
    }


    /**
     * @return void
     * @Author David
     * @Description 填充学习工具
     * @Date 2020/4/24 20:10
     * @Param [rightsSetting, wechatUserId]
     **/
    @ParamLog(value = "填充学习工具", isAfterReturn = false)
    private RightsSetting setCoach1V1(RightsSetting rightsSetting, Long wechatUserId, Integer readType, Long bookId, Long officialAccountsId) {
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemTypeNew.COACH, readType);
        if (null != rightsSettingTitle) {
            List<RightsNowItem> nowItems = rightsNowItemDao
                    .getListByRightsSettingTitleId(rightsSettingTitle.getId(), Collections.singletonList(RightsNowItemTypeNew.COACH.value));
            processNowItems(rightsSettingTitle, nowItems, RightsNowItemTypeNew.COACH, rightsSetting.getId(), wechatUserId,
                    Long.valueOf(RightsNowItemTypeNew.COACH.value), BookConstant.MAX_NEWS_COUNT, bookId, null, null,officialAccountsId);
            rightsSetting.setLearningToolTitle(rightsSettingTitle);
        }
        return rightsSetting;
    }



    /**
     * @return void
     * @Author David
     * @Description 填充学习工具
     * @Date 2020/4/24 20:10
     * @Param [rightsSetting, wechatUserId]
     **/
    @ParamLog(value = "填充学习工具", isAfterReturn = false)
    private RightsSetting setLearningTool(RightsSetting rightsSetting, Long wechatUserId, Integer readType, Long bookId, Long officialAccountsId) {
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemTypeNew.LEARNING_TOOL, readType);
        if (null != rightsSettingTitle) {
            List<RightsNowItem> nowItems = rightsNowItemDao
                    .getListByRightsSettingTitleId(rightsSettingTitle.getId(), Collections.singletonList(RightsNowItemTypeNew.LEARNING_TOOL.value));
            processNowItems(rightsSettingTitle, nowItems, RightsNowItemTypeNew.LEARNING_TOOL, rightsSetting.getId(), wechatUserId,
                    Long.valueOf(RightsNowItemTypeNew.LEARNING_TOOL.value), BookConstant.MAX_NEWS_COUNT, bookId, null, null,officialAccountsId);
            rightsSetting.setLearningToolTitle(rightsSettingTitle);
        }
        return rightsSetting;
    }

    /**
     * @return void
     * @Author David
     * @Description 填充抽奖
     * @Date 2020/4/24 20:10
     * @Param [rightsSetting, wechatUserId]
     **/
    @ParamLog(value = "填充抽奖", isAfterReturn = false)
    private RightsSetting setDraw(RightsSetting rightsSetting, Long wechatUserId, Integer readType, Long bookId, Long officialAccountsId) {
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemTypeNew.DRAW, readType);
        if (null != rightsSettingTitle){
            List<RightsNowItem> nowItems = rightsNowItemDao
                    .getListByRightsSettingTitleId(rightsSettingTitle.getId(), Collections.singletonList(RightsNowItemTypeNew.DRAW.value));
            processNowItems(rightsSettingTitle, nowItems, RightsNowItemTypeNew.DRAW, rightsSetting.getId(), wechatUserId,
                    Long.valueOf(RightsNowItemTypeNew.DRAW.value), BookConstant.MAX_NEWS_COUNT, bookId, null, null,officialAccountsId);
            rightsSetting.setDrawSettingTitle(rightsSettingTitle);
        }
        return rightsSetting;
    }

    @ParamLog(value = "填充礼券包", isAfterReturn = false)
    private RightsSetting setGiftCouponPackage(RightsSetting rightsSetting, Long wechatUserId, Integer readType, Long bookId) {
        fillGiftCouponPack(rightsSetting, readType);
        fillUserGiftReceiveStatus(rightsSetting, wechatUserId);
        return rightsSetting;
    }

    /**
     * @return com.pcloud.book.rightsSetting.entity.RightsSettingTitle
     * @Author David
     * @Description 获取权益标题
     * @Date 2020/4/24 20:07
     * @Param [rightsSetting, learningTool]
     **/
    private RightsSettingTitle getRightsSettingTitle(RightsSetting rightsSetting, RightsNowItemTypeNew learningTool, Integer readType) {
        List<RightsSettingTitle> rightsSettingTitles = rightsSettingTitleMapper.getByRightSettingId(rightsSetting.getId(), readType);
        Map<Integer, RightsSettingTitle> rightsSettingTitleMap = new HashMap<>();
        if (!ListUtils.isEmpty(rightsSettingTitles)) {
            rightsSettingTitleMap = rightsSettingTitles.stream()
                    .collect(Collectors.toMap(RightsSettingTitle::getRightsSettingNowType, Function.identity()));
        }
        RightsSettingTitle rightsSettingTitle = new RightsSettingTitle();
        if (null != rightsSettingTitleMap.get(learningTool.value)) {
            rightsSettingTitle = rightsSettingTitleMap.get(learningTool.value);
        }
        return rightsSettingTitle;
    }

    /**
     * @return void
     * @Author David
     * @Description 处理即刻资源
     * @Date 2020/4/24 17:45
     * @Param [nowItems]
     **/
    private void processNowItems(RightsSettingTitle rightsSettingTitle, List<RightsNowItem> nowItems, RightsNowItemTypeNew itemType,
                                 Long rightsSettingId, Long wechatUserId, Long rightsClassifyId,
                                 Integer top, Long bookId, Integer currentPage, Integer numPerPage,Long officialAccountsId) {
        if (null == rightsSettingTitle || null == rightsSettingTitle.getRightsSettingId()) {
            return;
        }
        Integer collage = 1;
        List<RightsNowItem> items = Lists.newArrayList();
        if (CollectionUtils.isEmpty(nowItems) &&
                rightsSettingTitle.getCollageState()!= null &&
                rightsSettingTitle.getCollageState().intValue() == collage.intValue() &&
                RightsServeTypeEnum.NEWS.name().equals(rightsSettingTitle.getServeType())) {
            // 填充咨询
            supplementNews(rightsSettingId, wechatUserId, rightsClassifyId, top, items,bookId, itemType.value, officialAccountsId);
            // 处理权益中的应用/作品
            fillProductAndApp(items);
            rightsSettingTitle.setRightsSettingItemList(items);
            return;
        }
//        // 处理权益中的应用/作品
//        fillProductAndApp(nowItems);
        //移除不能购买的应用或作品
        removeCanNotBuy(nowItems);
        for (RightsNowItem nowItem : nowItems) {
            if (itemType.value.equals(nowItem.getType())) {
                items.add(nowItem);
            }
        }
        // 首页才会拼 此处只有资讯才会补充资讯
        boolean hasPage = Objects.isNull(currentPage) || (Objects.equals(currentPage, 0) && Objects.equals(numPerPage, 4));
        if (hasPage && RightsServeTypeEnum.NEWS.name().equalsIgnoreCase(rightsSettingTitle.getServeType())) {
            if (items.size() < top && rightsSettingTitle.getCollageState() != null && rightsSettingTitle.getCollageState().intValue() == collage.intValue()) {
                // 填充咨询
                supplementNews(rightsSettingId, wechatUserId, rightsClassifyId, top - items.size(), items, bookId, itemType.value,officialAccountsId);
            }
        }
        // 处理权益中的应用/作品
        fillProductAndApp(items);
        rightsSettingTitle.setRightsSettingItemList(items);
    }

    /**
     * @return void
     * @Author David
     * @Description 补充咨询
     * @Date 2020/4/25 12:20
     * @Param [rightsSettingId, wechatUserId, rightsClassifyId, top, items]
     **/
    private void supplementNews(Long rightsSettingId, Long wechatUserId, Long rightsClassifyId, Integer top, List<RightsNowItem> items,
                                Long bookId, Integer type, Long officialAccountsId) {
        FillRightsSettingAppletsDTO applets = getFillRightsSettingApplets(rightsSettingId, wechatUserId, rightsClassifyId, top, bookId, officialAccountsId);
        List<AppletNews> news = applets.getDesignatedNews();
        if (ListUtils.isEmpty(news)) {
            return;
        }
        List<AppletNewsDTO> appletNewsDTOList = new ArrayList<>();
        BeanUtils.copyListProperties(news, appletNewsDTOList, AppletNewsDTO.class);
        appletNewsBiz.fillBrowseCount(appletNewsDTOList);
        Map<Long, Integer> newsBrowseCountMap = appletNewsDTOList.stream().collect(Collectors.toMap(AppletNewsDTO::getId, AppletNewsDTO::getBrowseCount,(key1, key2) -> key2));
        for (AppletNews appletNews : news) {
            Integer browseCount = MapUtils.isEmpty(newsBrowseCountMap) || null == newsBrowseCountMap.get(appletNews.getId()) ?
                    0 : newsBrowseCountMap.get(appletNews.getId());
            items.add(RightsNowItem.builder().serveId(appletNews.getId()).serveName(appletNews.getNewsName()).serveType(RightsServeTypeEnum.NEWS.name())
                    .serveTypeName("资讯").servePic(appletNews.getPic1()).type(type).jumpType(appletNews.getJumpType())
                    .jumpUrl(appletNews.getJumpUrl()).newsType(appletNews.getType()).crossedPrice(appletNews.getCrossedPrice()).
                                    appraisalType(appletNews.getAppraisalType()).appraisalImg(appletNews.getAppraisalImg()).
                            appraisalPrice(appletNews.getAppraisalPrice()).browseCount(browseCount).build());
        }
    }


    @Deprecated
    @ParamLog("填充资源")
    private void fillRightsNowItems(RightsSetting rightsSetting) {
        List<Integer> types = new ArrayList<>();
        types.add(RightsNowItemTypeNew.ONLINE_COURSE.value);
        types.add(RightsNowItemTypeNew.LEARNING_TOOL.value);
        types.add(RightsNowItemTypeNew.GIFT_COUPON_PACKAGE.value);
        types.add(RightsNowItemTypeNew.DRAW.value);
        types.add(RightsNowItemTypeNew.GROUP_SERVICE.value);
        List<RightsSettingTitle> rightsSettingTitles = rightsSettingTitleMapper.getByRightSettingId(rightsSetting.getId(), null);
        RightsSettingTitle rightsSettingTitler4Online = new RightsSettingTitle();
        RightsSettingTitle rightsSettingTitler4Learningtool = new RightsSettingTitle();
        RightsSettingTitle rightsSettingTitler4Draw = new RightsSettingTitle();
        RightsSettingTitle rightsSettingTitler4Serves = new RightsSettingTitle();
        rightsSettingTitler4Serves.setOpenState(Boolean.TRUE);
        rightsSettingTitler4Serves.setRightsSettingNowType(RightsNowItemTypeNew.SERVES.value);
        RightsSettingTitle rightsSettingTitler4Group = new RightsSettingTitle();
        Map<Integer, RightsSettingTitle> rightsSettingTitleMap = new HashMap<>();
        if (!ListUtils.isEmpty(rightsSettingTitles)) {
            rightsSettingTitleMap =
                    rightsSettingTitles.stream()
                            .collect(Collectors.toMap(RightsSettingTitle::getRightsSettingNowType, Function.identity()));
        }
        if (null != rightsSettingTitleMap.get(RightsNowItemTypeNew.ONLINE_COURSE.value)) {
            rightsSettingTitler4Online = rightsSettingTitleMap.get(RightsNowItemTypeNew.ONLINE_COURSE.value);
        }
        if (null != rightsSettingTitleMap.get(RightsNowItemTypeNew.LEARNING_TOOL.value)) {
            rightsSettingTitler4Learningtool = rightsSettingTitleMap.get(RightsNowItemTypeNew.LEARNING_TOOL.value);
        }
        if (null != rightsSettingTitleMap.get(RightsNowItemTypeNew.DRAW.value)) {
            rightsSettingTitler4Draw = rightsSettingTitleMap.get(RightsNowItemTypeNew.DRAW.value);
        }
        if (null != rightsSettingTitleMap.get(RightsNowItemTypeNew.GROUP_SERVICE.value)) {
            rightsSettingTitler4Group = rightsSettingTitleMap.get(RightsNowItemTypeNew.GROUP_SERVICE.value);
        }
        List<RightsNowItem> nowItems = rightsNowItemDao.getListByRightsSettingId(rightsSetting.getId(), types);
        if (!ListUtils.isEmpty(nowItems)) {
            rightsSettingTitler4Online.setRightsSettingItemList(
                    nowItems.stream().filter(s -> RightsNowItemTypeNew.ONLINE_COURSE.value.equals(s.getType()))
                            .collect(Collectors.toList()));
            rightsSettingTitler4Learningtool.setRightsSettingItemList(
                    nowItems.stream().filter(s -> RightsNowItemTypeNew.LEARNING_TOOL.value.equals(s.getType()))
                            .collect(Collectors.toList()));
            rightsSettingTitler4Draw.setRightsSettingItemList(
                    nowItems.stream().filter(s -> RightsNowItemTypeNew.DRAW.value.equals(s.getType())).collect(Collectors.toList()));
            rightsSettingTitler4Group.setRightsSettingItemList(
                    nowItems.stream().filter(s -> RightsNowItemTypeNew.GROUP_SERVICE.value.equals(s.getType()) && s.getServeType() != null)
                            .collect(Collectors.toList()));
            // 填充应用、作品、社群、资讯
            fillProductAndApp(nowItems);
        }
        rightsSetting.setOnlineRightsSettingTitle(rightsSettingTitler4Online);
        rightsSetting.setLearningToolTitle(rightsSettingTitler4Learningtool);
        rightsSetting.setDrawSettingTitle(rightsSettingTitler4Draw);
        rightsSetting.setGroupServiceTitle(rightsSettingTitler4Group);
        rightsSetting.setGiftCouponPackageTitle(null == rightsSettingTitleMap.get(RightsNowItemTypeNew.GIFT_COUPON_PACKAGE.value) ?
                new RightsSettingTitle() : rightsSettingTitleMap.get(RightsNowItemTypeNew.GIFT_COUPON_PACKAGE.value));
        rightsSetting.setServesTitle(null == rightsSettingTitleMap.get(RightsNowItemTypeNew.SERVES.value) ?
                rightsSettingTitler4Serves : rightsSettingTitleMap.get(RightsNowItemTypeNew.SERVES.value));
    }


    @Override
    public void fillProductAndApp(List<RightsNowItem> nowItems) {
        log.info("即享权益填充产品和app内容");
        if (ListUtils.isEmpty(nowItems)) {
            return;
        }
        List<Long> productIds = new ArrayList<>();
        List<Long> appIds = new ArrayList<>();
        List<Long> groupIds = new ArrayList<>();
        List<Long> appletNewsId = new ArrayList<>();
        List<Long> booklistIds = new ArrayList<>();
        for (RightsNowItem item : nowItems) {
            if (item.getServeId() != null && AppAndProductTypeEnum.PRODUCT.value.equals(item.getServeType())
                    && !productIds.contains(item.getServeId())) {
                productIds.add(item.getServeId());
            }
            if (item.getServeId() != null && AppAndProductTypeEnum.APP.value.equals(item.getServeType())
                    && !productIds.contains(item.getServeId())) {
                appIds.add(item.getServeId());
            }
            if (item.getServeId() != null && RightsServeTypeEnum.GROUP.name().equals(item.getServeType())
                    && !groupIds.contains(item.getServeId())) {
                groupIds.add(item.getServeId());
            }
            if (item.getServeId() != null && RightsServeTypeEnum.NEWS.name().equals(item.getServeType())
                    && !appletNewsId.contains(item.getServeId())) {
                appletNewsId.add(item.getServeId());
            }
            if (item.getServeId() != null && RightsServeTypeEnum.BOOKLIST.name().equals(item.getServeType()) && !booklistIds
                    .contains(item.getServeId())){
                booklistIds.add(item.getServeId());
            }
        }
        Map<Long, ProductDto> productDtoMap = new HashMap<>();
        Map<Long, AppDto> appDtoMap = new HashMap<>();
        Map<Long, GroupActivity4AppletDTO> groupDtoMap = new HashMap<>();
        Map<Long, AppletNewsDTO> newsDtoMap = new HashMap<>();
        Map<Long, AppletOuterBooklistDTO> outerBooklistDTOMap = new HashMap<>();
        List<RightsNowItem> list_remove = new ArrayList<>(); //存储已经删除群的群分类; 精选文章类型并且跳转链接包含qrcode.5rs.me
        FutureTask<Map<Long, ProductDto>> task = null;
        FutureTask<Map<Long, AppDto>> task2 = null;
        if (!ListUtils.isEmpty(productIds)) {
            Callable<Map<Long, ProductDto>> callable = () -> productConsr.getProBasesByIds(productIds);
            task = new FutureTask<>(callable);
            new Thread(task).start();
        }
        if (!ListUtils.isEmpty(appIds)) {
            Callable<Map<Long, AppDto>> callable = () -> appConsr.mapByIds4AuditPass(appIds);
            task2 = new FutureTask<>(callable);
            new Thread(task2).start();
        }
        if (task!=null) {
            try {
                productDtoMap = task.get();
            } catch (InterruptedException e) {
                log.error("获取商品失败fillProductAndApp");
            } catch (ExecutionException e) {
                log.error("获取商品失败fillProductAndApp");
            }
        }
        if (task2!=null) {
            try {
                appDtoMap = task2.get();
            } catch (InterruptedException e) {
                log.error("获取应用失败fillProductAndApp");
            } catch (ExecutionException e) {
                log.error("获取应用失败fillProductAndApp");
            }
        }
        if (!ListUtils.isEmpty(groupIds)) {
            groupDtoMap = pcloudGroupActivityBiz.getByIds4Now(groupIds);
        }
        if (!ListUtils.isEmpty(appletNewsId)) {
            newsDtoMap = appletNewsBiz.getByIds(appletNewsId);
        }
        if (!ListUtils.isEmpty(booklistIds)){
            outerBooklistDTOMap = appletBooklistBiz.getByIds(booklistIds);
        }
        Map<Long,AccountSettingDto>offMap = new HashMap<>();
        for (RightsNowItem item : nowItems) {
            Integer type = item.getType();
            //默认设置
            item.setOuterBooklistDTOS(Lists.newArrayList());
            //排序值，答案听力优先
            item.setRank(nowItems.indexOf(item)+10);
            if (null != type) {
                AccountSettingDto accountSettingDto;
                if (AppAndProductTypeEnum.PRODUCT.value.equals(item.getServeType())) {
                    ProductDto productDto = productDtoMap.get(item.getServeId());
                    if (productDto != null) {
                        item.setServeName(productDto.getProductName());
                        item.setServePic(productDto.getCoverImg());
                        item.setTransverseImg(productDto.getPicture1());
                        if (productDto.getProductTypeDto() != null) {
                            item.setServeTypeCode(productDto.getProductTypeDto().getTypeCode());
                            item.setServeTypeName(productDto.getProductTypeDto().getTypeName());
                        }
                        //获取channelId,/C1404/product/display/10234028?adviserId=1001587&proType=MEMBER&source_type=QRCODE
                        Long channelId = null;
                        String url = item.getLinkUrl();
                        if (url.contains("/C") && !url.startsWith("https")) {
                            url = url.substring(url.indexOf("/C") + 2);
                            url = url.substring(0, url.indexOf("/"));
                            if (!StringUtil.isEmpty(url)) {
                                channelId = Long.valueOf(url);
                            }
                        }
                        if (null != channelId) {
                            accountSettingDto = offMap.get(channelId);
                            if(accountSettingDto==null){
                                accountSettingDto = qrcodeSceneConsr.getWechatInfo(channelId);
                                offMap.put(channelId,accountSettingDto);
                            }
                          //  accountSettingDto = qrcodeSceneConsr.getWechatInfo(channelId);
                            if (null == accountSettingDto){
                                throw new BookBizException(BookBizException.PARAM_IS_NULL, "运营平台未配置公众号");
                            }
                            String resultLinkUrl = SendWeixinRequestTools.splitUrl(accountSettingDto, item.getLinkUrl());
                            item.setResultUrl(resultLinkUrl);
                        } else {
                            item.setResultUrl(item.getLinkUrl());
                        }
                        if (!StringUtil.isEmpty(productDto.getSkipUrl())){
                            item.setHasThirdLink(true);
                        } else {
                            item.setHasThirdLink(false);
                        }
                        if (bookGroupBiz.checkRayUrl(productDto.getSkipUrl()) && ProductTypeConstant.ARTICLE.equals(item.getServeTypeCode())){
                            list_remove.add(item);
                        }
                    }
                    this.setRank(item);
                    continue;
                }
                if (AppAndProductTypeEnum.APP.value.equals(item.getServeType())) {
                    AppDto appDto = appDtoMap.get(item.getServeId());
                    if (appDto != null) {
                        if (bookGroupBiz.checkRayUrl(appDto.getTurnUrl()) && AppTypeEnum.ARTICLE.value.equals(appDto.getTypeCode())){
                            list_remove.add(item);
                        }
                        item.setServeName(appDto.getTitle());
                        item.setServePic(appDto.getSquareImg());
                        item.setServeTypeCode(appDto.getTypeCode());
                        item.setServeTypeName(appDto.getTypeName());
                        item.setTransverseImg(appDto.getTransverseImg());
                        accountSettingDto = offMap.get(appDto.getChannelId());
                        if(accountSettingDto==null){
                            accountSettingDto = qrcodeSceneConsr.getWechatInfo(appDto.getChannelId());
                            offMap.put(appDto.getChannelId(),accountSettingDto);
                        }
                        if (null == accountSettingDto){
                            throw new BookBizException(BookBizException.PARAM_IS_NULL, "运营平台未配置公众号");
                        }
                        String resultLinkUrl = SendWeixinRequestTools.splitUrl(accountSettingDto, item.getLinkUrl());
                        item.setResultUrl(resultLinkUrl);
                        if (!StringUtil.isEmpty(appDto.getTurnUrl())){
                            item.setHasThirdLink(true);
                        } else {
                            item.setHasThirdLink(false);
                        }
                    } else {
                        list_remove.add(item); //把要移除的统一放在一个集合
                    }
                    this.setRank(item);
                    continue;
                }
                if (RightsServeTypeEnum.GROUP.name().equals(item.getServeType())) {
                    GroupActivity4AppletDTO groupActivity4AppletDTO = groupDtoMap.get(item.getServeId());
                    if (groupActivity4AppletDTO != null) {
                        item.setGroupName(groupActivity4AppletDTO.getName());
                        item.setGroupDesc(groupActivity4AppletDTO.getCutDesc());
                        item.setPrice(groupActivity4AppletDTO.getPrice());
                        if (StringUtil.isEmpty(item.getGroupType())){ //add by pans 编辑段群groupType来源于rightNowItem
                            item.setGroupType(groupActivity4AppletDTO.getGroupType() == null ? null :groupActivity4AppletDTO.getGroupType().toString());
                            item.setLinkUrl(groupActivity4AppletDTO.getGroupLink());
                        }
                        // 填充头像
                        fillGroupActivityHead(Collections.singletonList(groupActivity4AppletDTO));
                        item.setGroupQrCode(groupActivity4AppletDTO.getGroupPic());
                        item.setGroupActivity4AppletDTO(groupActivity4AppletDTO);
                    }else{
                        list_remove.add(item); //把要移除的统一放在一个集合
                    }
                    continue;
                }
                if (RightsServeTypeEnum.NEWS.name().equals(item.getServeType())) {
                    AppletNewsDTO appletNewsDTO = newsDtoMap.get(item.getServeId());
                    if (appletNewsDTO != null) {
                        item.setNewsName(appletNewsDTO.getNewsName());
                        item.setNewsSource(appletNewsDTO.getSource());
                        item.setSource(appletNewsDTO.getSource());
                        // item的type字段跟appletNewsDTO的type字段有些冲突，前端会根据type来展示不同的样式
                        //item.setType(appletNewsDTO.getType());
                        item.setNewsType(appletNewsDTO.getType());
                        item.setServeId(appletNewsDTO.getId());
                        item.setServePic(appletNewsDTO.getPic1());
                        item.setServeName(appletNewsDTO.getNewsName());
                        item.setServeTypeName("资讯");
                        item.setJumpType(appletNewsDTO.getJumpType());
                        item.setJumpUrl(appletNewsDTO.getJumpUrl());
                        item.setPic1(appletNewsDTO.getPic1());
                        item.setPic2(appletNewsDTO.getPic2());
                        item.setPic3(appletNewsDTO.getPic3());
                        item.setDigest(appletNewsDTO.getDigest());
                        item.setDigest(appletNewsDTO.getDigest());
                        item.setUrlNumber(appletNewsDTO.getUrlNumber());
                        item.setCrossedPrice(appletNewsDTO.getCrossedPrice());
                        item.setAppraisalPrice(appletNewsDTO.getAppraisalPrice());
                        item.setAppraisalType(appletNewsDTO.getAppraisalType());
                        item.setAppraisalImg(appletNewsDTO.getAppraisalImg());
                        item.setBrowseCount(appletNewsDTO.getBrowseCount());
                    }
                    continue;
                }
                if (RightsServeTypeEnum.BOOKLIST.name().equals(item.getServeType())) {
                    AppletOuterBooklistDTO outerBooklistDTO = outerBooklistDTOMap.get(item.getServeId());
                    if (null != outerBooklistDTO){
                        item.getOuterBooklistDTOS().add(outerBooklistDTO);
                        item.setBooklistName(outerBooklistDTO.getBooklistName());
                        item.setUserName(outerBooklistDTO.getUserName());
                        item.setPublish(outerBooklistDTO.getPublish());
                        item.setDisplayPic(outerBooklistDTO.getDisplayPic());
                    }
                    continue;
                }
            }
        }

        nowItems.removeAll(list_remove);
    }

    @Override
    public AppletNewsDTO getAppletNewsDTO4UserReadBook(AppletUserBookcase userReadBook) {
        AppletNewsDTO appletNewsDTO = new AppletNewsDTO();
        BaseTempletClassify baseTempletClassify = appletUserBookcaseDao.getBookClassifyInfo(userReadBook.getBookId(), userReadBook.getChannelId(), userReadBook.getAdviserId());
        if (Objects.nonNull(baseTempletClassify) && Objects.nonNull(baseTempletClassify.getFirstClassify())) {
            rightsSettingBiz.setClassifyAndLabel(baseTempletClassify);
            Integer deepRead = null;
            Integer easyRead = null;
            Integer efficientRead = null;
            if (ReadTypeEnum.QS_READ.value.equals(userReadBook.getReadType())) {
                easyRead = 1;
            } else if (ReadTypeEnum.GX_READ.value.equals(userReadBook.getReadType())) {
                efficientRead = 1;
            } else if (ReadTypeEnum.SD_READ.value.equals(userReadBook.getReadType())) {
                deepRead = 1;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("firstClassify", baseTempletClassify.getFirstClassify());
            map.put("secondClassify", baseTempletClassify.getSecondClassify());
            map.put("gradeLabelId", baseTempletClassify.getGradeLabelId());
            map.put("subjectLabelId", baseTempletClassify.getSubjectLabelId());
            map.put("deepRead", deepRead);
            map.put("easyRead", easyRead);
            map.put("efficientRead", efficientRead);
            PageBeanNew<AppletNewsDTO> page = appletNewsDao.listPageNew(new PageParam(0, 1), map, "getClassifyNewsByTempletLabel");
            if (Objects.nonNull(page) && CollUtil.isNotEmpty(page.getRecordList())) {
                appletNewsDTO = page.getRecordList().get(0);
            } else {
                map.put("firstClassify", baseTempletClassify.getFirstClassify());
                map.put("secondClassify", baseTempletClassify.getSecondClassify());
                map.put("gradeLabelId", baseTempletClassify.getGradeLabelId());
                map.put("subjectLabelId", baseTempletClassify.getSubjectLabelId());
                map.put("rightsType", null);
                page = appletNewsDao.listPageNew(new PageParam(0, 1), map, "getPageByNewsByTempletLabel");
                if (Objects.nonNull(page) && CollUtil.isNotEmpty(page.getRecordList())) {
                    appletNewsDTO = page.getRecordList().get(0);
                }
            }
        }
        return appletNewsDTO;
    }

    @Override
    @ParamLog("落地页获取本书配套资料")
    public QrcodeMessage4WechatVO getRightsItemGroupsByBookGroup(Long bookGroupId, Long wechatUserId) {
        QrcodeMessage4WechatVO qrcodeMessage4WechatVO = new QrcodeMessage4WechatVO();
        if (null == bookGroupId) {
            return qrcodeMessage4WechatVO;
        }
        BookGroupDTO bookGroupDTO = bookGroupDao.getDTOById(bookGroupId);
        if (null == bookGroupDTO) {
            return qrcodeMessage4WechatVO;
        }
        Long bookId = bookGroupDTO.getBookId();
        Long channelId = bookGroupDTO.getChannelId();
        Long adviserId = bookGroupDTO.getCreateUser();
        //获取出版社名称
        Map<Long, AdviserBaseInfoDto> adviserInfoDtoMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(Lists.newArrayList(adviserId));
        if (MapUtils.isNotEmpty(adviserInfoDtoMap) && null != adviserInfoDtoMap.get(adviserId)) {
            qrcodeMessage4WechatVO.setAgentName(adviserInfoDtoMap.get(adviserId).getAgentName());
        }
        BookDto bookDto = bookBiz.getBaseById(bookId);
        if (null == bookDto) {
            return qrcodeMessage4WechatVO;
        }
        //设置图书基本信息
        qrcodeMessage4WechatVO.setBookId(bookId);
        qrcodeMessage4WechatVO.setBookName(bookDto.getBookName());
        qrcodeMessage4WechatVO.setBookCoverImg(bookDto.getCoverImg());
        qrcodeMessage4WechatVO.setReaderInfo(Lists.newArrayList());
        List<WechatMessageVO> messages = new ArrayList<>();
        List<BookServeDTO> bookServeVOS;
        if (JoinGroupTypeEnum.XIAORUI.getCode().equals(bookGroupDTO.getJoinGroupType())
                && QrcodeJumpType.H5_RESOURCE.getCode().equals(bookGroupDTO.getJumpType())){
            //获取该码下配的资源
            bookServeVOS = bookGroupBiz.getServeListByBookGroupId(bookGroupId, channelId);
        } else {
            //获取本书资源
            bookServeVOS = bookGroupBiz.getBookAndBookGroupServeIds(adviserId, bookId, channelId);
        }
        if (ListUtils.isEmpty(bookServeVOS)) {
            return qrcodeMessage4WechatVO;
        }
        //填充作品应用
        bookGroupBiz.fillBookServe(bookServeVOS);
        if (ListUtils.isEmpty(bookServeVOS)) {
            return qrcodeMessage4WechatVO;
        }
        AccountSettingDto accountSettingDto = qrcodeSceneConsr.getWechatInfo(channelId);
        if (null == accountSettingDto){
            return qrcodeMessage4WechatVO;
        }
        //转换数据格式
        bookServeVOS.stream().forEach(bookServeDTO -> {
            WechatMessageVO wechatMessageVO = new WechatMessageVO();
            wechatMessageVO.setUrl(SendWeixinRequestTools.splitUrl(accountSettingDto, bookServeDTO.getUrl()));
            wechatMessageVO.setTitle(bookServeDTO.getServeName());
            wechatMessageVO.setTypeCode(bookServeDTO.getServeType());
            wechatMessageVO.setFromId(bookServeDTO.getServeId());
            wechatMessageVO.setFromType(bookServeDTO.getFromType());
            wechatMessageVO.setShortName(bookServeDTO.getFromTypeName());
            messages.add(wechatMessageVO);
        });
        qrcodeMessage4WechatVO.setMessages(messages);
        return qrcodeMessage4WechatVO;
    }

    @Override
    public Integer getPopupCount(Long wechatUserId, Long bookId, Integer popupType) {
        return rightsNowPopupDao.getPopupCount(wechatUserId, bookId, popupType);
    }

    private void fillGiftCouponPack(RightsSetting rightsSetting, Integer readType) {
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemTypeNew.GIFT_COUPON_PACKAGE, readType);
        if (null != rightsSettingTitle){
            List<RightsNowItem> giftCouponPackItems = rightsNowItemDao.getGiftCouponListByRightsSettingTitleId(rightsSettingTitle.getId());
            if (null == rightsSettingTitle || null == rightsSettingTitle.getRightsSettingId()) {
                return;
            }
            rightsSettingTitle.setRightsSettingItemList(giftCouponPackItems);
            rightsSetting.setGiftCouponPackageTitle(rightsSettingTitle);
        }
    }


    @Override
    @ParamLog(value = "获取权益分类分页列表", isAfterReturn = false)
    public PageBeanNew<RightsSettingDto> listRightsSettingPage(Integer currentPage, Integer numPerPage, RightsSetting rightsSetting) {
        Map<String, Object> paramMap = new HashMap<>();
        if (null != rightsSetting.getFirstClassify()) {
            setClassifyAndLabel(rightsSetting);
        }
        paramMap.put("rightsSettingType", rightsSetting.getRightsSettingType());
        PageBeanNew<RightsSettingDto> rightsSettingDtoPageBeanNew;
        if (rightsSetting.getRightsSettingType() == 2) {//书刊权益
            if (!StringUtil.isEmpty(rightsSetting.getBookQuery())) {
                String bookQueryString = rightsSetting.getBookQuery().trim();
                String[] bookQuerys = bookQueryString.split(" ");
                List<String> bookQueryList = Arrays.stream(bookQuerys).map(e -> e.trim()).filter(e -> StringUtil.isNotBlank(e)).collect(Collectors.toList());
                paramMap.put("bookQueryList", bookQueryList);
            }
            Long agentId = rightsSetting.getAgentId();
            if (null != agentId && agentId>0){
                List<Long> adviserIds = adviserConsr.getByAgentId(agentId);
                if (!ListUtils.isEmpty(adviserIds)){
                    paramMap.put("adviserIds", adviserIds);
                }
            }
            paramMap.put("firstClassify", rightsSetting.getFirstClassify());
            paramMap.put("secondClassify", rightsSetting.getSecondClassify());
            paramMap.put("thirdClassify", rightsSetting.getThirdClassify());
            paramMap.put("gradeLabelId", rightsSetting.getGradeLabelId());
            paramMap.put("subjectLabelId", rightsSetting.getSubjectLabelId());
            paramMap.put("volLabelId", rightsSetting.getVolLabelId());
            paramMap.put("verLabelId", rightsSetting.getVerLabelId());
            rightsSettingDtoPageBeanNew = rightsSettingDAO
                    .listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listBookRightsSettingPage");
            //填充编辑名称
            fillAdviserName(rightsSettingDtoPageBeanNew.getRecordList());
            fillPartyName(rightsSettingDtoPageBeanNew.getRecordList());
            fillBookGroupUrl(rightsSettingDtoPageBeanNew.getRecordList());
            //填充书籍分类
            fillLabelNames4DTO(rightsSettingDtoPageBeanNew.getRecordList());
        } else {
            paramMap.put("firstClassify", rightsSetting.getFirstClassify());
            paramMap.put("secondClassify", rightsSetting.getSecondClassify());
            paramMap.put("thirdClassify", rightsSetting.getThirdClassify());
            paramMap.put("gradeLabelId", rightsSetting.getGradeLabelId());
            paramMap.put("subjectLabelId", rightsSetting.getSubjectLabelId());
            paramMap.put("volLabelId", rightsSetting.getVolLabelId());
            paramMap.put("verLabelId", rightsSetting.getVerLabelId());
            rightsSettingDtoPageBeanNew = rightsSettingDAO
                    .listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listRightsSettingPage");
        }
        if (null != rightsSettingDtoPageBeanNew && !ListUtils.isEmpty(rightsSettingDtoPageBeanNew.getRecordList())) {
            List<RightsSettingDto> rightsSettingDtos = rightsSettingDtoPageBeanNew.getRecordList();
            setLabelContent(rightsSettingDtos);
        }


        return rightsSettingDtoPageBeanNew;
    }

    private void fillBookGroupUrl(List<RightsSettingDto> recordList) {
        if (ListUtils.isEmpty(recordList) ) {
            return;
        }
        List<Long> bookIds = new ArrayList<>();
        recordList.stream().forEach(rightsSettingDto -> {
            List<RightsSettingBookRelation> rightsSettingBookRelations = rightsSettingDto.getRightsSettingBookRelations();
            if (ListUtils.isEmpty(rightsSettingBookRelations)) {
                return;
            }
            rightsSettingBookRelations.stream().forEach(rightsSettingBookRelation -> bookIds.add(rightsSettingBookRelation.getBookId()));
        });
        if (ListUtils.isEmpty(bookIds)) {
            return;
        }
        Map<Long, QrcodeSceneDto> qrcodeSceneDtoMap = channelConsr.listQrcodeScene4Rights(bookIds);
        if (MapUtils.isEmpty(qrcodeSceneDtoMap)) {
            return;
        }
        recordList.forEach(rightsSettingDto -> {
            List<RightsSettingBookRelation> rightsSettingBookRelations = rightsSettingDto.getRightsSettingBookRelations();
            if (ListUtils.isEmpty(rightsSettingBookRelations)) {
                return;
            }
            rightsSettingBookRelations.stream().forEach(rightsSettingBookRelation -> {
                if (null == rightsSettingBookRelation.getGroupQrcodeUrl() && null != qrcodeSceneDtoMap.get(rightsSettingBookRelation.getBookId())) {
                    rightsSettingBookRelation.setGroupQrcodeUrl(qrcodeSceneDtoMap.get(rightsSettingBookRelation.getBookId()).getQrcodeUrl());
                }
            });
        });

    }

    private void fillLabelNames4DTO(List<RightsSettingDto> rightsSettingList) {
        if (ListUtils.isEmpty(rightsSettingList)) {
            return;
        }
        List<Long> classifyIds = new ArrayList<>();
        List<Long> bookLabelIds = new ArrayList<>();
        List<Long> labelIds = new ArrayList<>();
        rightsSettingList.stream().forEach(rightsSetting -> {
            if (null == rightsSetting || ListUtils.isEmpty(rightsSetting.getRightsSettingBookRelations())) {
                return;
            }
            List<RightsSettingBookRelation> rightsSettingBookRelations = rightsSetting.getRightsSettingBookRelations();
            rightsSettingBookRelations.stream().forEach(rightsSettingBookRelation -> {
                if (null != rightsSettingBookRelation.getTempletId()) {
                    classifyIds.add(rightsSettingBookRelation.getTempletId());
                }
                if (null != rightsSettingBookRelation.getSecondTempletId()) {
                    classifyIds.add(rightsSettingBookRelation.getSecondTempletId());
                }
                if (null != rightsSettingBookRelation.getThirdTempletId()) {
                    classifyIds.add(rightsSettingBookRelation.getThirdTempletId());
                }

                if (null != rightsSettingBookRelation.getGraLabelId()) {
                    bookLabelIds.add(rightsSettingBookRelation.getGraLabelId());
                }
                if (null != rightsSettingBookRelation.getSubLabelId()) {
                    bookLabelIds.add(rightsSettingBookRelation.getSubLabelId());
                }
                if (null != rightsSettingBookRelation.getVolLabelId()) {
                    bookLabelIds.add(rightsSettingBookRelation.getVolLabelId());
                }
                if (null != rightsSettingBookRelation.getVerLabelId()){
                    bookLabelIds.add(rightsSettingBookRelation.getVerLabelId());
                }
                if (null != rightsSettingBookRelation.getAreaLabelId()) {
                    bookLabelIds.add(rightsSettingBookRelation.getAreaLabelId());
                }
                if (rightsSettingBookRelation.getProLabelId() != null) {
                    labelIds.add(rightsSettingBookRelation.getProLabelId());
                }
                if (rightsSettingBookRelation.getPurLabelId() != null) {
                    labelIds.add(rightsSettingBookRelation.getPurLabelId());
                }
                if (rightsSettingBookRelation.getDepLabelId() != null) {
                    labelIds.add(rightsSettingBookRelation.getDepLabelId());
                }
            });
        });
        Map<Long, AssistTempletDTO> classifyMap = new HashMap<>();
        Map<Long, BookLabel> bookLabelMap = new HashMap<>();
        Map<Long, String> labelMap = new HashMap<>();


        if (!ListUtils.isEmpty(classifyIds)) {
            classifyMap = assistTempletConsr.mapByIds4Classify(classifyIds);
        }
        if (!ListUtils.isEmpty(bookLabelIds)) {
            bookLabelMap = bookLabelDao.getMapByIds(bookLabelIds);
        }
        if (!ListUtils.isEmpty(labelIds)) {
            labelMap = ResponseHandleUtil.parseMap(labelService.getLabelName(labelIds), Long.class, String.class);
        }
        for (RightsSettingDto rightsSetting : rightsSettingList) {
            if (null == rightsSetting || ListUtils.isEmpty(rightsSetting.getRightsSettingBookRelations())) {
                continue;
            }
            List<RightsSettingBookRelation> rightsSettingBookRelations = rightsSetting.getRightsSettingBookRelations();
            for (RightsSettingBookRelation rightsSettingBookRelation : rightsSettingBookRelations) {

                if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingBookRelation.getTempletId())) {
                    rightsSettingBookRelation.setTempletName(classifyMap.get(rightsSettingBookRelation.getTempletId()).getTempletName());
                }
                if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingBookRelation.getSecondTempletId())) {
                    rightsSettingBookRelation.setSecondTempletName(classifyMap.get(rightsSettingBookRelation.getSecondTempletId()).getTempletName());
                }
                if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingBookRelation.getThirdTempletId())) {
                    rightsSettingBookRelation.setThirdTempletName(classifyMap.get(rightsSettingBookRelation.getThirdTempletId()).getTempletName());
                }
                if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingBookRelation.getGraLabelId())) {
                    rightsSettingBookRelation.setGraLabelName(bookLabelMap.get(rightsSettingBookRelation.getGraLabelId()).getName());
                }
                if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingBookRelation.getSubLabelId())) {
                    rightsSettingBookRelation.setSubLabelName(bookLabelMap.get(rightsSettingBookRelation.getSubLabelId()).getName());
                }
                if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingBookRelation.getVolLabelId())) {
                    rightsSettingBookRelation.setVolLabelName(bookLabelMap.get(rightsSettingBookRelation.getVolLabelId()).getName());
                }
                if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingBookRelation.getVerLabelId())) {
                    rightsSettingBookRelation.setVerLabelName(bookLabelMap.get(rightsSettingBookRelation.getVerLabelId()).getName());
                }
                if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingBookRelation.getAreaLabelId())) {
                    rightsSettingBookRelation.setAreaLabelName(bookLabelMap.get(rightsSettingBookRelation.getAreaLabelId()).getName());
                }
                //设置深度标签
                if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingBookRelation.getDepLabelId())) {
                    rightsSettingBookRelation.setDepLabelName(labelMap.get(rightsSettingBookRelation.getDepLabelId()));
                }
                if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingBookRelation.getPurLabelId())) {
                    rightsSettingBookRelation.setPurLabelName(labelMap.get(rightsSettingBookRelation.getPurLabelId()));
                }
                if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingBookRelation.getProLabelId())) {
                    rightsSettingBookRelation.setProLabelName(labelMap.get(rightsSettingBookRelation.getProLabelId()));
                }
            }
        }
    }

    private void fillPartyName(List<RightsSettingDto> recordList) {
        if (ListUtils.isEmpty(recordList) ) {
            return;
        }
        List<Long> userIds = new ArrayList<>();
        recordList.stream().forEach(rightsSettingDto -> {
            if (null != rightsSettingDto.getCreateUserId()) {
                userIds.add(rightsSettingDto.getCreateUserId());
            }
            if (null != rightsSettingDto.getUpdateUserId()) {
                userIds.add(rightsSettingDto.getUpdateUserId());
            }
        });
        if (ListUtils.isEmpty(userIds)) {
            return;
        }
        Map<Long, String> userNamesMap = partyConsr.getAllUserLoginName(0L, SystemCode.pcloud.code);
        if (MapUtils.isEmpty(userNamesMap)) {
            return;
        }
        recordList.stream().forEach(rightsSettingDto -> {
            if (null != rightsSettingDto.getCreateUserId()) {
                rightsSettingDto.setCreateUserName(userNamesMap.get(rightsSettingDto.getCreateUserId()));
            }
            if (null != rightsSettingDto.getUpdateUserId()) {
                rightsSettingDto.setUpdateUserName(userNamesMap.get(rightsSettingDto.getUpdateUserId()));
            }
        });

    }


    private void fillAdviserName(List<RightsSettingDto> recordList) {
        if (ListUtils.isEmpty(recordList) ) {
            return;
        }
        List<Long> adviserIds = new ArrayList<>();
        recordList.stream().forEach(rightsSettingDto -> {
            List<RightsSettingBookRelation> rightsSettingBookRelations = rightsSettingDto.getRightsSettingBookRelations();
            if (ListUtils.isEmpty(rightsSettingBookRelations)) {
                return;
            }
            rightsSettingBookRelations.stream().forEach(rightsSettingBookRelation -> adviserIds.add(rightsSettingBookRelation.getAdviserId()));
        });
        if (ListUtils.isEmpty(adviserIds)) {
            return;
        }
        Map<Long, AdviserBaseInfoDto> infoDtoMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(adviserIds);
        if (MapUtils.isEmpty(infoDtoMap)) {
            return;
        }
        recordList.forEach(rightsSettingDto -> {
            List<RightsSettingBookRelation> rightsSettingBookRelations = rightsSettingDto.getRightsSettingBookRelations();
            if (ListUtils.isEmpty(rightsSettingBookRelations)) {
                return;
            }
            rightsSettingBookRelations.stream().forEach(rightsSettingBookRelation -> {
                if (null != infoDtoMap.get(rightsSettingBookRelation.getAdviserId())) {
                    rightsSettingBookRelation.setAdviserName(infoDtoMap.get(rightsSettingBookRelation.getAdviserId()).getPartyName());
                    rightsSettingBookRelation.setAgentName(infoDtoMap.get(rightsSettingBookRelation.getAdviserId()).getAgentName());
                }
            });
        });
    }

    private void setRelationBooks(List<RightsSettingDto> rightsSettingDtos) {
        List<RightsSettingBookRelation> rightsSettingBookRelations = new ArrayList<>();
        rightsSettingDtos.forEach(rightsSettingDto -> {
            if (!ListUtils.isEmpty(rightsSettingDto.getRightsSettingBookRelations())) {
                rightsSettingBookRelations.addAll(rightsSettingDto.getRightsSettingBookRelations());
            }
        });
        if (ListUtils.isEmpty(rightsSettingBookRelations)) {
            return;
        }
        List<Long> bookIds = rightsSettingBookRelations.stream().map(e -> e.getBookId()).collect(Collectors.toList());
        if (ListUtils.isEmpty(bookIds)) {
            return;
        }
        Map<Long, BookDto> bookDtoMap = bookBiz.getListByIds(bookIds);
        if (MapUtils.isEmpty(bookDtoMap)) {
            return;
        }
        rightsSettingDtos.forEach(rightsSettingDto -> {
            if (ListUtils.isEmpty(rightsSettingDto.getRightsSettingBookRelations())) {
                return;
            }
            rightsSettingDto.getRightsSettingBookRelations().forEach(rightsSettingBookRelation -> {
                if (bookDtoMap.containsKey(rightsSettingBookRelation.getBookId()) && null != bookDtoMap
                        .get(rightsSettingBookRelation.getBookId())) {
                    rightsSettingBookRelation.setBookName(bookDtoMap.get(rightsSettingBookRelation.getBookId()).getBookName());
                }
            });
        });
    }


    private void setLabelContent(List<RightsSettingDto> rightsSettingDtos) {
        log.info("权益设置标签具体内容");
        if (ListUtils.isEmpty(rightsSettingDtos)) {
            return;
        }
        List<Long> classifyIds = new ArrayList<>();
        List<Long> bookLabelIds = new ArrayList<>();
        List<Long> labelIds = new ArrayList<>();
        for (RightsSettingDto rightsSettingDto : rightsSettingDtos) {
            if (null != rightsSettingDto.getFirstClassify()) {
                classifyIds.add(rightsSettingDto.getFirstClassify());
            }
            if (null != rightsSettingDto.getSecondClassify()) {
                classifyIds.add(rightsSettingDto.getSecondClassify());
            }
            if (null != rightsSettingDto.getThirdClassify()) {
                classifyIds.add(rightsSettingDto.getThirdClassify());
            }
            if (null != rightsSettingDto.getGradeLabelId()) {
                bookLabelIds.add(rightsSettingDto.getGradeLabelId());
            }
            if (null != rightsSettingDto.getSubjectLabelId()) {
                bookLabelIds.add(rightsSettingDto.getSubjectLabelId());
            }
            if (null != rightsSettingDto.getVolLabelId()) {
                bookLabelIds.add(rightsSettingDto.getVolLabelId());
            }
            if (null != rightsSettingDto.getVerLabelId()){
                bookLabelIds.add(rightsSettingDto.getVerLabelId());
            }
            if (null != rightsSettingDto.getAreaLabelId()){
                bookLabelIds.add(rightsSettingDto.getAreaLabelId());
            }
            if (rightsSettingDto.getProLabelId() != null) {
                labelIds.add(rightsSettingDto.getProLabelId());
            }
            if (rightsSettingDto.getPurLabelId() != null) {
                labelIds.add(rightsSettingDto.getPurLabelId());
            }
            if (rightsSettingDto.getDepLabelId() != null) {
                labelIds.add(rightsSettingDto.getDepLabelId());
            }
        }
        Map<Long, AssistTempletDTO> classifyMap = new HashMap<>();
        Map<Long, BookLabel> bookLabelMap = new HashMap<>();
        Map<Long, String> labelMap = new HashMap<>();

        if (!ListUtils.isEmpty(classifyIds)) {
            classifyMap = assistTempletConsr.mapByIds4Classify(classifyIds);
        }
        if (!ListUtils.isEmpty(bookLabelIds)) {
            bookLabelMap = bookLabelDao.getMapByIds(bookLabelIds);
        }
        if (!ListUtils.isEmpty(labelIds)) {
            labelMap = ResponseHandleUtil.parseMap(labelService.getLabelName(labelIds), Long.class, String.class);
        }
        for (RightsSettingDto rightsSettingDto : rightsSettingDtos) {
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingDto.getFirstClassify())) {
                rightsSettingDto.setFirstClassifyContent(classifyMap.get(rightsSettingDto.getFirstClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingDto.getSecondClassify())) {
                rightsSettingDto.setSecondClassifyContent(classifyMap.get(rightsSettingDto.getSecondClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingDto.getThirdClassify())) {
                rightsSettingDto.setThirdClassifyContent(classifyMap.get(rightsSettingDto.getThirdClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingDto.getGradeLabelId())) {
                rightsSettingDto.setGradeLabelIdContent(bookLabelMap.get(rightsSettingDto.getGradeLabelId()).getName());
            }
            if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingDto.getSubjectLabelId())) {
                rightsSettingDto.setSubjectLabelIdContent(bookLabelMap.get(rightsSettingDto.getSubjectLabelId()).getName());
            }
            if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingDto.getVolLabelId())) {
                rightsSettingDto.setVolLabelContent(bookLabelMap.get(rightsSettingDto.getVolLabelId()).getName());
            }
            if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingDto.getVerLabelId())){
                rightsSettingDto.setVerLabelContent(bookLabelMap.get(rightsSettingDto.getVerLabelId()).getName());
            }
            if (!MapUtils.isEmpty(bookLabelMap) && bookLabelMap.containsKey(rightsSettingDto.getAreaLabelId())){
                rightsSettingDto.setAreaLabelContent(bookLabelMap.get(rightsSettingDto.getAreaLabelId()).getName());
            }
            //设置深度标签
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingDto.getDepLabelId())){
                rightsSettingDto.setDepLabelName(labelMap.get(rightsSettingDto.getDepLabelId()));
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingDto.getPurLabelId())){
                rightsSettingDto.setPurLabelName(labelMap.get(rightsSettingDto.getPurLabelId()));
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingDto.getProLabelId())){
                rightsSettingDto.setProLabelName(labelMap.get(rightsSettingDto.getProLabelId()));
            }
        }
    }

    @Override
    public RightsSettingDto getByLabel(Long firstClassify, Long secondClassify, Long gradeLabelId, Long subjectLabelId, Long volLabelId,
                                       Long verLabelId, Long thirdTempletId) {

       /* //医疗保健分类校验
        if (ArrayUtils.contains(RightsSettingConstant.MEDICAL_INSURANCE_TEMPLET_ID, firstClassify)) {
            subjectLabelId = null;
            gradeLabelId = null;
        }
        //k12教育分类校验
        else if ("test".equals(envStr) && ArrayUtils.contains(RightsSettingConstant.K12_TEMPLET_ID_TEST, firstClassify)) {
            secondClassify = null;
        } else if (!"test".equals(envStr) && ArrayUtils.contains(RightsSettingConstant.K12_TEMPLET_ID, firstClassify)) {
            secondClassify = null;
        } else {
            secondClassify = null;
            subjectLabelId = null;
            gradeLabelId = null;
        }
        //上下册分类校验
        if (!ArrayUtils.contains(RightsSettingConstant.K12_VOLUME_ID, firstClassify)) {
            volLabelId = null;
        }
        //版本标签校验
        if (!ArrayUtils.contains(RightsSettingConstant.K12_VERSION_ID, firstClassify)){
            verLabelId = null;
        }*/
        //todo 新分类
        BaseTempletClassify baseTempletClassify = new BaseTempletClassify();
        baseTempletClassify.setFirstClassify(firstClassify);
        baseTempletClassify.setSecondClassify(secondClassify);
        baseTempletClassify.setThirdClassify(thirdTempletId);
        baseTempletClassify.setGradeLabelId(gradeLabelId);
        baseTempletClassify.setSubjectLabelId(subjectLabelId);
        baseTempletClassify.setVolLabelId(volLabelId);
        baseTempletClassify.setVerLabelId(verLabelId);
        setClassifyAndLabel(baseTempletClassify);
        RightsSettingDto dto = rightsSettingDAO.getByLabel(firstClassify, secondClassify, gradeLabelId, subjectLabelId, volLabelId, verLabelId, thirdTempletId);
        if (null == dto) {
            dto = rightsSettingDAO.getByLabel(firstClassify, secondClassify, gradeLabelId, subjectLabelId, volLabelId, verLabelId, null);
            if (null == dto) {
                dto = rightsSettingDAO.getByLabel(firstClassify, null, gradeLabelId, subjectLabelId, volLabelId, verLabelId, null);
            }
        }
        //有版本筛选但权益未配置
        if (null == dto && null != verLabelId && verLabelId > 0) {
            Long commonLabelId = bookLabelDao.getByNameType("通用版", 3);
            dto = rightsSettingDAO.getByLabel(firstClassify, secondClassify, gradeLabelId, subjectLabelId, volLabelId, commonLabelId, thirdTempletId);
            if (null == dto) {
                dto = rightsSettingDAO.getByLabel(firstClassify, secondClassify, gradeLabelId, subjectLabelId, volLabelId, commonLabelId, null);
                if (null == dto) {
                    dto = rightsSettingDAO.getByLabel(firstClassify, null, gradeLabelId, subjectLabelId, volLabelId, commonLabelId, null);
                }
            }
        }
        if (null == dto) {
            Long defaultRightsSettingId = bookBiz.getDefaultRightsSettingId();
            dto = rightsSettingDAO.getDTOById(defaultRightsSettingId);
        }
        return dto;
    }

    @Override
    public Integer getUserCount() {
        Integer userCount = null;
        String key = "BOOK:APPLET:RIGHTS_SETTING_USER_COUNT";
        String value = JedisClusterUtils.get(key);
        if (StringUtil.isEmpty(value)) {
            userCount = RandomUtil.randomInt(3000, 5000);
            JedisClusterUtils.set(key, userCount.toString(), 24 * 3600);
        } else {
            userCount = Integer.valueOf(value);
        }
        return userCount;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void batchInsertRightsSettingItem(List<RightsSettingItem> rightsSettingItemList, Long rightsSettingId, String rightsType) {
        if (null == rightsSettingId || StringUtil.isEmpty(rightsType)) {
            return;
        }
        // 删除子数据
        RightsSettingItem paramItem = new RightsSettingItem();
        paramItem.setRightsSettingId(rightsSettingId);
        paramItem.setRightsType(rightsType);
        List<RightsSettingItem> list = rightsSettingItemDao.queryAll(paramItem);
        if (!ListUtils.isEmpty(list)) {
            rightsSettingItemDetailDao.deleteByItemIds(list.stream().map(x -> x.getId()).collect(Collectors.toList()));
        }
        rightsSettingItemDao.deleteByRightsSettingId(rightsSettingId, rightsType);
        if (!ListUtils.isEmpty(rightsSettingItemList)) {
            for (RightsSettingItem rightsSettingItem : rightsSettingItemList) {
                rightsSettingItem.setRightsSettingId(rightsSettingId);
                rightsSettingItem.setRightsType(rightsType);
                rightsSettingItem.setDisplayType(rightsSettingItem.getDisplayType()==null?0:rightsSettingItem.getDisplayType());
            }
            rightsSettingItemDao.insert(rightsSettingItemList);
        }
    }

    @Override
    public List<RightsSettingItem> getItemsByRightsSettingId(Long rightsSettingId, String rightsType, Integer readType, Integer currentPage, Integer numPerPage) {
        RightsSettingItem item = new RightsSettingItem();
        item.setRightsSettingId(rightsSettingId);
        item.setRightsType(rightsType);
        item.setReadType(readType);
        return rightsSettingItemDao.queryAll(item);
    }

    @Override
    @ParamLog(value = "小程序首页权益查询", isAfterReturn = false)
    public RightsSettingDto getRightsSettingByBookId4AppletHome(Long bookId, Long adviserId, Long channelId) {
        //根据书获取权益
        RightsSettingDto rightsSettingDto = rightsSettingDAO.getByBookId(bookId);
        if (null != rightsSettingDto && Objects.equals(Boolean.TRUE, rightsSettingDto.getShowState()) ) {
            rightsSettingDto
                    .setRightsSettingBookRelations(rightsSettingBookRelationMapper.selectByRithsSettingId(rightsSettingDto.getId()));
        }
        if (null == rightsSettingDto || !Objects.equals(Boolean.TRUE, rightsSettingDto.getShowState())) {
            //根据分类获取权益
            BookAdviserDto adviserDto = bookAdviserBiz.getBase(bookId, channelId, adviserId);
            if (null != adviserDto) {
                rightsSettingDto = getByLabel(adviserDto.getTempletId(), adviserDto.getSecondTempletId(), adviserDto.getGraLabelId(),
                        adviserDto.getSubLabelId(), adviserDto.getVolLabelId(), adviserDto.getVerLabelId(), adviserDto.getThirdTempletId());
            }
        }
        if (null == rightsSettingDto) {
            return new RightsSettingDto();
        }
        return rightsSettingDto;
    }

    @Override
    @ParamLog(value = "小程序首页权益类型", isAfterReturn = false)
    public Integer getRightsTypeByBookId4AppletHome(Long bookId, Long adviserId, Long channelId) {
        //根据书获取权益
        RightsSettingDto rightsSettingDto = rightsSettingDAO.getByBookId(bookId);
        if (null != rightsSettingDto && Objects.equals(Boolean.TRUE, rightsSettingDto.getShowState()) ) {
            return 1;
        }
        if (null == rightsSettingDto || !Objects.equals(Boolean.TRUE, rightsSettingDto.getShowState())) {
            //根据分类获取权益
            BookAdviserDto adviserDto = bookAdviserBiz.getBase(bookId, channelId, adviserId);
            if (null != adviserDto) {
                rightsSettingDto = getByLabel(adviserDto.getTempletId(), adviserDto.getSecondTempletId(), adviserDto.getGraLabelId(),
                        adviserDto.getSubLabelId(), adviserDto.getVolLabelId(), adviserDto.getVerLabelId(), adviserDto.getThirdTempletId());
            }
        }
        if (null != rightsSettingDto && rightsSettingDto.getId() != null) {
            return 2;
        }
        return 3;
    }

    @Override
    @ParamLog(value = "小程序首页本周/长期权益查询", isAfterReturn = false)
    public RightsSettingDto getItemByRightsSettingId4AppletHome(Long rightsSettingId, Long wechatUserId, String rightsType,
                                                                Integer readType, Long bookId, Long adviserId, Long channelId, Integer currentPage, Integer numPerPage,Long officialAccountsId) {
        RightsSettingDto rightsSettingDto = new RightsSettingDto();
        Long agentId = appletNewsBiz.getAgentIdByAccountId(officialAccountsId);
        //每周/长期权益
        if (RightsTypeEnum.WEEK.value.equals(rightsType)) {
            rightsSettingDto.setRightsSettingWeekItems(
                    getItemsByRightsSettingId4Applet(rightsSettingId, RightsTypeEnum.WEEK.value, wechatUserId, readType, bookId, adviserId, channelId, null, currentPage, numPerPage,agentId));
        } else if (RightsTypeEnum.LONG_TERM.value.equals(rightsType)) {
            String cityCode = readerConsr.getCityCodeByWechatUserId(wechatUserId);
            rightsSettingDto.setRightsSettingLongTermItems(getItemsByRightsSettingId4Applet(rightsSettingId, RightsTypeEnum.LONG_TERM.value, wechatUserId, readType, bookId, adviserId, channelId, cityCode, currentPage, numPerPage,agentId));
        }
        // 处理馆配图书
        processLibraryBook(bookId, adviserId, rightsSettingDto);
        //填充收藏
        fillCollect(wechatUserId, rightsSettingDto, RightsWeekTypeEnum.ONLINE_REMIND.key);
        return rightsSettingDto;
    }

    /**
     * 馆配图书 不展示书单
     *
     */
    private void processLibraryBook(Long bookId, Long adviserId, RightsSettingDto rightsSettingDto) {
        if (bookBiz.checkIsLibraryBook(adviserId, bookId)) {
            List<RightsSettingItem> rightsSettingLongTermItems = rightsSettingDto.getRightsSettingLongTermItems();
            if (CollUtil.isNotEmpty(rightsSettingLongTermItems)) {
                for (RightsSettingItem rightsSettingLongTermItem : rightsSettingLongTermItems) {
                    if (Objects.nonNull(rightsSettingLongTermItem)) {
                        rightsSettingLongTermItem.setOuterBooklistDTOS(new ArrayList<>());
                    }
                }
            }

            List<RightsSettingItem> rightsSettingWeekItems = rightsSettingDto.getRightsSettingWeekItems();
            if (CollUtil.isNotEmpty(rightsSettingWeekItems)) {
                for (RightsSettingItem rightsSettingWeekItem : rightsSettingWeekItems) {
                    if (Objects.nonNull(rightsSettingWeekItem)) {
                        rightsSettingWeekItem.setOuterBooklistDTOS(new ArrayList<>());
                    }
                }
            }
        }
    }

    @Override
    public List<RightsSettingItem> getItemsByRightsSettingId4Applet(Long rightsSettingId, String rightsType, Long wechatUserId,
                                                                           Integer readType, Long bookId, Long adviserId, Long channelId, String cityCode, Integer currentPage, Integer numPerPage,Long agentId) {
        List<RightsSettingItem> list = getItemsByRightsSettingId(rightsSettingId, rightsType, readType, currentPage, numPerPage);
        Integer collage = 1; //拼群

        if (ListUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        // 加载平台端自己选择的社群、方案、资讯等数据
        fillRightsSettingItemDetail(list);
        // 线上学习/阅读提醒
        fillReadPlan(list, rightsType, readType, bookId, adviserId, channelId);
        // 筛选出没有选择 社群、方案、资讯 的数据
        List<RightsSettingItem> needFillAppletNews = Lists.newArrayList();
        for (RightsSettingItem rightsSettingItem : list) {

            if (RightsServeTypeEnum.GROUP.name().equals(rightsSettingItem.getServeType()) && rightsSettingItem.getCollageState() != null
                    && rightsSettingItem.getCollageState().intValue() == collage.intValue()
                    && (ListUtils.isEmpty(rightsSettingItem.getGroupActivity4AppletList())
                    || rightsSettingItem.getGroupActivity4AppletList().size() < 3)) {

                Integer top = 3;
                if (!ListUtils.isEmpty(rightsSettingItem.getGroupActivity4AppletList())) {
                    top = top - rightsSettingItem.getGroupActivity4AppletList().size();
                }
                // 填充群
                List<RightsNowItem> items = new ArrayList<>();
                List<GroupActivity4AppletDTO> collageList = supplementGroup(rightsSettingId, wechatUserId, rightsSettingItem.getRightsClassifyId(), top, items, bookId, rightsType,
                        readType,agentId);
                if (!ListUtils.isEmpty(collageList)){
                    for (GroupActivity4AppletDTO item :collageList){
                        rightsSettingItem.getGroupActivity4AppletList().add(item);

                        // 填充头像
                        fillGroupActivityHead(Collections.singletonList(item));
                    }
                }
            }
            if (rightsSettingItem.getServeType() == null
                    || RightsServeTypeEnum.GROUP.name().equalsIgnoreCase(rightsSettingItem.getServeType()) && ListUtils
                    .isEmpty(rightsSettingItem.getGroupActivity4AppletList())
                    || RightsServeTypeEnum.NEWS.name().equalsIgnoreCase(rightsSettingItem.getServeType())) {
                if ((ListUtils.isEmpty(rightsSettingItem.getAppletNewsDTOS()) || rightsSettingItem.getAppletNewsDTOS().size() <3)
                        && rightsSettingItem.getCollageState()!= null  && rightsSettingItem.getCollageState().intValue() == collage.intValue()){
                    needFillAppletNews.add(rightsSettingItem);
                }
            }
        }

        // 有分页参数时，只有首页需要补充
        if ((Objects.nonNull(currentPage)&&Objects.nonNull(numPerPage)&&currentPage!=0) || ListUtils.isEmpty(needFillAppletNews)) {
            fillPageParam(list,currentPage,numPerPage);
            return list;
        }
        // 将未选择服务的数据补充资讯
        setAppletNews4Week(rightsSettingId, rightsType, wechatUserId, needFillAppletNews,bookId,cityCode,agentId);
        //填充资讯的浏览量
        fillNewsBrowseCount(needFillAppletNews);

        /*
        List<Long> rightsSettingItemIds =
                list.stream().filter(e -> YesOrNoEnums.YES.getValue().equals(e.getIsOpen())
                    && RightsNowItemTypeNew.ONLINE_REMIND.value.equals(e.getRightsClassifyId().intValue()))
                    .map(e -> e.getId()).collect(Collectors.toList());

        if (!ListUtils.isEmpty(rightsSettingItemIds)) {
            List<RightsCustomRelation> rightsCustomRelations = rightsCustomRelationDao.getCustomByItemIds(rightsSettingItemIds);
            list = setReadPlan4Week(rightsCustomRelations, list);
        }

        // 线上读书活动社群
        rightsSettingItemIds = list.stream().filter(e -> YesOrNoEnums.YES.getValue().equals(e.getIsOpen())
            && RightsNowItemTypeNew.ONLINE_READING_ACTIVITY.value.equals(e.getRightsClassifyId().intValue()))
            .map(e -> e.getId()).collect(Collectors.toList());
        if (!ListUtils.isEmpty(rightsSettingItemIds)) {
            setGroupActivity(list, rightsSettingItemIds);
        }
        */
        fillPageParam(list,currentPage,numPerPage);
        return list;
    }

    private void fillNewsBrowseCount(List<RightsSettingItem> needFillAppletNews) {
        log.info("填充资讯浏览量：{}", needFillAppletNews);
        List<Long> appletNewsIds = new ArrayList<>();
        needFillAppletNews.stream().forEach(rightsSettingItem -> {
            if (!ListUtils.isEmpty(rightsSettingItem.getAppletNewsDTOS())) {
                appletNewsIds.addAll(rightsSettingItem.getAppletNewsDTOS().stream().map(e -> e.getId()).collect(Collectors.toList()));
            }
        });
        if (ListUtils.isEmpty(appletNewsIds)) {
            return;
        }
        Map<Long, AppletNewsDTO> appletMap = appletNewsBiz.getByIds(appletNewsIds);
        if (MapUtils.isEmpty(appletMap)) {
            return;
        }
        needFillAppletNews.stream().forEach(rightsSettingItem -> {
            List<AppletNewsDTO> appletNewsDTOS = rightsSettingItem.getAppletNewsDTOS();
            if (ListUtils.isEmpty(appletNewsDTOS)) {
                return;
            }
            appletNewsDTOS.stream().forEach(appletNewsDTO -> {
                if (null != appletMap.get(appletNewsDTO.getId())) {
                    appletNewsDTO.setBrowseCount(appletMap.get(appletNewsDTO.getId()).getBrowseCount());
                }
            });
        });
    }

    private void fillPageParam(List<RightsSettingItem> list, Integer currentPage, Integer numPerPage) {
        if (Objects.nonNull(currentPage)&&Objects.nonNull(numPerPage)){
            for (RightsSettingItem rightsSettingItem : list) {
                if (Objects.nonNull(rightsSettingItem) && RightsWeekTypeEnum.OFFLINE_READING_ACTIVITY.getKey() == rightsSettingItem.getRightsClassifyId().intValue()) {
                    List<AppletNewsDTO> appletNewsDTOS = rightsSettingItem.getAppletNewsDTOS();
                    if (CollUtil.isNotEmpty(appletNewsDTOS)) {
                        rightsSettingItem.setAppletNewsDTOS4Page(new PageBeanNew<>(currentPage, numPerPage, appletNewsDTOS));
                    }
                }
            }
        }
    }

    // 线上学习/阅读提醒（方案特殊处理）
    private void fillReadPlan(List<RightsSettingItem> list, String rightsType, Integer readType, Long bookId, Long adviserId, Long channelId) {
        List<RightsSettingItem> needFillPlanItems = Lists.newArrayList();
        boolean existsOnlineRemind = false;
        // 筛选点击方案单选框，并没有选具体方案的数据
        for (RightsSettingItem rightsSettingItem : list) {
            if(rightsSettingItem.getRightsClassifyId() != RightsWeekTypeEnum.ONLINE_REMIND.key.longValue()){
                continue;
            }
            existsOnlineRemind = true;
            if (RightsServeTypeEnum.PLAN.name().equalsIgnoreCase(rightsSettingItem.getServeType())
                    && ListUtils.isEmpty(rightsSettingItem.getCustomPlanList())) {
                needFillPlanItems.add(rightsSettingItem);
            }
        }
        // 如果书刊权益的线上学习的方案为空，那么取分类权益的对应的方案
        if(ListUtils.isEmpty(needFillPlanItems) && !existsOnlineRemind){
            // 根据分类获取权益
            BookAdviserDto adviserDto = bookAdviserBiz.getBase(bookId, channelId, adviserId);
            if (null == adviserDto) {
                return;
            }
            // 处理分类信息
            BaseTempletClassify classify = new BaseTempletClassify();
            classify.setFirstClassify(adviserDto.getTempletId());
            classify.setSecondClassify(adviserDto.getSecondTempletId());
            classify.setThirdClassify(adviserDto.getThirdTempletId());
            classify.setGradeLabelId(adviserDto.getGraLabelId());
            classify.setSubjectLabelId(adviserDto.getSubLabelId());
            classify.setVolLabelId(adviserDto.getVolLabelId());
            setClassifyAndLabel(classify);
            // 匹配分类下的分类权益所对应的方案
            List<RightsSettingItem> itemList = rightsSettingItemDao.getItemsByClassify(classify.getFirstClassify(),classify.getSecondClassify(),
                    classify.getGradeLabelId(),classify.getSubjectLabelId(),classify.getVolLabelId(),rightsType, readType, RightsWeekTypeEnum.ONLINE_REMIND.key.longValue(),classify.getThirdClassify());
            if(ListUtils.isEmpty(itemList)){
                return;
            }
            needFillPlanItems.add(itemList.get(0));
            list.add(itemList.get(0));
        }

        if(ListUtils.isEmpty(needFillPlanItems) || !NumberUtil.isNumber(bookId)|| !NumberUtil.isNumber(readType)){ return; }
        // 匹配ERP数据
        CustomPlan customPlan = null;
        // 根据 bookId 拿到 erp 的 projectId，再根据erp的bookId 在 custom_plan 匹配方案
        Long projectId = erpConsr.getProjectIdByBookId(bookId, adviserId, channelId);
        if(NumberUtil.isNumber(projectId)){
            customPlan = customPlanMapper.getLastCustomPlan(Lists.newArrayList(projectId), readType);
        }
        if(customPlan != null && NumberUtil.isNumber(customPlan.getId())){
            for (RightsSettingItem rightsSettingItem : needFillPlanItems) {
                rightsSettingItem.setCustomPlanList(Lists.newArrayList(customPlan));
            }
        }
    }

    private List<RightsSettingItem> setReadPlan4Week(List<RightsCustomRelation> rightsCustomRelations, List<RightsSettingItem> list) {
        log.info("为每周权益设置读书计划");
        if (ListUtils.isEmpty(list) || ListUtils.isEmpty(rightsCustomRelations)) {
            return list;
        }
        List<Long> customPlanIds = rightsCustomRelations.stream().map(e -> e.getCustomPlanId()).collect(Collectors.toList());
        if (ListUtils.isEmpty(customPlanIds)) {
            return list;
        }
        Map<Long, List<RightsCustomRelation>> rightsCustomRelationMap =
                rightsCustomRelations.stream().collect(Collectors.groupingBy(RightsCustomRelation::getRightsSettingItemId));
        List<CustomPlan> customPlans = customPlanMapper.getCustomPlanByIds(customPlanIds);
        if (ListUtils.isEmpty(customPlans)) {
            return list;
        }
        Map<Integer, CustomPlan> customPlanMap = customPlans.stream().collect(Collectors.toMap(CustomPlan::getId, a -> a, (k1, k2) -> k1));
        for (RightsSettingItem item : list) {
            List<CustomPlan> customPlans4ReadPlan = new ArrayList<>();
            List<RightsCustomRelation> customRelations = rightsCustomRelationMap.get(item.getId());
            if (ListUtils.isEmpty(customRelations)) {
                continue;
            }
            for (RightsCustomRelation rightsCustomRelation : customRelations) {
                if (customPlanMap.containsKey(rightsCustomRelation.getCustomPlanId().intValue())) {
                    customPlans4ReadPlan.add(customPlanMap.get(rightsCustomRelation.getCustomPlanId().intValue()));
                }
            }
            item.setCustomPlanList(customPlans4ReadPlan);
        }
        return list;
    }

    private List<RightsSettingItem> setAppletNews4Week(Long rightsSettingId, String rightsType, Long wechatUserId,
                                                       List<RightsSettingItem> list, Long bookId, String cityCode,Long agentId) {
        RightsSetting rightsSetting = rightsSettingDAO.selectByPrimaryKey(rightsSettingId);
        if (rightsSetting.getRightsSettingType() == 2) {//书刊权益，分类标签从编辑书刊取
            List<RightsSettingBookRelation> rightsSettingBookRelations =
                    rightsSettingBookRelationMapper.selectByRithsSettingId(rightsSettingId);
            if (ListUtils.isEmpty(rightsSettingBookRelations)) {
                return new ArrayList<>();
            }
            BookAdviserDto adviserDto = bookAdviserBiz.getOneMainBook(bookId);
            rightsSetting.setFirstClassify(adviserDto.getTempletId());
            rightsSetting.setSecondClassify(adviserDto.getSecondTempletId());
            rightsSetting.setThirdClassify(adviserDto.getThirdTempletId());
            rightsSetting.setGradeLabelId(adviserDto.getGraLabelId());
            rightsSetting.setSubjectLabelId(adviserDto.getSubLabelId());
        }
        //匹配资讯
        List<AppletNewsDTO> appletNewsDTOS = appletNewsBiz
                .getNewsByTempletLabel(rightsSetting.getFirstClassify(), rightsSetting.getSecondClassify(), rightsSetting.getGradeLabelId(),
                        rightsSetting.getSubjectLabelId(), rightsType, agentId, rightsSetting.getThirdClassify());
        if (ListUtils.isEmpty(appletNewsDTOS)) {
            //没有则根据书刊分类和标签获取
            appletNewsDTOS = appletNewsBiz.getNewsByTempletLabel(rightsSetting.getFirstClassify(), rightsSetting.getSecondClassify(),
                    rightsSetting.getGradeLabelId(), rightsSetting.getSubjectLabelId(), null,agentId, rightsSetting.getThirdClassify());
        }
        // 查询IP所在城市
        List<AppletNewsDTO> appletNews4Area = null;
        if (StrUtil.isNotBlank(cityCode)){
            // 查询城市对应资讯
            appletNews4Area = appletNewsDao.listNewsByCityCode(cityCode);
        }

        Map<Long, List<AppletNewsDTO>> map = null;
        if (CollUtil.isNotEmpty(appletNewsDTOS)) {
            map = appletNewsDTOS.stream().collect(Collectors.groupingBy(AppletNewsDTO::getRightsClassifyId));
        }
        for (RightsSettingItem item : list) {
            int top = 3;
            if(!ListUtils.isEmpty(item.getAppletNewsDTOS())){
                top = top - item.getAppletNewsDTOS().size();
            }

            //用户-权益-权益分类
            String key = "BOOK:RIGHTS_SETTING:USER_RIGHTS_ITEM" + wechatUserId + "-" + rightsSettingId + "-" + item.getRightsClassifyId();
            //权益分类下资讯
            List<AppletNewsDTO> newsDTOS = JedisClusterUtils.getJsonList(key, AppletNewsDTO.class);
            //数据库取
            if (ListUtils.isEmpty(newsDTOS) || newsDTOS.size() < top) {
                if (item.getRightsClassifyId() == 13){
                    if (CollUtil.isNotEmpty(appletNews4Area)&&CollUtil.isNotEmpty(item.getAppletNewsDTOS())){
                        Map<Long, AppletNewsDTO> itemMap = item.getAppletNewsDTOS().stream().collect(Collectors.toMap(AppletNewsDTO::getId, AppletNewsDTO -> AppletNewsDTO));
                        appletNews4Area.removeIf(appletNewsDTO -> itemMap.containsKey(appletNewsDTO.getId()));
                    }
                    newsDTOS = appletNews4Area;
                }else if(!MapUtils.isEmpty(map) && map.containsKey(item.getRightsClassifyId())) {
                    newsDTOS = map.get(item.getRightsClassifyId());
                }
                //随机取三条
                if (Objects.nonNull(newsDTOS) && newsDTOS.size() > top) {
                    List<AppletNewsDTO> dtos = new ArrayList<>();
                    while (dtos.size() < top) {
                        AppletNewsDTO dto = newsDTOS.get(new Random().nextInt(newsDTOS.size()));
                        if (!dtos.contains(dto)) {
                            dtos.add(dto);
                        }
                    }
                    newsDTOS = dtos;
                }
                // 地理位置匹配时，不进行缓存
                if (item.getRightsClassifyId() != 13){
                    JedisClusterUtils.setJsonList(key, newsDTOS, 60);
                }
            }
            if (!ListUtils.isEmpty(newsDTOS)){
                newsDTOS.forEach(newDto->{
                    item.getAppletNewsDTOS().add(newDto);
                });
            }
        }
        return list;
    }

    @Override
    public List<RightsSettingClassify> getAllRightsClassify(String rightsType) {
        return rightsSettingItemDao.getAllRightsClassify(rightsType);
    }

    @ParamLog("根据权益id获取即享权益项")
    @Override
    public RightsSetting getRightsSettingRightsNowItems(Long rightsSettingId, Long wechatUserId) {
        RightsSetting rightsSetting = rightsSettingDAO.selectByPrimaryKey(rightsSettingId);
        if (rightsSetting == null) {
            throw new BookBizException(BookBizException.ERROR, "未找到权益！");
        }
        fillRightsNowItems(rightsSetting);
        return rightsSetting;
    }

    @ParamLog("根据权益id和类型获取即享权益项")
    @Override
    public RightsSetting getRightsSettingRightsNowItemsByType(Long rightsSettingId, Long wechatUserId, Integer type, Long adviserId, Long bookId, Long channelId, Integer readType, Integer currentPage, Integer numPerPage,Long officialAccountsId) {
        RightsSetting rightsSetting = rightsSettingDAO.selectByPrimaryKey(rightsSettingId);
        if (rightsSetting == null) {
            throw new BookBizException(BookBizException.ERROR, "未找到权益！");
        }
        // 获取配套资料
        if (RightsNowItemTypeNew.SERVES.value.equals(type)) {
            String key = "SERVER_TYPE:"+rightsSettingId+"_"+adviserId+"_"+bookId+"_"+channelId+"_"+readType;
            if(JedisClusterUtils.exists(key)){
                String s = JedisClusterUtils.get(key);
                rightsSetting = JSON.parseObject(s, RightsSetting.class);
            }else {
                setServe(rightsSetting, adviserId, bookId, channelId, readType);
                JedisClusterUtils.set(key,JSON.toJSONString(rightsSetting),10*60);
            }
        }
        // 获取抽奖权益
        if (RightsNowItemTypeNew.DRAW.value.equals(type)) {
           setDraw(rightsSetting, wechatUserId, readType, bookId, officialAccountsId);
        }
        // 获取学习工具权益
        if (RightsNowItemTypeNew.LEARNING_TOOL.value.equals(type)) {
           setLearningTool(rightsSetting, wechatUserId, readType, bookId, officialAccountsId);
        }
        // 获取线上网课权益
        if (RightsNowItemTypeNew.ONLINE_COURSE.value.equals(type)) {
           setOnlineCourse(rightsSetting, wechatUserId, readType, bookId, currentPage, numPerPage,officialAccountsId);
        }
        // 获取专享礼券包权益
        if (RightsNowItemTypeNew.GIFT_COUPON_PACKAGE.value.equals(type)) {
          setGiftCouponPackage(rightsSetting, wechatUserId, readType, bookId);
        }
        // 获取专享社群
        if (RightsNowItemTypeNew.GROUP_SERVICE.value.equals(type)) {
           setGroupService(rightsSetting, wechatUserId, readType, bookId, currentPage, numPerPage,officialAccountsId);
        }
        // 老师1V1
        if (RightsNowItemTypeNew.COACH.value.equals(type)) {
           setCoach1V1(rightsSetting, wechatUserId, readType, bookId, officialAccountsId);
        }
        // 获取线上专课
        if (RightsNowItemTypeNew.ONLINE_EXCL_COURSE.value.equals(type)) {
           setOnlineExclCourse(rightsSetting, wechatUserId, readType, bookId, currentPage, numPerPage,officialAccountsId);
        }
        fillCollect(wechatUserId, rightsSetting, type);
        return rightsSetting;
    }

    private void fillCollect(Long wechatUserId, RightsSetting rightsSetting4Serves, Integer type) {
        if (null == wechatUserId || null == rightsSetting4Serves) {
            return;
        }
        List<RightsNowItem> rightsNowItemList = new ArrayList<>();
        if (RightsNowItemTypeNew.SERVES.value.equals(type)) {
            if (fillCollect4Serve(wechatUserId, rightsSetting4Serves)) {return;}
        } else if (RightsNowItemTypeNew.ONLINE_COURSE.value.equals(type)) {
            if (null != rightsSetting4Serves.getOnlineRightsSettingTitle() && !ListUtils.isEmpty(rightsSetting4Serves.getOnlineRightsSettingTitle().getRightsSettingItemList())){
                rightsNowItemList = rightsSetting4Serves.getOnlineRightsSettingTitle().getRightsSettingItemList();
            }
        } else if (RightsNowItemTypeNew.LEARNING_TOOL.value.equals(type)) {
            if (null != rightsSetting4Serves.getLearningToolTitle() && !ListUtils.isEmpty(rightsSetting4Serves.getLearningToolTitle().getRightsSettingItemList())){
                rightsNowItemList = rightsSetting4Serves.getLearningToolTitle().getRightsSettingItemList();
            }
        } else if (RightsNowItemTypeNew.DRAW.value.equals(type)) {
            if (null != rightsSetting4Serves.getDrawSettingTitle() && !ListUtils.isEmpty(rightsSetting4Serves.getDrawSettingTitle().getRightsSettingItemList())){
                rightsNowItemList = rightsSetting4Serves.getDrawSettingTitle().getRightsSettingItemList();
            }
        } else if (RightsNowItemTypeNew.ONLINE_EXCL_COURSE.value.equals(type)) {
            if (null != rightsSetting4Serves.getOnlineRightsSettingTitle() && !ListUtils.isEmpty(rightsSetting4Serves.getOnlineRightsSettingTitle().getRightsSettingItemList())){
                rightsNowItemList = rightsSetting4Serves.getOnlineRightsSettingTitle().getRightsSettingItemList();
            }
        } else if (RightsNowItemTypeNew.COACH.value.equals(type)) {
            if (null != rightsSetting4Serves.getLearningToolTitle() && !ListUtils.isEmpty(rightsSetting4Serves.getLearningToolTitle().getRightsSettingItemList())){
                rightsNowItemList = rightsSetting4Serves.getLearningToolTitle().getRightsSettingItemList();
            }
        } else if (RightsWeekTypeEnum.ONLINE_REMIND.key.equals(type)) {
            if (!ListUtils.isEmpty(rightsSetting4Serves.getRightsSettingWeekItems())){
                for (RightsSettingItem rightsSettingItem : rightsSetting4Serves.getRightsSettingWeekItems()) {
                    if (!ListUtils.isEmpty(rightsSettingItem.getRightsSettingItemList4Serve())) {
                        rightsNowItemList.addAll(rightsSettingItem.getRightsSettingItemList4Serve());
                    }
                }
            }
        }
        if (!ListUtils.isEmpty(rightsNowItemList)) {
            fillCollect4RightsNowItem(wechatUserId,rightsNowItemList);
        }
    }

    private boolean fillCollect4Serve(Long wechatUserId, RightsSetting rightsSetting4Serves) {
        List<RightsItemGroup> rightsItemGroups = rightsSetting4Serves.getRightsItemGroups();
        if (ListUtils.isEmpty(rightsItemGroups)) {
            return true;
        }
        List<RightsNowItem> rightsNowItems = new ArrayList<>();
        rightsItemGroups.forEach(rightsItemGroup -> {
            List<RightsNowItem> nowItems = rightsItemGroup.getRightsNowItems();
            if (ListUtils.isEmpty(nowItems)) {
                return;
            }
            List<RightsNowItem> productOrApps = nowItems.stream().filter(e -> Objects.equals(e.getServeType(), AppAndProductTypeEnum.PRODUCT.value) ||
                    Objects.equals(e.getServeType(), AppAndProductTypeEnum.APP.value)).collect(Collectors.toList());
            if (!ListUtils.isEmpty(productOrApps)) {
                rightsNowItems.addAll(productOrApps);
            }
        });
        if (ListUtils.isEmpty(rightsNowItems)) {
            return true;
        }
//        List<ServeCollect> serveCollects = new ArrayList<>();
//        rightsNowItems.forEach(e -> {
//            ServeCollect serveCollect = new ServeCollect();
//            serveCollect.setWechatUserId(wechatUserId);
//            serveCollect.setServeId(e.getServeId());
//            serveCollect.setServeType(Objects.equals(e.getServeType(), AppAndProductTypeEnum.PRODUCT.value) ? AppletRecordTypeEnum.PRODUCT.value : AppletRecordTypeEnum.APP.value);
//            serveCollects.add(serveCollect);
//        });
//      List<ServeCollect> serveCollectList = serveCollectBiz.getList4RightsSetting(serveCollects);
        List<ServeCollect> serveCollectList = serveCollectBiz.getList4RightsSettingByWechatUserId(wechatUserId);
        if (ListUtils.isEmpty(serveCollectList)) {
            return true;
        }
        List<ServeCollect> collect4Product = serveCollectList.stream().filter(e -> Objects.equals(e.getServeType(), AppletRecordTypeEnum.PRODUCT.value)).collect(Collectors.toList());
        List<ServeCollect> collect4App = serveCollectList.stream().filter(e -> Objects.equals(e.getServeType(), AppletRecordTypeEnum.APP.value)).collect(Collectors.toList());
        Map<Long, ServeCollect> serveCollectMap4Product = new HashMap<>();
        Map<Long, ServeCollect> serveCollectMap4App = new HashMap<>();
        if (!ListUtils.isEmpty(collect4Product)) {
            serveCollectMap4Product = collect4Product.stream().collect(Collectors.toMap(e -> e.getServeId(), a -> a, (k1, k2) -> k1));
        }
        if (!ListUtils.isEmpty(collect4App)) {
            serveCollectMap4App = collect4App.stream().collect(Collectors.toMap(e -> e.getServeId(), a -> a, (k1, k2) -> k1));
        }
        for (RightsItemGroup rightsItemGroup : rightsItemGroups) {
            List<RightsNowItem> nowItems = rightsItemGroup.getRightsNowItems();
            if (ListUtils.isEmpty(nowItems)) {
                continue;
            }
            List<RightsNowItem> productOrApps = nowItems.stream().filter(e -> Objects.equals(e.getServeType(), AppAndProductTypeEnum.PRODUCT.value) ||
                    Objects.equals(e.getServeType(), AppAndProductTypeEnum.APP.value)).collect(Collectors.toList());
            if (!ListUtils.isEmpty(productOrApps)) {
                for (RightsNowItem rightsNowItem : productOrApps) {
                    if (Objects.equals(rightsNowItem.getServeType(), AppAndProductTypeEnum.PRODUCT.value) && MapUtils.isNotEmpty(serveCollectMap4Product) &&
                            null != serveCollectMap4Product.get(rightsNowItem.getServeId())) {
                        rightsNowItem.setIsCollect(YesOrNoEnums.YES.getValue());
                    } else if (Objects.equals(rightsNowItem.getServeType(), AppAndProductTypeEnum.APP.value) && MapUtils.isNotEmpty(serveCollectMap4App) &&
                            null != serveCollectMap4App.get(rightsNowItem.getServeId())) {
                        rightsNowItem.setIsCollect(YesOrNoEnums.YES.getValue());
                    }
                }
            }
        }
        return false;
    }

    private void fillCollect4RightsNowItem(Long wechatUserId, List<RightsNowItem> rightsNowItems) {
        log.info("为应用或作品填充是否收藏");
//        List<ServeCollect> serveCollects = new ArrayList<>();
//        rightsNowItems.forEach(e -> {
//            ServeCollect serveCollect = new ServeCollect();
//            serveCollect.setWechatUserId(wechatUserId);
//            serveCollect.setServeId(e.getServeId());
//            serveCollect.setServeType(Objects.equals(e.getServeType(), AppAndProductTypeEnum.PRODUCT.value) ? AppletRecordTypeEnum.PRODUCT.value : AppletRecordTypeEnum.APP.value);
//            serveCollects.add(serveCollect);
//        });
       // List<ServeCollect> serveCollectList = serveCollectBiz.getList4RightsSetting(serveCollects);
        if (ListUtils.isEmpty(rightsNowItems)) {
            return;
        }
        List<ServeCollect> serveCollectList = serveCollectBiz.getList4RightsSettingByWechatUserId(wechatUserId);
        if (ListUtils.isEmpty(serveCollectList)) {
            return;
        }
        List<ServeCollect> collect4Product = serveCollectList.stream().filter(e -> Objects.equals(e.getServeType(), AppletRecordTypeEnum.PRODUCT.value)).collect(Collectors.toList());
        List<ServeCollect> collect4App = serveCollectList.stream().filter(e -> Objects.equals(e.getServeType(), AppletRecordTypeEnum.APP.value)).collect(Collectors.toList());
        Map<Long, ServeCollect> serveCollectMap4Product = new HashMap<>();
        Map<Long, ServeCollect> serveCollectMap4App = new HashMap<>();
        if (!ListUtils.isEmpty(collect4Product)) {
            serveCollectMap4Product = collect4Product.stream().collect(Collectors.toMap(e -> e.getServeId(), a -> a, (k1, k2) -> k1));
        }
        if (!ListUtils.isEmpty(collect4App)) {
            serveCollectMap4App = collect4App.stream().collect(Collectors.toMap(e -> e.getServeId(), a -> a, (k1, k2) -> k1));
        }
        List<RightsNowItem> productOrApps = rightsNowItems.stream().filter(e -> Objects.equals(e.getServeType(), AppAndProductTypeEnum.PRODUCT.value) ||
                Objects.equals(e.getServeType(), AppAndProductTypeEnum.APP.value)).collect(Collectors.toList());
        if (!ListUtils.isEmpty(productOrApps)) {
            for (RightsNowItem rightsNowItem : productOrApps) {
                if (Objects.equals(rightsNowItem.getServeType(), AppAndProductTypeEnum.PRODUCT.value) && MapUtils.isNotEmpty(serveCollectMap4Product) &&
                        null != serveCollectMap4Product.get(rightsNowItem.getServeId())) {
                    rightsNowItem.setIsCollect(YesOrNoEnums.YES.getValue());
                } else if (Objects.equals(rightsNowItem.getServeType(), AppAndProductTypeEnum.APP.value) && MapUtils.isNotEmpty(serveCollectMap4App) &&
                        null != serveCollectMap4App.get(rightsNowItem.getServeId())) {
                    rightsNowItem.setIsCollect(YesOrNoEnums.YES.getValue());
                }
            }
        }
    }

    @ParamLog(value = "填充专享社群", isAfterReturn = false)
    private RightsSetting setGroupService(RightsSetting rightsSetting, Long wechatUserId, Integer readType, Long bookId, Integer currentPage, Integer numPerPage, Long officialAccountsId) {
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemTypeNew.GROUP_SERVICE, readType);
        boolean hasPage = Objects.nonNull(currentPage) && Objects.nonNull(numPerPage);
        if (null != rightsSettingTitle) {
            List<RightsNowItem> nowItems = null;

            if(hasPage){
                Map<String, Object> map = CollUtil.newHashMap(2);
                map.put("rightsSettingTitleId",rightsSettingTitle.getId());
                map.put("types",Collections.singletonList(RightsNowItemTypeNew.GROUP_SERVICE.value));
                PageBeanNew<RightsNowItem> pageBeanNew = rightsNowItemDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getListByRightsSettingTitleId");
                nowItems = pageBeanNew.getRecordList();
                rightsSettingTitle.setRightsSettingItemList4Page(pageBeanNew);
            }else {
                nowItems = rightsNowItemDao.getListByRightsSettingTitleId(rightsSettingTitle.getId(), Collections.singletonList(RightsNowItemTypeNew.GROUP_SERVICE.value));
            }

            if (RightsServeTypeEnum.NEWS.name().equalsIgnoreCase(rightsSettingTitle.getServeType())){
                processNowItems(rightsSettingTitle, nowItems, RightsNowItemTypeNew.GROUP_SERVICE, rightsSetting.getId(), wechatUserId,
                        Long.valueOf(RightsNowItemTypeNew.GROUP_SERVICE.value), BookConstant.MAX_NEWS_COUNT, bookId, null, null,officialAccountsId);
                rightsSetting.setGroupServiceTitle(rightsSettingTitle);
            } else {
                processNowItems4Group(rightsSettingTitle, nowItems, RightsNowItemTypeNew.GROUP_SERVICE, rightsSetting.getId(), wechatUserId,
                        Long.valueOf(RightsNowItemTypeNew.GROUP_SERVICE.value), BookConstant.MAX_NEWS_COUNT, bookId,readType,officialAccountsId);
                rightsSetting.setGroupServiceTitle(rightsSettingTitle);
            }

        }
        return rightsSetting;
    }

    private void processNowItems4Group(RightsSettingTitle rightsSettingTitle, List<RightsNowItem> nowItems, RightsNowItemTypeNew itemType,
            Long rightsSettingId, Long wechatUserId, Long rightsClassifyId,
            Integer top, Long bookId, Integer readType,Long officialAccountsId) {
        if (null == rightsSettingTitle || null == rightsSettingTitle.getRightsSettingId()) {
            return;
        }
        Long agentId = appletNewsBiz.getAgentIdByAccountId(officialAccountsId);
        Integer collage = 1;  //状态为拼群
        List<RightsNowItem> items = Lists.newArrayList();

        if (CollectionUtils.isEmpty(nowItems) && rightsSettingTitle.getCollageState()!= null && rightsSettingTitle.getCollageState().intValue() == collage.intValue()) {
            // 填充群
            supplementGroup(rightsSettingId, wechatUserId, rightsClassifyId, top, items,bookId,null,readType,agentId);
            // 处理权益中的应用/作品
            fillProductAndApp(items);
            rightsSettingTitle.setRightsSettingItemList(items);
            return;
        }
        //移除不能购买的应用或作品
        removeCanNotBuy(nowItems);

        fillProductAndApp(nowItems);

        for (RightsNowItem nowItem : nowItems) {
            if (itemType.value.equals(nowItem.getType())) {
                items.add(nowItem);
            }
        }

        if (items.size() < top && rightsSettingTitle.getCollageState()!= null && rightsSettingTitle.getCollageState().intValue() == collage.intValue()) {
            // 填充咨询
            supplementGroup(rightsSettingId, wechatUserId, rightsClassifyId, top, items, bookId,null, readType,agentId);
        }
        // 处理权益中的应用/作品
        fillProductAndApp(items);
        rightsSettingTitle.setRightsSettingItemList(items);
    }

    private List<GroupActivity4AppletDTO> supplementGroup(Long rightsSettingId, Long wechatUserId,
            Long rightsClassifyId, Integer top, List<RightsNowItem> items, Long bookId, String rightsType,
            Integer readType,Long agentId) {
        // 书刊分类
        List<GroupActivity4AppletDTO> groupActivity4AppletDTOList = null;
        BookAdviserDto bookAdviserDto = bookAdviserBiz.getOneMainBook(bookId);
        if (bookAdviserDto != null && NumberUtil.isNumber(bookAdviserDto.getTempletId())) {
            BaseTempletClassify baseTempletClassify = new BaseTempletClassify();
            baseTempletClassify.setFirstClassify(bookAdviserDto.getTempletId());
            baseTempletClassify.setSecondClassify(bookAdviserDto.getSecondTempletId());
            baseTempletClassify.setThirdClassify(bookAdviserDto.getThirdTempletId());
            baseTempletClassify.setGradeLabelId(bookAdviserDto.getGraLabelId());
            baseTempletClassify.setSubjectLabelId(bookAdviserDto.getSubLabelId());
            baseTempletClassify.setVolLabelId(bookAdviserDto.getVolLabelId());
            baseTempletClassify.setAgentId(agentId);
            setClassifyAndLabel(baseTempletClassify);
            if (!ListUtils.isEmpty(items)) {
                top = top - items.size();
            }
            if (NumberUtil.isNumber(baseTempletClassify.getFirstClassify())) {
                // 通过书刊分类拿群
                groupActivity4AppletDTOList = pcloudGroupActivityBiz.getTishBookSchoolListWrap(baseTempletClassify, top);
            }
        }
        if (ListUtils.isEmpty(groupActivity4AppletDTOList)) {
            // 如果书刊没拿到群，则通过权益分类拿群
            RightsSetting rightsSetting = rightsSettingDAO.selectByPrimaryKey(rightsSettingId);

            //add by pansy 查询权益的拼群开关
            boolean isCollage= false;
            Integer collage= 1;
            if(!StringUtil.isEmpty(rightsType)){ //长期权益
                List<RightsSettingItem> rightsSettingItems = rightsSettingItemDao.getRightSettingInfo(RightsServeTypeEnum.GROUP.name(),rightsType,rightsSettingId);
                Iterator<RightsSettingItem> it = rightsSettingItems.iterator();
                while(it.hasNext()){
                    RightsSettingItem item= it.next();
                    if (item.getCollageState()!= null && item.getCollageState().intValue() == collage.intValue()){
                        isCollage = true;
                        break;
                    }
                }
            }else { //立享权益
                RightsSettingTitle rightsSettingTitle = rightsSettingTitleMapper.getByRightSettingIdAndType(rightsSettingId, RightsNowItemTypeNew.GROUP_SERVICE.value,readType);
//                List<RightsSettingTitle> rightsSettingTitles = rightsSettingTitleMapper.getByRightSettingId(rightsSettingId, null);
//                Iterator<RightsSettingTitle> it = rightsSettingTitles.iterator();
//                while(it.hasNext()){
//                    RightsSettingTitle item= it.next();
                    if (rightsSettingTitle.getCollageState()!= null && rightsSettingTitle.getCollageState().intValue() == collage.intValue() && RightsServeTypeEnum.GROUP.name().equalsIgnoreCase(rightsSettingTitle.getServeType()) ){
                        isCollage = true;
//                        break;
                    }
//                }
            }

            if(isCollage){
                setClassifyAndLabel(rightsSetting);
                rightsSetting.setAgentId(agentId);
                if (NumberUtil.isNumber(rightsSetting.getFirstClassify())) {
                    groupActivity4AppletDTOList = pcloudGroupActivityBiz.getTishBookSchoolListWrap(rightsSetting, top);
                }
            }
        }
        if (!ListUtils.isEmpty(groupActivity4AppletDTOList)) {
            for (GroupActivity4AppletDTO groupActivity4AppletDTO : groupActivity4AppletDTOList) {
                RightsNowItem rightsNowItem = new RightsNowItem();
                rightsNowItem.setServeId(groupActivity4AppletDTO.getId());
                rightsNowItem.setServeType(RightsServeTypeEnum.GROUP.name());
                rightsNowItem.setType(RightsNowItemTypeNew.GROUP_SERVICE.value);
                rightsNowItem.setRightsSettingId(rightsSettingId);
                rightsNowItem.setBookGroupId(groupActivity4AppletDTO.getBookGroupId());
                rightsNowItem.setRelatedBookGroupId(groupActivity4AppletDTO.getRelatedBookGroupId());
                rightsNowItem.setClassifyId(groupActivity4AppletDTO.getClassifyId());
                rightsNowItem.setPrice(groupActivity4AppletDTO.getPrice());
                items.add(rightsNowItem);
            }
        }

        return groupActivity4AppletDTOList;
    }

    @ParamLog(value = "填充配套资料", isAfterReturn = false)
    private RightsSetting setServe(RightsSetting rightsSetting, Long adviserId, Long bookId, Long channelId, Integer readType) {
        RightsSettingTitle rightsSettingTitle = rightsSettingTitleMapper
                .getByRightSettingIdAndType(rightsSetting.getId(), RightsNowItemTypeNew.SERVES.value, null);
        rightsSetting.setServesTitle(rightsSettingTitle != null ? rightsSettingTitle : new RightsSettingTitle());
        rightsSetting.setRightsItemGroups(getRightsItemGroups(rightsSetting.getId(), adviserId, bookId, channelId, true, readType, null,true));
        return rightsSetting;
    }

    @ParamLog("根据权益id获取即享权益项专享礼包")
    @Override
    public RightsSetting getRightsSettingGiftCoupons(Long rightsSettingId, Long wechatUserId, Integer readType) {
        RightsSetting rightsSetting = new RightsSetting();
        rightsSetting.setId(rightsSettingId);
        RightsSettingTitle rightsSettingTitle4Gift = rightsSettingTitleMapper
                .getByRightSettingIdAndType(rightsSettingId, RightsNowItemTypeNew.GIFT_COUPON_PACKAGE.value, readType);
        if (null == rightsSettingTitle4Gift || null == rightsSettingTitle4Gift.getRightsSettingId()) {
            return rightsSetting;
        }
        rightsSetting.setGiftCouponPackageTitle(rightsSettingTitle4Gift);
        fillGiftCouponPack(rightsSetting, readType);
        fillUserGiftReceiveStatus(rightsSetting, wechatUserId);
        return rightsSetting;
    }


    @ParamLog("根据权益id获取即享权益项补充咨询")
    @Override
    public FillRightsSettingAppletsDTO getFillRightsSettingApplets(Long rightsSettingId, Long wechatUserId, Long rightsClassifyId,
            Integer top, Long bookId, Long officialAccountsId) {
        if (rightsSettingId == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数有误！");
        }
        FillRightsSettingAppletsDTO fill = new FillRightsSettingAppletsDTO();
        RightsSetting rightsSetting = rightsSettingDAO.selectByPrimaryKey(rightsSettingId);
        if (rightsSetting == null) {
            return fill;
        }
        Long firstClassify = rightsSetting.getFirstClassify();
        Long secondClassify = rightsSetting.getSecondClassify();
        Long thirdClassify = rightsSetting.getThirdClassify();
        Long gradeLabelId = rightsSetting.getGradeLabelId();
        Long subjectLabelId = rightsSetting.getSubjectLabelId();
        Long volLabelId = rightsSetting.getVolLabelId();
        if (rightsSetting.getRightsSettingType() == 2) {
            //书刊权益，分类标签从编辑书刊取
            if (null == bookId){
                List<RightsSettingBookRelation> rightsSettingBookRelations =
                        rightsSettingBookRelationMapper.selectByRithsSettingId(rightsSettingId);
                if (ListUtils.isEmpty(rightsSettingBookRelations)) {
                    return fill;
                }
                bookId = rightsSettingBookRelations.get(0).getBookId();
            }
            BookAdviserDto adviserDto = bookAdviserBiz.getOneMainBook(bookId);
            firstClassify = adviserDto.getTempletId();
            secondClassify = adviserDto.getSecondTempletId();
            thirdClassify = adviserDto.getThirdTempletId();
            gradeLabelId = adviserDto.getGraLabelId();
            subjectLabelId = adviserDto.getSubLabelId();
            volLabelId = adviserDto.getVolLabelId();
        }
        BaseTempletClassify classify = new BaseTempletClassify();
        classify.setFirstClassify(firstClassify);
        classify.setSecondClassify(secondClassify);
        classify.setThirdClassify(thirdClassify);
        classify.setGradeLabelId(gradeLabelId);
        classify.setSubjectLabelId(subjectLabelId);
        classify.setVolLabelId(volLabelId);
        setClassifyAndLabel(classify);
        firstClassify = classify.getFirstClassify();
        secondClassify = classify.getSecondClassify();
        thirdClassify = classify.getThirdClassify();
        gradeLabelId = classify.getGradeLabelId();
        subjectLabelId = classify.getSubjectLabelId();
        volLabelId = classify.getVolLabelId();
        Long agentId = appletNewsBiz.getAgentIdByAccountId(officialAccountsId);
        if (Objects.isNull(rightsClassifyId)) {
            fill.setFillServes(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 1L, 4, agentId, thirdClassify));
            fill.setFillOnlineCourses(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 2L, 3, agentId, thirdClassify));
            fill.setFillLearningTools(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 3L, 1, agentId, thirdClassify));
            fill.setFillDraws(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 4L, 1, agentId, thirdClassify));
            fill.setFillGiftCouponPackages(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 5L, 4, agentId, thirdClassify));
            fill.setFillGroups(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 6L, 1, agentId, thirdClassify));
        } else {
            fill.setDesignatedNews(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, rightsClassifyId, top, agentId, thirdClassify));
        }
        return fill;
    }

   /* private void getFillRightsSettingAppletsDTO(Long rightsClassifyId, Integer top, FillRightsSettingAppletsDTO fill,
            Long firstClassify, Long secondClassify, Long gradeLabelId, Long subjectLabelId, Long volLabelId) {
        BaseTempletClassify classify = new BaseTempletClassify();
        classify.setFirstClassify(firstClassify);
        classify.setSecondClassify(secondClassify);
        classify.setGradeLabelId(gradeLabelId);
        classify.setSubjectLabelId(subjectLabelId);
        classify.setVolLabelId(volLabelId);
        setClassifyAndLabel(classify);
        firstClassify = classify.getFirstClassify();
        secondClassify = classify.getSecondClassify();
        gradeLabelId = classify.getGradeLabelId();
        subjectLabelId = classify.getSubjectLabelId();
        volLabelId = classify.getVolLabelId();
        if (Objects.isNull(rightsClassifyId)) {
            fill.setFillServes(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 1L, 4));
            fill.setFillOnlineCourses(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 2L, 3));
            fill.setFillLearningTools(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 3L, 1));
            fill.setFillDraws(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 4L, 1));
            fill.setFillGiftCouponPackages(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 5L, 4));
            fill.setFillGroups(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 6L, 1));
        } else {
            fill.setDesignatedNews(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, rightsClassifyId, top));
        }
    }*/


    @ParamLog("根据权益id获取即享权益配套资料分组集合")
    @Override
    public List<RightsItemGroup> getRightsItemGroups(Long rightsSettingId, Long adviserId, Long bookId, Long channelId,
                                                     Boolean removeCanNotBuy, Integer readType, Long wechatUserId,boolean homePage) {
        if (rightsSettingId == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数有误！");
        }
        List<RightsItemGroup> groups = rightsItemGroupDao.getListByRightSettingId(rightsSettingId, readType);
        if (ListUtils.isEmpty(groups)) {
            return groups;
        }
        List<Long> groupIds = new ArrayList<>();
        List<RightsItemGroup> originals = new ArrayList<>();
        List<RightsNowItem> nowItems = new ArrayList<>();
        for (RightsItemGroup group : groups) {
            if (group.getShowState() == null || group.getShowState()) {
                groupIds.add(group.getId());
                if (RightsItemGroupType.ORIGINAL.value.equals(group.getType())) {
                    originals.add(group);
                }
            }
            List<String> descList = new ArrayList<>();
            if (!StringUtil.isEmpty(group.getDesc1())) {
                descList.add(group.getDesc1());
            }
            if (!StringUtil.isEmpty(group.getDesc2())) {
                descList.add(group.getDesc2());
            }
            if (!StringUtil.isEmpty(group.getDesc3())) {
                descList.add(group.getDesc3());
            }
            group.setDescList(descList);
        }
        if (!ListUtils.isEmpty(groupIds)) {
            nowItems = rightsNowItemDao.getListByGroupIds(groupIds);
            if (nowItems == null) {
                nowItems = new ArrayList<>();
            }
        }
        if (!ListUtils.isEmpty(originals) && adviserId != null && bookId != null && channelId != null) {
            //获取原有的资源
            RightsItemGroup originalGroup = originals.get(0);
            List<RightsNowItem> originalItems = getOriginalItems(originalGroup.getId(), adviserId, bookId, channelId, rightsSettingId,homePage);
            nowItems.addAll(originalItems);
        }
        //填充应用和作品
        fillProductAndApp(nowItems);
        if (removeCanNotBuy != null && removeCanNotBuy) {
            //移除不能购买的应用或作品
            removeCanNotBuy(nowItems);
        }
        Map<Long, List<RightsNowItem>> itemMap = nowItems.stream().collect(Collectors.groupingBy(RightsNowItem::getRightsItemGroupId));
        for (RightsItemGroup group : groups) {
            group.setRightsNowItems(itemMap.get(group.getId()));
        }
        RightsSetting rightsSetting4Serves = new RightsSetting();
        rightsSetting4Serves.setRightsItemGroups(groups);
        fillCollect(wechatUserId, rightsSetting4Serves, RightsNowItemTypeNew.SERVES.value);
        return rightsSetting4Serves.getRightsItemGroups();
    }

    @ParamLog("获取即享权益图片库")
    @Override
    public List<RightsNowPic> getAllDefaultRightsNowPics(Integer type) {
        return rightsNowPicDao.getAllDefaultRightsNowPics(type);
    }

    @ParamLog("新增即享权益图片")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void addRightsNowPic(RightsNowPic rightsNowPic) {
        if (rightsNowPic == null || StringUtil.isEmpty(rightsNowPic.getPicUrl()) || null == rightsNowPic.getType()) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数有误！");
        }
        rightsNowPic.setDefaultPic(false);
        if (null == rightsNowPic.getAgentId()){
            rightsNowPic.setAgentId(0L);
        }
        rightsNowPicDao.insert(rightsNowPic);
    }

    @ParamLog("获取即享权益图片列表")
    @Override
    public PageBeanNew<RightsNowPic> getRightsNowPics(Integer currentPage, Integer numPerPage, Integer type, Long agentId) {
        if (currentPage == null || numPerPage == null || currentPage < 0 || numPerPage <= 0) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数有误！");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("type", type);
        map.put("agentId", agentId);
        PageBeanNew<RightsNowPic> pageNew = rightsNowPicDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getRightsNowPics");
        return pageNew;
    }

    @ParamLog("删除即享权益图片")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteRightsNowPic(Long rightsNowPicId) {
        if (rightsNowPicId == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数有误！");
        }
        rightsNowPicDao.deleteById(rightsNowPicId);
    }

    @Override
    @ParamLog("获取当前图书的阅读方式")
    public RightsSettingDto getReadType4Book(Long wechatUserId, Long bookId, Long channelId, Long adviserId) {
        RightsSettingDto rightsSettingDto = rightsSettingDAO.getByBookId(bookId);
        AppletUserBookcase appletUserBookcase = appletUserBookcaseBiz.getUserReadType(wechatUserId, bookId, adviserId, channelId);
        Integer chooseReadType = null == appletUserBookcase || null == appletUserBookcase.getReadType() ? null :
                appletUserBookcase.getReadType();
        if (null != rightsSettingDto && Objects.equals(Boolean.TRUE, rightsSettingDto.getShowState())) {
            Long rightsSettingId = rightsSettingDto.getId();
            rightsSettingDto
                    .setRightsSettingBookRelations(rightsSettingBookRelationMapper.selectByRithsSettingId(rightsSettingDto.getId()));
            ;
            List<RightsReadType> rightsReadTypes = rightsReadTypeMapper.getByRightsSettingId(rightsSettingId);
            ReadTypeCountDTO readTypeCountDTO = new ReadTypeCountDTO();
            readTypeCountDTO.setRightsSettingId(rightsSettingId);
            ReadTypeCountDTO readTypeCountDTO4Title = rightsSettingTitleMapper.getCount4Title(rightsSettingId);
            ReadTypeCountDTO readTypeCountDTO4Item = rightsSettingItemDao.getCount4Item(rightsSettingId);
            ReadTypeCountDTO readTypeCountDTO4Group = rightsItemGroupDao.getCount4Group(rightsSettingId);
            getAllCount(readTypeCountDTO, readTypeCountDTO4Title, readTypeCountDTO4Item, readTypeCountDTO4Group);
            setReadType(rightsSettingDto, readTypeCountDTO, rightsReadTypes);
            rightsSettingDto.setChooseReadType(chooseReadType);
            return rightsSettingDto;
        }
        //根据分类获取权益
        BookAdviserDto adviserDto = bookAdviserBiz.getBase(bookId, channelId, adviserId);
        if (null != adviserDto) {
            rightsSettingDto = getByLabel(adviserDto.getTempletId(), adviserDto.getSecondTempletId(), adviserDto.getGraLabelId(),
                    adviserDto.getSubLabelId(), adviserDto.getVolLabelId(), adviserDto.getVerLabelId(), adviserDto.getThirdTempletId());
            if (null == rightsSettingDto) {
                RightsSettingDto rightsSettingDto4New = rightsSettingDAO.getDTOById(bookBiz.getDefaultRightsSettingId());
                return rightsSettingDto4New;
            }
            Long rightsSettingId = rightsSettingDto.getId();
            List<RightsReadType> rightsReadTypes = rightsReadTypeMapper.getByRightsSettingId(rightsSettingId);
            ReadTypeCountDTO readTypeCountDTO = new ReadTypeCountDTO();
            readTypeCountDTO.setRightsSettingId(rightsSettingId);
            ReadTypeCountDTO readTypeCountDTO4Title = rightsSettingTitleMapper.getCount4Title(rightsSettingId);
            ReadTypeCountDTO readTypeCountDTO4Item = rightsSettingItemDao.getCount4Item(rightsSettingId);
            ReadTypeCountDTO readTypeCountDTO4Group = rightsItemGroupDao.getCount4Group(rightsSettingId);
            getAllCount(readTypeCountDTO, readTypeCountDTO4Title, readTypeCountDTO4Item, readTypeCountDTO4Group);
            setReadType(rightsSettingDto, readTypeCountDTO, rightsReadTypes);
            rightsSettingDto.setChooseReadType(chooseReadType);
        }

        return rightsSettingDto;
    }

    private void getAllCount(ReadTypeCountDTO readTypeCountDTO, ReadTypeCountDTO readTypeCountDTO4Title,
            ReadTypeCountDTO readTypeCountDTO4Item, ReadTypeCountDTO readTypeCountDTO4Group) {
        readTypeCountDTO.setEasyReadCount(0);
        readTypeCountDTO.setEfficientReadCount(0);
        readTypeCountDTO.setDeepReadCount(0);
        if (null != readTypeCountDTO4Title) {
            readTypeCountDTO.setEasyReadCount(readTypeCountDTO4Title.getEasyReadCount());
            readTypeCountDTO.setEfficientReadCount(readTypeCountDTO4Title.getEfficientReadCount());
            readTypeCountDTO.setDeepReadCount(readTypeCountDTO4Title.getDeepReadCount());
        }
        if (null != readTypeCountDTO4Item) {
            readTypeCountDTO.setEasyReadCount(readTypeCountDTO.getEasyReadCount() + readTypeCountDTO4Item.getEasyReadCount());
            readTypeCountDTO
                    .setEfficientReadCount(readTypeCountDTO.getEfficientReadCount() + readTypeCountDTO4Item.getEfficientReadCount());
            readTypeCountDTO.setDeepReadCount(readTypeCountDTO.getDeepReadCount() + readTypeCountDTO4Item.getDeepReadCount());
        }
        if (null != readTypeCountDTO4Group) {
            readTypeCountDTO.setEasyReadCount(readTypeCountDTO.getEasyReadCount() + readTypeCountDTO4Group.getEasyReadCount());
            readTypeCountDTO
                    .setEfficientReadCount(readTypeCountDTO.getEfficientReadCount() + readTypeCountDTO4Group.getEfficientReadCount());
            readTypeCountDTO.setDeepReadCount(readTypeCountDTO.getDeepReadCount() + readTypeCountDTO4Group.getDeepReadCount());
        }
    }

    private void setReadType(RightsSettingDto rightsSettingDto, ReadTypeCountDTO readTypeCountDTO, List<RightsReadType> rightsReadTypes) {
        if (!ListUtils.isEmpty(rightsReadTypes) && null != readTypeCountDTO && (
                !Objects.equals(BookConstant.zero, readTypeCountDTO.getEasyReadCount()) ||
                        !Objects.equals(BookConstant.zero, readTypeCountDTO.getEfficientReadCount()) ||
                        !Objects.equals(BookConstant.zero, readTypeCountDTO.getDeepReadCount())
        )) {
            rightsReadTypes.forEach(e -> {
                if (ReadTypeEnum.QS_READ.value.equals(e.getReadType())) {
                    e.setRightsCount(readTypeCountDTO.getEasyReadCount());
                } else if (ReadTypeEnum.GX_READ.value.equals(e.getReadType())) {
                    e.setRightsCount(readTypeCountDTO.getEfficientReadCount());
                } else if (ReadTypeEnum.SD_READ.value.equals(e.getReadType())) {
                    e.setRightsCount(readTypeCountDTO.getDeepReadCount());
                }
            });
        }
        rightsSettingDto.setRightsReadTypes(ListUtils.isEmpty(rightsReadTypes) ? new ArrayList<>() : rightsReadTypes);
    }

    @ParamLog("移除不能购买的应用或作品")
    private void removeCanNotBuy(List<RightsNowItem> nowItems) {
        if (ListUtils.isEmpty(nowItems)) {
            return;
        }
        List<RightsNowItem> toRemoveList = new ArrayList<>();
        for (RightsNowItem item : nowItems) {
            if (AppAndProductTypeEnum.APP.value.equals(item.getServeType()) && ArrayUtils
                    .contains(RightsSettingConstant.APPLET_APP_NOT_SUPPORT, item.getServeTypeCode())
                    || AppAndProductTypeEnum.PRODUCT.value.equals(item.getServeType()) && ArrayUtils
                    .contains(RightsSettingConstant.APPLET_PRODUCT_NOT_SUPPORT, item.getServeTypeCode())) {
                toRemoveList.add(item);
            }
        }
        if (!ListUtils.isEmpty(toRemoveList)) {
            nowItems.removeAll(toRemoveList);
        }
    }

    @ParamLog("获取原有配套资料")
    private List<RightsNowItem> getOriginalItems(Long originalGroupId, Long adviserId, Long bookId, Long channelId, Long rightsSettingId,boolean homePage) {
        List<RightsNowItem> nowItems = new ArrayList<>();
        if (originalGroupId == null || rightsSettingId == null) {
            return nowItems;
        }
        List<BookServeDTO> bookServeVOS = new ArrayList<>();
        if(homePage){
            bookServeVOS = bookGroupBiz.getBookAndBookGroupServeIdsFive(adviserId, bookId, channelId);
        }else{
            bookServeVOS = bookGroupBiz.getBookAndBookGroupServeIds(adviserId, bookId, channelId);
        }
        if (!ListUtils.isEmpty(bookServeVOS)) {
            for (BookServeDTO vo : bookServeVOS) {
                RightsNowItem item = new RightsNowItem();
                item.setRightsSettingId(rightsSettingId);
                item.setRightsItemGroupId(originalGroupId);
                item.setType(RightsNowItemTypeNew.SERVES.value);
                item.setServeId(vo.getServeId());
                item.setServeType(vo.getTypeCode());
                item.setLinkUrl(vo.getUrl());
                nowItems.add(item);
            }
        }
        return nowItems;
    }

    private List<AppletNews> getAppletItems(Long firstClassify, Long secondClassify, Long gradeLabelId, Long subjectLabelId,
                                            Long rightsClassifyId, Integer top, Long agentId, Long thirdClassify) {
        List<AppletNews> appletNews = appletNewsDao
                .getByTempletAndClassify(firstClassify, secondClassify, gradeLabelId, subjectLabelId, rightsClassifyId, top, agentId, thirdClassify);
        if (ListUtils.isEmpty(appletNews)) {
            appletNews = appletNewsDao
                    .getByTempletAndClassify(firstClassify, secondClassify, gradeLabelId, subjectLabelId, rightsClassifyId, top, agentId, null);
            if (ListUtils.isEmpty(appletNews)) {
                appletNews = appletNewsDao
                        .getByTempletAndClassify(firstClassify, null, gradeLabelId, subjectLabelId, rightsClassifyId, top, agentId, null);
            }
        }
        return appletNews;
    }

    @ParamLog("用户是否领取专享礼包券")
    private void fillUserGiftReceiveStatus(RightsSetting rightsSetting, Long wechatUserId) {
        if (rightsSetting == null || wechatUserId == null || null == rightsSetting.getGiftCouponPackageTitle() || ListUtils
                .isEmpty(rightsSetting.getGiftCouponPackageTitle().getRightsSettingItemList())) {
            return;
        }
        List<Long> list = giftReceiveDao.getUserReceiveGiftId(wechatUserId, rightsSetting.getId());
        if (ListUtils.isEmpty(list)) {
            list = new ArrayList<>();
        }
        for (RightsNowItem item : rightsSetting.getGiftCouponPackageTitle().getRightsSettingItemList()) {
            if (list.contains(item.getGiftCouponPackageId())) {
                item.setUserGiftReceive(true);
            } else {
                item.setUserGiftReceive(false);
            }
        }
    }

    /**
     * 根据书刊获取权益
     *
     * @return
     */
    @Override
    public RightsSettingDto getRightSettingByBookId(Long bookId, Long adviserId, Long channelId) {
        //根据分类获取权益
        BookAdviserDto adviserDto = bookAdviserBiz.getBase(bookId, channelId, adviserId);
        return getByLabel(adviserDto.getTempletId(), adviserDto.getSecondTempletId(), adviserDto.getGraLabelId(),
                adviserDto.getSubLabelId(), adviserDto.getVolLabelId(), adviserDto.getVerLabelId(), adviserDto.getThirdTempletId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void copyRightsSetting(List<Long> volLabelIds) {
        if (ListUtils.isEmpty(volLabelIds) || volLabelIds.size() > 5) {
            return;
        }
        //所有分类权益
        Map<String, Object> map = new HashMap<>();
        map.put("rightsSettingType", 1);
        List<RightsSettingDto> list = rightsSettingDAO.listRightsSettingPage(map);
        if (ListUtils.isEmpty(list)) {
            return;
        }
        for (RightsSettingDto rightsSettingDto : list) {
            RightsSetting base = this.getRightsSetting(rightsSettingDto.getId());
            RightsSetting rightsSetting = new RightsSetting();
            rightsSetting.setIntroduce(rightsSettingDto.getIntroduce());
            rightsSetting.setDetail(rightsSettingDto.getDetail());
            rightsSetting.setCount(rightsSettingDto.getCount());
            rightsSetting.setFirstClassify(rightsSettingDto.getFirstClassify());
            rightsSetting.setSecondClassify(rightsSettingDto.getSecondClassify());
            rightsSetting.setGradeLabelId(rightsSettingDto.getGradeLabelId());
            rightsSetting.setSubjectLabelId(rightsSettingDto.getSubjectLabelId());
            rightsSetting.setEnableGroupService(rightsSettingDto.getEnableGroupService());
            rightsSetting.setRightsSettingType(rightsSettingDto.getRightsSettingType());
            rightsSetting.setOnlineCourseOpen(rightsSettingDto.getOnlineCourseOpen());
            rightsSetting.setLearningToolOpen(rightsSettingDto.getLearningToolOpen());
            rightsSetting.setDrawNowOpen(rightsSettingDto.getDrawNowOpen());
            rightsSetting.setReadTypeTitle(rightsSettingDto.getReadTypeTitle());
            for (Long volLabelId : volLabelIds) {
                rightsSetting.setVolLabelId(volLabelId);
                if (existCheck(rightsSetting) > 0) {
                    continue;
                }
                this.addRightsSetting(rightsSetting);
                Long newId = rightsSetting.getId();
                //复制
                base.setId(newId);
                base.setVolLabelId(volLabelId);
                this.updateRightsSetting(base);
            }
        }
    }

    @Override
    public PageBeanNew<AppletNewsDTO> getWeekRightsSettingNewsByBookId(AppletUserBookcase userReadBook, Integer currentPage, Integer numPerPage) {
        PageBeanNew<AppletNewsDTO> appletNewsDTOS = new PageBeanNew<>();

        List<RightsSettingDto> rightsSettingDtos = rightsSettingDAO.listByBookId(userReadBook.getBookId());
        if (CollUtil.isEmpty(rightsSettingDtos)) {
            return getAppletNewsDTOPageBeanNew(userReadBook, currentPage, numPerPage);
        }

        Integer deepRead = null;
        Integer easyRead = null;
        Integer efficientRead = null;
        if (ReadTypeEnum.QS_READ.value.equals(userReadBook.getReadType())) {
            easyRead = 1;
        } else if (ReadTypeEnum.GX_READ.value.equals(userReadBook.getReadType())) {
            efficientRead = 1;
        } else if (ReadTypeEnum.SD_READ.value.equals(userReadBook.getReadType())) {
            deepRead = 1;
        }

        // 查询书刊权益ID列表
        List<Long> rightsSettingIds = rightsSettingDtos.stream().map(RightsSettingDto::getId).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(rightsSettingIds)) {
            Map<String, Object> map = CollUtil.newHashMap(4);
            map.put("list", rightsSettingIds);
            map.put("deepRead", deepRead);
            map.put("easyRead", easyRead);
            map.put("efficientRead", efficientRead);
            appletNewsDTOS = rightsSettingItemDao.listPageNew(new PageParam(currentPage, numPerPage), map, "selectNewsByRightsSettingIds");
        }

        if (Objects.nonNull(appletNewsDTOS) && CollUtil.isNotEmpty(appletNewsDTOS.getRecordList())) {
            return appletNewsDTOS;
        } else {
            return getAppletNewsDTOPageBeanNew(userReadBook, currentPage, numPerPage);
        }
    }

    @Override
    @ParamLog("批量上下架")
    public void batchUpdateShowState(RightsSettingShowStateDTO rightsSettingShowStateDTO) {
        rightsSettingDAO.batchUpdateShowState(rightsSettingShowStateDTO);
    }

    @Override
    @ParamLog("删除无效的资源")
    public void deleteInvalidNews(List<Long> newsIds) {
        //查询该资讯关联了多少权益
        List<RightsNowItem> rightsNowItems = rightsNowItemDao.getByNewsIds(newsIds);
        List<RightsSettingItemDetail> rightsSettingItemDetails = rightsSettingItemDetailDao.getByNewsIds(newsIds);
        if (!ListUtils.isEmpty(rightsNowItems)) {
            log.info("删除无效的资源前先查询rightsNowItems:{}", rightsNowItems);
            rightsNowItemDao.deleteInvalidNews(newsIds);
        }
        if (!ListUtils.isEmpty(rightsSettingItemDetails)) {
            log.info("删除无效的资源前先查询rightsSettingItemDetails:{}", rightsSettingItemDetails);
            rightsSettingItemDetailDao.deleteInvalidNews(newsIds);
        }
    }

    private PageBeanNew<AppletNewsDTO> getAppletNewsDTOPageBeanNew(AppletUserBookcase userReadBook, Integer currentPage, Integer numPerPage) {
        PageBeanNew<AppletNewsDTO> appletNewsDTOS = new PageBeanNew<>();
        // 查询书籍分类下对应的资讯分类
        BaseTempletClassify baseTempletClassify = appletUserBookcaseDao.getBookClassifyInfo(userReadBook.getBookId(), userReadBook.getChannelId(), userReadBook.getAdviserId());
        if (Objects.nonNull(baseTempletClassify) && Objects.nonNull(baseTempletClassify.getFirstClassify())) {
            rightsSettingBiz.setClassifyAndLabel(baseTempletClassify);
            Integer deepRead = null;
            Integer easyRead = null;
            Integer efficientRead = null;
            if (ReadTypeEnum.QS_READ.value.equals(userReadBook.getReadType())) {
                easyRead = 1;
            } else if (ReadTypeEnum.GX_READ.value.equals(userReadBook.getReadType())) {
                efficientRead = 1;
            } else if (ReadTypeEnum.SD_READ.value.equals(userReadBook.getReadType())) {
                deepRead = 1;
            }
            Map<String, Object> map = new HashMap<>();
            map.put("firstClassify", baseTempletClassify.getFirstClassify());
            map.put("secondClassify", baseTempletClassify.getSecondClassify());
            map.put("gradeLabelId", baseTempletClassify.getGradeLabelId());
            map.put("subjectLabelId", baseTempletClassify.getSubjectLabelId());
            map.put("deepRead", deepRead);
            map.put("easyRead", easyRead);
            map.put("efficientRead", efficientRead);
            PageBeanNew<AppletNewsDTO> page = appletNewsDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getClassifyNewsByTempletLabel");
            if (Objects.nonNull(page) && CollUtil.isNotEmpty(page.getRecordList())) {
                appletNewsDTOS = page;
            } else {
                map.put("firstClassify", baseTempletClassify.getFirstClassify());
                map.put("secondClassify", baseTempletClassify.getSecondClassify());
                map.put("gradeLabelId", baseTempletClassify.getGradeLabelId());
                map.put("subjectLabelId", baseTempletClassify.getSubjectLabelId());
                map.put("rightsType", null);
                page = appletNewsDao.listPageNew(new PageParam(currentPage, numPerPage), map, "getPageByNewsByTempletLabel");
                if (Objects.nonNull(page) && CollUtil.isNotEmpty(page.getRecordList())) {

                    appletNewsDTOS = page;
                }
            }
        }
        return appletNewsDTOS;
    }

    @Override
    public Map<Long, RightsSettingDto> listByBookIds(List<Long> bookIds){
        Map<Long, RightsSettingDto> rightsSettingDtoMap = rightsSettingDAO.listByBookIds(bookIds);
        if(rightsSettingDtoMap == null){
            return new HashMap<>();
        }
        return rightsSettingDtoMap;
    }

    @Override
    public PopupResourceInfoDTO getPopupResourceInfoByBook(Long wechatUserId, Long bookId, Long channelId, Long adviserId,
                                                           Long rightsSettingId, Integer readType){
        PopupResourceInfoDTO popupResourceInfoDTO = new PopupResourceInfoDTO();
        Integer answerClickCount = rightsNowPopupDao.getUserPopupClickCount(wechatUserId,bookId,channelId,adviserId, RightsNowPopupType.SERVES_ANSWER.value);
        //答案应用
        List<RightsNowItem> answerList = getPopupAnswerList(bookId,channelId,adviserId, rightsSettingId,readType);
        //有答案应用且答案应用未点击
        if (!ListUtils.isEmpty(answerList) && answerClickCount<=0){
            popupResourceInfoDTO.setPopupState(true);
            popupResourceInfoDTO.setPopupList(answerList);
            popupResourceInfoDTO.setPopupType(RightsNowPopupType.SERVES_ANSWER.value);
            return popupResourceInfoDTO;
        }
        //品牌方资源-线上网课
        Boolean popState = false;
        Integer popupType = RightsNowPopupType.ONLINE_COURSE.value;
        List<RightsNowItem> popupList = getPopupCourseList(rightsSettingId, readType);
        Integer courseClickCount = rightsNowPopupDao.getUserPopupClickCount(wechatUserId, bookId, channelId, adviserId, popupType);
        //有资源且未点击
        if (!ListUtils.isEmpty(popupList) && courseClickCount<=0){
            popState = true;
        }
        popupResourceInfoDTO.setPopupState(popState);
        popupResourceInfoDTO.setPopupList(popupList);
        popupResourceInfoDTO.setPopupType(popupType);
        return popupResourceInfoDTO;
    }

    /**
     * 要弹出的品牌方资源-线上网课
     * @author：zhuyajie
     * @date：2020/9/17 14:46
     *  * @param null
     */
    private List<RightsNowItem> getPopupCourseList(Long rightsSettingId, Integer readType) {
        if (null == rightsSettingId || null == readType) {
            return new ArrayList<>();
        }
        String key = RightsSettingConstant.COURSE_POPUP;
        String field = rightsSettingId + "-" + readType;
        List<RightsNowItem> popupList = JedisClusterUtils.hgetJson2List(key, field, RightsNowItem.class);
        if (!ListUtils.isEmpty(popupList)) {
            return popupList;
        }
        popupList = new ArrayList<>();
        RightsSetting rightsSetting = rightsSettingDAO.selectByPrimaryKey(rightsSettingId);
        if (null == rightsSetting){
            return new ArrayList<>();
        }
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemTypeNew.ONLINE_COURSE, readType);
        if (null != rightsSettingTitle && null!= rightsSettingTitle.getOpenState() && rightsSettingTitle.getOpenState()) {
            List<RightsNowItem> resourceItems = rightsNowItemDao.getListByRightsSettingTitleId(rightsSettingTitle.getId(), Collections.singletonList(RightsNowItemTypeNew.ONLINE_COURSE.value));
            if (!ListUtils.isEmpty(resourceItems)) {
                fillProductAndApp(resourceItems);
                if (!ListUtils.isEmpty(resourceItems)) {
                    popupList.addAll(resourceItems);
                }
            }
        }
        if (!ListUtils.isEmpty(popupList)) {
            JedisClusterUtils.hset2Json(key, field, popupList);
            JedisClusterUtils.expire(key, 10);
        }
        return popupList;
    }
    /**
     * 要弹出的答案应用
     * @author：zhuyajie
     * @date：2020/9/17 14:42
     *  * @param null
     */
    private List<RightsNowItem> getPopupAnswerList(Long bookId, Long channelId, Long adviserId, Long rightsSettingId, Integer readType) {
        RightsSettingTitle rightsSettingTitle = rightsSettingTitleMapper.getByRightSettingIdAndType(rightsSettingId, RightsNowItemTypeNew.FIXED_FIRST.value, readType);
        if (null == rightsSettingTitle || null == rightsSettingTitle.getOpenState() || !rightsSettingTitle.getOpenState()) {
            return new ArrayList<>();
        }
        String key = RightsSettingConstant.ANSWER_POPUP;
        String field = bookId + "-" + adviserId + "-" + channelId;
        List<RightsNowItem> answerList = JedisClusterUtils.hgetJson2List(key, field, RightsNowItem.class);
        if (!ListUtils.isEmpty(answerList)) {
            return answerList;
        }
        answerList = new ArrayList<>();
        List<RightsNowItem> itemList = getOriginServeRightsNowItem(bookId, channelId, adviserId, false, null);
        fillProductAndApp(itemList);
        removeCanNotBuy(itemList);
        if (!ListUtils.isEmpty(itemList)){
            answerList = itemList.stream().
                    filter(s->s.getServeName().contains("答案") || s.getServeTypeCode().equals(AppTypeEnum.ANSWER.value)).collect(Collectors.toList());
        }
        if (!ListUtils.isEmpty(answerList) && answerList.size() > 2) {
            //最多取两个
            answerList = answerList.subList(0, 2);
        }
        if (!ListUtils.isEmpty(answerList)) {
            JedisClusterUtils.hset2Json(key, field, answerList);
            JedisClusterUtils.expire(key, 10);
        }
        return answerList;
    }

    @Override
    public void addPopupRecord(RightsNowPopup rightsNowPopup) {
        if (null==rightsNowPopup.getBookId() || null==rightsNowPopup.getChannelId()||null==rightsNowPopup.getAdviserId()){
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少书刊信息参数");
        }
        if (null==rightsNowPopup.getRecordType()){
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少记录类型参数");
        }
        rightsNowPopupDao.insert(rightsNowPopup);
    }

    @Override
    public ResourceList4Answer getResourceListByBook4Answer(
            Long wechatUserId, Long bookId, Long channelId, Long adviserId, Long sceneId) {
        if (null == bookId && null == sceneId){
            return new ResourceList4Answer();
        }
        if (null != sceneId){
            QrcodeSceneDto qrcodeSceneDto = qrcodeSceneConsr.getById(sceneId);
            if (null != qrcodeSceneDto){
                bookId = qrcodeSceneDto.getAdviserBookId();
                channelId = qrcodeSceneDto.getChannelPartyId();
                adviserId = qrcodeSceneDto.getCreatedByUserLogin();
            }
        }
        if (null == bookId || null == channelId || null == adviserId){
            return new ResourceList4Answer();
        }
        BookAdviserDto bookAdviserDto = bookAdviserBiz.getBase(bookId,channelId,adviserId);
        //处理答案应用运营平台和书刊运营平台不一致的情况
        if (null == bookAdviserDto){
            BookAdviserDto adviserDto = bookAdviserBiz.getBookByBookIdAdviserId(bookId, adviserId);
            if (null != adviserDto){
                channelId = adviserDto.getChannelId();
            }
        }
        ResourceList4Answer resourceList4Answer = new ResourceList4Answer();
        resourceList4Answer.setBookId(bookId);
        resourceList4Answer.setChannelId(channelId);
        resourceList4Answer.setAdviserId(adviserId);
        //本书原版资料
        String coursekey = RightsSettingConstant.ANSWER_COURSE;
        String field = bookId + "-" + adviserId + "-" + channelId;
        List<RightsNowItem> courseList = JedisClusterUtils.hgetJson2List(coursekey, field, RightsNowItem.class);
        if (ListUtils.isEmpty(courseList)){
            courseList = new ArrayList<>();
            List<RightsNowItem> itemList = getOriginServeRightsNowItem(bookId, channelId, adviserId, false, wechatUserId);
            if (!ListUtils.isEmpty(itemList)) {
                for (RightsNowItem rightsNowItem : itemList) {
                    String typeCode = rightsNowItem.getServeTypeCode();
                    //视频课直播课
                    if (typeCode.equals(AppTypeEnum.VIDEO.value) || typeCode.equals(ProductTypeConstant.VIDEO)
                            || typeCode.equals(ProductTypeConstant.VIDEO_SCHEDULE) || typeCode.equals(AppTypeEnum.LIVE_TIMETABLE.value)
                            || typeCode.equals(ProductTypeConstant.LIVE) || typeCode.equals(ProductTypeConstant.SCHEDULE)) {
                        courseList.add(rightsNowItem);
                    }
                }
            }
            fillProductAndApp(courseList);
            removeCanNotBuy(courseList);
            JedisClusterUtils.hset2Json(coursekey, field, courseList);
            JedisClusterUtils.expire(coursekey, 20);
        }
        resourceList4Answer.setCourseList(courseList);
        //小睿书 有权益
        String groupkey = RightsSettingConstant.ANSWER_GROUP;
        List<RightsNowItem> groupList = JedisClusterUtils.hgetJson2List(groupkey, field, RightsNowItem.class);
        if (ListUtils.isEmpty(groupList)){
            groupList = new ArrayList<>();
            RightsSettingDto rightsSettingDto = this.getRightsSettingByBookId4AppletHome(bookId, adviserId, channelId);
            if (null != rightsSettingDto) {
                //专享社群服务
                groupList = rightsNowItemDao.getItemListByRightsSettingId(rightsSettingDto.getId(), RightsNowItemTypeNew.GROUP_SERVICE.value, null, 1, RightsServeTypeEnum.GROUP.name());
                fillProductAndApp(groupList);
                JedisClusterUtils.hset2Json(groupkey, field, groupList);
                JedisClusterUtils.expire(groupkey, 20);
            }
        }
        resourceList4Answer.setGroupList(groupList);
        return resourceList4Answer;
    }

    /**
     * 获取立享权益本书配套原版资源
     * @author：zhuyajie
     * @date：2020/9/30 14:26
     *  * @param null
     */
    private List<RightsNowItem> getOriginServeRightsNowItem(Long bookId, Long channelId, Long adviserId, Boolean fillCollect, Long wechatUserId){
        List<RightsNowItem> itemList = new ArrayList<>();
        List<BookServeDTO> bookServeVOS = new ArrayList<>();
        bookServeVOS = bookGroupBiz.getBookAndBookGroupServeIds(adviserId, bookId, channelId);
        if (fillCollect && null != wechatUserId){
            bookGroupBiz.fillCollect4Book(wechatUserId, bookServeVOS);
        }
        if (!ListUtils.isEmpty(bookServeVOS)) {
            for (BookServeDTO vo : bookServeVOS) {
                RightsNowItem item = new RightsNowItem();
                item.setType(RightsNowItemTypeNew.SERVES.value);
                item.setServeId(vo.getServeId());
                item.setServeType(vo.getTypeCode());
                item.setLinkUrl(vo.getUrl());
                item.setIsCollect(vo.getIsCollect());
                item.setServeTypeCode(vo.getFromType());
                itemList.add(item);
            }
        }
        return itemList;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateRightsSettingNew(RightsSetting rightsSetting) {
        if (rightsSetting == null) {
            return;
        }
        //处理前端传过来的数据
        handleRightsSetting4Sort(rightsSetting);
        rightsSettingCheck.rightsSettingCheck(rightsSetting);
        if (null == rightsSetting.getId()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少id！");
        }
        Long rightsSettingId = rightsSetting.getId();
        if (Objects.equals(RightsTypeEnum.BASE.code, rightsSetting.getStepType())) {
            //更新基本信息
            updateRightsSettingBase(rightsSetting, rightsSettingId);
        } else if (Objects.equals(RightsTypeEnum.NOW.code, rightsSetting.getStepType())) {
            //更新即享权益
            updateRightNowItemByRightIdNew(rightsSetting);
            rightsSettingDAO.updateUser(rightsSetting);
        }else if (Objects.equals(RightsTypeEnum.UP_NUMBER.code, rightsSetting.getStepType())) {
            updateNumber(rightsSetting);
            rightsSettingDAO.updateUser(rightsSetting);
        }
    }

    private void updateRightNowItemByRightIdNew(RightsSetting rightsSetting) {
        rightsSettingCheck.rightsSettingCheckUpdateNew(rightsSetting);
        Long rightsSettingId = rightsSetting.getId();
        List<RightsNowItem> items = new ArrayList<>();
        RightsSettingNow rightsSettingNow = rightsSetting.getRightsSettingNow();
        //根据权益id删除原来的
        rightsSettingTitleMapper.deleteByRightSettingId(rightsSettingId);
        rightsNowItemDao.deleteByRightsSettingId(rightsSettingId);
        List<RightsSettingTitle> rightsSettingTitleList = rightsSettingNow.getNewRightsSettingTitles();
        if (ListUtils.isEmpty(rightsSettingTitleList)) {
            return;
        }
        //给每个权益设置id
        rightsSettingTitleList.forEach(e -> {
            e.setRightsSettingId(rightsSettingId);
            e.setDisplayType(e.getDisplayType()==null?0:e.getDisplayType());
        });
        rightsSettingTitleMapper.batchInsert(rightsSettingTitleList);
        //设置每个权益详情
        setNowItems(rightsSettingTitleList, rightsSettingId, items);
        //校验itme参数
        rightsSettingCheck.checkRightNowItems(items);
        if (!ListUtils.isEmpty(items)) {
            rightsNowItemDao.batchInsert(items);
        }
    }

    @Override
    @ParamLog("获取权益设置")
    public RightsSetting getRightsSettingNew(Long id) {
        RightsSetting rightsSetting = rightsSettingDAO.selectByPrimaryKey(id);
        if (null == rightsSetting) {
            return new RightsSetting();
        }
        //书刊分类关联书刊
        fillBookName(id, rightsSetting);
        //立享权益
        List<Integer> types = new ArrayList<>();
        types.addAll(Arrays.asList(RightsSettingConstant.RIGHTSSETTING_TYPES_NEW));
        List<RightsSettingTitle> rightsSettingTitles = rightsSettingTitleMapper.getByRightSettingIdAndTypes(rightsSetting.getId(), types);
        if (!ListUtils.isEmpty(rightsSettingTitles)) {
            List<RightsNowItem> nowItems = rightsNowItemDao.getListByRightsSettingId(rightsSetting.getId(), types);
            if (!ListUtils.isEmpty(nowItems)) {
                rightsSettingTitles = fillRightsNowItems4RightsSettingNew(rightsSettingTitles, nowItems);
            }
        }
        RightsSettingNow rightsSettingNow = new RightsSettingNow();
        rightsSettingNow.setRightsSettingTitles(rightsSettingTitles);
        rightsSetting.setRightsSettingNow(rightsSettingNow);
        //设置阅读指引
        fillReadGuide(rightsSetting.getRightsSettingBanners());
        //填充分类及标签
        fillLabelNames(Lists.newArrayList(rightsSetting));
        return rightsSetting;
    }

    private List<RightsSettingTitle> fillRightsNowItems4RightsSettingNew(List<RightsSettingTitle> rightsSettingTitles, List<RightsNowItem> nowItems) {
        log.info("即享权益内容填充");
        if (ListUtils.isEmpty(rightsSettingTitles) || ListUtils.isEmpty(nowItems)) {
           return rightsSettingTitles;
        }
        fillProductAndApp(nowItems);
        Map<Long, List<RightsNowItem>> nowItemMap = nowItems.stream().filter(e -> null != e.getRightsSettingTitleId())
                .collect(Collectors.groupingBy(x -> x.getRightsSettingTitleId()));
        List<RightsSettingTitle> removeList = new ArrayList<>();
        for (RightsSettingTitle rightsSettingTitle : rightsSettingTitles) {
            // 填充应用、作品、社群、资讯
            if (!MapUtils.isEmpty(nowItemMap) && !ListUtils.isEmpty(nowItemMap.get(rightsSettingTitle.getId()))) {
                rightsSettingTitle.setRightsSettingItemList(nowItemMap.get(rightsSettingTitle.getId()));
            }
            //填充礼券包
            if (RightsNowItemTypeNew.GIFT_COUPON_PACKAGE.value.equals(rightsSettingTitle.getRightsSettingNowType())) {
                List<RightsNowItem> giftCouponPackItems = rightsNowItemDao.getGiftCouponListByRightsSettingTitleId(rightsSettingTitle.getId());
                if (!ListUtils.isEmpty(giftCouponPackItems)) {
                    rightsSettingTitle.setRightsSettingItemList(giftCouponPackItems);
                } else {
                    removeList.add(rightsSettingTitle);
                }
            }
        }
        rightsSettingTitles.removeAll(removeList);
        if (!ListUtils.isEmpty(rightsSettingTitles)) {
            rightsSettingTitles = rightsSettingTitles.stream().
                    sorted(Comparator.comparing(item -> item.getSeqNum(), Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
        }
        return rightsSettingTitles;
    }

    @ParamLog("根据权益id和类型获取即享权益项")
    @Override
    public RightsSetting getRightsSettingItemsByTypeListNew(RightsSettingQueryDTO rightsSettingQueryDTO) {
        Long rightsSettingId = rightsSettingQueryDTO.getRightsSettingId();
        Long wechatUserId = rightsSettingQueryDTO.getWechatUserId();
        List<Integer> types = rightsSettingQueryDTO.getRightsSettingTypes();
        Long adviserId = rightsSettingQueryDTO.getAdviserId();
        Long bookId = rightsSettingQueryDTO.getBookId();
        Long channelId = rightsSettingQueryDTO.getChannelId();
        if (ListUtils.isEmpty(types)) {
            throw new BookBizException(BookBizException.ERROR, "权益类型为空！");
        }
        RightsSetting rightsSetting = null;
        if (null != rightsSettingId) {
            rightsSetting = rightsSettingDAO.selectByPrimaryKey(rightsSettingId);
        }
        List<RightsSettingTitle> rightsSettingTitles = new ArrayList<>();
        //权益配置的模块
        if (null != rightsSetting) {
            rightsSettingTitles = rightsSettingTitleMapper.getByRightSettingIdAndTypes(rightsSetting.getId(), types);
            if (!ListUtils.isEmpty(rightsSettingTitles)) {
                List<RightsNowItem> nowItems = rightsNowItemDao.getListByRightsSettingId(rightsSetting.getId(), types);
                if (!ListUtils.isEmpty(nowItems)) {
                    rightsSettingTitles = fillRightsNowItems4RightsSettingNew(rightsSettingTitles, nowItems);
                    //设置收藏状态
                    this.fillCollect4RightsNowItem(wechatUserId, nowItems);
                }
            }
        }
        //本书配套资源
        Map<Integer, List<RightsNowItem>> integerListMap = new HashMap<>();
        if (types.contains(RightsNowItemTypeNew.FIXED_FIRST.value) && types.contains(RightsNowItemTypeNew.FIXED_SECOND.value)
                && types.contains(RightsNowItemTypeNew.FIXED_THIRD.value)) {
            List<RightsNowItem> servesNowItems = getServeRightsSetting4New(adviserId, bookId, channelId);
            //设置收藏状态
            this.fillCollect4RightsNowItem(wechatUserId, servesNowItems);
            integerListMap = servesNowItems.stream().collect(Collectors.groupingBy(RightsNowItem::getType));
        }
        if (!MapUtils.isEmpty(integerListMap)) {
            //本书配套资源添加到各个模块
            if (!ListUtils.isEmpty(rightsSettingTitles)) {
                for (RightsSettingTitle rightsSettingTitle : rightsSettingTitles) {
                    if (null != integerListMap.get(rightsSettingTitle.getRightsSettingNowType())) {
                        List<RightsNowItem> newItemList = new ArrayList<>();
                        newItemList.addAll(integerListMap.get(rightsSettingTitle.getRightsSettingNowType()));
                        if (!ListUtils.isEmpty(rightsSettingTitle.getRightsSettingItemList())) {
                            newItemList.addAll(rightsSettingTitle.getRightsSettingItemList());
                        }
                        if (!ListUtils.isEmpty(newItemList)) {
                            //根据自定义排序
                            newItemList = newItemList.stream().sorted(Comparator.comparing(item -> item.getRank(), Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
                        }
                        rightsSettingTitle.setRightsSettingItemList(newItemList);
                    }
                }
            } else {
                for (Map.Entry<Integer, List<RightsNowItem>> entry : integerListMap.entrySet()) {
                    RightsSettingTitle rightsSettingTitle = new RightsSettingTitle();
                    List<RightsNowItem> newItemList = entry.getValue();
                    if (!ListUtils.isEmpty(newItemList)) {
                        //根据自定义排序
                        newItemList = newItemList.stream().sorted(Comparator.comparing(item -> item.getRank(), Comparator.nullsLast(Integer::compareTo))).collect(Collectors.toList());
                    }
                    rightsSettingTitle.setRightsSettingNowType(entry.getKey());
                    rightsSettingTitle.setRightsSettingItemList(newItemList);
                    rightsSettingTitles.add(rightsSettingTitle);
                }
            }
        }
        RightsSettingNow rightsSettingNow = new RightsSettingNow();
        rightsSettingNow.setRightsSettingTitles(rightsSettingTitles);
        rightsSetting = rightsSetting==null?new RightsSetting():rightsSetting;
        rightsSetting.setRightsSettingNow(rightsSettingNow);
        return rightsSetting;
    }

    /**
     * 本书配套服务按固定模块区分
     * @author：zhuyajie
     * @date：2020/12/25 9:17
     *  * @param null
     */
    private List<RightsNowItem> getServeRightsSetting4New(Long adviserId, Long bookId, Long channelId){
        List<RightsNowItem> servesNowItems = new ArrayList<>();
        List<BookServeDTO> bookServeVOS = bookGroupBiz.getBookAndBookGroupServeIds(adviserId, bookId, channelId);
        bookGroupBiz.removeCanNotBuy(bookServeVOS);
        bookGroupBiz.fillBookServe4RightsSetting(bookServeVOS);
        if (ListUtils.isEmpty(bookServeVOS)) {
            return servesNowItems;
        }
        for (BookServeDTO vo : bookServeVOS) {
            String typeCode = vo.getFromType();
            String serveName = vo.getServeName();
            RightsNowItem rightsNowItem = null;
            //根据名称归类,排序在前面
            if (serveName.contains("答案") || AppTypeEnum.ANSWER.value.equals(typeCode)) {
                rightsNowItem = bookServeToRightsSettingItem(vo, RightsNowItemTypeNew.FIXED_FIRST.value, 1);
            } else if (serveName.contains("听力") || AppTypeEnum.MATCH_LISTEN.value.equals(typeCode)) {
                rightsNowItem = bookServeToRightsSettingItem(vo, RightsNowItemTypeNew.FIXED_FIRST.value, 2);
            } else if (serveName.contains("视频") || serveName.contains("名师") || serveName.contains("微课")) {
                rightsNowItem = bookServeToRightsSettingItem(vo, RightsNowItemTypeNew.FIXED_SECOND.value, 1);
            }
            //资料包、课件、试卷、图文、知识点汇总、测试卷、拓展资料、素材包、自测卷
            else if (serveName.contains("资料包") ||serveName.contains("课件") || serveName.contains("试卷") || serveName.contains("图文")
                    || serveName.contains("知识点汇总") || serveName.contains("测试卷") || serveName.contains("拓展资料")
                    || serveName.contains("素材包") || serveName.contains("自测卷")){
                rightsNowItem = bookServeToRightsSettingItem(vo,RightsNowItemTypeNew.FIXED_THIRD.value, 1);
            } else {
                //根据类型归类
                if (AppAndProductTypeEnum.APP.value.equals(vo.getServeType())) {
                    if (RightsSettingConstant.FIXED_SECOND_APPLET_APP_LIST.contains(typeCode)) {
                        rightsNowItem = bookServeToRightsSettingItem(vo,RightsNowItemTypeNew.FIXED_SECOND.value,
                                RightsSettingConstant.FIXED_SECOND_APPLET_APP_LIST.indexOf(typeCode));
                    } else if (RightsSettingConstant.FIXED_THIRD_APPLET_APP_LIST.contains(typeCode)) {
                        rightsNowItem = bookServeToRightsSettingItem(vo,RightsNowItemTypeNew.FIXED_THIRD.value,
                                RightsSettingConstant.FIXED_THIRD_APPLET_APP_LIST.indexOf(typeCode));
                    } else {
                        rightsNowItem = bookServeToRightsSettingItem(vo,RightsNowItemTypeNew.FIXED_FIRST.value,10);
                    }
                } else if (AppAndProductTypeEnum.PRODUCT.value.equals(vo.getServeType())){
                    if (RightsSettingConstant.FIXED_SECOND_APPLET_PRODUCT_LIST.contains(typeCode)) {
                        rightsNowItem = bookServeToRightsSettingItem(vo,RightsNowItemTypeNew.FIXED_SECOND.value,
                                RightsSettingConstant.FIXED_SECOND_APPLET_PRODUCT_LIST.indexOf(typeCode));
                    } else if (RightsSettingConstant.FIXED_THIRD_APPLET_PRODUCT_LIST.contains(typeCode)) {
                        rightsNowItem = bookServeToRightsSettingItem(vo,RightsNowItemTypeNew.FIXED_THIRD.value,
                                RightsSettingConstant.FIXED_THIRD_APPLET_PRODUCT_LIST.indexOf(typeCode));
                    } else {
                        rightsNowItem = bookServeToRightsSettingItem(vo,RightsNowItemTypeNew.FIXED_FIRST.value, 10);
                    }
                }
            }
            if (null != rightsNowItem) {
                servesNowItems.add(rightsNowItem);
            }
        }
        return servesNowItems;
    }

    private RightsNowItem bookServeToRightsSettingItem(BookServeDTO bookServeDTO, Integer type, Integer rank) {
        RightsNowItem item = new RightsNowItem();
        item.setType(type);
        item.setServeId(bookServeDTO.getServeId());
        item.setServeType(bookServeDTO.getTypeCode());
        item.setLinkUrl(bookServeDTO.getUrl());
        item.setServeTypeCode(bookServeDTO.getFromType());
        item.setServeTypeName(bookServeDTO.getFromTypeName());
        item.setServeName(bookServeDTO.getServeName());
        item.setResultUrl(bookServeDTO.getResultUrl());
        item.setServePic(bookServeDTO.getCoverImg());
        item.setTransverseImg(bookServeDTO.getTransverseImg());
        item.setHasThirdLink(bookServeDTO.getHasThirdLink());
        item.setRank(rank);
        return item;
    }

    private RightsNowItem setRank(RightsNowItem item) {
        if (null == item || StringUtil.isEmpty(item.getServeName())) {
            return item;
        }
        String serveName = item.getServeName();
        String serveTypeCode = item.getServeTypeCode();
        if (serveName.contains("答案") || AppTypeEnum.ANSWER.value.equals(serveTypeCode)) {
            item.setRank(1);
        } else if (serveName.contains("听力") || AppTypeEnum.MATCH_LISTEN.value.equals(serveTypeCode)) {
            item.setRank(2);
        }
        return item;
    }

    @Override
    public List<RightsSettingClassify> getAllRightsClassifyNew() {
        List<Integer> types = Arrays.asList(RightsSettingConstant.RIGHTSSETTING_TYPES_NEW);
        return rightsSettingItemDao.getRightsClassifyByIds(types);
    }

    @Override
    public List<BookServeDTO> getRightsSettingAppProduct(Long bookId, Long channelId, Long adviserId, Integer limit) {
        RightsSettingDto rightsSettingDto = this.getRightsSettingByBookId4AppletHome(bookId, adviserId, channelId);
        if (null == rightsSettingDto || null == rightsSettingDto.getId()) {
            return new ArrayList<>();
        }
        List<String> serveTypes = Arrays.asList(AppAndProductTypeEnum.APP.value, AppAndProductTypeEnum.PRODUCT.value);
        List<BookServeDTO> list = rightsNowItemDao.getServeItemsByServeTypes(rightsSettingDto.getId(), serveTypes,limit);
        return list;
    }

}
