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


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.math.MathUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.pcloud.appcenter.app.dto.AppDto;
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.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.AppletNewsServeDTO;
import com.pcloud.book.applet.dto.AppletOuterBooklistDTO;
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.AppletNewsServeTypeEnum;
import com.pcloud.book.applet.enums.AppletRecordTypeEnum;
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.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.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.tools.SendWeixinRequestTools;
import com.pcloud.book.group.vo.ClassifyQrcodeVO;
import com.pcloud.book.push.dao.PersonalAppletsDao;
import com.pcloud.book.push.entity.PersonalApplets;
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.RightsSettingShowStateDTO;
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.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.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.skill.dto.GroupActivity4AppletDTO;
import com.pcloud.book.util.common.YesOrNoEnums;
import com.pcloud.channelcenter.qrcode.dto.QrcodeSceneDto;
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.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.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.common.utils.string.StringUtilParent;
import com.pcloud.resourcecenter.product.dto.ProductDto;
import com.pcloud.usercenter.party.adviser.dto.AdviserBaseInfoDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.elasticsearch.common.math.MathUtils;
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.Random;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;

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

    @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, "新增权益设置失败");
        }
        //新增关联书刊
        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("对于某些特殊分类做处理");
        Boolean contain4K12 = false;
        if ("test".equals(envStr) && ArrayUtils
                .contains(RightsSettingConstant.K12_TEMPLET_ID_TEST, baseTempletClassify.getFirstClassify())) {
            contain4K12 = true;
        } else if (!"test".equals(envStr) && ArrayUtils
                .contains(RightsSettingConstant.K12_TEMPLET_ID, baseTempletClassify.getFirstClassify())) {
            contain4K12 = true;
        }
        if (!ArrayUtils.contains(RightsSettingConstant.MEDICAL_INSURANCE_TEMPLET_ID, baseTempletClassify.getFirstClassify())) {
            baseTempletClassify.setSecondClassify(null);
        }
        if (!contain4K12) {
            baseTempletClassify.setGradeLabelId(null);
            baseTempletClassify.setSubjectLabelId(null);
        }
        if (!ArrayUtils.contains(RightsSettingConstant.K12_VOLUME_ID, baseTempletClassify.getFirstClassify())) {
            baseTempletClassify.setVolLabelId(null);
        }
        if (!ArrayUtils.contains(RightsSettingConstant.K12_VERSION_ID, baseTempletClassify.getFirstClassify())) {
            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("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);
        } else if (Objects.equals(RightsTypeEnum.WEEK.code, rightsSetting.getStepType())) {
            // 更新每周、长期权益
            updateRightsWeek(rightsSetting);
        } else if (Objects.equals(RightsTypeEnum.LONG_TERM.code, rightsSetting.getStepType())) {
            // 更新每周、长期权益
            updateRightsLongTerm(rightsSetting);
        }else if (Objects.equals(RightsTypeEnum.UP_NUMBER.code, rightsSetting.getStepType())) {
            // 更新每周、长期权益
            updateNumber(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);
        //更新关联书刊
        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);

        return rightsSetting;
    }

    private void fillReadGuide(RightsSetting rightsSetting){
        RightsNowItem rightsNowItem = new RightsNowItem();

        if (RightsServeTypeEnum.NEWS.name().equalsIgnoreCase(rightsSetting.getGuideType()) && rightsSetting.getGuideId()!=null){
            Long newsId = rightsSetting.getGuideId();

            AppletNewsDTO appletNewsDTO = appletNewsBiz.getNewsById(newsId);

            BeanUtils.copyProperties(appletNewsDTO,rightsNowItem);

            rightsNowItem.setNewsSource(appletNewsDTO.getSource());
            rightsNowItem.setRightsSettingId(rightsSetting.getId());
            rightsNowItem.setServeName(appletNewsDTO.getNewsName());
            rightsNowItem.setServePic(appletNewsDTO.getPic1());
            rightsNowItem.setServeType(RightsServeTypeEnum.NEWS.name());
            rightsNowItem.setServeName("资讯");
            rightsNowItem.setSource(appletNewsDTO.getSource());
            rightsNowItem.setJumpType(appletNewsDTO.getJumpType());

            rightsSetting.setGuideNewsItem(rightsNowItem);

        }else if (AppAndProductTypeEnum.APPLET.name().equalsIgnoreCase(rightsSetting.getGuideType()) && rightsSetting.getGuideId()!=null){
            Long newsId =rightsSetting.getGuideId();
            if (null == newsId) {
                return;
            }
            AppletThirdResources appletThirdResources= appletThirdResourcesDao.getByResourcesId(newsId);
            if(appletThirdResources == null){
                return;
            }
            rightsSetting.setGuideAppletServe(appletThirdResources);
        } else if ((RightsServeTypeEnum.PRODUCT.name().equalsIgnoreCase(rightsSetting.getGuideType())  ||
                RightsServeTypeEnum.APP.name().equalsIgnoreCase(rightsSetting.getGuideType())) &&
                rightsSetting.getGuideId()!=null ) {
            rightsNowItem.setServeId(rightsSetting.getGuideId());
            rightsNowItem.setServeType(rightsSetting.getGuideType());
            rightsNowItem.setType(RightsNowItemTypeNew.ONLINE_COURSE.value);
            rightsNowItem.setLinkUrl(rightsSetting.getGuideLinkUrl());
            fillProductAndApp(Lists.newArrayList(rightsNowItem));
            rightsSetting.setGuideAppItem(rightsNowItem);
        }
    }

    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));
        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, String> adviserNameMap = new HashMap<>();
        if (!ListUtils.isEmpty(adviserIds)) {
            adviserNameMap = adviserConsr.getNames(adviserIds);
        }
        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(adviserNameMap) && null != adviserNameMap.get(rightsSettingBookRelation.getAdviserId())) {
                rightsSettingBookRelation.setAdviserName(adviserNameMap.get(rightsSettingBookRelation.getAdviserId()));
            }
        }
        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()).
                            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<>();
        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());
            }
        }
        Map<Long, ProductDto> productDtoMap = new HashMap<>();
        Map<Long, AppDto> appDtoMap = new HashMap<>();
        Map<Long, GroupActivity4AppletDTO> groupDtoMap = new HashMap<>();
        Map<Long, AppletNewsDTO> newsDtoMap = new HashMap<>();
        List<RightsNowItem> list_remove = new ArrayList<>(); //存储已经删除群的群分类; 精选文章类型并且跳转链接包含qrcode.5rs.me

        if (!ListUtils.isEmpty(productIds)) {
            productDtoMap = productConsr.getProBasesByIds(productIds);
        }
        if (!ListUtils.isEmpty(appIds)) {
            appDtoMap = appConsr.mapByIds4AuditPass(appIds);
        }
        if (!ListUtils.isEmpty(groupIds)) {
            groupDtoMap = pcloudGroupActivityBiz.getByIds4Now(groupIds);
        }
        if (!ListUtils.isEmpty(appletNewsId)) {
            newsDtoMap = appletNewsBiz.getByIds(appletNewsId);
        }
        for (RightsNowItem item : nowItems) {
            Integer type = item.getType();
            if (RightsNowItemTypeNew.ONLINE_COURSE.value.equals(type)
                    || RightsNowItemTypeNew.LEARNING_TOOL.value.equals(type)
                    || RightsNowItemTypeNew.DRAW.value.equals(type)
                    || RightsNowItemTypeNew.SERVES.value.equals(type)
                    || RightsNowItemTypeNew.GROUP_SERVICE.value.equals(type)
                    || RightsNowItemTypeNew.COACH.value.equals(type)
                    || RightsNowItemTypeNew.ONLINE_EXCL_COURSE.value.equals(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 = 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 (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 = qrcodeSceneConsr.getWechatInfo(appDto.getChannelId());
                        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); //把要移除的统一放在一个集合
                    }
                }
                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); //把要移除的统一放在一个集合
                    }
                }
                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.setBrowseCount(appletNewsDTO.getBrowseCount());
                    }
                }
            }
        }

        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 = bookGroupBiz.getBookAndBookGroupServeIds(adviserId, bookId, channelId);
        //填充作品应用
        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;
    }

    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) {//书刊权益
            paramMap.put("bookQuery", rightsSetting.getBookQuery());
            Long agentId = rightsSetting.getAgentId();
            if (null != agentId && agentId>0){
                List<Long> adviserIds = adviserConsr.getByAgentId(agentId);
                if (!ListUtils.isEmpty(adviserIds)){
                    paramMap.put("adviserIds", adviserIds);
                }
            }
            rightsSettingDtoPageBeanNew = rightsSettingDAO
                    .listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listBookRightsSettingPage");
            //填充编辑名称
            fillAdviserName(rightsSettingDtoPageBeanNew.getRecordList());
        } else {
            paramMap.put("firstClassify", rightsSetting.getFirstClassify());
            paramMap.put("secondClassify", rightsSetting.getSecondClassify());
            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 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, String> adviserNameMap = adviserConsr.getNames(adviserIds);
        if (MapUtils.isEmpty(adviserNameMap)) {
            return;
        }
        recordList.forEach(rightsSettingDto -> {
            List<RightsSettingBookRelation> rightsSettingBookRelations = rightsSettingDto.getRightsSettingBookRelations();
            if (ListUtils.isEmpty(rightsSettingBookRelations)) {
                return;
            }
            rightsSettingBookRelations.stream().forEach(rightsSettingBookRelation ->
                    rightsSettingBookRelation.setAdviserName(adviserNameMap.get(rightsSettingBookRelation.getAdviserId())));
        });
    }

    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> 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.getGradeLabelId()) {
                labelIds.add(rightsSettingDto.getGradeLabelId());
            }
            if (null != rightsSettingDto.getSubjectLabelId()) {
                labelIds.add(rightsSettingDto.getSubjectLabelId());
            }
            if (null != rightsSettingDto.getVolLabelId()) {
                labelIds.add(rightsSettingDto.getVolLabelId());
            }
            if (null != rightsSettingDto.getVerLabelId()){
                labelIds.add(rightsSettingDto.getVerLabelId());
            }
        }
        Map<Long, AssistTempletDTO> classifyMap = new HashMap<>();
        Map<Long, BookLabel> labelMap = new HashMap<>();
        if (!ListUtils.isEmpty(classifyIds)) {
            classifyMap = assistTempletConsr.mapByIds4Classify(classifyIds);
        }
        if (!ListUtils.isEmpty(labelIds)) {
            labelMap = bookLabelDao.getMapByIds(labelIds);
        }
        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(labelMap) && labelMap.containsKey(rightsSettingDto.getGradeLabelId())) {
                rightsSettingDto.setGradeLabelIdContent(labelMap.get(rightsSettingDto.getGradeLabelId()).getName());
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingDto.getSubjectLabelId())) {
                rightsSettingDto.setSubjectLabelIdContent(labelMap.get(rightsSettingDto.getSubjectLabelId()).getName());
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingDto.getVolLabelId())) {
                rightsSettingDto.setVolLabelContent(labelMap.get(rightsSettingDto.getVolLabelId()).getName());
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingDto.getVerLabelId())){
                rightsSettingDto.setVerLabelContent(labelMap.get(rightsSettingDto.getVerLabelId()).getName());
            }
        }
    }

    @Override
    public RightsSettingDto getByLabel(Long firstClassify, Long secondClassify, Long gradeLabelId, Long subjectLabelId, Long volLabelId,
                                       Long verLabelId) {
        //医疗保健分类校验
        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;
        }
        RightsSettingDto dto = rightsSettingDAO.getByLabel(firstClassify, secondClassify, gradeLabelId, subjectLabelId, volLabelId, verLabelId);
        //有版本筛选但权益未配置
        if (null == dto && null != verLabelId && verLabelId > 0) {
            Long commonLabelId = bookLabelDao.getByNameType("通用版",3);
            dto = rightsSettingDAO.getByLabel(firstClassify, secondClassify, gradeLabelId, subjectLabelId, volLabelId, commonLabelId);
        }
        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());
            }
        }
        if (null == rightsSettingDto) {
            log.error("该书没有匹配的分类权益，bookId=" + bookId);
            return new RightsSettingDto();
        }
        return rightsSettingDto;
    }

    @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, RightsNowItemTypeNew.ONLINE_REMIND.value);
        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);

        /*
        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 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.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());
            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.setGradeLabelId(adviserDto.getGraLabelId());
            rightsSetting.setSubjectLabelId(adviserDto.getSubLabelId());
        }
        //匹配资讯
        List<AppletNewsDTO> appletNewsDTOS = appletNewsBiz
                .getNewsByTempletLabel(rightsSetting.getFirstClassify(), rightsSetting.getSecondClassify(), rightsSetting.getGradeLabelId(),
                        rightsSetting.getSubjectLabelId(), rightsType, agentId);
        if (ListUtils.isEmpty(appletNewsDTOS)) {
            //没有则根据书刊分类和标签获取
            appletNewsDTOS = appletNewsBiz.getNewsByTempletLabel(rightsSetting.getFirstClassify(), rightsSetting.getSecondClassify(),
                    rightsSetting.getGradeLabelId(), rightsSetting.getSubjectLabelId(), null,agentId);
        }
        // 查询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)) {
            RightsSetting rightsSetting4Serves = setServe(rightsSetting, adviserId, bookId, channelId, readType);
            fillCollect(wechatUserId, rightsSetting4Serves, type);
        }
        // 获取抽奖权益
        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 (RightsNowItemTypeNew.ONLINE_REMIND.value.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);
        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(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.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));
        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 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();
            gradeLabelId = adviserDto.getGraLabelId();
            subjectLabelId = adviserDto.getSubLabelId();
            volLabelId = adviserDto.getVolLabelId();
        }
        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();
        Long agentId = appletNewsBiz.getAgentIdByAccountId(officialAccountsId);
        if (Objects.isNull(rightsClassifyId)) {
            fill.setFillServes(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 1L, 4, agentId));
            fill.setFillOnlineCourses(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 2L, 3, agentId));
            fill.setFillLearningTools(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 3L, 1, agentId));
            fill.setFillDraws(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 4L, 1, agentId));
            fill.setFillGiftCouponPackages(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 5L, 4, agentId));
            fill.setFillGroups(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, 6L, 1, agentId));
        } else {
            fill.setDesignatedNews(getAppletItems(firstClassify, secondClassify, gradeLabelId, subjectLabelId, rightsClassifyId, top, agentId));
        }
        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) {
        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);
            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());
            if (null == rightsSettingDto) {
                log.error("该书没有匹配的分类权益，bookId=" + bookId);
                return new RightsSettingDto();
            }
            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) {
        List<RightsNowItem> nowItems = new ArrayList<>();
        if (originalGroupId == null || rightsSettingId == null) {
            return nowItems;
        }
        List<BookServeDTO> 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) {
        List<AppletNews> appletNews = appletNewsDao
                .getByTempletAndClassify(firstClassify, secondClassify, gradeLabelId, subjectLabelId, rightsClassifyId, top, agentId);
        if (ListUtils.isEmpty(appletNews)) {
            return new ArrayList<>();
        }
        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());
    }

    @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) {
        List<RightsItemGroup> groups = rightsItemGroupDao.getListByRightSettingId(rightsSettingId, readType);
        if (ListUtils.isEmpty(groups)) {
            return new ArrayList<>();
        }
        for (RightsItemGroup group : groups) {
            //原版资源开关未开启
            if (group.getShowState() != null && !group.getShowState() && RightsItemGroupType.ORIGINAL.value.equals(group.getType())) {
                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 = 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;
    }
}
