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

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.contants.AppletConstants;
import com.pcloud.book.applet.dao.AppletLinkClickDao;
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.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.PvuvDTO;
import com.pcloud.book.applet.entity.AppletLinkClick;
import com.pcloud.book.applet.entity.AppletNews;
import com.pcloud.book.applet.entity.AppletNewsClassify;
import com.pcloud.book.applet.entity.AppletNewsClassifyUser;
import com.pcloud.book.applet.entity.AppletNewsComment;
import com.pcloud.book.applet.entity.AppletNewsCustomTag;
import com.pcloud.book.applet.entity.AppletNewsServe;
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.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.push.dao.PersonalAppletsDao;
import com.pcloud.book.push.entity.PersonalApplets;
import com.pcloud.book.rightsSetting.biz.RightsSettingBiz;
import com.pcloud.book.rightsSetting.entity.BaseTempletClassify;
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.NumberUtil;
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.awt.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;

    @Override
    public Long addAppletNewsClassify(AppletNewsClassify appletNewsClassify) {
        Integer seq = appletNewsClassifyDao.getMaxSeq();
        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) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        PageBeanNew<AppletNewsClassifyDTO> pageBeanNew = appletNewsClassifyDao.listPageNew(
                new PageParam(currentPage,numPerPage) ,paramMap,"listNewsClassify");
        return pageBeanNew;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long addAppletNews(AppletNews appletNews) {
        if (urlNumberExist(appletNews)){
            throw new BookBizException(BookBizException.ERROR,"链接编号重复");
        }
        appletNews.setShowState(false);
        rightsSettingBiz.setClassifyAndLabel(appletNews);
        appletNewsDao.insert(appletNews);
        // 保存选取的服务
        this.saveAppletNewsServe(appletNews.getAppletNewsServeList(), appletNews.getId());
        this.updateSource(null,appletNews.getSource());
        return appletNews.getId();
    }

    /**
     * 保存选取的服务
     * @param appletNewsServeList
     * @param appletNewsId
     */
    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为空");
        }
        if (urlNumberExist(appletNews)){
            throw new BookBizException(BookBizException.ERROR,"链接编号重复");
        }
        AppletNews beforeNews = appletNewsDao.getById(appletNews.getId());
        rightsSettingBiz.setClassifyAndLabel(appletNews);
        appletNewsDao.update(appletNews);
        this.saveAppletNewsServe(appletNews.getAppletNewsServeList(), appletNews.getId());
        this.updateSource(beforeNews.getSource(),appletNews.getSource());
        JedisClusterUtils.del(AppletConstants.HOME_NEWS_LIST);
    }

    @Override
    public void deleteAppletNewsById(Long id) {
        AppletNews beforeNews = appletNewsDao.getById(id);
        if (null == beforeNews) {
            return;
        }
        appletNewsDao.deleteById(id);
        this.updateSource(beforeNews.getSource(), null);
        JedisClusterUtils.del(AppletConstants.HOME_NEWS_LIST);
    }

    @Override
    public PageBeanNew<AppletNewsDTO> listAppletNews(Integer currentPage, Integer numPerPage, String name,
                                                     Long firstClassify,Long secondClassify,Long gradeLabelId,
                                                     Long subjectLabelId,Long rightsClassifyId,String source,Integer showState, Long newsClassifyId,
                                                     Long customTagId) {
        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);
        //处理分类
        if (null!=firstClassify){
            BaseTempletClassify classify = new BaseTempletClassify();
            classify.setFirstClassify(firstClassify);
            classify.setSecondClassify(secondClassify);
            classify.setGradeLabelId(gradeLabelId);
            classify.setSubjectLabelId(subjectLabelId);
            rightsSettingBiz.setClassifyAndLabel(classify);
            paramMap.put("firstClassify", classify.getFirstClassify());
            paramMap.put("secondClassify", classify.getSecondClassify());
            paramMap.put("gradeLabelId", classify.getGradeLabelId());
            paramMap.put("subjectLabelId", classify.getSubjectLabelId());
        }else {
            paramMap.put("gradeLabelId", gradeLabelId);
            paramMap.put("subjectLabelId", subjectLabelId);
        }
        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<>());
        }
        fillLabel(pageBeanNew.getRecordList());
        setLabelContent(pageBeanNew.getRecordList());
        return pageBeanNew;
    }

    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> 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());
            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(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(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) {
        return appletNewsClassifyDao.getAllNewsClassify(showState);
    }

    @Override
    public PageBeanNew<AppletNewsDTO> listAppletNews4Wechat(Integer currentPage, Integer numPerPage, Long newsClassifyId, Long wechatUserId) {
        PageBeanNew<AppletNewsDTO> pageBeanNew = new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>()); ;
        Map<String, Object> paramMap = new HashMap<>();
        if (null == newsClassifyId) {//首页资讯
            List<Long> classifyIds = appletNewsClassifyDao.getClassifyIdsByUserId(wechatUserId);
            if (ListUtils.isEmpty(classifyIds)) {//没有栏目id取第一个
                List<AppletNewsClassifyDTO> classifyDTOS = getAllNewsClassify(true);
                if (ListUtils.isEmpty(classifyDTOS)) {
                    return new PageBeanNew<>(currentPage, numPerPage, new ArrayList<>());
                }
                newsClassifyId = classifyDTOS.get(0).getId();
                classifyIds.add(newsClassifyId);
            }
            paramMap.put("newsClassifyIdList", classifyIds);
            paramMap.put("order", 1);
            //首页3条缓存5小时
            if (currentPage==0 && numPerPage==3){
                List<AppletNewsDTO> homeList = JedisClusterUtils.getJsonList(AppletConstants.HOME_NEWS_LIST, AppletNewsDTO.class);
                if (!ListUtils.isEmpty(homeList)) {
                    pageBeanNew = new PageBeanNew<>(0, 3, homeList.size(), homeList);
                } else {
                    pageBeanNew = appletNewsDao.listPageNew(new PageParam(0, 3), paramMap, "listAppletNews4Wechat");
                    JedisClusterUtils.setJsonList(AppletConstants.HOME_NEWS_LIST, pageBeanNew.getRecordList(), 5 * 3600);
                }
            }
        } else {//栏目下的资讯
            paramMap.put("newsClassifyId", newsClassifyId);
        }
        if (ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            pageBeanNew = appletNewsDao.listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listAppletNews4Wechat");
        }
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        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));
        return appletNewsDTO;
    }

    /**
     * 点击量浏览量
     *  * @param null
     */
    private 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);
        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);
            }
        }
    }

    /**
     * 填充第三方服务
     * @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);
        JedisClusterUtils.del(AppletConstants.HOME_NEWS_LIST);
    }

    @Override
    public List<AppletNewsDTO> getNewsByTempletLabel(Long firstClassify, Long secondClassify, Long gradeLabelId, Long subjectLabelId, String rightsType) {
        BaseTempletClassify classify = new BaseTempletClassify();
        classify.setFirstClassify(firstClassify);
        classify.setSecondClassify(secondClassify);
        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);
        return list;
    }

    @Override
    public void batchUpdateClassify(AppletNewsClassifyVO appletNewsClassifyVO) {
        if(appletNewsClassifyVO == null || ListUtils.isEmpty(appletNewsClassifyVO.getAppletNewsIds())){
            throw new BizException(BizException.PARAM_IS_NULL.getCode(), "参数为空");
        }
        if(!NumberUtil.isNumber(appletNewsClassifyVO.getFirstClassify()) ){
            throw new BizException(BizException.PARAM_IS_NULL.getCode(), "请选择一级分类");
        }
        rightsSettingBiz.setClassifyAndLabel(appletNewsClassifyVO);
        appletNewsDao.batchUpdateClassify(appletNewsClassifyVO);
    }

    @Override
    public void batchUpdateShowState(AppletNewsShowStateVO appletNewsShowStateVO) {
        appletNewsDao.batchUpdateShowState(appletNewsShowStateVO);
    }

    @Override
    public void batchDeleteAppletNews(List<Long> appletNewsIds) {
        appletNewsDao.batchDeleteAppletNews(appletNewsIds);
    }

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

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

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

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

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

    @Override
    public PageBeanNew<AppletNewsDTO> listAppletNews4Analysis(Integer currentPage, Integer numPerPage, String name, Long firstClassify, Long secondClassify, Long gradeLabelId, Long subjectLabelId, Integer linkOnly,Long rightsClassifyId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        paramMap.put("linkOnly", linkOnly);
        paramMap.put("rightsClassifyId", rightsClassifyId);
        //处理分类
        if (null!=firstClassify){
            BaseTempletClassify classify = new BaseTempletClassify();
            classify.setFirstClassify(firstClassify);
            classify.setSecondClassify(secondClassify);
            classify.setGradeLabelId(gradeLabelId);
            classify.setSubjectLabelId(subjectLabelId);
            rightsSettingBiz.setClassifyAndLabel(classify);
            paramMap.put("firstClassify", classify.getFirstClassify());
            paramMap.put("secondClassify", classify.getSecondClassify());
            paramMap.put("gradeLabelId", classify.getGradeLabelId());
            paramMap.put("subjectLabelId", classify.getSubjectLabelId());
        }else {
            paramMap.put("gradeLabelId", gradeLabelId);
            paramMap.put("subjectLabelId", subjectLabelId);
        }
        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<>());
        }
        setLabelContent(pageBeanNew.getRecordList());
        fillStatistic(pageBeanNew.getRecordList());
        return pageBeanNew;
    }

    /**
     * 点击量浏览量
     * @author：zhuyajie
     * @date：2020/5/11 20:09
     *  * @param null
     */
    private void fillStatistic(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> clickMap = appletLinkClickDao.mapPVUV(DataTypeEnum.news.code, DataRecordTypeEnum.click.code, newsIds);
        Map<Long, PvuvDTO> browseMap = appletLinkClickDao.mapPVUV(DataTypeEnum.news.code, DataRecordTypeEnum.browse.code, newsIds);
        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());
            } else {
                appletNewsDTO.setClickPVUV("0/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());
    }

    @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) {
        if (null == wechatUserId){
            return;
        }
        appletNewsClassifyDao.deleteClassifyByWechatUesrId(wechatUserId);
        if (ListUtils.isEmpty(newsClassifyIds)){
            List<AppletNewsClassifyDTO> list = appletNewsClassifyDao.getAllNewsClassify(true);
            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) {
        List<AppletNewsClassifyDTO> list = appletNewsClassifyDao.getAllNewsClassify(true);
        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) {
        List<AppletNewsClassifyDTO> list = appletNewsClassifyDao.getClassifysByUserId(wechatUserId);
        if (ListUtils.isEmpty(list)){
            List<AppletNewsClassifyDTO> allNewsClassify = appletNewsClassifyDao.getAllNewsClassify(true);
            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) {
        if (ListUtils.isEmpty(ids)) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "参数为空");
        }
        if (null == customTagId && !StringUtil.isEmpty(customTag)) {
            AppletNewsCustomTag appletNewsCustomTag = new AppletNewsCustomTag();
            appletNewsCustomTag.setCustomTag(customTag);
            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())) {
            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())){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"标识重复");
        }
        appletNewsDao.updateCustomTag(appletNewsCustomTag);
    }

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

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

}
