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

import com.pcloud.appcenter.assist.dto.AssistTempletDTO;
import com.pcloud.book.applet.biz.AppletNewsBiz;
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.dto.AppletNewsClassifyDTO;
import com.pcloud.book.applet.dto.AppletNewsCommentDTO;
import com.pcloud.book.applet.dto.AppletNewsDTO;
import com.pcloud.book.applet.dto.AppletNewsVO;
import com.pcloud.book.applet.entity.AppletNews;
import com.pcloud.book.applet.entity.AppletNewsClassify;
import com.pcloud.book.applet.entity.AppletNewsComment;
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.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.string.StringUtil;
import com.pcloud.common.utils.NumberUtil;
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 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;

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

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

    @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
    public Long addAppletNews(AppletNews appletNews) {
        appletNews.setShowState(false);
        rightsSettingBiz.setClassifyAndLabel(appletNews);
        appletNewsDao.insert(appletNews);
        this.updateSource(null,appletNews.getSource());
        return appletNews.getId();
    }

    @Override
    public void updateAppletNews(AppletNews appletNews) {
        if (null == appletNews.getId()){
            throw new BookBizException(BookBizException.ERROR,"id为空");
        }
        AppletNews beforeNews = appletNewsDao.getById(appletNews.getId());
        rightsSettingBiz.setClassifyAndLabel(appletNews);
        appletNewsDao.update(appletNews);
        this.updateSource(beforeNews.getSource(),appletNews.getSource());
    }

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

    @Override
    public PageBeanNew<AppletNewsDTO> listAppletNews(Integer currentPage, Integer numPerPage, String name,
                                                     Long firstClassify,Long secondClassify,Long gradeLabelId,
                                                     Long subjectLabelId,Long rightsClassifyId,String source) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        paramMap.put("rightsClassifyId", rightsClassifyId);
        paramMap.put("source", source);
        //处理分类
        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) {
        if (null == newsClassifyId){//没有栏目id取第一个
            List<AppletNewsClassifyDTO> classifyDTOS = getAllNewsClassify(true);
            if (ListUtils.isEmpty(classifyDTOS)){
                throw new BookBizException(BookBizException.ERROR,"没有资讯栏目");
            }
            newsClassifyId = classifyDTOS.get(0).getId();
        }
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("newsClassifyId", newsClassifyId);
        paramMap.put("showState",true);
        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());
        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);
        }
        fillLabel(Arrays.asList(appletNewsDTO));
        return appletNewsDTO;
    }

    @Override
    public void updateNewsShowState(AppletNews appletNews) {
        appletNewsDao.updateNewsShowState(appletNews);
    }

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

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

}
