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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.google.common.collect.Lists;
import com.pcloud.appcenter.assist.dto.AssistTempletDTO;
import com.pcloud.book.applet.biz.AppletNewsBiz;
import com.pcloud.book.applet.biz.AppletUserBookcaseBiz;
import com.pcloud.book.applet.biz.ServeCollectBiz;
import com.pcloud.book.applet.contants.AppletConstants;
import com.pcloud.book.applet.dao.AppletBusinessCardDao;
import com.pcloud.book.applet.dao.AppletLinkClickDao;
import com.pcloud.book.applet.dao.AppletNewsCategoryDao;
import com.pcloud.book.applet.dao.AppletNewsClassifyDao;
import com.pcloud.book.applet.dao.AppletNewsCommentDao;
import com.pcloud.book.applet.dao.AppletNewsDao;
import com.pcloud.book.applet.dao.AppletNewsServeDao;
import com.pcloud.book.applet.dao.AppletThirdResourcesDao;
import com.pcloud.book.applet.dao.AppletThirdResourcesRelationDao;
import com.pcloud.book.applet.dao.AppletUserBookcaseDao;
import com.pcloud.book.applet.dto.AppletNewsCategoryDTO;
import com.pcloud.book.applet.dto.AppletNewsClassifyDTO;
import com.pcloud.book.applet.dto.AppletNewsCommentDTO;
import com.pcloud.book.applet.dto.AppletNewsCustomTagDTO;
import com.pcloud.book.applet.dto.AppletNewsDTO;
import com.pcloud.book.applet.dto.AppletNewsServeDTO;
import com.pcloud.book.applet.dto.AppletNewsVO;
import com.pcloud.book.applet.dto.AppletThirdResourcesDTO;
import com.pcloud.book.applet.dto.PvuvDTO;
import com.pcloud.book.applet.entity.*;
import com.pcloud.book.applet.enums.AppletNewsServeTypeEnum;
import com.pcloud.book.applet.enums.DataRecordTypeEnum;
import com.pcloud.book.applet.enums.DataTypeEnum;
import com.pcloud.book.applet.mapper.AppletThirdResourcesPicMapper;
import com.pcloud.book.applet.vo.AppletNewsClassifyVO;
import com.pcloud.book.applet.vo.AppletNewsShowStateVO;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.dao.BookLabelDao;
import com.pcloud.book.book.entity.BookLabel;
import com.pcloud.book.consumer.app.AssistTempletConsr;
import com.pcloud.book.consumer.label.LabelConsr;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.consumer.user.ChannelConsr;
import com.pcloud.book.push.dao.PersonalAppletsDao;
import com.pcloud.book.push.entity.PersonalApplets;
import com.pcloud.book.record.biz.BookBrowseRecordBiz;
import com.pcloud.book.record.entity.RegionMap;
import com.pcloud.book.record.mapper.RegionMapMapper;
import com.pcloud.book.rightsSetting.biz.RightsSettingBiz;
import com.pcloud.book.rightsSetting.entity.BaseTempletClassify;
import com.pcloud.book.util.properties.BookProps;
import com.pcloud.channelcenter.wechat.entity.AccountSetting;
import com.pcloud.common.exceptions.BizException;
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.readercenter.wechat.entity.WechatUser;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 小程序资讯
 */
@Component
public class AppletNewsBizImpl implements AppletNewsBiz {

    @Autowired
    private AppletNewsClassifyDao appletNewsClassifyDao;
    @Autowired
    private AppletNewsDao appletNewsDao;
    @Autowired
    private LabelConsr labelConsr;
    @Autowired
    private AppletNewsCommentDao appletNewsCommentDao;
    @Autowired
    private ReaderConsr readerConsr;
    @Autowired
    private RightsSettingBiz rightsSettingBiz;
    @Autowired
    private BookLabelDao bookLabelDao;
    @Autowired
    private AssistTempletConsr assistTempletConsr;
    @Autowired
    private AppletLinkClickDao appletLinkClickDao;
    @Autowired
    private AppletNewsServeDao appletNewsServeDao;
    @Autowired
    private PersonalAppletsDao personalAppletsDao;
    @Autowired
    private AppletUserBookcaseBiz appletUserBookcaseBiz;
    @Autowired
    private AppletUserBookcaseDao appletUserBookcaseDao;
    @Autowired
    private AppletBusinessCardDao appletBusinessCardDao;
    @Autowired
    private AppletNewsCategoryDao appletNewsCategoryDao;
    @Autowired
    private AppletThirdResourcesRelationDao thirdResourcesRelationDao;
    @Autowired
    private AppletThirdResourcesDao thirdResourcesDao;
    @Autowired
    private BookBrowseRecordBiz bookBrowseRecordBiz;
    @Autowired
    private RegionMapMapper regionMapMapper;
    @Autowired
    private ServeCollectBiz serveCollectBiz;
    @Autowired
    private AppletThirdResourcesPicMapper appletThirdResourcesPicMapper;

    @Override
    public void deleteCategoryById(Long id) {
        appletNewsCategoryDao.deleteById(id);
    }
    @Autowired
    private ChannelConsr channelConsr;

    @Override
    public Long addAppletNewsClassify(AppletNewsClassify appletNewsClassify) {
        if (null == appletNewsClassify.getAgentId()){
            appletNewsClassify.setAgentId(0L);
        }
        Integer seq = appletNewsClassifyDao.getMaxSeq(appletNewsClassify.getAgentId());
        appletNewsClassify.setSeq(seq+1);
        appletNewsClassify.setShowState(false);
        appletNewsClassifyDao.insert(appletNewsClassify);
        return appletNewsClassify.getId();
    }

    @Override
    public void updateAppletNewsClassify(AppletNewsClassify appletNewsClassify) {
        if (null == appletNewsClassify.getId()){
            throw new BookBizException(BookBizException.ERROR,"id为空");
        }
        appletNewsClassifyDao.update(appletNewsClassify);
        JedisClusterUtils.del(AppletConstants.HOME_NEWS_LIST);
    }

    @Override
    public void deleteNewsClassifyById(Long id) {
        List<AppletNews> newsList = appletNewsDao.getByNewsClassifyId(id);
        if (!ListUtils.isEmpty(newsList)){
            throw new BookBizException(BookBizException.ERROR,"请先清空资讯");
        }
        appletNewsClassifyDao.deleteById(id);
        JedisClusterUtils.del(AppletConstants.HOME_NEWS_LIST);
    }

