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

import com.pcloud.appcenter.app.dto.AppDto;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.app.AppConsr;
import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.content.ResourceConsr;
import com.pcloud.book.consumer.resource.ProductConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.biz.BookGroupAppBiz;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dao.WeixinQrcodeGenerationDao;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.entity.WeixinQrcodeGeneration;
import com.pcloud.book.group.enums.AppAndProductTypeEnum;
import com.pcloud.book.group.tools.SendWeixinRequestTools;
import com.pcloud.book.keywords.biz.SelfRobotKeywordBiz;
import com.pcloud.book.keywords.dao.SelfRobotKeywordDao;
import com.pcloud.book.keywords.dao.SelfRobotKeywordReplyDao;
import com.pcloud.book.keywords.mapper.TempRobotSkillDao;
import com.pcloud.book.keywords.dto.MaxSeqNAndBGDTO;
import com.pcloud.book.keywords.entity.SelfRobotKeyword;
import com.pcloud.book.keywords.entity.SelfRobotKeywordReply;
import com.pcloud.book.keywords.entity.TempRobotSkill;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.book.keywords.vo.GuideWordVO;
import com.pcloud.book.keywords.vo.LabelVO;
import com.pcloud.book.keywords.vo.SelfRobotReplyVO;
import com.pcloud.book.util.common.ThreadPoolUtils;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.contentcenter.resource.dto.ResourceDTO;
import com.pcloud.resourcecenter.product.dto.ProductDto;
import com.pcloud.resourcecenter.product.dto.ProductTypeDto;
import com.pcloud.wechatgroup.group.dto.GroupRobotDTO;
import com.pcloud.wechatgroup.timecontrol.dto.LabelDto;
import com.pcloud.wechatgroup.timecontrol.dto.TaskDto;
import com.pcloud.wechatgroup.timecontrol.service.TimeControlTaskService;

import com.sdk.wxgroup.*;
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.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description
 * @Author ruansiyuan
 * @Date 2019/12/30 11:35
 **/
@Component("selfRobotKeywordBiz")
public class SelfRobotKeywordBizImpl implements SelfRobotKeywordBiz {

