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

import com.pcloud.appcenter.assist.dto.AssistTempletDTO;
import com.pcloud.book.applet.biz.AppletBooklistBiz;
import com.pcloud.book.applet.biz.AppletNewsBiz;
import com.pcloud.book.applet.contants.AppletConstants;
import com.pcloud.book.applet.dao.AppletBooklistClassifyDao;
import com.pcloud.book.applet.dao.AppletBooklistDao;
import com.pcloud.book.applet.dao.AppletOuterBookDao;
import com.pcloud.book.applet.dao.AppletOuterBooklistDao;
import com.pcloud.book.applet.dto.AddBookParamDTO;
import com.pcloud.book.applet.dto.AppletBooklistClassifyDTO;
import com.pcloud.book.applet.dto.AppletBooklistDTO;
import com.pcloud.book.applet.dto.AppletOuterBookDTO;
import com.pcloud.book.applet.dto.AppletOuterBooklistDTO;
import com.pcloud.book.applet.dto.BookDTO4Booklist;
import com.pcloud.book.applet.dto.OuterBooklistAddDTO;
import com.pcloud.book.applet.entity.AppletBookClassify;
import com.pcloud.book.applet.entity.AppletBooklist;
import com.pcloud.book.applet.entity.AppletBooklistClassify;
import com.pcloud.book.applet.entity.AppletBooklistClassifyUser;
import com.pcloud.book.applet.entity.AppletOuterBook;
import com.pcloud.book.applet.entity.AppletOuterBooklist;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.biz.BookAdviserBiz;
import com.pcloud.book.book.dao.BookLabelDao;
import com.pcloud.book.book.dto.BookAdviserDto;
import com.pcloud.book.book.entity.BookLabel;
import com.pcloud.book.consumer.app.AssistTempletConsr;
import com.pcloud.book.consumer.user.AdviserConsr;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.book.consumer.user.ChannelConsr;
import com.pcloud.book.util.properties.BookProps;
import com.pcloud.channelcenter.wechat.entity.AccountSetting;
import com.pcloud.book.es.biz.ESBookAndAdviserBiz;
import com.pcloud.book.es.entity.ESBookAndAdviser;
import com.pcloud.book.rightsSetting.biz.RightsSettingBiz;
import com.pcloud.book.rightsSetting.constants.RightsSettingConstant;
import com.pcloud.book.rightsSetting.entity.BaseTempletClassify;
import com.pcloud.book.util.properties.BookProps;
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.httpclient.UrlUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.usercenter.party.adviser.dto.AdviserBaseInfoDto;

import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
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.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 小程序书单
 */
@Component
public class AppletBooklistBizImpl implements AppletBooklistBiz {


    @Autowired
    private AppletBooklistClassifyDao appletBooklistClassifyDao;
    @Autowired
    private AppletBooklistDao appletBooklistDao;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private AssistTempletConsr assistTempletConsr;
    @Autowired
    private RightsSettingBiz rightsSettingBiz;
    @Autowired
    private AppletNewsBiz appletNewsBiz;
    @Autowired
    private AppletOuterBookDao appletOuterBookDao;
    @Autowired
    private AppletOuterBooklistDao appletOuterBooklistDao;
    @Autowired
    private BookLabelDao bookLabelDao;
    @Autowired
    private BookAdviserBiz bookAdviserBiz;
    @Autowired
    private ESBookAndAdviserBiz esBookAndAdviserBiz;


    @Override
    public Long addBooklistClassify(AppletBooklistClassify appletBooklistClassify) {
        if (null == appletBooklistClassify.getAgentId()){
            appletBooklistClassify.setAgentId(0L);
        }
        Integer seq = appletBooklistClassifyDao.getMaxSeq(appletBooklistClassify.getAgentId());
        appletBooklistClassify.setSeq(seq+1);
        appletBooklistClassify.setShowState(false);
        appletBooklistClassifyDao.insert(appletBooklistClassify);
        return appletBooklistClassify.getId();
    }

    @Override
    public void deleteBooklistClassifyById(Long id) {
        List<AppletBooklist> booklists = appletBooklistDao.getByClassifyId(id);
        if (!ListUtils.isEmpty(booklists)){
            throw new BookBizException(BookBizException.ERROR,"请先删除关联书单");
        }
        appletBooklistClassifyDao.deleteById(id);
    }

