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


import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
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.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.base.exception.BookBizException;
import com.pcloud.book.book.biz.BookAdviserBiz;
import com.pcloud.book.book.biz.BookBiz;
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.reader.ReaderConsr;
import com.pcloud.book.consumer.resource.ProductConsr;
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.dto.BookServeDTO;
import com.pcloud.book.group.enums.AppAndProductTypeEnum;
import com.pcloud.book.group.tools.SendWeixinRequestTools;
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.dto.FillRightsSettingAppletsDTO;
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.RightsReadPlan;
import com.pcloud.book.rightsSetting.entity.RightsSetting;
import com.pcloud.book.rightsSetting.entity.RightsSettingClassify;
import com.pcloud.book.rightsSetting.entity.RightsSettingItem;
import com.pcloud.book.rightsSetting.entity.RightsSettingTitle;
import com.pcloud.book.rightsSetting.enums.RightsItemGroupType;
import com.pcloud.book.rightsSetting.enums.RightsNowItemType;
import com.pcloud.book.rightsSetting.enums.RightsTypeEnum;
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.CommonUtils;
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 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 java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Random;
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;

    @Override
    @ParamLog("新增权益设置")
    public Long addRightsSetting(RightsSetting rightsSetting) {
        rightsSettingCheck.rightsSettingCheck(rightsSetting);
        setClassifyAndLabel(rightsSetting);
        if (existCheck(rightsSetting) > 0) {
            throw new BookBizException(BookBizException.ERROR, "已存在相同的权益设置");
        }
        rightsSettingDAO.insert(rightsSetting);
        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);
        }
    }

    /**
     * 校验权益是否存在
     *
     * @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) {
            paramMap.put("bookId", rightsSetting.getBookId());
        } 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());
        }
        List<RightsSettingDto> list = rightsSettingDAO.listRightsSettingPage(paramMap);
        count = list.size();
        return count;
    }

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

    @Override
    @ParamLog("更新权益设置")
    @Transactional(rollbackFor= Exception.class)
    public void updateRightsSetting(RightsSetting rightsSetting) {
        rightsSettingCheck.rightsSettingCheck(rightsSetting);
        if (null == rightsSetting.getId()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少id！");
        }
        if (existCheck(rightsSetting) > 0) {
            throw new BookBizException(BookBizException.ERROR, "已存在相同的权益设置");
        }
        setClassifyAndLabel(rightsSetting);
        rightsSetting.setUpdateTime(new Date());
        rightsSettingDAO.updateByPrimaryKey(rightsSetting);
        //更新即享权益
        updateRightNowItemByRightId(rightsSetting);
        //新增/修改每周或长期权益
        this.batchInsertRightsSettingItem(rightsSetting.getRightsSettingWeekItems(), rightsSetting.getId(), RightsTypeEnum.WEEK.value);
        if (!ListUtils.isEmpty(rightsSetting.getRightsSettingWeekItems())){
            for (RightsSettingItem rightsSettingItem : rightsSetting.getRightsSettingWeekItems()) {
                rightsSettingItem.setUuid(StringUtil.getUUID());
            }
        }
        this.batchInsertRightsSettingItem(rightsSetting.getRightsSettingWeekItems(), rightsSetting.getId(), RightsTypeEnum.WEEK.value);
        //根据rightsSetting.getId(),RightsTypeEnum.WEEK.value 查询rightSettingItem
        RightsSettingItem rightsSettingItem = new RightsSettingItem();
        rightsSettingItem.setRightsSettingId(rightsSetting.getId());
        rightsSettingItem.setRightsType(RightsTypeEnum.WEEK.value);
        List<RightsSettingItem> list = rightsSettingItemDao.queryAll(rightsSettingItem);
        List<RightsReadPlan> rightsReadPlans = new ArrayList<>();
        List<RightsCustomRelation> rightsCustomRelations = new ArrayList<>();
        if (!ListUtils.isEmpty(list)) {
            HashMap<String, RightsSettingItem> map = Maps.newHashMap();
            for (RightsSettingItem item : list) {
                map.put(item.getUuid(), item);
            }
            for (RightsSettingItem itemVO : rightsSetting.getRightsSettingWeekItems()) {
                RightsSettingItem vo = map.get(itemVO.getUuid());
                if (Objects.isNull(vo) || !(RightsNowItemType.ONLINE_REMIND.value.equals(vo.getRightsClassifyId().intValue()) || RightsNowItemType.ONLINE_READING_ACTIVITY.value.equals(vo.getRightsClassifyId().intValue()))) {
                    continue;
                }
                RightsReadPlan rightsReadPlan = new RightsReadPlan();
                rightsReadPlan.setRightsSettingItemId(vo.getId());
                rightsReadPlan.setIsOpen(itemVO.getIsOpen());
                rightsReadPlan.setServiceDesc(itemVO.getServiceDesc());
                rightsReadPlans.add(rightsReadPlan);
                if (ListUtils.isEmpty(itemVO.getCustomPlanList())){
                    continue;
                }
                for (CustomPlan plan : itemVO.getCustomPlanList()) {
                    RightsCustomRelation rightsCustomRelation = new RightsCustomRelation();
                    rightsCustomRelation.setCustomPlanId(Long.valueOf(plan.getId()));
                    rightsCustomRelation.setRightsSettingItemId(vo.getId());
                    rightsCustomRelations.add(rightsCustomRelation);
                }
            }
        }
        //批量插入rightsReadPlans和rightsCustomRelations
        rightsReadPlanDao.insert(rightsReadPlans);
        rightsCustomRelationDao.insert(rightsCustomRelations);
        this.batchInsertRightsSettingItem(rightsSetting.getRightsSettingLongTermItems(), rightsSetting.getId(), RightsTypeEnum.LONG_TERM.value);
    }

    @ParamLog("更新权益的即享权益项集合")
    private void updateRightNowItemByRightId(RightsSetting rightsSetting) {
        if (rightsSetting == null) {
            return;
        }
        Long rightsSettingId = rightsSetting.getId();
        List<RightsNowItem> items = new ArrayList<>();
        List<RightsSettingTitle> rightsSettingTitles = new ArrayList<>();
        //给每个权益设置id
        setRightsSettingId(rightsSetting, rightsSettingId, rightsSettingTitles);
        //设置每个权益详情
        setNowItems(rightsSetting, rightsSettingId, items);
        //处理权益配套资料分组
        dealItemGroups(rightsSetting,rightsSettingId,items);
        //根据权益id删除原来的
        rightsNowItemDao.deleteByRightsSettingId(rightsSettingId);
        if (!ListUtils.isEmpty(items)) {
            rightsNowItemDao.batchInsert(items);
        }
        if (null != rightsSetting.getOnlineRightsSettingTitle() && null == rightsSetting.getOnlineRightsSettingTitle().getId()) {
            rightsSettingTitleMapper.deleteByRightSettingId(rightsSettingId);
            if (!ListUtils.isEmpty(rightsSettingTitles)) {
                rightsSettingTitleMapper.batchInsert(rightsSettingTitles);
            }
        } else if (!ListUtils.isEmpty(rightsSettingTitles)) {
            rightsSettingTitleMapper.batchUpdate(rightsSettingTitles);
        }

    }

    @ParamLog("增加和删除分组")
    private void dealItemGroups(RightsSetting rightsSetting, Long rightsSettingId, List<RightsNowItem> items) {
        if (rightsSetting==null||ListUtils.isEmpty(rightsSetting.getRightsItemGroups())){
            return;
        }
        for (RightsItemGroup group:rightsSetting.getRightsItemGroups()){
            //集合转化为三个描述
            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.deleteByRightsSettingId(rightsSettingId);
        //新增新的
        rightsItemGroupDao.batchInsert(rightsSetting.getRightsItemGroups());
        for (RightsItemGroup group:rightsSetting.getRightsItemGroups()){
            if (ListUtils.isEmpty(group.getRightsNowItems())){
                continue;
            }
            for (RightsNowItem item:group.getRightsNowItems()){
                item.setType(RightsNowItemType.SERVES.value);
                item.setRightsItemGroupId(group.getId());
                item.setRightsSettingId(rightsSettingId);
                items.add(item);
            }
        }
    }

    private void setNowItems(RightsSetting rightsSetting, Long rightsSettingId, List<RightsNowItem> items) {
        log.info("填充即享权益具体项目的的基本参数");
        if (null != rightsSetting.getOnlineRightsSettingTitle() && !ListUtils
                .isEmpty(rightsSetting.getOnlineRightsSettingTitle().getRightsSettingItemList())) {
            for (RightsNowItem item : rightsSetting.getOnlineRightsSettingTitle().getRightsSettingItemList()) {
                item.setType(RightsNowItemType.ONLINE_COURSE.value);
                item.setRightsSettingId(rightsSettingId);
                items.add(item);
            }
        }
        if (null != rightsSetting.getLearningToolTitle() && !ListUtils
                .isEmpty(rightsSetting.getLearningToolTitle().getRightsSettingItemList())) {
            for (RightsNowItem item : rightsSetting.getLearningToolTitle().getRightsSettingItemList()) {
                item.setType(RightsNowItemType.LEARNING_TOOL.value);
                item.setRightsSettingId(rightsSettingId);
                items.add(item);
            }
        }
        if (null != rightsSetting.getDrawSettingTitle() && !ListUtils
                .isEmpty(rightsSetting.getDrawSettingTitle().getRightsSettingItemList())) {
            for (RightsNowItem item : rightsSetting.getDrawSettingTitle().getRightsSettingItemList()) {
                item.setType(RightsNowItemType.DRAW.value);
                item.setRightsSettingId(rightsSettingId);
                items.add(item);
            }
        }
        if (null != rightsSetting.getGiftCouponPackageTitle() && !ListUtils
                .isEmpty(rightsSetting.getGiftCouponPackageTitle().getRightsSettingItemList())) {
            for (RightsNowItem item : rightsSetting.getGiftCouponPackageTitle().getRightsSettingItemList()) {
                item.setType(RightsNowItemType.GIFT_COUPON_PACKAGE.value);
                item.setRightsSettingId(rightsSettingId);
                items.add(item);
            }
        }
    }

    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(RightsNowItemType.ONLINE_COURSE.value);
            rightsSettingTitles.add(onlineRightsSettingTitle);
        }
        if (null != learningToolTitle) {
            learningToolTitle.setRightsSettingId(rightsSettingId);
            learningToolTitle.setRightsSettingNowType(RightsNowItemType.LEARNING_TOOL.value);
            rightsSettingTitles.add(learningToolTitle);
        }
        if (null != drawSettingTitle) {
            drawSettingTitle.setRightsSettingId(rightsSettingId);
            drawSettingTitle.setRightsSettingNowType(RightsNowItemType.DRAW.value);
            rightsSettingTitles.add(drawSettingTitle);
        }
        if (null != giftCouponPackageTitle) {
            giftCouponPackageTitle.setRightsSettingId(rightsSettingId);
            giftCouponPackageTitle.setRightsSettingNowType(RightsNowItemType.GIFT_COUPON_PACKAGE.value);
            rightsSettingTitles.add(giftCouponPackageTitle);
        }
        if (null != groupServiceTitle) {
            groupServiceTitle.setRightsSettingId(rightsSettingId);
            groupServiceTitle.setRightsSettingNowType(RightsNowItemType.GROUP_SERVICE.value);
            rightsSettingTitles.add(groupServiceTitle);
        }
        if (null != servesTitle) {
            servesTitle.setRightsSettingId(rightsSettingId);
            servesTitle.setRightsSettingNowType(RightsNowItemType.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();
        }
        if (rightsSetting.getRightsSettingType() == 2 && null != rightsSetting.getBookId()) {
            BookDto bookDto = bookBiz.getBaseById(rightsSetting.getBookId());
            rightsSetting.setBookName(bookDto == null ? "" : bookDto.getBookName());
        }
        fillRightsNowItems(rightsSetting);
        rightsSetting.setRightsItemGroups(getRightsItemGroups(rightsSetting.getId(),null,null,null, false));
        fillGiftCouponPack(rightsSetting);
        List<RightsSettingItem> rightsItems = rightsSettingItemDao.getItemsByRightsSettingId4Read(id, RightsTypeEnum.WEEK.value);
        List<Long> itemIdList = new ArrayList<>();
        for (RightsSettingItem item : rightsItems) {
            itemIdList.add(item.getId());
        }
        //获取集合对应的rightsCustomRelation
        List<Long> customPlanIds = new ArrayList<>();
        if (!ListUtils.isEmpty(itemIdList)) {
            List<RightsCustomRelation> rightsCustomRelations = rightsCustomRelationDao.getCustomByItemIds(itemIdList);
            for (RightsSettingItem item : rightsItems) {
                List<CustomPlan> list = new ArrayList<>();
                for (RightsCustomRelation rightsCustomRelation : rightsCustomRelations) {
                    if (item.getId().equals(rightsCustomRelation.getRightsSettingItemId())) {
                        CustomPlan customPlan = new CustomPlan();
                        customPlan.setId(Integer.valueOf(rightsCustomRelation.getCustomPlanId().toString()));
                        list.add(customPlan);
                        customPlanIds.add(rightsCustomRelation.getCustomPlanId());
                    }
                }
                item.setCustomPlanList(list);
            }
        }
        List<CustomPlan> customPlanList = new ArrayList<>();
        if (!ListUtils.isEmpty(customPlanIds)) {
            customPlanList = customPlanMapper.getCustomPlanByIds(customPlanIds);
        }
        if (!ListUtils.isEmpty(customPlanList)) {
            Map<Integer, CustomPlan> appleMap = Optional
                    .ofNullable(customPlanList.stream().collect(Collectors.toMap(CustomPlan::getId, a -> a, (k1, k2) -> k1)))
                    .orElse(new HashMap<>());
            for (RightsSettingItem item : rightsItems) {
                List<CustomPlan> customPlanList1 = item.getCustomPlanList();
                List<CustomPlan> customPlanList2 = new ArrayList<>();
                for (CustomPlan customPlan : customPlanList1) {
                    CustomPlan customPlan1 = appleMap.get(customPlan.getId());
                    customPlanList2.add(customPlan1);
                }
                item.setCustomPlanList(customPlanList2);
            }
        }

        rightsSetting.setRightsSettingWeekItems(rightsItems);
        rightsSetting.setRightsSettingLongTermItems(getItemsByRightsSettingId(id, RightsTypeEnum.LONG_TERM.value));
        return rightsSetting;
    }

    /**
     * @return void
     * @Author David
     * @Description 设置线上网课
     * @Date 2020/4/24 16:59
     * @Param [rightsSetting, wechatUserId]
     **/
    @ParamLog(value = "填充线上网课", isAfterReturn = false)
    private RightsSetting setOnlineCourse(RightsSetting rightsSetting, Long wechatUserId) {
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemType.ONLINE_COURSE);
        List<RightsNowItem> nowItems = rightsNowItemDao.getListByRightsSettingId(rightsSetting.getId(), Collections.singletonList(RightsNowItemType.ONLINE_COURSE.value));
        processNowItems(rightsSettingTitle, nowItems, RightsNowItemType.ONLINE_COURSE, rightsSetting.getId(), wechatUserId, 2L, 3);
        rightsSetting.setOnlineRightsSettingTitle(rightsSettingTitle);
        return rightsSetting;
    }

    /**
     * @Author David
     * @Description 填充学习工具
     * @Date 2020/4/24 20:10
     * @Param [rightsSetting, wechatUserId]
     * @return void
     **/
    @ParamLog(value = "填充学习工具", isAfterReturn = false)
    private RightsSetting setLearningTool(RightsSetting rightsSetting, Long wechatUserId) {
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemType.LEARNING_TOOL);
        List<RightsNowItem> nowItems = rightsNowItemDao.getListByRightsSettingId(rightsSetting.getId(), Collections.singletonList(RightsNowItemType.LEARNING_TOOL.value));
        processNowItems(rightsSettingTitle, nowItems, RightsNowItemType.LEARNING_TOOL, rightsSetting.getId(), wechatUserId, 3L, 1);
        rightsSetting.setLearningToolTitle(rightsSettingTitle);
        return rightsSetting;
    }

    /**
     * @Author David
     * @Description 填充抽奖
     * @Date 2020/4/24 20:10
     * @Param [rightsSetting, wechatUserId]
     * @return void
     **/
    @ParamLog(value = "填充抽奖", isAfterReturn = false)
    private RightsSetting setDraw(RightsSetting rightsSetting, Long wechatUserId) {
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemType.DRAW);
        List<RightsNowItem> nowItems = rightsNowItemDao.getListByRightsSettingId(rightsSetting.getId(), Collections.singletonList(RightsNowItemType.DRAW.value));
        processNowItems(rightsSettingTitle, nowItems, RightsNowItemType.DRAW, rightsSetting.getId(), wechatUserId, 4L, 1);
        rightsSetting.setDrawSettingTitle(rightsSettingTitle);
        return rightsSetting;
    }

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

    /**
     * @Author David
     * @Description 获取权益标题
     * @Date 2020/4/24 20:07
     * @Param [rightsSetting, learningTool]
     * @return com.pcloud.book.rightsSetting.entity.RightsSettingTitle
     **/
    private RightsSettingTitle getRightsSettingTitle(RightsSetting rightsSetting, RightsNowItemType learningTool) {
        List<RightsSettingTitle> rightsSettingTitles = rightsSettingTitleMapper.getByRightSettingId(rightsSetting.getId());
        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, RightsNowItemType itemType,
                                 Long rightsSettingId, Long wechatUserId, Long rightsClassifyId,
                                 Integer top) {
        List<RightsNowItem> items = Lists.newArrayList();
        if (CollectionUtils.isEmpty(nowItems)) {
            // 填充咨询
            supplementNews(rightsSettingId, wechatUserId, rightsClassifyId, top, items);
            rightsSettingTitle.setRightsSettingItemList(items);
            return;
        }
        // 处理权益中的应用/作品
        fillProductAndApp(nowItems);
        //移除不能购买的应用或作品
        removeCanNotBuy(nowItems);
        for (RightsNowItem nowItem : nowItems) {
            if (itemType.value.equals(nowItem.getType())) {
                items.add(nowItem);
            }
        }
        if (items.size() < top) {
            // 填充咨询
            supplementNews(rightsSettingId, wechatUserId, rightsClassifyId, top, items);
        }
        rightsSettingTitle.setRightsSettingItemList(items);
    }

    /**
     * @Author David
     * @Description 补充咨询
     * @Date 2020/4/25 12:20
     * @Param [rightsSettingId, wechatUserId, rightsClassifyId, top, items]
     * @return void
     **/
    private void supplementNews( Long rightsSettingId, Long wechatUserId, Long rightsClassifyId, Integer top, List<RightsNowItem> items) {
        FillRightsSettingAppletsDTO applets = getFillRightsSettingApplets(rightsSettingId, wechatUserId, rightsClassifyId, top);
        List<AppletNews> news = applets.getDesignatedNews();
        for (AppletNews appletNews : news) {
            items.add(RightsNowItem.builder().serveId(appletNews.getId()).serveName(appletNews.getNewsName())
                    .serveTypeName("资讯").servePic(appletNews.getPic1()).type(0).jumpType(appletNews.getJumpType()).jumpUrl(appletNews.getJumpUrl()).build());
        }
    }


    @Deprecated
    @ParamLog("填充资源")
    private void fillRightsNowItems(RightsSetting rightsSetting) {
        List<Integer> types = new ArrayList<>();
        types.add(RightsNowItemType.ONLINE_COURSE.value);
        types.add(RightsNowItemType.LEARNING_TOOL.value);
        types.add(RightsNowItemType.DRAW.value);
        List<RightsSettingTitle> rightsSettingTitles = rightsSettingTitleMapper.getByRightSettingId(rightsSetting.getId());
        RightsSettingTitle rightsSettingTitler4Online = new RightsSettingTitle();
        RightsSettingTitle rightsSettingTitler4Learningtool = new RightsSettingTitle();
        RightsSettingTitle rightsSettingTitler4Draw = new RightsSettingTitle();
        RightsSettingTitle rightsSettingTitler4Serves = new RightsSettingTitle();
        rightsSettingTitler4Serves.setOpenState(Boolean.TRUE);
        rightsSettingTitler4Serves.setRightsSettingNowType(RightsNowItemType.SERVES.value);
        Map<Integer, RightsSettingTitle> rightsSettingTitleMap = new HashMap<>();
        if (!ListUtils.isEmpty(rightsSettingTitles)) {
            rightsSettingTitleMap =
                    rightsSettingTitles.stream()
                            .collect(Collectors.toMap(RightsSettingTitle::getRightsSettingNowType, Function.identity()));
        }
        if (null != rightsSettingTitleMap.get(RightsNowItemType.ONLINE_COURSE.value)) {
            rightsSettingTitler4Online = rightsSettingTitleMap.get(RightsNowItemType.ONLINE_COURSE.value);
        }
        if (null != rightsSettingTitleMap.get(RightsNowItemType.LEARNING_TOOL.value)) {
            rightsSettingTitler4Learningtool = rightsSettingTitleMap.get(RightsNowItemType.LEARNING_TOOL.value);
        }
        if (null != rightsSettingTitleMap.get(RightsNowItemType.DRAW.value)) {
            rightsSettingTitler4Draw = rightsSettingTitleMap.get(RightsNowItemType.DRAW.value);
        }
        List<RightsNowItem> nowItems = rightsNowItemDao.getListByRightsSettingId(rightsSetting.getId(), types);
        if (!ListUtils.isEmpty(nowItems)) {
            fillProductAndApp(nowItems);
            rightsSettingTitler4Online.setRightsSettingItemList(
                    nowItems.stream().filter(s -> RightsNowItemType.ONLINE_COURSE.value.equals(s.getType())).collect(Collectors.toList()));
            rightsSettingTitler4Learningtool.setRightsSettingItemList(
                    nowItems.stream().filter(s -> RightsNowItemType.LEARNING_TOOL.value.equals(s.getType())).collect(Collectors.toList()));
            rightsSettingTitler4Draw.setRightsSettingItemList(
                    nowItems.stream().filter(s -> RightsNowItemType.DRAW.value.equals(s.getType())).collect(Collectors.toList()));
        }
        rightsSetting.setOnlineRightsSettingTitle(rightsSettingTitler4Online);
        rightsSetting.setLearningToolTitle(rightsSettingTitler4Learningtool);
        rightsSetting.setDrawSettingTitle(rightsSettingTitler4Draw);
        rightsSetting.setGroupServiceTitle(null == rightsSettingTitleMap.get(RightsNowItemType.GROUP_SERVICE.value) ?
                new RightsSettingTitle() : rightsSettingTitleMap.get(RightsNowItemType.GROUP_SERVICE.value));
        rightsSetting.setGiftCouponPackageTitle(null == rightsSettingTitleMap.get(RightsNowItemType.GIFT_COUPON_PACKAGE.value) ?
                new RightsSettingTitle() : rightsSettingTitleMap.get(RightsNowItemType.GIFT_COUPON_PACKAGE.value));
        rightsSetting.setServesTitle(null == rightsSettingTitleMap.get(RightsNowItemType.SERVES.value) ?
                rightsSettingTitler4Serves : rightsSettingTitleMap.get(RightsNowItemType.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<>();
        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());
            }
        }
        Map<Long, ProductDto> productDtoMap = new HashMap<>();
        Map<Long, AppDto> appDtoMap = new HashMap<>();
        if (!ListUtils.isEmpty(productIds)) {
            productDtoMap = productConsr.getProBasesByIds(productIds);
        }
        if (!ListUtils.isEmpty(appIds)) {
            appDtoMap = appConsr.mapByIds(appIds);
        }
        for (RightsNowItem item : nowItems) {
            Integer type = item.getType();
            if (RightsNowItemType.ONLINE_COURSE.value.equals(type)
                    || RightsNowItemType.LEARNING_TOOL.value.equals(type)
                    || RightsNowItemType.DRAW.value.equals(type)
                    || RightsNowItemType.SERVES.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);
                    }
                }
            }
        }
    }

    private void fillGiftCouponPack(RightsSetting rightsSetting) {
        List<RightsNowItem> giftCouponPackItems = rightsNowItemDao.getGiftCouponListByRightsSettingId(rightsSetting.getId());
        RightsSettingTitle rightsSettingTitle = getRightsSettingTitle(rightsSetting, RightsNowItemType.GIFT_COUPON_PACKAGE);
        if (null != rightsSetting.getGiftCouponPackageTitle()) {
            // 礼券包默认开启
            rightsSettingTitle.setOpenState(true);
            rightsSetting.setGiftCouponPackageTitle(rightsSettingTitle);
            rightsSettingTitle = rightsSetting.getGiftCouponPackageTitle();
        }
        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());
            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 setLabelContent(List<RightsSettingDto> rightsSettingDtos) {
        log.info("权益设置标签具体内容");
        if (ListUtils.isEmpty(rightsSettingDtos)) {
            return;
        }
        List<Long> firstClassifyIds;
        List<Long> secondClassifyIds;
        List<Long> classifyIds = new ArrayList<>();
        List<Long> gradeLabelIds;
        List<Long> subjectLabelIds;
        List<Long> labelIds = new ArrayList<>();
        firstClassifyIds = rightsSettingDtos.stream().map(RightsSetting::getFirstClassify).collect(Collectors.toList());
        secondClassifyIds = rightsSettingDtos.stream().map(RightsSetting::getSecondClassify).collect(Collectors.toList());
        gradeLabelIds = rightsSettingDtos.stream().map(RightsSetting::getGradeLabelId).collect(Collectors.toList());
        subjectLabelIds = rightsSettingDtos.stream().map(RightsSetting::getSubjectLabelId).collect(Collectors.toList());
        if (!ListUtils.isEmpty(firstClassifyIds)) {
            classifyIds.addAll(firstClassifyIds);
        }
        if (!ListUtils.isEmpty(secondClassifyIds)) {
            classifyIds.addAll(secondClassifyIds);
        }
        if (!ListUtils.isEmpty(gradeLabelIds)) {
            labelIds.addAll(gradeLabelIds);
        }
        if (!ListUtils.isEmpty(subjectLabelIds)) {
            labelIds.addAll(subjectLabelIds);
        }
        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());
            }
        }
    }

    @Override
    public RightsSettingDto getByLabel(Long firstClassify, Long secondClassify, Long gradeLabelId, Long subjectLabelId) {
        //医疗保健分类校验
        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;
        }
        RightsSettingDto dto = rightsSettingDAO.getByLabel(firstClassify, secondClassify, gradeLabelId, subjectLabelId);
        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
    public void batchInsertRightsSettingItem(List<RightsSettingItem> rightsSettingItemList, Long rightsSettingId, String rightsType) {
        if (null == rightsSettingId || StringUtil.isEmpty(rightsType)) {
            return;
        }
        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) {
        RightsSettingItem item = new RightsSettingItem();
        item.setRightsSettingId(rightsSettingId);
        item.setRightsType(rightsType);
        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) {
            //根据分类获取权益
            BookAdviserDto adviserDto = bookAdviserBiz.getBase(bookId, channelId, adviserId);
            if (null != adviserDto) {
                rightsSettingDto = getByLabel(adviserDto.getTempletId(), adviserDto.getSecondTempletId(), adviserDto.getGraLabelId(), adviserDto.getSubLabelId());
            }
        }
        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) {
        RightsSettingDto rightsSettingDto = new RightsSettingDto();
        //每周/长期权益
        if (RightsTypeEnum.WEEK.value.equals(rightsType)) {
            rightsSettingDto.setRightsSettingWeekItems(getItemsByRightsSettingId4Applet(rightsSettingId, RightsTypeEnum.WEEK.value, wechatUserId));
        } else if (RightsTypeEnum.LONG_TERM.value.equals(rightsType)) {
            rightsSettingDto.setRightsSettingLongTermItems(getItemsByRightsSettingId4Applet(rightsSettingId, RightsTypeEnum.LONG_TERM.value, wechatUserId));
        }
        return rightsSettingDto;
    }


    @Override
    public List<RightsSettingItem> getItemsByRightsSettingId4Applet(Long rightsSettingId, String rightsType, Long wechatUserId) {
        List<RightsSettingItem> list = getItemsByRightsSettingId(rightsSettingId, rightsType);
        if (ListUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        list = setAppletNews4Week(rightsSettingId, rightsType, wechatUserId, list);
        List<Long> rightsSettingItemIds =
                list.stream().filter(e -> YesOrNoEnums.YES.getValue().equals(e.getIsOpen())
                    && RightsNowItemType.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())
            && RightsNowItemType.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 setGroupActivity(List<RightsSettingItem> list, List<Long> rightsSettingItemIds){
        if(ListUtils.isEmpty(list)){
            return;
        }
        GroupActivity4AppletDTO groupActivity4AppletDTO = null;
        // 书刊分类
        BookAdviserDto bookAdviserDto = bookAdviserBiz.getOneMainBook(list.get(0).getBookId());
        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());
            setClassifyAndLabel(baseTempletClassify);
            // 通过书刊分类拿群
            groupActivity4AppletDTO = pcloudGroupActivityDao.getGroupActivity4Applet(baseTempletClassify.getFirstClassify(),baseTempletClassify.getSecondClassify(),baseTempletClassify.getGradeLabelId(),baseTempletClassify.getSubjectLabelId());
        }

        if(groupActivity4AppletDTO == null){
            // 如果书刊没拿到群，则通过权益分类拿群
            RightsSetting rightsSetting = rightsSettingDAO.selectByPrimaryKey(list.get(0).getRightsSettingId());
            setClassifyAndLabel(rightsSetting);
            groupActivity4AppletDTO = pcloudGroupActivityDao.getGroupActivity4Applet(rightsSetting.getFirstClassify(), rightsSetting.getSecondClassify(),rightsSetting.getGradeLabelId(),rightsSetting.getSubjectLabelId());
        }
        if(groupActivity4AppletDTO != null){
            String filterStr = StringUtilParent.replaceHtml(groupActivity4AppletDTO.getDesc());
            String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
            groupActivity4AppletDTO.setCutDesc(subStr);
            //头像列表从缓存里取
            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);
            for(RightsSettingItem rightsSettingItem : list){
                if(rightsSettingItemIds.contains(rightsSettingItem.getId())){
                    rightsSettingItem.setGroupActivity4AppletDTO(groupActivity4AppletDTO);
                }
            }
        }
    }

    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) {
        RightsSetting rightsSetting = rightsSettingDAO.selectByPrimaryKey(rightsSettingId);
        if (rightsSetting.getRightsSettingType() == 2) {//书刊权益，分类标签从编辑书刊取
            BookAdviserDto adviserDto = bookAdviserBiz.getOneMainBook(rightsSetting.getBookId());
            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) {
            //用户-权益-权益分类
            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() < 3) {//数据库取
                if (!MapUtils.isEmpty(map) && map.containsKey(item.getRightsClassifyId())) {
                    newsDTOS = map.get(item.getRightsClassifyId());
                    if (newsDTOS.size() > 3) {//随机取三条
                        List<AppletNewsDTO> dtos = new ArrayList<>();
                        while (dtos.size() < 3) {
                            AppletNewsDTO dto = newsDTOS.get(new Random().nextInt(newsDTOS.size()));
                            if (!dtos.contains(dto)) {
                                dtos.add(dto);
                            }
                        }
                        newsDTOS = dtos;
                    }
                    JedisClusterUtils.setJsonList(key, newsDTOS, 60);
                }
            }
            item.setAppletNewsDTOS(newsDTOS);
        }
        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) {
        RightsSetting rightsSetting = rightsSettingDAO.selectByPrimaryKey(rightsSettingId);
        if (rightsSetting == null) {
            throw new BookBizException(BookBizException.ERROR, "未找到权益！");
        }
        // 获取配套资料
        if (RightsNowItemType.SERVES.value.equals(type)){
            return setServe(rightsSetting,adviserId, bookId, channelId);
        }
        // 获取抽奖权益
        if (RightsNowItemType.DRAW.value.equals(type)) {
            return setDraw(rightsSetting, wechatUserId);
        }
        // 获取学习工具权益
        if (RightsNowItemType.LEARNING_TOOL.value.equals(type)) {
            return setLearningTool(rightsSetting, wechatUserId);
        }
        // 获取线上网课权益
        if (RightsNowItemType.ONLINE_COURSE.value.equals(type)) {
            return setOnlineCourse(rightsSetting, wechatUserId);
        }
        // 获取专享礼券包权益
        if (RightsNowItemType.GIFT_COUPON_PACKAGE.value.equals(type)) {
            return setGiftCouponPackage(rightsSetting, wechatUserId);
        }
        return rightsSetting;
    }

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

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


    @ParamLog("根据权益id获取即享权益项补充咨询")
    @Override
    public FillRightsSettingAppletsDTO getFillRightsSettingApplets(Long rightsSettingId, Long wechatUserId, Long rightsClassifyId,
                                                                   Integer top) {
        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 = null;
        Long subjectLabelId = null;
        if (rightsSetting.getRightsSettingType() == 2) {//书刊权益，分类标签从编辑书刊取
            BookAdviserDto adviserDto = bookAdviserBiz.getOneMainBook(rightsSetting.getBookId());
            firstClassify = adviserDto.getTempletId();
            secondClassify = adviserDto.getSecondTempletId();
            gradeLabelId = adviserDto.getGraLabelId();
            subjectLabelId = adviserDto.getSubLabelId();
        }
        BaseTempletClassify classify = new BaseTempletClassify();
        classify.setFirstClassify(firstClassify);
        classify.setSecondClassify(secondClassify);
        classify.setGradeLabelId(gradeLabelId);
        classify.setSubjectLabelId(subjectLabelId);
        setClassifyAndLabel(classify);
        firstClassify = classify.getFirstClassify();
        secondClassify = classify.getSecondClassify();
        gradeLabelId = classify.getGradeLabelId();
        subjectLabelId = classify.getSubjectLabelId();
        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;
    }



    @ParamLog("根据权益id获取即享权益配套资料分组集合")
    @Override
    public List<RightsItemGroup> getRightsItemGroups(Long rightsSettingId, Long adviserId, Long bookId, Long channelId, Boolean removeCanNotBuy) {
        if (rightsSettingId == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数有误！");
        }
        List<RightsItemGroup> groups = rightsItemGroupDao.getListByRightSettingId(rightsSettingId);
        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() {
        return rightsNowPicDao.getAllDefaultRightsNowPics();
    }

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

    @ParamLog("获取即享权益图片列表")
    @Override
    public PageBeanNew<RightsNowPic> getRightsNowPics(Integer currentPage, Integer numPerPage) {
        if (currentPage==null||numPerPage==null||currentPage<0||numPerPage<=0){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"参数有误！");
        }
        PageBeanNew<RightsNowPic> pageNew = rightsNowPicDao.listPageNew(new PageParam(currentPage, numPerPage), new HashMap<>(), "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);
    }

    @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(RightsNowItemType.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 || 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
     */
    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());
    }
}