    @Override
    public PageBeanNew<AppletNewsClassifyDTO> listNewsClassify(Integer currentPage, Integer numPerPage, String name, Long agentId) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        paramMap.put("agentId", agentId);
        PageBeanNew<AppletNewsClassifyDTO> pageBeanNew = appletNewsClassifyDao.listPageNew(
                new PageParam(currentPage,numPerPage) ,paramMap,"listNewsClassify");
        return pageBeanNew;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addAppletNews(AppletNews appletNews) {
        if (null == appletNews.getAgentId()){
            appletNews.setAgentId(0L);
        }
        if (urlNumberExist(appletNews)){
            throw new BookBizException(BookBizException.ERROR,"链接编号重复");
        }
        if(appletNews.getBusinessCardType()!= null && appletNews.getBusinessCardType()==0){
            AppletBusinessCard appletBusinessCard = new AppletBusinessCard();
            BeanUtils.copyProperties(appletNews,appletBusinessCard);
            Long businessId = appletBusinessCardDao.insert(appletBusinessCard);
            appletNews.setBusinessCardId(businessId);
        }
        if (null == appletNews.getNewsClassifyId()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"新增时栏目不能为空");
        }
        appletNews.setShowState(false);
//        rightsSettingBiz.setClassifyAndLabel(appletNews);
        appletNewsDao.insert(appletNews);
        //保存咨询类别
        this.saveAppletNewsCategory(appletNews.getAppletNewsCategoryList(), appletNews.getId());
        // 保存选取的服务
//        this.saveAppletNewsServe(appletNews.getAppletNewsServeList(), appletNews.getId());
        this.updateSource(null,appletNews.getSource(), appletNews.getAgentId());
        //保存第三方资源
        this.saveThirdResources(appletNews.getThirdResourcesRelations(), appletNews.getId());
        return appletNews.getId();
    }

    private void saveThirdResources(List<AppletThirdResourcesRelation> thirdResourcesRelations, Long appletNewsId) {
        // 删除旧数据
        thirdResourcesRelationDao.deleteByAppletNewsId(appletNewsId);
        if (ListUtils.isEmpty(thirdResourcesRelations)) {
            return;
        }
        for (AppletThirdResourcesRelation dto : thirdResourcesRelations) {
            dto.setFromId(appletNewsId);
        }
        thirdResourcesRelationDao.insert(thirdResourcesRelations);
    }

    private void saveAppletNewsCategory(List<AppletNewsCategory> categoryList, Long newsId) {
        appletNewsCategoryDao.deletebyNewsId(newsId);
        if (ListUtils.isEmpty(categoryList)) {
            return;
        }

        List<AppletNewsCategory> list = new ArrayList<>();
        for (AppletNewsCategory category : categoryList) {
            if (Objects.nonNull(category.getFirstClassify())){
                rightsSettingBiz.setClassifyAndLabel(category);
                category.setAppletNewId(newsId);
                list.add(category);
            }
        }

        if (CollUtil.isNotEmpty(list)){
            appletNewsCategoryDao.batchCreate(list);
        }
    }


    /**
     * 保存选取的服务
     * @param appletNewsServeList
     * @param
     */