    @Autowired
    private SelfRobotKeywordDao selfRobotKeywordDao;
    @Autowired
    private BookGroupDao bookGroupDao;
    @Autowired
    private AppConsr appConsr;
    @Autowired
    private BookGroupAppBiz bookGroupAppBiz;
    @Autowired
    private ProductConsr productConsr;
    @Autowired
    private ResourceConsr resourceConsr;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;
    @Autowired
    private SelfRobotKeywordReplyDao selfRobotKeywordReplyDao;
    @Autowired
    private TimeControlTaskService timeControlTaskService;
    @Autowired
    private TempRobotSkillDao tempRobotSkillDao;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private WeixinQrcodeGenerationDao weixinQrcodeGenerationDao;

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("批量新增个人号关键词")
    @Override
    public void batchAddSelfRobotKeyword(Long partyId, List<SelfRobotKeyword> selfRobotKeywords) {
        checkBatchAddSelfRobotKeyword(selfRobotKeywords);
        List<Long> bookGroupIds = selfRobotKeywords.stream().map(SelfRobotKeyword::getBookGroupId).distinct().collect(Collectors.toList());
        List<BookGroupDTO> dtos = bookGroupDao.getDTOByIds(bookGroupIds);
        Map<Long, Long> btcMap = new HashMap<>();
        for (BookGroupDTO bookGroupDTO : dtos) {
            btcMap.put(bookGroupDTO.getId(), bookGroupDTO.getChannelId());
        }
        //获取最大排序值
        List<MaxSeqNAndBGDTO> maxSeqNAndBGDTOS = selfRobotKeywordDao.getMaxSeqNumByBookGroupIds(bookGroupIds);
        Map<Long, Integer> maxSeqMap = new HashMap<>();
        if (!ListUtils.isEmpty(maxSeqNAndBGDTOS)) {
            for (MaxSeqNAndBGDTO maxSeqNAndBGDTO : maxSeqNAndBGDTOS) {
                maxSeqMap.put(maxSeqNAndBGDTO.getBookGroupId(), maxSeqNAndBGDTO.getMaxSeqNum());
            }
        }
        for (SelfRobotKeyword selfRobotKeyword : selfRobotKeywords) {
            selfRobotKeyword.setCreateUser(partyId);
            Long bookGroupId = selfRobotKeyword.getBookGroupId();
            Integer maxSeqNum = maxSeqMap.get(bookGroupId);
            if (maxSeqNum == null) {
                maxSeqNum = 0;
            }
            selfRobotKeyword.setSeqNum(maxSeqNum + 1);
            maxSeqNum = maxSeqNum + 1;
            maxSeqMap.put(bookGroupId, maxSeqNum);
            //新增
            selfRobotKeywordDao.insert(selfRobotKeyword);
            Long keywordId = selfRobotKeyword.getId();
            List<SelfRobotKeywordReply> replyList = selfRobotKeyword.getKeywordReplyList();
            replyList.forEach(selfRobotKeywordReply -> {
                selfRobotKeywordReply.setKeywordId(keywordId);
                selfRobotKeywordReply.setCreateUser(partyId);
            });
            selfRobotKeywordReplyDao.insert(replyList);
        }
        //将作品应用关键词加到社群书应用
        bookGroupAppBiz.addSelfKeywordToBookGroupApp(selfRobotKeywords);
        for (Long bookGroupId : bookGroupIds) {
            List<SelfRobotKeyword> list = selfRobotKeywordDao.getListByBookGroupId(bookGroupId);
            for (SelfRobotKeyword keyword : list){
                List<SelfRobotKeywordReply> replyList = selfRobotKeywordReplyDao.getListByKeywordId(keyword.getId());
                if (!ListUtils.isEmpty(replyList)) {
                    List<SelfRobotKeywordReply> replyProductList = replyList.stream().filter(s -> AppAndProductTypeEnum.PRODUCT.value.equalsIgnoreCase(s.getServeType())).collect(Collectors.toList());
                    if (ListUtils.isEmpty(replyProductList)){
                        continue;
                    }
                    List<Long> productIds = replyProductList.stream().filter(s -> s.getServeId() != null).map(SelfRobotKeywordReply::getServeId).collect(Collectors.toList());
                    //自动上架
                    productConsr.productAutoOnShelves(btcMap.get(bookGroupId), productIds);
                }
            }
        }

    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("更新个人号关键词")
    @Override
    public void updateSelfRobotKeyword(Long partyId, SelfRobotKeyword selfRobotKeyword) {
        checkUpdateSelfRobotKeyword(selfRobotKeyword);
        BookGroupDTO dto = bookGroupDao.getDTOById(selfRobotKeyword.getBookGroupId());
        if (dto==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "未找到该社群书！");
        }
        selfRobotKeywordDao.updateSelfRobotKeyword(selfRobotKeyword);
        selfRobotKeywordReplyDao.deleteByKeywordId(selfRobotKeyword.getId());
        List<SelfRobotKeywordReply> replyList = selfRobotKeyword.getKeywordReplyList();
        replyList.forEach(selfRobotKeywordReply -> {
            selfRobotKeywordReply.setKeywordId(selfRobotKeyword.getId());
            selfRobotKeywordReply.setCreateUser(partyId);
        });
        selfRobotKeywordReplyDao.insert(replyList);
        for (SelfRobotKeywordReply selfRobotKeywordReply:replyList){
            if (ReplyTypeEnum.APP.value.equals(selfRobotKeywordReply.getType())
                    && AppAndProductTypeEnum.PRODUCT.value.equals(selfRobotKeywordReply.getServeType())) {
                //上架
                productConsr.productAutoOnShelves(dto.getChannelId(), Arrays.asList(selfRobotKeywordReply.getServeId()));
            }
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("删除个人号关键词")
    @Override
    public void deleteSelfRobotKeyword(Long id) {
        selfRobotKeywordDao.deleteById(id);
        selfRobotKeywordReplyDao.deleteByKeywordId(id);
    }

    @ParamLog("获取个人号关键词列表")
    @Override
    public PageBeanNew<SelfRobotKeyword> getSelfRobotKeywordList(Long bookGroupId, String keyword, Integer currentPage, Integer numPerPage) {
        if (bookGroupId == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "bookGroupId参数为空！");
        }
        if (currentPage == null || numPerPage == null || currentPage < 0 || numPerPage <= 0) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "分页参数错误！");
        }
        PageParam pageParam = new PageParam(currentPage, numPerPage);
        Map<String, Object> map = new HashMap<>();
        map.put("bookGroupId", bookGroupId);
        map.put("keyword", keyword);
        PageBeanNew<SelfRobotKeyword> page = selfRobotKeywordDao.listPageNew(pageParam, map, "getSelfRobotKeywordList");
        fillSelfRobotKeyword(page.getRecordList());
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @ParamLog("删除个人号关键词")
    @Override
    public void updateSelfRobotKeywordSeqNum(SelfRobotKeyword selfRobotKeyword) {
        if (selfRobotKeyword==null||selfRobotKeyword.getId()==null||selfRobotKeyword.getSeqNum()==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"参数有误！");
        }
        selfRobotKeywordDao.updateSeqNum(selfRobotKeyword.getId(),selfRobotKeyword.getSeqNum());
    }

    @ParamLog("获取应用或作品链接")
    @Override
    public String getAppOrProductServeUrl(Long bookGroupId, Long serveId, String serveType, String serveUrl) {
        if (bookGroupId==null||serveId==null||StringUtil.isEmpty(serveUrl)){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"参数有误！");
        }
        BookGroupDTO dto = bookGroupDao.getDTOById(bookGroupId);
        if (dto==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数错误！");
        }
        AccountSettingDto accountSettingDto = qrcodeSceneConsr.getWechatInfo(dto.getChannelId());
        if ("APP".equalsIgnoreCase(serveType)) {
            AppDto appDto = appConsr.getBaseById(serveId);
            if (appDto != null) {
                accountSettingDto = qrcodeSceneConsr.getWechatInfo(appDto.getChannelId());
            }
        }
        // 处理链接地址
        String endUrl = serveUrl + "&book_group_id=" + bookGroupId;
        String linkUrl = SendWeixinRequestTools.splitUrl(accountSettingDto, endUrl);
        return  linkUrl;
    }


    @Override
    public List<GuideWordVO> getGuideWordListByType(Integer type) {
        List<GuideWordVO> list = new ArrayList<>();
            List<TempRobotSkill> skillList = tempRobotSkillDao.getTempRobotSkillListByType(type);
            for (TempRobotSkill skill : skillList) {
                GuideWordVO guideWordVO = new GuideWordVO();
                guideWordVO.setId(skill.getId());
                guideWordVO.setType(type);
                guideWordVO.setGuideWord(skill.getGuideWord());
                guideWordVO.setKeyWord(skill.getKeyWord());
                list.add(guideWordVO);
        }
        return list;
    }


    @Override
    public List<LabelVO> listLabelByType(Integer type) {
        List<LabelVO> list = new ArrayList<>();
        if (type == 1) {
            //时间管理
            List<LabelDto> labelList = ResponseHandleUtil.parseList(timeControlTaskService.listMaxDepLabel(10), LabelDto.class);
            if (!ListUtils.isEmpty(labelList)) {
                for (LabelDto item : labelList) {
                    LabelVO labelVO = new LabelVO();
                    labelVO.setLabelId(item.getDepLabelId());
                    labelVO.setLabelName(item.getDepLabelName());
                    list.add(labelVO);
                }
            }
        }
        if(type == 2 || type == 3) {
            list = tempRobotSkillDao.getLabelListByType(type);
        }
        return list;
    }

    @Override
    public List<SelfRobotReplyVO> getReplyByLabel(Integer type, Long labelId, String robotId, String wxUserId) {
        List<SelfRobotReplyVO> list = new ArrayList<>();
        if (type == 1) {
            List<TaskDto> taskDtoList = ResponseHandleUtil.parseList(timeControlTaskService.listTaskByLabelIds4User(wxUserId, labelId), TaskDto.class);
            if (!ListUtils.isEmpty(taskDtoList)) {
                taskDtoList.forEach(item -> {
                    SelfRobotReplyVO selfRobotReplyVO = new SelfRobotReplyVO();
                    BeanUtils.copyProperties(item, selfRobotReplyVO);
                    list.add(selfRobotReplyVO);
                });
            }
        }
        if (type == 2) {
            List<TempRobotSkill> skillList = tempRobotSkillDao.getTempRobotSkillListByLabelId(type, labelId.intValue());
            for (TempRobotSkill skill : skillList) {
                SelfRobotReplyVO selfRobotReplyVO = new SelfRobotReplyVO();
                selfRobotReplyVO.setId(skill.getId());
                selfRobotReplyVO.setReplyContent(skill.getReplyContent());
                selfRobotReplyVO.setKeyWord(skill.getKeyWord());
                selfRobotReplyVO.setGuideWord(skill.getGuideWord());
                list.add(selfRobotReplyVO);
            }

        }
        if (type == 3) {
            List<TempRobotSkill> skillList = tempRobotSkillDao.getTempRobotSkillListByLabelId(type, labelId.intValue());
            for (TempRobotSkill skill : skillList) {
                SelfRobotReplyVO selfRobotReplyVO = new SelfRobotReplyVO();
                selfRobotReplyVO.setId(skill.getId());
                selfRobotReplyVO.setReplyContent(skill.getReplyContent());
                selfRobotReplyVO.setWxGroupId(skill.getGroupId());
                selfRobotReplyVO.setWxGroupName(skill.getGroupName());
                selfRobotReplyVO.setKeyWord(skill.getKeyWord());
                selfRobotReplyVO.setGuideWord(skill.getGuideWord());
                list.add(selfRobotReplyVO);
            }

        }
        return list;
    }

    @Override
    public List<SelfRobotReplyVO> getReplyByKeyWord(Integer type, String keyWord, String robotId, String wxUserId) {
        List<SelfRobotReplyVO> list = new ArrayList<>();
        if (type == 1) {
            List<TaskDto> taskDtoList = ResponseHandleUtil.parseList(timeControlTaskService.listTaskByKey4User(wxUserId, keyWord), TaskDto.class);
            if (!ListUtils.isEmpty(taskDtoList)) {
                taskDtoList.forEach(item -> {
                    SelfRobotReplyVO selfRobotReplyVO = new SelfRobotReplyVO();
                    BeanUtils.copyProperties(item, selfRobotReplyVO);
                    list.add(selfRobotReplyVO);
                });
            }
        }
        if (type == 2) {
            List<TempRobotSkill> skillList = tempRobotSkillDao.getTempRobotSkillListByKeyword(type, keyWord);
            for (TempRobotSkill skill : skillList) {
                SelfRobotReplyVO selfRobotReplyVO = new SelfRobotReplyVO();
                selfRobotReplyVO.setId(skill.getId());
                selfRobotReplyVO.setReplyContent(skill.getReplyContent());
                selfRobotReplyVO.setKeyWord(skill.getKeyWord());
                selfRobotReplyVO.setGuideWord(skill.getGuideWord());
                list.add(selfRobotReplyVO);
            }

        }
        if (type == 3) {
            List<TempRobotSkill> skillList = tempRobotSkillDao.getTempRobotSkillListByKeyword(type, keyWord);
            for (TempRobotSkill skill : skillList) {
                SelfRobotReplyVO selfRobotReplyVO = new SelfRobotReplyVO();
                selfRobotReplyVO.setId(skill.getId());
                selfRobotReplyVO.setReplyContent(skill.getReplyContent());
                selfRobotReplyVO.setWxGroupId(skill.getGroupId());
                selfRobotReplyVO.setWxGroupName(skill.getGroupName());
                selfRobotReplyVO.setKeyWord(skill.getKeyWord());
                selfRobotReplyVO.setGuideWord(skill.getGuideWord());
                list.add(selfRobotReplyVO);
            }
        }

        return list;
    }

    @Override
    public List<SelfRobotReplyVO> getReplyBuyGuide(Integer type, Integer id, String robotId, String wxUserId) {
        List<SelfRobotReplyVO> list = new ArrayList<>();
        if (type == 1) {
            //todo 根据全平台关键词查id 找关联任务id集合
            List<Integer> taskIds = new ArrayList<>();
            if (id == 1) {
                taskIds = Arrays.asList(7);
            }else if (id == 2) {
                taskIds = Arrays.asList(6);
            }else {
                taskIds = Arrays.asList(5);
            }
            List<TaskDto> taskDtoList = ResponseHandleUtil.parseList(timeControlTaskService.listTaskByIds4User(wxUserId, taskIds), TaskDto.class);
            if (!ListUtils.isEmpty(taskDtoList)) {
                taskDtoList.forEach(item -> {
                    SelfRobotReplyVO selfRobotReplyVO = new SelfRobotReplyVO();
                    BeanUtils.copyProperties(item, selfRobotReplyVO);
                    list.add(selfRobotReplyVO);
                });
            }
        }
        if (type == 2 || type == 3) {
            TempRobotSkill skill = tempRobotSkillDao.getById(id);
            SelfRobotReplyVO replyVO = new SelfRobotReplyVO();
            replyVO.setId(skill.getId());
            replyVO.setReplyContent(skill.getReplyContent());
            replyVO.setWxGroupId(skill.getGroupId());
            replyVO.setWxGroupName(skill.getGroupName());
            replyVO.setKeyWord(skill.getKeyWord());
            replyVO.setGuideWord(skill.getGuideWord());
            list.add(replyVO);
        }
        return list;
    }

    @Override
    public String getResource(Integer id, String robotId, String wxUserId) {
        TempRobotSkill skill = tempRobotSkillDao.getById(id);
        ThreadPoolUtils.OTHER_THREAD_POOL.execute(() -> {
            if("text".equals(skill.getResourceType())) {
                // 发送文本
                SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
                sendTextMessageVO.setContent(skill.getText());
                sendTextMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
                sendTextMessageVO.setWxId(robotId);
                sendTextMessageVO.setAltId(robotId);
                sendTextMessageVO.setWxGroupId(wxUserId);
                sendTextMessageVO.setIp(getIpByRobot(robotId));
                WxGroupSDK.sendTextMessage(sendTextMessageVO);
            } else if ("file".equals(skill.getResourceType()))  {
                // 发送文件
                SendFileVO sendFileVO = new SendFileVO();
                sendFileVO.setFileUrl(skill.getFileUrl());
                sendFileVO.setFileName(skill.getFileName());
                sendFileVO.setIp(getIpByRobot(robotId));
                sendFileVO.setAltId(robotId);
                sendFileVO.setWxId(wxUserId);
                WxGroupSDK.sendFile(sendFileVO);
            } else if ("img".equals(skill.getResourceType()))  {
                // 发送图片
                SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
                sendPicMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
                sendPicMessageVO.setAltId(robotId);
                sendPicMessageVO.setWxGroupId(wxUserId);
                sendPicMessageVO.setPicUrl(skill.getImgUrl());
                sendPicMessageVO.setIp(getIpByRobot(robotId));
                WxGroupSDK.sendPicMessage(sendPicMessageVO);
            }
        });
        return skill.getReplyContent();
    }

    /**
     * 获取ip
     * @param altId
     * @return
     */
    private String getIpByRobot(String altId) {
        String ip = null;
        GroupRobotDTO groupRobotDTO = wechatGroupConsr.getGroupRobotByWxId(altId);
        if (null != groupRobotDTO) {
            WeixinQrcodeGeneration weixinQrcodeGeneration = weixinQrcodeGenerationDao.getByGeneration(groupRobotDTO.getVersion());
            if (null != weixinQrcodeGeneration) {
                ip = weixinQrcodeGeneration.getWechatGroupIp();
            }
        }
        return ip;
    }

    @Override
    public String joinGroup(Integer id, String robotId, String wxUserId) {
        TempRobotSkill skill = tempRobotSkillDao.getById(id);
        ThreadPoolUtils.OTHER_THREAD_POOL.execute(() -> {
            // 发送群二维码图片
            SendPicMessageVO sendPicMessageVO = new SendPicMessageVO();
            sendPicMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
            sendPicMessageVO.setAltId(robotId);
            sendPicMessageVO.setWxGroupId(wxUserId);
            sendPicMessageVO.setPicUrl(skill.getImgUrl());
            sendPicMessageVO.setIp(getIpByRobot(robotId));
            WxGroupSDK.sendPicMessage(sendPicMessageVO);
        });
        return skill.getReplyContent();
    }

    @Override
    public void sendWhenNoReply(Integer id, String robotId, String wxUserId) {
        SendTextMessageVO sendTextMessageVO = new SendTextMessageVO();
        if (id == 1) {
            sendTextMessageVO.setContent("怎么样？计划很棒吧，等你订阅哦");
            sendTextMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
            sendTextMessageVO.setWxId(robotId);
            sendTextMessageVO.setAltId(robotId);
            sendTextMessageVO.setWxGroupId(wxUserId);
            sendTextMessageVO.setIp(getIpByRobot(robotId));
            WxGroupSDK.sendTextMessage(sendTextMessageVO);
        }else if (id == 2){
            sendTextMessageVO.setContent("计划怎么样？我按照计划执行后效果很好哦，等你订阅后我们一起阅读");
            sendTextMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
            sendTextMessageVO.setWxId(robotId);
            sendTextMessageVO.setAltId(robotId);
            sendTextMessageVO.setWxGroupId(wxUserId);
            sendTextMessageVO.setIp(getIpByRobot(robotId));
            WxGroupSDK.sendTextMessage(sendTextMessageVO);
        }else {
            sendTextMessageVO.setContent(" 你还在犹豫吗？早起的鸟儿有虫吃，我先行动起来喽~");
            sendTextMessageVO.setCode(SendMessageTypeEnum.SELF.getCode());
            sendTextMessageVO.setWxId(robotId);
            sendTextMessageVO.setAltId(robotId);
            sendTextMessageVO.setWxGroupId(wxUserId);
            sendTextMessageVO.setIp(getIpByRobot(robotId));
            WxGroupSDK.sendTextMessage(sendTextMessageVO);
        }
    }

    @ParamLog("填充列表")
    private void fillSelfRobotKeyword(List<SelfRobotKeyword> selfRobotKeywords) {
        if (ListUtils.isEmpty(selfRobotKeywords)){
            return;
        }
        List<Long> appIds=new ArrayList<>();
        List<Long> productIds=new ArrayList<>();
        List<Long> resourceIds=new ArrayList<>();
        for (SelfRobotKeyword selfRobotKeyword : selfRobotKeywords){
            List<SelfRobotKeywordReply> replyList = selfRobotKeywordReplyDao.getListByKeywordId(selfRobotKeyword.getId());
            if (ListUtils.isEmpty(replyList)){
                continue;
            }
            for (SelfRobotKeywordReply keywordReply : replyList){
                Integer type=keywordReply.getType();
                if (ReplyTypeEnum.APP.value.equals(type)){
                    if (AppAndProductTypeEnum.APP.value.equals(keywordReply.getServeType())){
                        appIds.add(keywordReply.getServeId());
                    }
                    if (AppAndProductTypeEnum.PRODUCT.value.equals(keywordReply.getServeType())){
                        productIds.add(keywordReply.getServeId());
                    }
                }
                if (ReplyTypeEnum.RESOURCE.value.equals(type)){
                    resourceIds.add(keywordReply.getResourceId());
                }
            }
        }
        Map<Long, AppDto> appDtoMap=new HashMap<>();
        Map<Long, ProductDto> productDtoMap=new HashMap<>();
        Map<Long, ResourceDTO> resourceDTOMap=new HashMap<>();
        if (!ListUtils.isEmpty(appIds)){
            appDtoMap = appConsr.getBaseByIds(appIds);
        }
        if (!ListUtils.isEmpty(productIds)){
            productDtoMap = productConsr.getProBasesByIds(productIds);
        }
        if (!ListUtils.isEmpty(resourceIds)){
            resourceDTOMap = resourceConsr.mapByIds(resourceIds);
        }
        for (SelfRobotKeyword selfRobotKeyword:selfRobotKeywords){
            List<SelfRobotKeywordReply> replyList = selfRobotKeywordReplyDao.getListByKeywordId(selfRobotKeyword.getId());
            if (ListUtils.isEmpty(replyList)){
                continue;
            }
            for (SelfRobotKeywordReply keywordReply : replyList){
                Integer type=keywordReply.getType();
                if (ReplyTypeEnum.APP.value.equals(type)){
                    Long serveId=keywordReply.getServeId();
                    if (AppAndProductTypeEnum.APP.value.equals(keywordReply.getServeType())){
                        AppDto appDto=appDtoMap.get(serveId);
                        if (appDto!=null){
                            keywordReply.setServePic(appDto.getSquareImg());
                            keywordReply.setServeName(appDto.getTitle());
                            keywordReply.setServeTypeCode(appDto.getTypeCode());
                            keywordReply.setServeTypeName(appDto.getTypeName());
                        }
                    }
                    if (AppAndProductTypeEnum.PRODUCT.value.equals(keywordReply.getServeType())){
                        ProductDto productDto=productDtoMap.get(serveId);
                        if (productDto!=null){
                            keywordReply.setServePic(productDto.getCoverImg());
                            keywordReply.setServeName(productDto.getProductName());
                            ProductTypeDto productTypeDto = productDto.getProductTypeDto();
                            if (productTypeDto!=null){
                                keywordReply.setServeTypeCode(productTypeDto.getTypeCode());
                                keywordReply.setServeTypeName(productTypeDto.getTypeName());
                            }
                        }
                    }
                }
                if (ReplyTypeEnum.RESOURCE.value.equals(type)){
                    ResourceDTO resourceDTO = resourceDTOMap.get(keywordReply.getResourceId());
                    if (resourceDTO!=null){
                        keywordReply.setResourceName(resourceDTO.getResourceName());
                        keywordReply.setResourceUrl(resourceDTO.getFileUrl());
                        keywordReply.setResourceTypeCode(resourceDTO.getTypeCode());
                        keywordReply.setResourceTypeName(resourceDTO.getTypeName());
                        keywordReply.setFileType(resourceDTO.getFileType());
                        keywordReply.setResourcePdfItems(resourceDTO.getResourcePdfItems());
                        keywordReply.setResourceOfficeItemDTOs(resourceDTO.getResourceOfficeItemDTOs());
                    }
                }
            }
            selfRobotKeyword.setKeywordReplyList(replyList);
        }
    }


    @ParamLog("批量新增个人号关键词参数校验")
    private void checkBatchAddSelfRobotKeyword(List<SelfRobotKeyword> selfRobotKeywords) {
        if (ListUtils.isEmpty(selfRobotKeywords)) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数为空！");
        }
        List<Long> bookGroupIds = selfRobotKeywords.stream().map(SelfRobotKeyword::getBookGroupId).distinct().collect(Collectors.toList());
        List<SelfRobotKeyword> list = selfRobotKeywordDao.getListByBookGroupIds(bookGroupIds);
        Map<Long,List<SelfRobotKeyword>> map=new HashMap<>();
        if (!ListUtils.isEmpty(list)){
            map=list.stream().filter(s->s.getBookGroupId()!=null).collect(Collectors.groupingBy(SelfRobotKeyword::getBookGroupId));
        }
        for (SelfRobotKeyword selfRobotKeyword : selfRobotKeywords) {
            checkAddSelfRobotKeyword(selfRobotKeyword);
            List<SelfRobotKeyword> keywordList = map.get(selfRobotKeyword.getBookGroupId());
            if (!ListUtils.isEmpty(keywordList)){
                List<String> keywords=keywordList.stream().map(SelfRobotKeyword::getKeyword).collect(Collectors.toList());
                if (!ListUtils.isEmpty(keywords)){
                    if (keywords.contains(selfRobotKeyword.getKeyword())){
                        throw new BookBizException(BookBizException.PARAM_IS_ERROR, "关键词不能重复！");
                    }
                }
            }
        }
    }

    @ParamLog("更新个人号关键词校验")
    private void checkUpdateSelfRobotKeyword(SelfRobotKeyword selfRobotKeyword){
        if (selfRobotKeyword==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数为空！");
        }
        if (selfRobotKeyword.getId()==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "id不能为空！");
        }
        List<SelfRobotKeyword> keywords = selfRobotKeywordDao.getListByBookGroupId(selfRobotKeyword.getBookGroupId());
        if (!ListUtils.isEmpty(keywords)){
            for (SelfRobotKeyword robotKeyword:keywords){
                if (!robotKeyword.getId().equals(selfRobotKeyword.getId())
                        &&robotKeyword.getKeyword().equals(selfRobotKeyword.getKeyword())){
                    throw new BookBizException(BookBizException.PARAM_IS_ERROR, "关键词不能重复！");
                }
            }
        }
        checkAddSelfRobotKeyword(selfRobotKeyword);
    }

    @ParamLog("校验新增个人号关键词")
    private void checkAddSelfRobotKeyword(SelfRobotKeyword selfRobotKeyword){
        if (selfRobotKeyword==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数为空！");
        }
        if (selfRobotKeyword.getBookGroupId() == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "社群码id不能为空！");
        }
        if (ListUtils.isEmpty(selfRobotKeyword.getKeywordReplyList())) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "回复不能为空！");
        }
        if (StringUtil.isEmpty(selfRobotKeyword.getKeyword())) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "关键词不能为空！");
        }
        for (SelfRobotKeywordReply selfRobotKeywordReply: selfRobotKeyword.getKeywordReplyList()){
            if (null == selfRobotKeywordReply.getType()){
                throw new BookBizException(BookBizException.PARAM_IS_ERROR, "回复类型不能为空！");
            }
            Integer type = selfRobotKeywordReply.getType();
            if (ReplyTypeEnum.TEXT.value.equals(type) && StringUtil.isEmpty(selfRobotKeywordReply.getContent())) {
                throw new BookBizException(BookBizException.PARAM_IS_ERROR, "内容不能为空！");
            }
            if (ReplyTypeEnum.IMAGE.value.equals(type) && StringUtil.isEmpty(selfRobotKeywordReply.getPicUrl())) {
                throw new BookBizException(BookBizException.PARAM_IS_ERROR, "图片地址不能为空！");
            }
            if (ReplyTypeEnum.LINK.value.equals(type) && StringUtil.isEmpty(selfRobotKeywordReply.getLinkUrl())) {
                throw new BookBizException(BookBizException.PARAM_IS_ERROR, "链接地址不能为空！");
            }
            if (ReplyTypeEnum.APP.value.equals(type) && (StringUtil.isEmpty(selfRobotKeywordReply.getServeType()) || selfRobotKeywordReply.getServeId() == null)) {
                throw new BookBizException(BookBizException.PARAM_IS_ERROR, "应用或作品id和类型不能为空！");
            }
            if (ReplyTypeEnum.RESOURCE.value.equals(type) && selfRobotKeywordReply.getResourceId() == null) {
                throw new BookBizException(BookBizException.PARAM_IS_ERROR, "资源id和连接不能为空！");
            }
        }
    }
}