    @Override
    public void updateBooklistClassify(AppletBooklistClassify appletBooklistClassify) {
        if (null==appletBooklistClassify.getId()){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"缺少id");
        }
        appletBooklistClassifyDao.update(appletBooklistClassify);
        JedisClusterUtils.del(AppletConstants.HOME_BOOKLIST);
    }

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

    @Override
    public Long addBooklist(AppletBooklist appletBooklist) {
        appletBooklistDao.insert(appletBooklist);
        return appletBooklist.getId();
    }

    @Override
    public void deleteBooklistById(Long id) {
        appletBooklistDao.updateDeleteState(id);
        appletBooklistDao.deleteConfigByBooklistId(id);
        //删除客户端缓存
        JedisClusterUtils.del(AppletConstants.BOOKLIST_BOOK+id);
        JedisClusterUtils.del(AppletConstants.HOME_BOOKLIST);
    }

    @Override
    public void updateBooklist(AppletBooklist appletBooklist) {
        if (null==appletBooklist.getId()){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"缺少id");
        }
        rightsSettingBiz.setClassifyAndLabel(appletBooklist);
        appletBooklistDao.update(appletBooklist);
    }

    @Override
    public AppletBooklistDTO getBooklistById(Long id) {
        AppletBooklist appletBooklist = appletBooklistDao.getById(id);
        AppletBooklistDTO dto = new AppletBooklistDTO();
        if (null != appletBooklist){
            BeanUtils.copyProperties(appletBooklist,dto);
        }
        return dto;
    }

    @Override
    public PageBeanNew<AppletBooklistDTO> listBooklist(Integer currentPage, Integer numPerPage, String name, Long classifyId, Long agentId,
                                                       Long firstClassify,Long secondClassify,Long gradeLabelId, Long subjectLabelId) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        paramMap.put("classifyId", classifyId);
        paramMap.put("agentId", agentId);
        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<AppletBooklistDTO> pageBeanNew = appletBooklistDao.listPageNew(
                new PageParam(currentPage,numPerPage), paramMap,"listBooklist");
        if(null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())){
            return new PageBeanNew<>(currentPage,numPerPage,0,new ArrayList<>());
        }
        //填充书刊，分类，标签
        List<Long> booklistIds = new ArrayList<>();
        List<Long> classifyIds = new ArrayList<>();
        List<Long> labelIds = new ArrayList<>();
        for(AppletBooklistDTO appletBooklistDTO : pageBeanNew.getRecordList()){
            booklistIds.add(appletBooklistDTO.getId());
            if (null != appletBooklistDTO.getFirstClassify()){
                classifyIds.add(appletBooklistDTO.getFirstClassify());
            }
            if (null != appletBooklistDTO.getSecondClassify()){
                classifyIds.add(appletBooklistDTO.getSecondClassify());
            }
            if (null != appletBooklistDTO.getGradeLabelId()) {
                labelIds.add(appletBooklistDTO.getGradeLabelId());
            }
            if (null != appletBooklistDTO.getSubjectLabelId()) {
                labelIds.add(appletBooklistDTO.getSubjectLabelId());
            }
        }
        List<BookDTO4Booklist> booklists = appletBooklistDao.getConfigByBooklistIds(booklistIds);
        Map<Long,List<BookDTO4Booklist>> map = new HashMap<>();
        if (!ListUtils.isEmpty(booklists)){
           map = booklists.stream().collect(Collectors.groupingBy(BookDTO4Booklist::getBooklistId));
        }
        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 (AppletBooklistDTO booklistDTO: pageBeanNew.getRecordList()){
            if (!MapUtils.isEmpty(map) && map.containsKey(booklistDTO.getId())){
                List<BookDTO4Booklist> bookDTO4Booklists = map.get(booklistDTO.getId());
                booklistDTO.setBookDTO4Booklists(bookDTO4Booklists);
            }
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(booklistDTO.getFirstClassify())){
                booklistDTO.setFirstClassifyContent(classifyMap.get(booklistDTO.getFirstClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(booklistDTO.getSecondClassify())){
                booklistDTO.setSecondClassifyContent(classifyMap.get(booklistDTO.getSecondClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(booklistDTO.getGradeLabelId())){
                booklistDTO.setGradeLabelIdContent(labelMap.get(booklistDTO.getGradeLabelId()).getName());
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(booklistDTO.getSubjectLabelId())){
                booklistDTO.setSubjectLabelIdContent(labelMap.get(booklistDTO.getSubjectLabelId()).getName());
            }
        }
        return pageBeanNew;
    }

    @Override
    public void addBookToBooklist(AddBookParamDTO addBookParamDTO) {
        Long booklistId = addBookParamDTO.getBooklistId();
        List<BookDTO4Booklist> configDTOS = addBookParamDTO.getBookDTO4Booklists();
        for(BookDTO4Booklist bookDTO4Booklist:configDTOS){
            bookDTO4Booklist.setBooklistId(booklistId);
            bookDTO4Booklist.setSeq(configDTOS.indexOf(bookDTO4Booklist));
        }
        appletBooklistDao.deleteConfigByBooklistId(booklistId);
        appletBooklistDao.addBooklistConfig(configDTOS);
        //删除客户端缓存
        JedisClusterUtils.del(AppletConstants.BOOKLIST_BOOK+booklistId);
        JedisClusterUtils.del(AppletConstants.HOME_BOOKLIST);
    }

    @Override
    public PageBeanNew<BookDTO4Booklist> listPageBook4AppletBooklist(Long booklistId, Integer currentPage, Integer numPerPage) {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("booklistId", booklistId);
        PageBeanNew<BookDTO4Booklist> pageBeanNew = appletBooklistDao.listPageNew(
                new PageParam(currentPage,numPerPage), paramMap, "listPageBook4AppletBooklist");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())){
            return new PageBeanNew<>(currentPage,numPerPage,0,new ArrayList<>());
        }
        fillAgentTempletName(pageBeanNew.getRecordList());
        return pageBeanNew;
    }

    private void fillAgentTempletName(List<BookDTO4Booklist> list) {
        List<Long> adviserIds=list.stream().filter(s->s.getAdviserId()!=null).map(BookDTO4Booklist::getAdviserId).distinct().collect(Collectors.toList());
        Map<Long, AdviserBaseInfoDto> infoDtoMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(adviserIds);
        List<Long> templetIds = new ArrayList<>();
        list.forEach(dto4Booklist -> {
            if (Objects.nonNull(dto4Booklist.getTempletId())) {
                templetIds.add(dto4Booklist.getTempletId());
            }
            if (Objects.nonNull(dto4Booklist.getSecondTempletId())) {
                templetIds.add(dto4Booklist.getSecondTempletId());
            }
        });
        Map<Long, AssistTempletDTO> assistTempletDTOMap = assistTempletConsr.mapByIds(templetIds);
        for (BookDTO4Booklist dto4Booklist : list) {
            Long secondTempletId = dto4Booklist.getSecondTempletId();
            Long templetId = dto4Booklist.getTempletId();
            if (secondTempletId!=null&&assistTempletDTOMap!=null) {
                AssistTempletDTO templetDTO = assistTempletDTOMap.get(secondTempletId);
                dto4Booklist.setSecondTempletName(Optional.ofNullable(templetDTO).map(AssistTempletDTO::getTempletName).orElse(null));
            }
            if (templetId!=null && assistTempletDTOMap!=null) {
                AssistTempletDTO templetDTO = assistTempletDTOMap.get(templetId);
                dto4Booklist.setTempletName(Optional.ofNullable(templetDTO).map(AssistTempletDTO::getTempletName).orElse(null));
            }
            Long adviserId=dto4Booklist.getAdviserId();
            if (!MapUtils.isEmpty(infoDtoMap)){
                AdviserBaseInfoDto infoDto = infoDtoMap.get(adviserId);
                if (infoDto!=null){
                    dto4Booklist.setAgentName(infoDto.getAgentName());
                }
            }
        }
    }

    @Override
    public void updateBookSeq(Long configId, Integer seq) {
        appletBooklistDao.updateBookSeq(configId, seq);
    }

    @Override
    public List<AppletBooklistClassifyDTO> getAllBooklistClassify(Boolean showState, Long agentId){
        return appletBooklistClassifyDao.getAllBooklistClassify(showState, agentId);
    }

    @Override
    public PageBeanNew<AppletBooklistDTO> listBooklist4Wechat(Long classifyId, Integer currentPage, Integer numPerPage, Long wechatUserId, Long officialAccountsId) {
        PageBeanNew<AppletBooklistDTO> pageBeanNew = new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        Map<String, Object> map = new HashMap<>();
        if (null == classifyId) {//首页书单推荐
            List<Long> classifyIds = appletBooklistClassifyDao.getClassifyIdsByUserId(wechatUserId);
            if (ListUtils.isEmpty(classifyIds)) {//没有栏目id取第一个
                Long agentId = appletNewsBiz.getAgentIdByAccountId(officialAccountsId);
                List<AppletBooklistClassifyDTO> classifyDTOS = getAllBooklistClassify(true, agentId);
                if (ListUtils.isEmpty(classifyDTOS)) {
                    return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
                }
                classifyId = classifyDTOS.get(0).getId();
                classifyIds.add(classifyId);
            }
            map.put("classifyIdList", classifyIds);
            map.put("order", 1);
            //首页3条缓存5小时
            if (currentPage==0 && numPerPage==3){
                List<AppletBooklistDTO> homeList = JedisClusterUtils.getJsonList(AppletConstants.HOME_BOOKLIST, AppletBooklistDTO.class);
                if (!ListUtils.isEmpty(homeList)) {
                    pageBeanNew = new PageBeanNew<>(0, 3, homeList.size(), homeList);
                } else {
                    pageBeanNew = appletBooklistDao.listPageNew(new PageParam(0, 3), map, "listBooklist4Wechat");
                    JedisClusterUtils.setJsonList(AppletConstants.HOME_BOOKLIST, pageBeanNew.getRecordList(), 5 * 3600);
                }
            }
        } else {
            map.put("classifyId", classifyId);
        }
        if (ListUtils.isEmpty(pageBeanNew.getRecordList())){
            pageBeanNew = appletBooklistDao.listPageNew(new PageParam(currentPage, numPerPage), map, "listBooklist4Wechat");
        }
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        for (AppletBooklistDTO booklistDTO : pageBeanNew.getRecordList()) {
            Long booklistId = booklistDTO.getId();
            String key = AppletConstants.BOOKLIST_BOOK + booklistId;
            List<BookDTO4Booklist> bookList = JedisClusterUtils.getJsonList(key, BookDTO4Booklist.class);
            if (ListUtils.isEmpty(bookList)) {
                bookList = appletBooklistDao.getBookBaseByBooklistId(booklistId, 0, 3);
                JedisClusterUtils.setJson(key, bookList);
                JedisClusterUtils.expire(key, 3600);
            }
            booklistDTO.setBookDTO4Booklists(bookList);
        }
        return pageBeanNew;
    }

    @Override
    public AppletBooklistDTO getBooklistById4Wechat(Long booklistId){
        AppletBooklistDTO booklistDTO = getBooklistById(booklistId);
        if (null==booklistDTO){
            return new AppletBooklistDTO();
        }
        List<BookDTO4Booklist> bookList = appletBooklistDao.listPageBook4AppletBooklist(booklistId);
        if (!ListUtils.isEmpty(bookList)){
            fillAgentTempletName(bookList);
            booklistDTO.setBookDTO4Booklists(bookList);
            booklistDTO.setBookCounts(bookList.size());
        }
        return booklistDTO;
    }

    @Override
    public BookDTO4Booklist getByBookIdAdviserChannel(Long adviserId, Long channelId, Long bookId) {
        BookDTO4Booklist bookDTO4Booklist = appletBooklistDao.getByBookIdAdviserChannel(adviserId,channelId,bookId);
        if (null!=bookDTO4Booklist){
            fillAgentTempletName(Arrays.asList(bookDTO4Booklist));
        }
        return bookDTO4Booklist;
    }

    @Override
    public void addUserBooklistClassify(List<Long> classifyIds, Long wechatUserId, Long officialAccountsId) {
        if (null == wechatUserId){
            return;
        }
        appletBooklistClassifyDao.deleteClassifyByWechatUesrId(wechatUserId);
        if (ListUtils.isEmpty(classifyIds)){
            Long agentId = appletNewsBiz.getAgentIdByAccountId(officialAccountsId);
            List<AppletBooklistClassifyDTO> classifyDTOS = getAllBooklistClassify(true, agentId);
            if (ListUtils.isEmpty(classifyDTOS)){
                return;
            }
            classifyIds.add(classifyDTOS.get(0).getId());
        }
        List<AppletBooklistClassifyUser> addList = new ArrayList<>();
        for (Long classifyId : classifyIds){
            AppletBooklistClassifyUser classifyUser = new AppletBooklistClassifyUser();
            classifyUser.setClassifyId(classifyId);
            classifyUser.setWechatUserId(wechatUserId);
            addList.add(classifyUser);
        }
        appletBooklistClassifyDao.batchInsertUserBooklistClassify(addList);
    }

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

    @Override
    public List<AppletBooklistClassifyDTO> getBooklistClassifyByUser(Long wechatUserId, Long officialAccountsId) {
        List<AppletBooklistClassifyDTO> list = appletBooklistClassifyDao.getClassifysByUserId(wechatUserId);
        if (ListUtils.isEmpty(list)){
            Long agentId = appletNewsBiz.getAgentIdByAccountId(officialAccountsId);
            List<AppletBooklistClassifyDTO> allBooklistClassify = appletBooklistClassifyDao.getAllBooklistClassify(true, agentId);
            if (ListUtils.isEmpty(allBooklistClassify)){
                return new ArrayList<>();
            }
            list.add(allBooklistClassify.get(0));
        }
        return list;
    }

    @Override
    public Long addOuterBook(AppletOuterBookDTO appletOuterBookDTO) {
        if (null == appletOuterBookDTO) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "参数缺失");
        }
        checkBookParam(appletOuterBookDTO);
        AppletOuterBook outerBook = new AppletOuterBook();
        BeanUtils.copyProperties(appletOuterBookDTO, outerBook);
        String linkUrl = UrlUtils.getShortUrl4Own(appletOuterBookDTO.getLinkUrl());
        outerBook.setLinkUrl(linkUrl);
        if (null != outerBook.getId()) {
            appletOuterBookDao.update(outerBook);
        } else {
            appletOuterBookDao.insert(outerBook);
        }
        return outerBook.getId();
    }

    private  void checkBookParam(AppletOuterBookDTO appletOuterBookDTO){
        if (StringUtil.isEmpty(appletOuterBookDTO.getCoverImg())){
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少封面图");
        }
        if (StringUtil.isEmpty(appletOuterBookDTO.getBookName())){
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少书籍名称");
        }
        if (StringUtil.isEmpty(appletOuterBookDTO.getPublish())){
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少出版社名称");
        }
        if (null == appletOuterBookDTO.getLinkType() || StringUtil.isEmpty(appletOuterBookDTO.getLinkUrl())){
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少链接");
        }
    }

    @Override
    public AppletOuterBookDTO getOuterBookById(Long outerBookId) {
        AppletOuterBookDTO appletOuterBookDTO = new AppletOuterBookDTO();
        AppletOuterBook outerBook = appletOuterBookDao.getById(outerBookId);
        if (null == outerBook){
            return appletOuterBookDTO;
        }
        BeanUtils.copyProperties(outerBook, appletOuterBookDTO);
        return appletOuterBookDTO;
    }

    @Override
    public PageBeanNew<AppletOuterBookDTO> listPageOuterBook(Integer currentPage, Integer numPerPage, String publish, String name, Long agentId) {
        Map<String,Object> map = new HashMap<>();
        map.put("publish", publish);
        map.put("name", name);
        map.put("agentId", agentId);
        PageBeanNew<AppletOuterBookDTO> pageBeanNew = appletOuterBookDao.listPageNew(new PageParam(currentPage,numPerPage), map,"listPageOuterBook");
        return pageBeanNew;
    }

    @Override
    public List<String> getOuterBookPublish(Long agentId) {
        return appletOuterBookDao.getAllPublish(agentId);
    }

    @Override
    public void deleteOuterBookById(Long id) {
        Integer booklistCount = appletOuterBooklistDao.getBooklistCountsByBookId(id);
        if (booklistCount>0){
            throw new BookBizException(BookBizException.ERROR,"先从书单中删除该书");
        }
        appletOuterBookDao.deleteById(id);
    }

    @Override
    public Long addOuterBooklist(AppletOuterBooklistDTO appletOuterBooklistDTO) {
        if (null == appletOuterBooklistDTO){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"参数缺失");
        }
        AppletOuterBooklist appletOuterBooklist = new AppletOuterBooklist();
        BeanUtils.copyProperties(appletOuterBooklistDTO,appletOuterBooklist);
        if (null!= appletOuterBooklist.getId()){
            appletOuterBooklistDao.update(appletOuterBooklist);
        }else {
            checkBooklistParam(appletOuterBooklistDTO);
            appletOuterBooklistDao.insert(appletOuterBooklist);
        }
        appletOuterBooklistDao.deleteConfigByOuterBooklistId(appletOuterBooklist.getId());
        if (!ListUtils.isEmpty(appletOuterBooklistDTO.getOuterBookIdList())){
            List<OuterBooklistAddDTO> addDTOS = new ArrayList<>();
            for (Long bookId : appletOuterBooklistDTO.getOuterBookIdList()){
                OuterBooklistAddDTO dto = new OuterBooklistAddDTO();
                dto.setBooklistId(appletOuterBooklist.getId());
                dto.setOuterBookId(bookId);
                addDTOS.add(dto);
            }
            appletOuterBooklistDao.addOuterBooklistConfig(addDTOS);
        }
        return appletOuterBooklist.getId();
    }

    private  void checkBooklistParam(AppletOuterBooklistDTO appletOuterBooklistDTO){
        if (StringUtil.isEmpty(appletOuterBooklistDTO.getBooklistName())){
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少书单主题名称");
        }
        if (StringUtil.isEmpty(appletOuterBooklistDTO.getUserName())){
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少创建者名称");
        }
        if (StringUtil.isEmpty(appletOuterBooklistDTO.getDisplayPic())){
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少展示图");
        }
        if (StringUtil.isEmpty(appletOuterBooklistDTO.getPublish())){
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "缺少出版社");
        }
    }

    @Override
    public AppletOuterBooklistDTO getOuterBooklistById(Long booklistId) {
        AppletOuterBooklistDTO appletOuterBooklistDTO = new AppletOuterBooklistDTO();
        AppletOuterBooklist appletOuterBooklist = appletOuterBooklistDao.getById(booklistId);
        if (null == appletOuterBooklist){
            return appletOuterBooklistDTO;
        }
        BeanUtils.copyProperties(appletOuterBooklist,appletOuterBooklistDTO);
        List<Long> bookIds = appletOuterBooklistDao.getBookIdsByBooklistId(booklistId);
        appletOuterBooklistDTO.setOuterBookIdList(bookIds);
        return appletOuterBooklistDTO;
    }

    @Override
    public PageBeanNew<AppletOuterBooklistDTO> listPageOuterBooklist(Integer currentPage, Integer numPerPage, String publish, String name, Long agentId) {
        Map<String,Object> map = new HashMap<>();
        map.put("publish", publish);
        map.put("name", name);
        map.put("agentId", agentId);
        PageBeanNew<AppletOuterBooklistDTO> pageBeanNew = appletOuterBooklistDao.listPageNew(new PageParam(currentPage,numPerPage), map,"listPageOuterBooklist");
        return pageBeanNew;
    }

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

    @Override
    public void deleteOuterBooklistById(Long id) {
        appletOuterBooklistDao.updateDeleteState(id);
        appletOuterBooklistDao.deleteConfigByOuterBooklistId(id);
    }

    @Override
    public AppletOuterBooklistDTO getOutBooklistById4Wechat(Long booklistId) {
        AppletOuterBooklistDTO appletOuterBooklistDTO = new AppletOuterBooklistDTO();
        AppletOuterBooklist appletOuterBooklist = appletOuterBooklistDao.getById(booklistId);
        if (null == appletOuterBooklist){
            return appletOuterBooklistDTO;
        }
        BeanUtils.copyProperties(appletOuterBooklist,appletOuterBooklistDTO);
        List<AppletOuterBookDTO> bookDTOS = appletOuterBooklistDao.getBookListByBooklistId(booklistId);
        appletOuterBooklistDTO.setOuterBookDTOS(bookDTOS);
        return appletOuterBooklistDTO;
    }

    @Override
    public Map<Long, AppletOuterBooklistDTO> getByIds(List<Long> booklistIds) {
        Map<Long, AppletOuterBooklistDTO> booklistDTOMap = appletOuterBooklistDao.getByIds(booklistIds);
        if (!MapUtils.isEmpty(booklistDTOMap)) {
            for (Map.Entry<Long, AppletOuterBooklistDTO> entry : booklistDTOMap.entrySet()) {
                Long booklistId = entry.getKey();
                //带3本书
                String key = AppletConstants.OUTER_BOOKLIST_BOOK + booklistId;
                List<AppletOuterBookDTO> bookList = JedisClusterUtils.getJsonList(key, AppletOuterBookDTO.class);
                if (ListUtils.isEmpty(bookList)) {
                    bookList = appletOuterBookDao.listPageOuterBookByBooklistId(booklistId, 3);
                    JedisClusterUtils.setJson(key, bookList);
                    JedisClusterUtils.expire(key, 3600);
                }
                entry.getValue().setOuterBookDTOS(bookList);
            }
        }
        return booklistDTOMap;
    }

    @Override
    public void batchDeleteOuterBookFromBooklist(List<Long> configIds) {
        appletOuterBooklistDao.batchDeleteOuterBookFromBooklist(configIds);
    }

    @Override
    public PageBeanNew<AppletOuterBookDTO> listPageOuterBookByBooklistId(Integer currentPage, Integer numPerPage, Long booklistId) {
        Map<String,Object> map = new HashMap<>();
        map.put("booklistId", booklistId);
        PageBeanNew<AppletOuterBookDTO> pageBeanNew = appletOuterBookDao.listPageNew(new PageParam(currentPage,numPerPage), map,"listPageOuterBookByBooklistId");
        return pageBeanNew;
    }

    @Override
    public void addDefaultBooklistClassify(Long agentId) {
        AppletBooklistClassify appletBooklistClassify = new AppletBooklistClassify();
        appletBooklistClassify.setSeq(0);
        appletBooklistClassify.setAgentId(agentId);
        appletBooklistClassify.setClassifyName("推荐");
        appletBooklistClassify.setPic("https://file.5rs.me/oss/uploadfe/png/30ac33d2ecd19649fd86250065a58e42.png");
        appletBooklistClassify.setShowState(false);
        appletBooklistClassifyDao.insert(appletBooklistClassify);
    }




    @Override
    public List<AppletBooklistDTO> getRecommendBooklistByBook(Long bookId, Long adviserId, Long channelId) {
        BookAdviserDto bookAdviserDto;
        if (channelId != null && channelId>0 && adviserId != null && adviserId>0){
            bookAdviserDto = bookAdviserBiz.getBase(bookId,channelId,adviserId);
        }else {
            bookAdviserDto = bookAdviserBiz.getOneMainBook(bookId);
        }
        if (null==bookAdviserDto){
            return new ArrayList<>();
        }
        BaseTempletClassify classify = new BaseTempletClassify();
        classify.setFirstClassify(bookAdviserDto.getTempletId());
        classify.setSecondClassify(bookAdviserDto.getSecondTempletId());
        classify.setGradeLabelId(bookAdviserDto.getGraLabelId());
        classify.setSubjectLabelId(bookAdviserDto.getSubLabelId());
        rightsSettingBiz.setClassifyAndLabel(classify);
        List<AppletBooklistDTO> list = appletBooklistDao.getByLabel(classify.getFirstClassify(), classify.getSecondClassify(), classify.getGradeLabelId(), classify.getSubjectLabelId(), 3);
        if (!ListUtils.isEmpty(list)){
            //带3本书
            for (AppletBooklistDTO booklistDTO : list) {
                Long booklistId = booklistDTO.getId();
                String key = AppletConstants.BOOKLIST_BOOK + booklistId;
                List<BookDTO4Booklist> bookList = JedisClusterUtils.getJsonList(key, BookDTO4Booklist.class);
                if (ListUtils.isEmpty(bookList)) {
                    bookList = appletBooklistDao.getBookBaseByBooklistId(booklistId, 0, 3);
                    JedisClusterUtils.setJson(key, bookList);
                    JedisClusterUtils.expire(key, 3600);
                }
                booklistDTO.setBookDTO4Booklists(bookList);
            }
        }
        return list;
    }

    @Override
    public void autoCreateBooklistByTemplet(Long firstClassify) {
        Boolean contain4K12 = false;
        if ("test".equals(BookProps.getSystemEnv()) && ArrayUtils
                .contains(RightsSettingConstant.K12_TEMPLET_ID_TEST, firstClassify)) {
            contain4K12 = true;
        } else if (!"test".equals(BookProps.getSystemEnv()) && ArrayUtils
                .contains(RightsSettingConstant.K12_TEMPLET_ID, firstClassify)) {
            contain4K12 = true;
        }
        //K12
        if (contain4K12){
           List<BookLabel> gradeLabelList =  bookLabelDao.getListByType(1);
           List<BookLabel> subjectLabelList = bookLabelDao.getListByType(2);
           for (BookLabel grade:gradeLabelList){
               for (BookLabel subject:subjectLabelList){
                   this.autoCreateBooklist(Arrays.asList(firstClassify),new ArrayList<>(),Arrays.asList(grade.getId()),Arrays.asList(subject.getId()));
               }
           }
           return;
        }
        //医疗保健
        if (ArrayUtils.contains(RightsSettingConstant.MEDICAL_INSURANCE_TEMPLET_ID, firstClassify)) {
            List<Long> secondList = assistTempletConsr.getChildIdListByParentId(firstClassify);
            for (Long secondId:secondList){
                this.autoCreateBooklist(Arrays.asList(firstClassify),Arrays.asList(secondId),new ArrayList<>(),new ArrayList<>());
            }
            return;
        }
        this.autoCreateBooklist(Arrays.asList(firstClassify),new ArrayList<>(),new ArrayList<>(),new ArrayList<>());
    }

    private void autoCreateBooklist(List<Long>templetIds, List<Long> secondTempletIds, List<Long> graLabelIds, List<Long> subLabelIds){
        for (int i = 0; i < 3; i++) {
            Page<ESBookAndAdviser> esPage = esBookAndAdviserBiz.getESAdviserBooks4Applet("1", null, templetIds, graLabelIds, subLabelIds, i, 20,secondTempletIds);
            if (ListUtils.isEmpty(esPage.getContent())){
                return;
            }
            AssistTempletDTO assistTempletDTO = assistTempletConsr.getTempletById(templetIds.get(0));
            AppletBooklist appletBooklist = new AppletBooklist();
            appletBooklist.setBooklistName(assistTempletDTO.getTempletName()+"推荐书单");
            appletBooklist.setUserName("小编推荐");
            appletBooklist.setFirstClassify(templetIds.get(0));
            appletBooklist.setSecondClassify(ListUtils.isEmpty(secondTempletIds)?null:secondTempletIds.get(0));
            appletBooklist.setGradeLabelId(ListUtils.isEmpty(graLabelIds)?null:graLabelIds.get(0));
            appletBooklist.setSubjectLabelId(ListUtils.isEmpty(subLabelIds)?null:subLabelIds.get(0));
            appletBooklist.setDigest((int) esPage.getTotalElements()+"本"+assistTempletDTO.getTempletName()+"书单推荐");
            appletBooklist.setDisplayPic("https://oss.5rs.me/oss/uploadfe/png/39e36255426a66454037fcde86e19bf2.png");
            appletBooklist.setClassifyId(1L);
            appletBooklist.setIntroduceType(1);
            appletBooklist.setIntroduceContent("<p>"+(int) esPage.getTotalElements()+"本"+assistTempletDTO.getTempletName()+"书单推荐</p>");
            Long booklistId = addBooklist(appletBooklist);
            List<BookDTO4Booklist> addList = new ArrayList<>();
            for (ESBookAndAdviser esBookAndAdviser :esPage.getContent()){
                BookDTO4Booklist booklist = new BookDTO4Booklist();
                booklist.setBookId(Long.valueOf(esBookAndAdviser.getBookId()));
                booklist.setAdviserId(Long.valueOf(esBookAndAdviser.getAdviserId()));
                booklist.setChannelId(Long.valueOf(esBookAndAdviser.getChannelId()));
                addList.add(booklist);
            }
            AddBookParamDTO addBookParamDTO = new AddBookParamDTO();
            addBookParamDTO.setBooklistId(booklistId);
            addBookParamDTO.setBookDTO4Booklists(addList);
            this.addBookToBooklist(addBookParamDTO);
        }
    }


    @Override
    @ParamLog("获取小程序精选书单")
    public Map<Long, AppletBooklistDTO> getBookListMap(List<Long> bookListIds) {
        return appletBooklistDao.getBookListMap(bookListIds);
    }
}