//    private void saveAppletNewsServe(List<AppletNewsServe> appletNewsServeList, Long appletNewsId) {
//        // 删除旧数据
//        appletNewsServeDao.deleteByAppletNewsId(appletNewsId);
//        if (ListUtils.isEmpty(appletNewsServeList)) {
//            return;
//        }
//        for (AppletNewsServe appletNewsServe : appletNewsServeList) {
//            appletNewsServe.setAppletNewsId(appletNewsId);
//        }
//        this.checkAppletNewsServe(appletNewsServeList);
//        appletNewsServeDao.insert(appletNewsServeList);
//    }

    private void checkAppletNewsServe(List<AppletNewsServe> appletNewsServeList) {
        for (AppletNewsServe appletNewsServe : appletNewsServeList) {
            if (!AppletNewsServeTypeEnum.LINK.code.equals(appletNewsServe.getServeType())) {
                continue;
            }
            if (StringUtil.isEmpty(appletNewsServe.getTitle())) {
                throw new BizException(BizException.PARAM_IS_NULL.getCode(), "标题不能为空");
            }
            if (StringUtil.isEmpty(appletNewsServe.getPicUrl())) {
                throw new BizException(BizException.PARAM_IS_NULL.getCode(), "导图不能为空");
            }
            if (StringUtil.isEmpty(appletNewsServe.getLinkUrl())) {
                throw new BizException(BizException.PARAM_IS_NULL.getCode(), "跳转链接不能为空");
            }
        }
        long appletCount = appletNewsServeList.stream()
                .filter(x -> AppletNewsServeTypeEnum.APPLET.code.equals(x.getServeType())).count();
        if (appletCount > 3) {
            throw new BizException(BizException.PARAM_IS_NULL.getCode(), "第三方小程序数量不能大于3个");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateAppletNews(AppletNews appletNews) {
        if (null == appletNews.getId()) {
            throw new BookBizException(BookBizException.ERROR, "id为空");
        }
        AppletNews news = appletNewsDao.getById(appletNews.getId());
        appletNews.setAgentId(news.getAgentId());
        if (urlNumberExist(appletNews)){
            throw new BookBizException(BookBizException.ERROR,"链接编号重复");
        }
        if (appletNews.getBusinessCardType() != null && appletNews.getBusinessCardType() == 0) {
            AppletBusinessCard appletBusinessCard = new AppletBusinessCard();
            BeanUtils.copyProperties(appletNews, appletBusinessCard);
            if (appletNews.getBusinessCardId() == null) {
                Long businessId = appletBusinessCardDao.insert(appletBusinessCard);
                appletNews.setBusinessCardId(businessId);
            } else {
                appletBusinessCard.setId(appletNews.getBusinessCardId());
                Long businessId = appletBusinessCardDao.update(appletBusinessCard);
            }
        }
        if (null == appletNews.getNewsClassifyId()) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "更新时栏目不能为空");
        }
        AppletNews beforeNews = appletNewsDao.getById(appletNews.getId());
        rightsSettingBiz.setClassifyAndLabel(appletNews);
        appletNewsDao.update(appletNews);
//        this.saveAppletNewsServe(appletNews.getAppletNewsServeList(), appletNews.getId());
        this.updateSource(beforeNews.getSource(),appletNews.getSource(), appletNews.getAgentId());
        //保存咨询分类
        this.saveAppletNewsCategory(appletNews.getAppletNewsCategoryList(), appletNews.getId());
        //保存第三方资源
        this.saveThirdResources(appletNews.getThirdResourcesRelations(), appletNews.getId());

        JedisClusterUtils.del(AppletConstants.HOME_NEWS_LIST);
    }

    @Override
    public void deleteAppletNewsById(Long id) {
        AppletNews beforeNews = appletNewsDao.getById(id);
        if (null == beforeNews) {
            return;
        }
        appletNewsDao.deleteByNews(Lists.newArrayList(id));
        //同时删除配置的资讯 1 删除即享权益 2 删除删除周或长期
        rightsSettingBiz.deleteInvalidNews(Lists.newArrayList(id));
        serveCollectBiz.deleteInvalidNews(Lists.newArrayList(id));
        this.updateSource(beforeNews.getSource(), null, beforeNews.getAgentId());
        JedisClusterUtils.del(AppletConstants.HOME_NEWS_LIST);
    }

    @Override
    public PageBeanNew<AppletNewsDTO> listAppletNews(Integer currentPage, Integer numPerPage, String name,
                                                     Long firstClassify, Long secondClassify, Long thirdClassify, Long gradeLabelId,
                                                     Long subjectLabelId, Long rightsClassifyId, String source, Integer showState, Long newsClassifyId,
                                                     Long customTagId, String cityCode,Long agentId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        paramMap.put("rightsClassifyId", rightsClassifyId);
        paramMap.put("source", source);
        paramMap.put("showState", showState);
        paramMap.put("newsClassifyId", newsClassifyId);
        paramMap.put("customTagId", customTagId);
        paramMap.put("agentId", agentId);
        //是否有分类筛选
        Boolean classifySelect = false;
        //处理分类
        if (null != firstClassify) {
            classifySelect = true;
            BaseTempletClassify classify = new BaseTempletClassify();
            classify.setFirstClassify(firstClassify);
            classify.setSecondClassify(secondClassify);
            classify.setThirdClassify(thirdClassify);
            classify.setGradeLabelId(gradeLabelId);
            classify.setSubjectLabelId(subjectLabelId);
            rightsSettingBiz.setClassifyAndLabel(classify);
            paramMap.put("firstClassify", classify.getFirstClassify());
            paramMap.put("secondClassify", classify.getSecondClassify());
            paramMap.put("thirdClassify", classify.getThirdClassify());
            paramMap.put("gradeLabelId", classify.getGradeLabelId());
            paramMap.put("subjectLabelId", classify.getSubjectLabelId());
        } else {
            paramMap.put("gradeLabelId", gradeLabelId);
            paramMap.put("subjectLabelId", subjectLabelId);
            if (null != gradeLabelId || null != subjectLabelId) {
                classifySelect = true;
            }
        }
        paramMap.put("classifySelect", classifySelect);
        List<String> cityCodes = null;
        if (StrUtil.isNotBlank(name)) {
            List<RegionMap> citysByPY = regionMapMapper.getCitysByPY(name);
            if (CollUtil.isNotEmpty(citysByPY)){
                cityCodes = citysByPY.stream().filter(x -> Objects.nonNull(x)).map(RegionMap::getRegionCode).distinct().collect(Collectors.toList());
            }

        }
        paramMap.put("cityCodes", cityCodes);
        paramMap.put("cityCode", cityCode);

        PageBeanNew<AppletNewsDTO> pageBeanNew = appletNewsDao.listPageNew(
                new PageParam(currentPage, numPerPage), paramMap, "listAppletNews");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        //填充咨询分类
        fillCategory(pageBeanNew.getRecordList());
        // 填充城市名称
        fillCity(pageBeanNew.getRecordList());
        return pageBeanNew;
    }

    private void fillCity(List<AppletNewsDTO> recordList) {
        if (CollUtil.isEmpty(recordList)){
            return;
        }

        List<String> codeList = recordList.stream().filter(Objects::nonNull).map(AppletNewsDTO::getCityCode).distinct().collect(Collectors.toList());

        if (CollUtil.isEmpty(codeList)) {
            return;
        }

        Map<String, RegionMap> regionMapMap = bookBrowseRecordBiz.getCitysByCodes(codeList);
        if (MapUtils.isNotEmpty(regionMapMap)){
            recordList.forEach(record -> {
                RegionMap regionMap = regionMapMap.get(record.getCityCode());
                if (regionMapMap.containsKey(record.getCityCode()) && null != regionMap){
                    record.setCity(regionMap.getRegionName());
                }
            });
        }
    }

    private void fillLabel(List<AppletNewsDTO> recordList) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        List<Long> labelIds = new ArrayList<>();
        for (AppletNewsDTO appletNewsDTO : recordList) {
            if (null != appletNewsDTO.getProLabelId()) {
                labelIds.add(appletNewsDTO.getProLabelId());
            }
            if (null != appletNewsDTO.getDepLabelId()) {
                labelIds.add(appletNewsDTO.getDepLabelId());
            }
            if (null != appletNewsDTO.getPurLabelId()) {
                labelIds.add(appletNewsDTO.getPurLabelId());
            }
        }
        if (!ListUtils.isEmpty(labelIds)) {
            Map<Long, String> labelMap = labelConsr.getLabelName(labelIds);
            if (!MapUtils.isEmpty(labelMap)) {
                for(AppletNewsDTO appletNewsDTO : recordList){
                    if (null != appletNewsDTO.getProLabelId() && labelMap.containsKey(appletNewsDTO.getProLabelId())) {
                        appletNewsDTO.setProLabelName(labelMap.get(appletNewsDTO.getProLabelId()));
                    }
                    if (null != appletNewsDTO.getDepLabelId() && labelMap.containsKey(appletNewsDTO.getDepLabelId())) {
                        appletNewsDTO.setDepLabelName(labelMap.get(appletNewsDTO.getDepLabelId()));
                    }
                    if (null != appletNewsDTO.getPurLabelId() && labelMap.containsKey(appletNewsDTO.getPurLabelId())) {
                        appletNewsDTO.setPurLabelName(labelMap.get(appletNewsDTO.getPurLabelId()));
                    }
                }
            }
        }
    }

    private void setLabelContent(List<AppletNewsDTO> appletNewsDTOS) {
        if (ListUtils.isEmpty(appletNewsDTOS)){
            return;
        }
        List<Long> firstClassifyIds = new ArrayList<>(appletNewsDTOS.size());
        List<Long> secondClassifyIds = new ArrayList<>(appletNewsDTOS.size());
        List<Long> thirdClassifyIds = new ArrayList<>(appletNewsDTOS.size());
        List<Long> classifyIds = new ArrayList<>();
        List<Long> gradeLabelIds = new ArrayList<>(appletNewsDTOS.size());
        List<Long> subjectLabelIds = new ArrayList<>(appletNewsDTOS.size());
        List<Long> labelIds = new ArrayList<>();
        for (AppletNewsDTO appletNewsDTO : appletNewsDTOS){
            firstClassifyIds.add(appletNewsDTO.getFirstClassify());
            secondClassifyIds.add(appletNewsDTO.getSecondClassify());
            thirdClassifyIds.add(appletNewsDTO.getThirdClassify());
            gradeLabelIds.add(appletNewsDTO.getGradeLabelId());
            subjectLabelIds.add(appletNewsDTO.getSubjectLabelId());
        }
        if (!ListUtils.isEmpty(firstClassifyIds)){
            classifyIds.addAll(firstClassifyIds);
        }
        if (!ListUtils.isEmpty(secondClassifyIds)){
            classifyIds.addAll(secondClassifyIds);
        }
        if (!ListUtils.isEmpty(thirdClassifyIds)){
            classifyIds.addAll(thirdClassifyIds);
        }
        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 (AppletNewsDTO appletNewsDTO : appletNewsDTOS){
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(appletNewsDTO.getFirstClassify())){
                appletNewsDTO.setFirstClassifyContent(classifyMap.get(appletNewsDTO.getFirstClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(appletNewsDTO.getSecondClassify())){
                appletNewsDTO.setSecondClassifyContent(classifyMap.get(appletNewsDTO.getSecondClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(appletNewsDTO.getThirdClassify())){
                appletNewsDTO.setThirdClassifyContent(classifyMap.get(appletNewsDTO.getThirdClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(appletNewsDTO.getGradeLabelId())){
                appletNewsDTO.setGradeLabelIdContent(labelMap.get(appletNewsDTO.getGradeLabelId()).getName());
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(appletNewsDTO.getSubjectLabelId())){
                appletNewsDTO.setSubjectLabelIdContent(labelMap.get(appletNewsDTO.getSubjectLabelId()).getName());
            }
        }
    }

    @Override
    public List<AppletNewsClassifyDTO> getAllNewsClassify(Boolean showState, Long agentId) {
        return appletNewsClassifyDao.getAllNewsClassify(showState, agentId);
    }

    @Override
    public PageBeanNew<AppletNewsDTO> listAppletNews4Wechat(Integer currentPage, Integer numPerPage, Long newsClassifyId, Long wechatUserId, Long officialAccountsId) {
        PageBeanNew<AppletNewsDTO> pageBeanNew = new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        Map<String, Object> paramMap = new HashMap<>();
        String subKey = wechatUserId + "_" + numPerPage + "_" + (null == newsClassifyId ? 1 : newsClassifyId);
        //判断是否第一页
        if (currentPage == 0) {
            //第一页
            if (null == newsClassifyId || newsClassifyId == 1){
                // 推荐栏目下的3条资讯更改为取自首页当前书刊的周权益下（资讯推送）权益分类
                // 1.当周权益下未配置，直接根据当前书刊所属分类获取最新资讯，优先呈现本书有周权益配置了的资讯，其次获取本书所属分类下最新更新的。
                // 2.当碰到部分无分类属性的书刊，沿用现有线上的推荐栏配置逻辑
                AppletUserBookcase userReadBook = appletUserBookcaseDao.getUserReadBook(wechatUserId);
                if (Objects.nonNull(userReadBook)) {
                    // 获取周权益资讯 如果周权益不为空 则直接返回
                    pageBeanNew = rightsSettingBiz.getWeekRightsSettingNewsByBookId(userReadBook, currentPage, numPerPage);
                    if (CollUtil.isNotEmpty(pageBeanNew.getRecordList())) {
                        //处理是否收藏流程
                        solvePageBeanCollectionState(pageBeanNew,wechatUserId);
                        return pageBeanNew;
                    }
                }
                // WARN: 分类为 null 或者 1 时，表示首页推荐，此时，若上面方法没有查到数据，固定分页参数为[0，3]
                List<Long> classifyIds = appletNewsClassifyDao.getClassifyIdsByUserId(wechatUserId);
                if (ListUtils.isEmpty(classifyIds)) {//没有栏目id取第一个
                    Long agentId = getAgentIdByAccountId(officialAccountsId);
                    List<AppletNewsClassifyDTO> classifyDTOS = getAllNewsClassify(true,agentId);
                    if (ListUtils.isEmpty(classifyDTOS)) {
                        return new PageBeanNew<>(currentPage, numPerPage, new ArrayList<>());
                    }
                    newsClassifyId = classifyDTOS.get(0).getId();
                    classifyIds.add(newsClassifyId);
                }
                paramMap.put("newsClassifyIdList", classifyIds);
            } else {
                //首页的其他栏目
                paramMap.put("newsClassifyId", newsClassifyId);
            }
            paramMap.put("order", 1);
            pageBeanNew = getAppletNewsDTOPageBeanNew(numPerPage, paramMap, subKey);
        } else {
            //非第一页    获取第一页的数据 并排除
            pageBeanNew = getAppletNewsDTOPageBeanNew(currentPage, numPerPage, newsClassifyId, paramMap, subKey);
        }
        if (!ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            fillBrowseCount(pageBeanNew.getRecordList());
        }
        //处理收藏状态
        solvePageBeanCollectionState(pageBeanNew,wechatUserId);
        return pageBeanNew;
    }

    private void solvePageBeanCollectionState(PageBeanNew<AppletNewsDTO> pageBeanNew,Long wechatUserId){
        if (null == wechatUserId){
            throw new BizException(BizException.PARAM_IS_NULL.getCode(),"参数为空") ;
        }
        //获取用户收藏列表
        List<ServeCollect>  list4RightsSettingByWechatUserId = serveCollectBiz.getList4RightsSettingByWechatUserId(wechatUserId);
        List<AppletNewsDTO> recordList = pageBeanNew.getRecordList();
        for (AppletNewsDTO appletNewsDTO : recordList) {
            fillCollectionState(appletNewsDTO,wechatUserId,list4RightsSettingByWechatUserId);
        }
    }


    private PageBeanNew<AppletNewsDTO> getAppletNewsDTOPageBeanNew(Integer currentPage, Integer numPerPage, Long newsClassifyId, Map<String, Object> paramMap, String subKey) {
        PageBeanNew<AppletNewsDTO> pageBeanNew;
        List<AppletNewsDTO> homeList = JedisClusterUtils.getJsonList(AppletConstants.HOME_NEWS_LIST + subKey, AppletNewsDTO.class);
        List<Long> firstPageIds = null;
        if (!ListUtils.isEmpty(homeList)) {
            firstPageIds = homeList.stream().map(e -> e.getId()).collect(Collectors.toList());
        }
        paramMap.put("newsClassifyId", newsClassifyId);
        paramMap.put("firstPageIds", firstPageIds);
        pageBeanNew = appletNewsDao.listPageNew(new PageParam(currentPage - 1, numPerPage), paramMap, "listAppletNews4Wechat");
        if (null != pageBeanNew && !ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            pageBeanNew = new PageBeanNew<>(currentPage, numPerPage, pageBeanNew.getTotalCount() + numPerPage, pageBeanNew.getRecordList());
        } else if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            paramMap.remove("firstPageIds");
            Integer count = appletNewsDao.listAppletNews4WechatCount(paramMap);
            pageBeanNew = new PageBeanNew<>(currentPage, numPerPage, count, new ArrayList<>());
        }
        return pageBeanNew;
    }

    private PageBeanNew<AppletNewsDTO> getAppletNewsDTOPageBeanNew(Integer numPerPage, Map<String, Object> paramMap, String subKey) {
        PageBeanNew<AppletNewsDTO> pageBeanNew;//第一页缓存5小时
        List<AppletNewsDTO> homeList = JedisClusterUtils.getJsonList(AppletConstants.HOME_NEWS_LIST + subKey, AppletNewsDTO.class);
        if (!ListUtils.isEmpty(homeList)) {
            Integer count = appletNewsDao.listAppletNews4WechatCount(paramMap);
            pageBeanNew = new PageBeanNew<>(0, numPerPage, count, homeList);
        } else {
            pageBeanNew = appletNewsDao.listPageNew(new PageParam(0, numPerPage), paramMap, "listAppletNews4Wechat");
        }
        fillStatistic(pageBeanNew.getRecordList(), null, null);
        //按点击量进行排序
        if (!ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            pageBeanNew.getRecordList().sort(new Comparator<AppletNewsDTO>() {
                @Override
                public int compare(AppletNewsDTO o1, AppletNewsDTO o2) {
                    return o2.getClickCount().compareTo(o1.getClickCount());
                }
            });
        }
        JedisClusterUtils.setJsonList(AppletConstants.HOME_NEWS_LIST + subKey, pageBeanNew.getRecordList(), 5 * 3600);
        return pageBeanNew;
    }

    @Override
    public void addAppletNewsComment(AppletNewsComment appletNewsComment, Long wechatUserId) {
        appletNewsComment.setWechatUserId(wechatUserId);
        appletNewsCommentDao.insert(appletNewsComment);
    }

    @Override
    public PageBeanNew<AppletNewsCommentDTO> listNewsCommentByNewsId(Integer currentPage, Integer numPerPage, Long newsId) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("newsId", newsId);
        PageBeanNew<AppletNewsCommentDTO> pageBeanNew = appletNewsCommentDao.listPageNew(
                new PageParam(currentPage,numPerPage),paramMap,"listNewsCommentByNewsId");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())){
            return new PageBeanNew<>(currentPage,numPerPage,0,new ArrayList<>());
        }
        //用户信息
        List<Long> wechatUserIds = pageBeanNew.getRecordList().stream().filter(s->s.getWechatUserId()!=null).
                map(AppletNewsCommentDTO::getWechatUserId).distinct().collect(Collectors.toList());
        if (!ListUtils.isEmpty(wechatUserIds)){
            Map<Long, WechatUser> wechatUserMap = readerConsr.getUserList(wechatUserIds);
            for (AppletNewsCommentDTO commentDTO:pageBeanNew.getRecordList()){
                Long wechatUserId = commentDTO.getWechatUserId();
                if (!MapUtils.isEmpty(wechatUserMap) && null != wechatUserId && wechatUserMap.containsKey(wechatUserId)){
                    WechatUser wechatUser = wechatUserMap.get(wechatUserId);
                    commentDTO.setNickName(null==wechatUser?"":wechatUser.getWechatUserNickname());
                    commentDTO.setHeadPic(null==wechatUser?"":wechatUser.getWechatUserHeadurl());
                }
            }
        }
        return pageBeanNew;
    }

    @Override
    public AppletNewsDTO getNewsById(Long id) {
        AppletNews appletNews = appletNewsDao.getById(id);
        AppletNewsDTO appletNewsDTO = new AppletNewsDTO();
        if (null!=appletNews){
            BeanUtils.copyProperties(appletNews,appletNewsDTO);
        }
//        this.fillAppletNewsServe(appletNewsDTO);
        this.fillBrowseCount(Lists.newArrayList(appletNewsDTO));
        fillLabel(Arrays.asList(appletNewsDTO));

        //填充类别集合
        fillCategory(Arrays.asList(appletNewsDTO));

        //填充第三方资源
        fillThirdResources(Arrays.asList(appletNewsDTO));

        fillBusinessCard(appletNewsDTO);

        // 填充城市信息
        if (null != appletNews && StrUtil.isNotBlank(appletNews.getCityCode())) {
            appletNewsDTO.setCity(regionMapMapper.getCitysByCode(appletNews.getCityCode()));
        }
        return appletNewsDTO;
    }

    private void fillThirdResources(List<AppletNewsDTO> appletNewsDTOList) {
        if (ListUtils.isEmpty(appletNewsDTOList)) {
            return;
        }
        for (AppletNewsDTO newsDTO : appletNewsDTOList) {
            Long newsId = newsDTO.getId();
            List<AppletThirdResources> thirdResourcesList = thirdResourcesDao.getThirdResourcesByNewsId(newsId);
            if (ListUtils.isEmpty(thirdResourcesList)) {
                continue;
            }
            newsDTO.setThirdResourcesRelations(thirdResourcesList);
        }
    }

    private void fillCategory(List<AppletNewsDTO> appletNewsDTOList) {
        if (ListUtils.isEmpty(appletNewsDTOList)) {
            return;
        }
        List<Long> classifyIds = new ArrayList<>();
        for (AppletNewsDTO newsDTO : appletNewsDTOList) {
            Long newsId = newsDTO.getId();
            List<AppletNewsCategoryDTO> newsCategoryDTOList = appletNewsCategoryDao.getByNewsId(newsId);
            if (ListUtils.isEmpty(newsCategoryDTOList)) {
                continue;
            }
            for (AppletNewsCategoryDTO appletNewsCategoryDTO : newsCategoryDTOList) {
                if (null != appletNewsCategoryDTO.getFirstClassify() && !classifyIds.contains(appletNewsCategoryDTO.getFirstClassify())) {
                    classifyIds.add(appletNewsCategoryDTO.getFirstClassify());
                }
                if (null != appletNewsCategoryDTO.getSecondClassify() && !classifyIds.contains(appletNewsCategoryDTO.getSecondClassify())) {
                    classifyIds.add(appletNewsCategoryDTO.getSecondClassify());
                }
            }
            newsDTO.setCategoryList(newsCategoryDTOList);
        }
        Map<Long, AssistTempletDTO> classifyMap = assistTempletConsr.mapByIds4Classify(classifyIds);
        if (MapUtils.isEmpty(classifyMap)) {
            return;
        }
        for (AppletNewsDTO newsDTO : appletNewsDTOList) {
            if (ListUtils.isEmpty(newsDTO.getCategoryList())){
                continue;
            }
            for (AppletNewsCategoryDTO categoryDTO : newsDTO.getCategoryList()) {
                if (null == categoryDTO){
                    continue;
                }
                if (classifyMap.containsKey(categoryDTO.getFirstClassify())) {
                    categoryDTO.setFirstClassifyName(classifyMap.get(categoryDTO.getFirstClassify()).getTempletName());
                }
                if (classifyMap.containsKey(categoryDTO.getSecondClassify())) {
                    categoryDTO.setSecondClassifyName(classifyMap.get(categoryDTO.getSecondClassify()).getTempletName());
                }
                if (classifyMap.containsKey(categoryDTO.getThirdClassify())) {
                    categoryDTO.setThirdClassifyName(classifyMap.get(categoryDTO.getThirdClassify()).getTempletName());
                }
            }
        }
    }

    private void fillBusinessCard(AppletNewsDTO appletNewsDTO) {
        if (null != appletNewsDTO.getBusinessCardId()) {
            AppletBusinessCard appletBusinessCard = appletBusinessCardDao.getById(appletNewsDTO.getBusinessCardId());
            if (appletBusinessCard == null){
                appletNewsDTO.setBusinessCardId(null);
                return;
            }
            appletNewsDTO.setBusinessCardHeadPhoto(appletBusinessCard.getHeadPhoto());
            appletNewsDTO.setBusinessCardName(appletBusinessCard.getName());
            appletNewsDTO.setBusinessCardQrcode(appletBusinessCard.getQrcode());
            appletNewsDTO.setBusinessCardTitle(appletBusinessCard.getTitle());
            appletNewsDTO.setBusinessCardWechatNum(appletBusinessCard.getWechatNum());
            appletNewsDTO.setBusinessPhone(appletBusinessCard.getPhone());
        }
    }

    /**
     * 点击量浏览量
     *  * @param null
     */
    @Override
    public void fillBrowseCount(List<AppletNewsDTO> recordList) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        List<Long> newsIds = recordList.stream().filter(s -> s != null).map(AppletNewsDTO::getId).distinct().collect(Collectors.toList());
        Map<Long, PvuvDTO> browseMap = appletLinkClickDao.mapPVUV(DataTypeEnum.news.code, DataRecordTypeEnum.browse.code, newsIds,null);
        for (AppletNewsDTO appletNewsDTO : recordList) {
            Long newsId = appletNewsDTO.getId();
            if (!MapUtils.isEmpty(browseMap) && browseMap.containsKey(newsId)) {
                PvuvDTO pvuvDTO = browseMap.get(newsId);
                appletNewsDTO.setBrowseCount(pvuvDTO.getPv());
            } else {
                appletNewsDTO.setBrowseCount(0);
            }
        }
    }

    @Override
    public AppletThirdResourcesDTO getThirdResourceById(Long thirdResourcesId) {
        if (null == thirdResourcesId) {
            return new AppletThirdResourcesDTO();
        }
        AppletThirdResources byResourcesId = thirdResourcesDao.getByResourcesId(thirdResourcesId);
        AppletThirdResourcesDTO appletThirdResourcesDTO = new AppletThirdResourcesDTO();
        BeanUtils.copyProperties(byResourcesId, appletThirdResourcesDTO);
        if (appletThirdResourcesDTO.getType()==2) {
            List<String> pics = appletThirdResourcesPicMapper.getPicList(appletThirdResourcesDTO.getId());
            appletThirdResourcesDTO.setPicUrlList(pics);
        }
        return appletThirdResourcesDTO;
    }

    /**
     * 填充第三方服务
     * @param appletNewsDTO
     */
