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


import com.pcloud.appcenter.app.dto.AppDto;
import com.pcloud.appcenter.assist.dto.AssistTempletDTO;
import com.pcloud.book.applet.biz.AppletNewsBiz;
import com.pcloud.book.applet.dao.AppletNewsDao;
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.resource.ProductConsr;
import com.pcloud.book.giftcoupon.dao.GiftReceiveDao;
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.constants.RightsSettingConstant;
import com.pcloud.book.rightsSetting.dao.RightsNowItemDao;
import com.pcloud.book.rightsSetting.dao.RightsSettingDAO;
import com.pcloud.book.rightsSetting.dao.RightsSettingItemDao;
import com.pcloud.book.rightsSetting.dao.check.RightsSettingCheck;
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.RightsNowItem;
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.enums.RightsNowItemType;
import com.pcloud.book.rightsSetting.enums.RightsTypeEnum;
import com.pcloud.book.util.common.CommonUtils;
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.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.resourcecenter.product.dto.ProductDto;
import lombok.extern.slf4j.Slf4j;
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 java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
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 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;

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

    @Override
    @ParamLog("更新权益设置")
    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);
        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<>();
        if (!ListUtils.isEmpty(rightsSetting.getOnlineCourseNowItems())){
            for (RightsNowItem item:rightsSetting.getOnlineCourseNowItems()){
                item.setType(RightsNowItemType.ONLINE_COURSE.value);
                item.setRightsSettingId(rightsSettingId);
                items.add(item);
            }
        }
        if (!ListUtils.isEmpty(rightsSetting.getLearningToolNowItems())){
            for (RightsNowItem item:rightsSetting.getLearningToolNowItems()){
                item.setType(RightsNowItemType.LEARNING_TOOL.value);
                item.setRightsSettingId(rightsSettingId);
                items.add(item);
            }
        }
        if (!ListUtils.isEmpty(rightsSetting.getDrawNowItems())){
            for (RightsNowItem item:rightsSetting.getDrawNowItems()){
                item.setType(RightsNowItemType.DRAW.value);
                item.setRightsSettingId(rightsSettingId);
                items.add(item);
            }
        }
        if (!ListUtils.isEmpty(rightsSetting.getGiftCouponPackageNowItems())){
            for (RightsNowItem item:rightsSetting.getGiftCouponPackageNowItems()){
                item.setType(RightsNowItemType.GIFT_COUPON_PACKAGE.value);
                item.setRightsSettingId(rightsSettingId);
                items.add(item);
            }
        }
        //根据权益id删除原来的
        rightsNowItemDao.deleteByRightsSettingId(rightsSettingId);
        if (!ListUtils.isEmpty(items)){
            rightsNowItemDao.batchInsert(items);
        }
    }

    @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);
        fillGiftCouponPack(rightsSetting);
        rightsSetting.setRightsSettingWeekItems(getItemsByRightsSettingId(id, RightsTypeEnum.WEEK.value));
        rightsSetting.setRightsSettingLongTermItems(getItemsByRightsSettingId(id,RightsTypeEnum.LONG_TERM.value));
        return rightsSetting;
    }


    @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<RightsNowItem> nowItems = rightsNowItemDao.getListByRightsSettingId(rightsSetting.getId(),types);
        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)){
                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);
                    }
                }
            }
        }
        rightsSetting.setOnlineCourseNowItems(nowItems.stream().filter(s->RightsNowItemType.ONLINE_COURSE.value.equals(s.getType())).collect(Collectors.toList()));
        rightsSetting.setLearningToolNowItems(nowItems.stream().filter(s->RightsNowItemType.LEARNING_TOOL.value.equals(s.getType())).collect(Collectors.toList()));
        rightsSetting.setDrawNowItems(nowItems.stream().filter(s->RightsNowItemType.DRAW.value.equals(s.getType())).collect(Collectors.toList()));
    }

    private void fillGiftCouponPack(RightsSetting rightsSetting){
        List<RightsNowItem> giftCouponPackItems = rightsNowItemDao.getGiftCouponListByRightsSettingId(rightsSetting.getId());
        rightsSetting.setGiftCouponPackageNowItems(giftCouponPackItems);
    }

    @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 = new ArrayList<>();
        List<Long> secondClassifyIds = new ArrayList<>();
        List<Long> classifyIds = new ArrayList<>();
        List<Long> gradeLabelIds = new ArrayList<>();
        List<Long> subjectLabelIds = new ArrayList<>();
        List<Long> labelIds = new ArrayList<>();
        firstClassifyIds  = rightsSettingDtos.stream().map(e -> e.getFirstClassify()).collect(Collectors.toList());
        secondClassifyIds  = rightsSettingDtos.stream().map(e -> e.getSecondClassify()).collect(Collectors.toList());
        gradeLabelIds  = rightsSettingDtos.stream().map(e -> e.getGradeLabelId()).collect(Collectors.toList());
        subjectLabelIds  = rightsSettingDtos.stream().map(e -> e.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<>();
        }
        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, CommonUtils.todayRemainingSeconds());
               }
           }
           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 getRightsSettingGiftCoupons(Long rightsSettingId, Long wechatUserId) {
        RightsSetting rightsSetting=new RightsSetting();
        rightsSetting.setId(rightsSettingId);
        fillGiftCouponPack(rightsSetting);
        fillUserGiftReceiveStatus(rightsSetting,wechatUserId);
        return rightsSetting;
    }

    @ParamLog("根据权益id获取即享权益项补充咨询")
    @Override
    public FillRightsSettingAppletsDTO getFillRightsSettingApplets(Long rightsSettingId, Long wechatUserId) {
        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();
        fill.setFillServes(getAppletItems(firstClassify,secondClassify,gradeLabelId,subjectLabelId,1L,4));
        fill.setFillOnlineCourses(getAppletItems(firstClassify,secondClassify,gradeLabelId,subjectLabelId,2L,2));
        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));
        return fill;
    }

    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.getGiftCouponPackageNowItems())){
            return;
        }
        List<Long> list = giftReceiveDao.getUserReceiveGiftId(wechatUserId);
        if (ListUtils.isEmpty(list)){
            list=new ArrayList<>();
        }
        for (RightsNowItem item:rightsSetting.getGiftCouponPackageNowItems()){
            if (list.contains(item.getGiftCouponPackageId())){
                item.setUserGiftReceive(true);
            }else {
                item.setUserGiftReceive(false);
            }
        }
    }


}
