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


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.AppletGroupSearchRecordBiz;
import com.pcloud.book.applet.biz.AppletNewsBiz;
import com.pcloud.book.applet.biz.AppletUserBookcaseBiz;
import com.pcloud.book.applet.dao.AppletNewsDao;
import com.pcloud.book.applet.dto.AppletGroupStatementDTO;
import com.pcloud.book.applet.dto.AppletNewsDTO;
import com.pcloud.book.applet.entity.AppletNews;
import com.pcloud.book.applet.entity.AppletUserBookcase;
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.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.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.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.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.ReadTypeCountDTO;
import com.pcloud.book.rightsSetting.dto.RightsSettingDto;
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.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.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.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.wechat.dto.AccountSettingDto;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
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 java.util.Comparator;
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.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
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.concurrent.atomic.AtomicReference;
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;

    @Override
    @ParamLog("新增权益设置")
    @Transactional(rollbackFor = Exception.class)
    public Long addRightsSetting(RightsSetting rightsSetting) {
        rightsSettingCheck.rightsSettingCheck4Insert(rightsSetting);
        setClassifyAndLabel(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<RightsReadType> rightsReadTypes = rightsSetting.getRightsReadTypes();
        if (!ListUtils.isEmpty(rightsReadTypes)) {
            rightsReadTypes.forEach(e -> e.setRightsSettingId(rightsSettingId));
            rightsReadTypeMapper.batchInsert(rightsReadTypes);
        }
        //新增关联书刊
        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);
        }
    }

    /**
     * 校验权益是否存在
     *
     * @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());
        }
        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);
        }
    }

    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, "已存在相同的权益设置");
        }
        rightsSettingDAO.updateByPrimaryKey(rightsSetting);
        //更新阅读方式
        rightsReadTypeMapper.deleteByRightsSettingId(rightsSettingId);
        List<RightsReadType> rightsReadTypes = rightsSetting.getRightsReadTypes();
        if (!ListUtils.isEmpty(rightsReadTypes)) {
            rightsReadTypes.forEach(e -> e.setRightsSettingId(rightsSettingId));
            rightsReadTypeMapper.batchInsert(rightsReadTypes);
        }
        //更新关联书刊
        updateRelationBook(rightsSetting, rightsSettingId);
    }

    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());
        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());
        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;
        // 处理资讯、社群等子项列表数据
        for (RightsSettingItem rightsItem : rightsSettingItemList) {
            groupActivity4AppletList = rightsItem.getGroupActivity4AppletList();
            appletNewsDTOS = rightsItem.getAppletNewsDTOS();
            customPlanList = rightsItem.getCustomPlanList();

            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);
                    }
                }
            }
        }
        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));
        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);
        return rightsSetting;
    }

    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));
        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) {
                    rightsSettingTitle.setRightsSettingItemList(nowItemMap.get(rightsSettingTitle.getId()));
                }
            }
            fillProductAndApp(nowItems);
        }
        List<RightsNowItem> giftCouponPackItems = rightsNowItemDao.getGiftCouponListByRightsSettingId(rightsSetting.getId());
        Iterator<RightsSettingTitle> iterator = rightsSettingTitles.iterator();
        while (iterator.hasNext()) {
            RightsSettingTitle rightsSettingTitle = iterator.next();
            if (RightsNowItemTypeNew.SERVES.value.equals(rightsSettingTitle.getRightsSettingNowType())) {
                servesTitle = rightsSettingTitle;
                iterator.remove();
            }
            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));
        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());
        Map<Long, BookDto> bookDtoMap = bookBiz.getListByIds(bookIds);
        if (MapUtils.isEmpty(bookDtoMap)) {
            return;
        }
        rightsSettingBookRelations.forEach(rightsSettingBookRelation -> {
            if (bookDtoMap.containsKey(rightsSettingBookRelation.getBookId()) && null != bookDtoMap
                    .get(rightsSettingBookRelation.getBookId())) {
                rightsSettingBookRelation.setBookName(bookDtoMap.get(rightsSettingBookRelation.getBookId()).getBookName());
            }
        });
        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(x -> x.getId()).collect(Collectors.toList());
        // 查询周、长期权益的列表子项
        List<RightsSettingItemDetail> allItemDetailList = rightsSettingItemDetailDao.getByItemIds(itemIds);
        // 按 rightsSettingItemId 分组
        Map<Long, List<RightsSettingItemDetail>> itemDetailMap = allItemDetailList.stream()
                .collect(Collectors.groupingBy(x -> x.getRightsSettingItemId()));

        List<Long> groupIds = new ArrayList<>();
        List<Long> appletNewsId = new ArrayList<>();
        List<Long> planIds = 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()) && !appletNewsId
                    .contains(item.getServeId())) {
                planIds.add(item.getServeId());
            }
        }

        Map<Long, GroupActivity4AppletDTO> groupDtoMap = new HashMap<>();
        Map<Long, AppletNewsDTO> newsDtoMap = new HashMap<>();
        Map<Long, CustomPlan> planDtoMap = 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);
        }

        List<RightsSettingItemDetail> itemDetailList;
        GroupActivity4AppletDTO groupActivity4AppletDTO;
        AppletNewsDTO appletNewsDTO;
        CustomPlan plan;
        for (RightsSettingItem rightsSettingItem : rightsSettingItemList) {
            // 默认值
            rightsSettingItem.setGroupActivity4AppletList(Lists.newArrayList());
            rightsSettingItem.setAppletNewsDTOS(Lists.newArrayList());
            rightsSettingItem.setCustomPlanList(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;
                    }
                    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);
                }
            }
        }
    }

    private 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()){
                    //头像列表从缓存里取
                    List<String> headUrlList = appletGroupSearchRecordBiz
                            .getHeadUrlList(3, 3l);
                    groupActivity4AppletDTO.setHeadUrlList(headUrlList);
                    continue;
                }
                //第三方群获取头像 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);
                    }
                }

            }
        }
    }

    /**
     * @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) {
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemTypeNew.ONLINE_COURSE, readType);
        if (null != rightsSettingTitle){
            List<RightsNowItem> 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);
            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 setLearningTool(RightsSetting rightsSetting, Long wechatUserId, Integer readType, Long bookId) {
        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);
            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) {
        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);
            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) {
        if (null == rightsSettingTitle || null == rightsSettingTitle.getRightsSettingId()) {
            return;
        }
        Integer collage = 1;
        List<RightsNowItem> items = Lists.newArrayList();
        if (CollectionUtils.isEmpty(nowItems) && rightsSettingTitle.getCollageState().intValue() == collage.intValue()) {
            // 填充咨询
            supplementNews(rightsSettingId, wechatUserId, rightsClassifyId, top, items,bookId, itemType.value);
            // 处理权益中的应用/作品
            fillProductAndApp(items);
            rightsSettingTitle.setRightsSettingItemList(items);
            return;
        }
//        // 处理权益中的应用/作品
//        fillProductAndApp(nowItems);
        //移除不能购买的应用或作品
        removeCanNotBuy(nowItems);
        for (RightsNowItem nowItem : nowItems) {
            if (itemType.value.equals(nowItem.getType())) {
                items.add(nowItem);
            }
        }
        // 此处只有资讯才会补充资讯
        if (RightsServeTypeEnum.NEWS.name().equalsIgnoreCase(rightsSettingTitle.getServeType())){
            if (items.size() < top &&  rightsSettingTitle.getCollageState().intValue() == collage.intValue()){
                // 填充咨询
                supplementNews(rightsSettingId, wechatUserId, rightsClassifyId, top - items.size(), items, bookId, itemType.value);
            }
        }
        // 处理权益中的应用/作品
        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) {
        FillRightsSettingAppletsDTO applets = getFillRightsSettingApplets(rightsSettingId, wechatUserId, rightsClassifyId, top, bookId);
        List<AppletNews> news = applets.getDesignatedNews();
        for (AppletNews appletNews : news) {
            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()).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));
    }


    private 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<>();

        if (!ListUtils.isEmpty(productIds)) {
            productDtoMap = productConsr.getProBasesByIds(productIds);
        }
        if (!ListUtils.isEmpty(appIds)) {
            appDtoMap = appConsr.mapByIds(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)) {
                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());
                        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);
                            String resultLinkUrl = SendWeixinRequestTools.splitUrl(accountSettingDto, item.getLinkUrl());
                            item.setResultUrl(resultLinkUrl);
                        } else {
                            item.setResultUrl(item.getLinkUrl());
                        }
                    }
                }
                if (AppAndProductTypeEnum.APP.value.equals(item.getServeType())) {
                    AppDto appDto = appDtoMap.get(item.getServeId());
                    if (appDto != null) {
                        item.setServeName(appDto.getTitle());
                        item.setServePic(appDto.getSquareImg());
                        item.setServeTypeCode(appDto.getTypeCode());
                        item.setServeTypeName(appDto.getTypeName());
                        accountSettingDto = qrcodeSceneConsr.getWechatInfo(appDto.getChannelId());
                        String resultLinkUrl = SendWeixinRequestTools.splitUrl(accountSettingDto, item.getLinkUrl());
                        item.setResultUrl(resultLinkUrl);
                    }
                }
                if (RightsServeTypeEnum.GROUP.name().equals(item.getServeType())) {
                    GroupActivity4AppletDTO groupActivity4AppletDTO = groupDtoMap.get(item.getServeId());
                    if (groupActivity4AppletDTO != null) {
                        item.setGroupName(groupActivity4AppletDTO.getName());
                        item.setGroupDesc(groupActivity4AppletDTO.getCutDesc());
                        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);
                    }
                }
                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());
                    }
                }
            }
        }
    }

    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());
            rightsSettingDtoPageBeanNew = rightsSettingDAO
                    .listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listBookRightsSettingPage");
        } 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());
            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 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());
            }
        }
        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());
            }
        }
    }

    @Override
    public RightsSettingDto getByLabel(Long firstClassify, Long secondClassify, Long gradeLabelId, Long subjectLabelId, Long volLabelId) {
        //医疗保健分类校验
        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;
        }
        RightsSettingDto dto = rightsSettingDAO.getByLabel(firstClassify, secondClassify, gradeLabelId, subjectLabelId, volLabelId);
        return dto;
    }

    @Override
    public Integer getUserCount() {
        Integer userCount = 102336;
        String key = "BOOK:APPLET:RIGHTS_SETTING_USER_COUNT";
        String value = JedisClusterUtils.get(key);
        if (StringUtil.isEmpty(value)) {
            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);
            }
            rightsSettingItemDao.insert(rightsSettingItemList);
        }
    }

    @Override
    public List<RightsSettingItem> getItemsByRightsSettingId(Long rightsSettingId, String rightsType, Integer readType) {
        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) {
            rightsSettingDto
                    .setRightsSettingBookRelations(rightsSettingBookRelationMapper.selectByRithsSettingId(rightsSettingDto.getId()));
            ;
        }
        if (null == rightsSettingDto) {
            //根据分类获取权益
            BookAdviserDto adviserDto = bookAdviserBiz.getBase(bookId, channelId, adviserId);
            if (null != adviserDto) {
                rightsSettingDto = getByLabel(adviserDto.getTempletId(), adviserDto.getSecondTempletId(), adviserDto.getGraLabelId(),
                        adviserDto.getSubLabelId(), adviserDto.getVolLabelId());
            }
        }
        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) {
        RightsSettingDto rightsSettingDto = new RightsSettingDto();
        //每周/长期权益
        if (RightsTypeEnum.WEEK.value.equals(rightsType)) {
            rightsSettingDto.setRightsSettingWeekItems(
                    getItemsByRightsSettingId4Applet(rightsSettingId, RightsTypeEnum.WEEK.value, wechatUserId, readType, bookId, adviserId, channelId));
        } else if (RightsTypeEnum.LONG_TERM.value.equals(rightsType)) {
            rightsSettingDto.setRightsSettingLongTermItems(
                    getItemsByRightsSettingId4Applet(rightsSettingId, RightsTypeEnum.LONG_TERM.value, wechatUserId, readType, bookId, adviserId, channelId));
        }
        return rightsSettingDto;
    }


    @Override
    public List<RightsSettingItem> getItemsByRightsSettingId4Applet(Long rightsSettingId, String rightsType, Long wechatUserId,
            Integer readType, Long bookId, Long adviserId, Long channelId) {
        List<RightsSettingItem> list = getItemsByRightsSettingId(rightsSettingId, rightsType, readType);
        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().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);
                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().intValue() == collage.intValue()){
                    needFillAppletNews.add(rightsSettingItem);
                }
            }
        }
        if (ListUtils.isEmpty(needFillAppletNews)) {
            return list;
        }
        // 将未选择服务的数据补充资讯
        setAppletNews4Week(rightsSettingId, rightsType, wechatUserId, needFillAppletNews,bookId);

        /*
        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);
        }
        */

        return list;
    }

    // 线上学习/阅读提醒（方案特殊处理）
    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) {
        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);
        if (ListUtils.isEmpty(appletNewsDTOS)) {
            //没有则根据书刊分类和标签获取
            appletNewsDTOS = appletNewsBiz.getNewsByTempletLabel(rightsSetting.getFirstClassify(), rightsSetting.getSecondClassify(),
                    rightsSetting.getGradeLabelId(), rightsSetting.getSubjectLabelId(), null);
            if (ListUtils.isEmpty(appletNewsDTOS)) {
                return list;
            }
        }
        Map<Long, List<AppletNewsDTO>> 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 (!MapUtils.isEmpty(map) && map.containsKey(item.getRightsClassifyId())) {
                    newsDTOS = map.get(item.getRightsClassifyId());
                    if (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;
                    }
                    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) {
        RightsSetting rightsSetting = rightsSettingDAO.selectByPrimaryKey(rightsSettingId);
        if (rightsSetting == null) {
            throw new BookBizException(BookBizException.ERROR, "未找到权益！");
        }
        // 获取配套资料
        if (RightsNowItemTypeNew.SERVES.value.equals(type)) {
            return setServe(rightsSetting, adviserId, bookId, channelId, readType);
        }
        // 获取抽奖权益
        if (RightsNowItemTypeNew.DRAW.value.equals(type)) {
            return setDraw(rightsSetting, wechatUserId, readType, bookId);
        }
        // 获取学习工具权益
        if (RightsNowItemTypeNew.LEARNING_TOOL.value.equals(type)) {
            return setLearningTool(rightsSetting, wechatUserId, readType, bookId);
        }
        // 获取线上网课权益
        if (RightsNowItemTypeNew.ONLINE_COURSE.value.equals(type)) {
            return setOnlineCourse(rightsSetting, wechatUserId, readType, bookId);
        }
        // 获取专享礼券包权益
        if (RightsNowItemTypeNew.GIFT_COUPON_PACKAGE.value.equals(type)) {
            return setGiftCouponPackage(rightsSetting, wechatUserId, readType, bookId);
        }
        // 获取专享社群
        if (RightsNowItemTypeNew.GROUP_SERVICE.value.equals(type)) {
            return setGroupService(rightsSetting, wechatUserId, readType, bookId);
        }
        return rightsSetting;
    }

    @ParamLog(value = "填充专享社群", isAfterReturn = false)
    private RightsSetting setGroupService(RightsSetting rightsSetting, Long wechatUserId, Integer readType, Long bookId) {
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemTypeNew.GROUP_SERVICE, readType);
        if (null != rightsSettingTitle) {
            List<RightsNowItem> 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);
                rightsSetting.setGroupServiceTitle(rightsSettingTitle);
            } else {
                processNowItems4Group(rightsSettingTitle, nowItems, RightsNowItemTypeNew.GROUP_SERVICE, rightsSetting.getId(), wechatUserId,
                        Long.valueOf(RightsNowItemTypeNew.GROUP_SERVICE.value), BookConstant.MAX_NEWS_COUNT, bookId);
                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) {
        if (null == rightsSettingTitle || null == rightsSettingTitle.getRightsSettingId()) {
            return;
        }

        Integer collage = 1;  //状态为拼群
        List<RightsNowItem> items = Lists.newArrayList();

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

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

    private List<GroupActivity4AppletDTO> supplementGroup(Long rightsSettingId, Long wechatUserId, Long rightsClassifyId, Integer top, List<RightsNowItem> items, Long bookId,String rightsType) {
        // 书刊分类
        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());
            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().intValue() == collage.intValue()){
                        isCollage = true;
                        break;
                    }
                }
            }else { //立享权益
                RightsSettingTitle rightsSettingTitle = rightsSettingTitleMapper.getByRightSettingIdAndType(rightsSettingId, 6,null);
//                List<RightsSettingTitle> rightsSettingTitles = rightsSettingTitleMapper.getByRightSettingId(rightsSettingId, null);
//                Iterator<RightsSettingTitle> it = rightsSettingTitles.iterator();
//                while(it.hasNext()){
//                    RightsSettingTitle item= it.next();
                    if (rightsSettingTitle.getCollageState().intValue() == collage.intValue() && RightsServeTypeEnum.GROUP.name().equalsIgnoreCase(rightsSettingTitle.getServeType()) ){
                        isCollage = true;
//                        break;
                    }
//                }
            }

            if(isCollage){
                setClassifyAndLabel(rightsSetting);
                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));
        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) {
        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();
        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));
        }
        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) {
        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()));
        }
        return groups;
    }

    @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);
        rightsNowPicDao.insert(rightsNowPic);
    }

    @ParamLog("获取即享权益图片列表")
    @Override
    public PageBeanNew<RightsNowPic> getRightsNowPics(Integer currentPage, Integer numPerPage, Integer type) {
        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);
        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) {
            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());
            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) {
        List<AppletNews> appletNews = appletNewsDao
                .getByTempletAndClassify(firstClassify, secondClassify, gradeLabelId, subjectLabelId, rightsClassifyId, top);
        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());
    }

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

}