//    private void fillAppletNewsServe(AppletNewsDTO appletNewsDTO) {
//        List<AppletNewsServeDTO> appletNewsServeList = appletNewsServeDao.getByAppletNewsId(appletNewsDTO.getId());
//        if (ListUtils.isEmpty(appletNewsServeList)) {
//            appletNewsDTO.setAppletNewsServeList(Lists.newArrayList());
//        }
//        this.fillPersonalApplet(appletNewsServeList);
//        appletNewsDTO.setAppletNewsServeList(appletNewsServeList);
//    }

    /**
     * 填充小程序相关数据
     * @param appletNewsServeList
     */
    private void fillPersonalApplet(List<AppletNewsServeDTO> appletNewsServeList) {
        List<Long> personalAppletIds = appletNewsServeList.stream().filter(x -> AppletNewsServeTypeEnum.APPLET.code.equals(x.getServeType())).map(x -> x.getServeId()).collect(Collectors.toList());
        if(ListUtils.isEmpty(personalAppletIds)){
            return;
        }
        Map<Long, PersonalApplets> personalAppletsMap = personalAppletsDao.mapByIds(personalAppletIds);
        if(personalAppletsMap == null || personalAppletsMap.isEmpty()){
            return;
        }
        PersonalApplets personalApplets;
        for (AppletNewsServeDTO appletNewsServeDTO : appletNewsServeList) {
            personalApplets = personalAppletsMap.get(appletNewsServeDTO.getServeId());
            if(personalApplets == null){
                continue;
            }
            appletNewsServeDTO.setAppletsId(personalApplets.getAppletsId());
            appletNewsServeDTO.setSlogan(personalApplets.getSlogan());
            appletNewsServeDTO.setSloganImgUrl(personalApplets.getSloganImgUrl());
            appletNewsServeDTO.setAppletsUrl(personalApplets.getAppletsUrl());
            appletNewsServeDTO.setRemark(personalApplets.getRemark());
        }
    }

    @Override
    public void updateNewsShowState(AppletNews appletNews) {
        appletNewsDao.updateNewsShowState(appletNews);
        //资讯下架 删除与权益的关联关系
        if (!appletNews.getShowState()) {
            rightsSettingBiz.deleteInvalidNews(Lists.newArrayList(appletNews.getId()));
        }
        JedisClusterUtils.del(AppletConstants.HOME_NEWS_LIST);
    }

    @Override
    public List<AppletNewsDTO> getNewsByTempletLabel(Long firstClassify, Long secondClassify, Long gradeLabelId, Long subjectLabelId, String rightsType, Long agentId, Long thirdClassify) {
        BaseTempletClassify classify = new BaseTempletClassify();
        classify.setFirstClassify(firstClassify);
        classify.setSecondClassify(secondClassify);
        classify.setThirdClassify(thirdClassify);
        classify.setGradeLabelId(gradeLabelId);
        classify.setSubjectLabelId(subjectLabelId);
        rightsSettingBiz.setClassifyAndLabel(classify);
        List<AppletNewsDTO> list = new ArrayList<>();
        list=appletNewsDao.getByNewsByTempletLabel(classify.getFirstClassify(),classify.getSecondClassify(),classify.getGradeLabelId(),classify.getSubjectLabelId(),rightsType, agentId, classify.getThirdClassify());
        return list;
    }

    @Override
    public void batchUpdateClassify(AppletNewsClassifyVO appletNewsClassifyVO) {
        if(appletNewsClassifyVO == null || ListUtils.isEmpty(appletNewsClassifyVO.getAppletNewsIds())){
            throw new BizException(BizException.PARAM_IS_NULL.getCode(), "参数为空");
        }
        rightsSettingBiz.setClassifyAndLabel(appletNewsClassifyVO);

        List<AppletNewsCategory> categoryDTOList = appletNewsClassifyVO.getCategoryDTOList();
        if (CollUtil.isNotEmpty(categoryDTOList)) {
            for (Long id : appletNewsClassifyVO.getAppletNewsIds()) {
                this.saveAppletNewsCategory(categoryDTOList, id);
            }
        }
        appletNewsDao.batchUpdateClassify(appletNewsClassifyVO);
    }

    @Override
    public void batchUpdateShowState(AppletNewsShowStateVO appletNewsShowStateVO) {
        appletNewsDao.batchUpdateShowState(appletNewsShowStateVO);
        //资讯下架 删除与权益的关联关系
        if (!appletNewsShowStateVO.getShowState()) {
            rightsSettingBiz.deleteInvalidNews(appletNewsShowStateVO.getAppletNewsIds());
        }
        JedisClusterUtils.del(AppletConstants.HOME_NEWS_LIST);
    }

    @Override
    public void batchDeleteAppletNews(List<Long> appletNewsIds) {
        appletNewsDao.deleteByNews(appletNewsIds);
        //资讯下架 删除与权益的关联关系
        rightsSettingBiz.deleteInvalidNews(appletNewsIds);
        serveCollectBiz.deleteInvalidNews(Lists.newArrayList(appletNewsIds));
        JedisClusterUtils.del(AppletConstants.HOME_NEWS_LIST);
    }

    @Override
    public AppletNewsVO getNewsVOById(Long newsId) {
        AppletNews appletNews = appletNewsDao.getById(newsId);
        AppletNewsVO appletNewsVO = new AppletNewsVO();
        if (null != appletNews) {
            BeanUtils.copyProperties(appletNews, appletNewsVO);
        }
        // 填充第三方服务
//        this.fillAppletNewsServe(appletNewsVO);
        //填充第三方资源
        fillThirdResources(appletNewsVO);

        return appletNewsVO;
    }

    /**
     * 填充第三方服务
     * @param appletNewsVO
     */
//    private void fillAppletNewsServe(AppletNewsVO appletNewsVO) {
//        List<AppletNewsServeDTO> appletNewsServeList = appletNewsServeDao.getByAppletNewsId(appletNewsVO.getId());
//        if(ListUtils.isEmpty(appletNewsServeList)){
//            appletNewsVO.setAppletNewsServeList(Lists.newArrayList());
//        }
//        this.fillPersonalApplet(appletNewsServeList);
//        appletNewsVO.setAppletNewsServeList(appletNewsServeList);
//    }
    private void fillThirdResources(AppletNewsVO appletNewsVO) {
        Long newsId = appletNewsVO.getId();
        List<AppletThirdResources> thirdResourcesList = thirdResourcesDao.getThirdResourcesByNewsId(newsId);
        if (ListUtils.isEmpty(thirdResourcesList)) {
            return;
        }
        List<AppletThirdResourcesDTO> dtoList = new ArrayList<>();
        AppletThirdResourcesDTO dto = null;

        com.pcloud.common.utils.BeanUtils
                .copyListProperties(thirdResourcesList, dtoList, AppletThirdResourcesDTO.class);
        //图片类型
        for (AppletThirdResourcesDTO resourcesDTO : dtoList) {
            if (resourcesDTO.getType()==2) {
                List<String> pics = appletThirdResourcesPicMapper.getPicList(resourcesDTO.getId());
                resourcesDTO.setPicUrlList(pics);
            }
        }
        appletNewsVO.setThirdResourcesRelations(dtoList);
    }

    @Override
    public List<String> getNewsSourceList(Long agentId) {
        return appletNewsDao.getNewsSourceList(agentId);
    }

    /**
     * 资讯来源维护
     * @author：zhuyajie
     * @date：2020/4/27 15:23
     *  * @param null
     */
    public void updateSource(String before,String source, Long agentId){
        //修改
        if (!StringUtil.isEmpty(before) && !StringUtil.isEmpty(source) && !before.equals(source)){
            Integer beforeCount = appletNewsDao.getAppletNewsSourceCount(before, agentId);
            if (beforeCount==0){
                appletNewsDao.deleteSource(before, agentId);
            }
            Boolean exist = appletNewsDao.newsSourceExist(source, agentId);
            if (!exist){
                appletNewsDao.insertSource(source, agentId);
            }
            return;
        }
        //新增
        if (StringUtil.isEmpty(before) && !StringUtil.isEmpty(source)){
            Boolean exist = appletNewsDao.newsSourceExist(source, agentId);
            if (!exist){
                appletNewsDao.insertSource(source, agentId);
            }
            return;
        }
        //删除
        if (!StringUtil.isEmpty(before) && StringUtil.isEmpty(source)){
            Integer beforeCount = appletNewsDao.getAppletNewsSourceCount(before, agentId);
            if (beforeCount==0){
                appletNewsDao.deleteSource(before, agentId);
            }
            return;
        }
    }

    @Override
    public void addClickRecord(AppletLinkClick appletLinkClick) {
        appletLinkClickDao.insert(appletLinkClick);
    }

    @Override
    public String getUrlNumberByUrl(String jumpUrl, Long agentId) {
        if (StringUtil.isEmpty(jumpUrl)){
            return "";
        }
        return appletNewsDao.getUrlNumberByJumpUrl(jumpUrl, agentId);
    }

    @Override
    public PageBeanNew<AppletNewsDTO> listAppletNews4Analysis(Integer currentPage, Integer numPerPage, String name, Long firstClassify, Long secondClassify, Long gradeLabelId, Long subjectLabelId, Integer linkOnly, Long rightsClassifyId,
                                                              String source, Integer browseQty, Integer clickQty, Long agentId, Long thirdClassify) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        paramMap.put("linkOnly", linkOnly);
        paramMap.put("rightsClassifyId", rightsClassifyId);
        paramMap.put("agentId", agentId);
        //处理分类
        if (null!=firstClassify){
            BaseTempletClassify classify = new BaseTempletClassify();
            classify.setFirstClassify(firstClassify);
            classify.setSecondClassify(secondClassify);
            classify.setThirdClassify(thirdClassify);
            classify.setGradeLabelId(gradeLabelId);
            classify.setSubjectLabelId(subjectLabelId);
            rightsSettingBiz.setClassifyAndLabel(classify);
            paramMap.put("firstClassify", classify.getFirstClassify());
            paramMap.put("secondClassify", classify.getSecondClassify());
            paramMap.put("thirdClassify", classify.getThirdClassify());
            paramMap.put("gradeLabelId", classify.getGradeLabelId());
            paramMap.put("subjectLabelId", classify.getSubjectLabelId());
        }else {
            paramMap.put("gradeLabelId", gradeLabelId);
            paramMap.put("subjectLabelId", subjectLabelId);
        }

        paramMap.put("source", source);
        PageBeanNew<AppletNewsDTO> pageBeanNew = appletNewsDao.listPageNew(
                new PageParam(currentPage, numPerPage), paramMap, "listAppletNews4Analysis");

        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }

        fillCategory(pageBeanNew.getRecordList());  //填充咨询适用类别
        setLabelContent(pageBeanNew.getRecordList());
        fillStatistic(pageBeanNew.getRecordList(),browseQty,clickQty);
        return pageBeanNew;
    }

    /**
     * 点击量浏览量
     * @author：zhuyajie
     * @date：2020/5/11 20:09
     *  * @param null
     */
    private void fillStatistic(List<AppletNewsDTO> recordList,Integer browseQty,Integer clickQty) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        if (null != browseQty && browseQty.intValue()>1){  //等于1 值查询当天数据。大于1时，从昨天开始倒推7天，所以要+1
            browseQty += 1;
        }
        if (null != clickQty && clickQty.intValue() >1){
            clickQty += 1;
        }
        List<Long> newsIds = recordList.stream().filter(s -> s != null).map(AppletNewsDTO::getId).distinct().collect(Collectors.toList());
        Map<Long, PvuvDTO> clickMap = appletLinkClickDao.mapPVUV(DataTypeEnum.news.code, DataRecordTypeEnum.click.code, newsIds,clickQty);
        Map<Long, PvuvDTO> browseMap = appletLinkClickDao.mapPVUV(DataTypeEnum.news.code, DataRecordTypeEnum.browse.code, newsIds,browseQty);
        for (AppletNewsDTO appletNewsDTO : recordList) {
            Long newsId = appletNewsDTO.getId();
            if (!MapUtils.isEmpty(clickMap) && clickMap.containsKey(newsId)) {
                PvuvDTO pvuvDTO = clickMap.get(newsId);
                appletNewsDTO.setClickPVUV(pvuvDTO.getPv() + "/" + pvuvDTO.getUv());
                appletNewsDTO.setClickCount(pvuvDTO.getPv());
            } else {
                appletNewsDTO.setClickPVUV("0/0");
                appletNewsDTO.setClickCount(0);
            }
            if (!MapUtils.isEmpty(browseMap) && browseMap.containsKey(newsId)) {
                PvuvDTO pvuvDTO = browseMap.get(newsId);
                appletNewsDTO.setBrowsePVUV(pvuvDTO.getPv() + "/" + pvuvDTO.getUv());
            } else {
                appletNewsDTO.setBrowsePVUV("0/0");
            }
        }
    }

    /**
     * 链接编号是否重复
     * @author：zhuyajie
     * @date：2020/5/11 18:50
     *  * @param null
     */
    public Boolean urlNumberExist(AppletNews appletNews) {
        if (StringUtil.isEmpty(appletNews.getUrlNumber())){
            throw new BookBizException(BookBizException.ERROR,"资讯/外链编号不能为空");
        }
        return appletNewsDao.urlNumberExist(appletNews.getUrlNumber(),appletNews.getId(), appletNews.getAgentId());
    }

    @Override
    public Map<Long, AppletNewsDTO> getByIds(List<Long> appletNewsIds) {
        if(ListUtils.isEmpty(appletNewsIds)){
            new HashMap<>();
        }
        return appletNewsDao.getByIds(appletNewsIds);
    }

    @Override
    public void addUserNewsClassify(List<Long> newsClassifyIds, Long wechatUserId, Long officialAccountsId) {
        if (null == wechatUserId){
            return;
        }
        appletNewsClassifyDao.deleteClassifyByWechatUesrId(wechatUserId);
        if (ListUtils.isEmpty(newsClassifyIds)){
            Long agentId = getAgentIdByAccountId(officialAccountsId);
            List<AppletNewsClassifyDTO> list = appletNewsClassifyDao.getAllNewsClassify(true, agentId);
            if (ListUtils.isEmpty(list)){
                return;
            }
            newsClassifyIds.add(list.get(0).getId());
        }
        List<AppletNewsClassifyUser> addList = new ArrayList<>();
        for (Long classifyId : newsClassifyIds){
            AppletNewsClassifyUser classifyUser = new AppletNewsClassifyUser();
            classifyUser.setNewsClassifyId(classifyId);
            classifyUser.setWechatUserId(wechatUserId);
            addList.add(classifyUser);
        }
        appletNewsClassifyDao.batchInsertUserNewsClassify(addList);
    }

    @Override
    public List<AppletNewsClassifyDTO> getAllNewsClassify4Wechat(Long wechatUserId, Long officialAccountsId) {
        Long agentId = getAgentIdByAccountId(officialAccountsId);
        List<AppletNewsClassifyDTO> list = appletNewsClassifyDao.getAllNewsClassify(true, agentId);
        if (ListUtils.isEmpty(list)) {
            return new ArrayList<>();
        }
        List<Long> chooseIds = appletNewsClassifyDao.getClassifyIdsByUserId(wechatUserId);
        if (ListUtils.isEmpty(chooseIds)) {
            chooseIds.add(list.get(0).getId());
        }
        for (AppletNewsClassifyDTO appletNewsClassifyDTO : list) {
            if (!ListUtils.isEmpty(chooseIds) && chooseIds.contains(appletNewsClassifyDTO.getId())) {
                appletNewsClassifyDTO.setChoose(true);
            } else {
                appletNewsClassifyDTO.setChoose(false);
            }
        }
        return list;
    }

    @Override
    public List<AppletNewsClassifyDTO> getNewsClassifyByUser(Long wechatUserId, Long officialAccountsId) {
        List<AppletNewsClassifyDTO> list = appletNewsClassifyDao.getClassifysByUserId(wechatUserId);
        if (ListUtils.isEmpty(list)){
            Long agentId = getAgentIdByAccountId(officialAccountsId);
            List<AppletNewsClassifyDTO> allNewsClassify = appletNewsClassifyDao.getAllNewsClassify(true, agentId);
            if (ListUtils.isEmpty(allNewsClassify)) {
                return new ArrayList<>();
            }
            list.add(allNewsClassify.get(0));
        }
        return list;
    }

    @Override
    public void batchUpdateNewsClassify(AppletNewsClassifyVO appletNewsClassifyVO) {
        if (appletNewsClassifyVO == null || ListUtils.isEmpty(appletNewsClassifyVO.getAppletNewsIds())) {
            throw new BizException(BizException.PARAM_IS_NULL.getCode(), "参数为空");
        }
        if (null == appletNewsClassifyVO.getNewsClassifyId()) {
            throw new BizException(BizException.PARAM_IS_NULL.getCode(), "请选择资讯栏目");
        }
        appletNewsDao.batchUpdateNewsClassify(appletNewsClassifyVO);
    }

    @Override
    public void batchUpdateCustomTagId(List<Long> ids, Long customTagId, String customTag, Long agentId) {
        if (ListUtils.isEmpty(ids)) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "参数为空");
        }
        if (null == customTagId && !StringUtil.isEmpty(customTag)) {
            AppletNewsCustomTag appletNewsCustomTag = new AppletNewsCustomTag();
            appletNewsCustomTag.setCustomTag(customTag);
            appletNewsCustomTag.setAgentId(agentId==null?0L:agentId);
            customTagId = insertCustomTag(appletNewsCustomTag);
        }
        appletNewsDao.batchUpdateCustomTagId(ids, customTagId);
    }

    @Override
    public Long insertCustomTag(AppletNewsCustomTag appletNewsCustomTag) {
        if (null == appletNewsCustomTag || StringUtil.isEmpty(appletNewsCustomTag.getCustomTag())) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "参数为空");
        }
        if (appletNewsDao.customTagExist(appletNewsCustomTag.getCustomTag(),appletNewsCustomTag.getAgentId())) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "标识重复");
        }
        appletNewsDao.insertCustomTag(appletNewsCustomTag);
        return appletNewsCustomTag.getId();
    }

    @Override
    public void updateCustomTag(AppletNewsCustomTag appletNewsCustomTag) {
        if (null == appletNewsCustomTag || StringUtil.isEmpty(appletNewsCustomTag.getCustomTag()) || null == appletNewsCustomTag.getId()){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"参数为空");
        }
        if (appletNewsDao.customTagExist(appletNewsCustomTag.getCustomTag(),appletNewsCustomTag.getAgentId())){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"标识重复");
        }
        appletNewsDao.updateCustomTag(appletNewsCustomTag);
    }

    @Override
    public List<AppletNewsCustomTagDTO> getCustomTagList(Long agentId) {
        return appletNewsDao.getCustomTagList(agentId);
    }

    @Override
    public List<Long> getNewsIdListByCustomTagId(Long customTagId) {
        return appletNewsDao.getNewsIdListByCustomTagId(customTagId);
    }

    @Override
    public void batchInsert(List<AppletNews> appletNewsList) {
        if (ListUtils.isEmpty(appletNewsList)) {
            return;
        }

        appletNewsDao.insert(appletNewsList);

        for (AppletNews appletNews: appletNewsList){
            if (Objects.nonNull(appletNews.getFirstClassify()) && appletNews.getFirstClassify()!=0){
                AppletNewsCategory category = new AppletNewsCategory();
                category.setFirstClassify(appletNews.getFirstClassify());
                category.setSecondClassify(appletNews.getSecondClassify());
                category.setGradeLabelId(appletNews.getGradeLabelId());
                category.setSubjectLabelId(appletNews.getSubjectLabelId());
                saveAppletNewsCategory(Arrays.asList(category),appletNews.getId());
            }
        }
    }

    @Override
    public void batchUpdateCardShowState(AppletNewsShowStateVO appletNewsShowStateVO) {
        Iterator<Long> it= appletNewsShowStateVO.getAppletNewsIds().iterator();

        while(it.hasNext()){
            Long newId = it.next();
            AppletNews newAppletNews =  appletNewsDao.getById(newId);
            if(newAppletNews.getBusinessCardType() == null || newAppletNews.getBusinessCardId()== null){
                it.remove();
            }
        }

        if(ListUtils.isEmpty(appletNewsShowStateVO.getAppletNewsIds())){
            throw new BookBizException(BookBizException.ERROR, "所勾选资讯未配置名片");
        }

        appletNewsDao.batchUpdateCardShowState(appletNewsShowStateVO);
    }

    @Override
    public void updateCardShowState(AppletNews appletNews) {
        AppletNews newAppletNews =  appletNewsDao.getById(appletNews.getId());
        if(newAppletNews.getBusinessCardType() == null || newAppletNews.getBusinessCardId()== null){
            throw new BookBizException(BookBizException.ERROR,"名片未配置");
        }
        appletNewsDao.updateCardShowState(appletNews);
        JedisClusterUtils.del(AppletConstants.HOME_NEWS_LIST);
    }

    @Override
    public AppletNewsDTO getNewsById4Applet(Long id,Long wechatUserId) {
        AppletNews appletNews = appletNewsDao.getById(id);
        AppletNewsDTO appletNewsDTO = new AppletNewsDTO();
        if (null!=appletNews){
            BeanUtils.copyProperties(appletNews,appletNewsDTO);
        }
//        this.fillAppletNewsServe(appletNewsDTO);
        this.fillBrowseCount(Lists.newArrayList(appletNewsDTO));
        fillLabel(Arrays.asList(appletNewsDTO));

        //填充类别集合
        fillCategory(Arrays.asList(appletNewsDTO));

        //填充第三方资源
        fillThirdResources4Applet(Arrays.asList(appletNewsDTO));

        fillBusinessCard(appletNewsDTO);

        // 填充城市信息
        if (StrUtil.isNotBlank(appletNews.getCityCode())) {
            appletNewsDTO.setCity(regionMapMapper.getCitysByCode(appletNews.getCityCode()));
        }
        //填充收藏状态
        if (wechatUserId != null){
            fillCollectionState(appletNewsDTO,wechatUserId,null);
        }
        return appletNewsDTO;
    }

    /**
     * 填充是否收藏状态
     * @param appletNewsDTO
     * @param wechatUserId
     */
    private void fillCollectionState(AppletNewsDTO appletNewsDTO,Long wechatUserId,List<ServeCollect> list4RightsSettingByWechatUserId){
        //被收藏为1，未收藏为0
        //用户收藏列表为空，直接将收藏状态置为0
        if (null == list4RightsSettingByWechatUserId) {
            list4RightsSettingByWechatUserId = serveCollectBiz.getList4RightsSettingByWechatUserId(wechatUserId);
            if (ListUtils.isEmpty(list4RightsSettingByWechatUserId)) {
                appletNewsDTO.setIsCollection(0);
                return;
            }
        }
        List<Long> serverIdList = list4RightsSettingByWechatUserId.stream().filter(s -> s.getServeId() != null)
                .filter(s -> s.getServeType() == 1).map(ServeCollect::getServeId).collect(Collectors.toList());
        boolean contains = serverIdList.contains(appletNewsDTO.getId());
        if (contains) {
            appletNewsDTO.setIsCollection(1);
        } else {
            appletNewsDTO.setIsCollection(0);
        }
    }

    @Override
    public Map<Long, AppletNewsDTO> getByIds4Record(List<Long> newsIds) {
        if(ListUtils.isEmpty(newsIds)){
            new HashMap<>();
        }
        return appletNewsDao.getByIds4Record(newsIds);
    }

    private void fillThirdResources4Applet(List<AppletNewsDTO> appletNewsDTOList) {
        if (ListUtils.isEmpty(appletNewsDTOList)) {
            return;
        }
        for (AppletNewsDTO newsDTO : appletNewsDTOList) {
            Long newsId = newsDTO.getId();
            List<AppletThirdResources> thirdResourcesList = thirdResourcesDao.getThirdResourcesByNewsId(newsId);
            newsDTO.setThirdResourcesRelations(ListUtils.isEmpty(thirdResourcesList) ? new ArrayList<>() : thirdResourcesList);
        }
    }

    @Override
    public Long getAgentIdByAccountId(Long officialAccountsId){
        Long agentId = null;
        if (null != officialAccountsId && !BookProps.getMiniOfficialAccountsId().equals(officialAccountsId)) {
            AccountSetting accountSetting = channelConsr.getAppInfo(officialAccountsId);
            agentId = accountSetting == null ? null : accountSetting.getAgentId();
        }
        return  agentId;
    }

    @Override
    public void addDefaultAppletNewsClassify(Long agentId) {
        AppletNewsClassify appletNewsClassify = new AppletNewsClassify();
        appletNewsClassify.setAgentId(agentId);
        appletNewsClassify.setNewsClassify("推荐");
        appletNewsClassify.setSeq(0);
        appletNewsClassify.setShowState(false);
        appletNewsClassify.setPic("https://file.5rs.me/oss/uploadfe/png/30ac33d2ecd19649fd86250065a58e42.png");
        appletNewsClassifyDao.insert(appletNewsClassify);
    }


    @Override
    public Map<Long, Integer> getStayOnlineAppClickCount() {
        Map<Long, Integer> map = new HashMap<>();
        List<PvuvDTO> list = appletLinkClickDao.getStayOnlineAppClickCount();
        if (!ListUtils.isEmpty(list)) {
            for (PvuvDTO dto:list){
                map.put(dto.getFromId(), dto.getCount());
            }
        }
        return map;
    }

    @Override
    public List<AppletNews> getListByIds(List<Long> newsIds) {
        return appletNewsDao.getListByIds(newsIds);
    }
}
