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

import com.alibaba.fastjson.JSONObject;
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.common.ExportConsr;
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.SelfRobotBookRecordDao;
import com.pcloud.book.keywords.dao.SelfRobotGuideDao;
import com.pcloud.book.keywords.dao.SelfRobotKeywordDao;
import com.pcloud.book.keywords.dao.SelfRobotKeywordReplyDao;
import com.pcloud.book.keywords.dto.MaxSeqNAndBGDTO;
import com.pcloud.book.keywords.dto.SelfRobotBookRecordDTO;
import com.pcloud.book.keywords.entity.*;
import com.pcloud.book.keywords.enums.ReplyTypeEnum;
import com.pcloud.book.keywords.mapper.TempRobotSkillDao;
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.personal.dao.PcloudSkillRecordDao;
import com.pcloud.book.personal.entity.PcloudSkillRecord;
import com.pcloud.book.skill.biz.PcloudGroupActivityBiz;
import com.pcloud.book.skill.biz.PcloudSubRemindBiz;
import com.pcloud.book.skill.biz.impl.PcloudSkillBizImpl;
import com.pcloud.book.skill.dao.PcloudGroupActivityDao;
import com.pcloud.book.skill.dao.PcloudResourceDao;
import com.pcloud.book.skill.dao.PcloudSkillDao;
import com.pcloud.book.skill.dao.PcloudSubRemindDao;
import com.pcloud.book.skill.entity.PcloudGroupActivity;
import com.pcloud.book.skill.entity.PcloudSkill;
import com.pcloud.book.skill.entity.PcloudSubRemind;
import com.pcloud.book.skill.enums.SkillTypeEnum;
import com.pcloud.book.skill.enums.SubTypeEnum;
import com.pcloud.book.skill.facade.response.QueryPcloudResponseVO;
import com.pcloud.book.timecontrol.biz.TaskBiz;
import com.pcloud.book.timecontrol.biz.TaskSubscribeBiz;
import com.pcloud.book.timecontrol.entity.TimeControlTaskSubscribe;
import com.pcloud.book.timecontrol.mapper.TimeControlTaskSubscribeMapper;
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.core.biz.MessageBiz;
import com.pcloud.common.core.dto.SendNotifyDto;
import com.pcloud.common.core.enums.NotifyOriginTypeEnum;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.DateUtils;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.ResponseHandleUtil;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.common.utils.string.StringUtilParent;
import com.pcloud.contentcenter.resource.dto.ResourceDTO;
import com.pcloud.labelcenter.label.service.LabelService;
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.group.dto.GroupUserDTO;
import com.pcloud.book.timecontrol.dto.TaskDto;
import com.sdk.wxgroup.SendFileVO;
import com.sdk.wxgroup.SendMessageTypeEnum;
import com.sdk.wxgroup.SendPicMessageVO;
import com.sdk.wxgroup.SendTextMessageVO;
import com.sdk.wxgroup.WxGroupSDK;
import lombok.extern.slf4j.Slf4j;
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.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
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")
@Slf4j
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 TaskBiz taskBiz;
    @Autowired
    private TempRobotSkillDao tempRobotSkillDao;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private WeixinQrcodeGenerationDao weixinQrcodeGenerationDao;
    @Autowired
    private SelfRobotGuideDao selfRobotGuideDao;
    @Autowired
    private SelfRobotBookRecordDao selfRobotBookRecordDao;
    @Autowired
    private ExportConsr exportConsr;
    @Autowired
    private MessageBiz messageBiz;
    @Autowired
    private PcloudSkillDao pcloudSkillDao;
    @Autowired
    private LabelService labelService;
    @Autowired
    private PcloudGroupActivityDao pcloudGroupActivityDao;
    @Autowired
    private PcloudResourceDao pcloudResourceDao;
    @Autowired
    private TaskSubscribeBiz taskSubscribeBiz;
    @Autowired
    private PcloudGroupActivityBiz pcloudGroupActivityBiz;
    @Autowired
    private PcloudSkillBizImpl pcloudSkillBiz;
    @Autowired
    private TimeControlTaskSubscribeMapper timeControlTaskSubscribeMapper;
    @Autowired
    private PcloudSubRemindBiz pcloudSubRemindBiz;
    @Autowired
    private PcloudSubRemindDao pcloudSubRemindDao;
    @Autowired
    private PcloudSkillRecordDao pcloudSkillRecordDao;



    @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);
            List<SelfRobotGuide> guides = selfRobotKeyword.getGuideList();
            if (!ListUtils.isEmpty(guides)){
               guides.forEach(selfRobotGuide -> {
                   selfRobotGuide.setKeywordId(keywordId);
                   selfRobotGuide.setCreateUser(partyId);
               });
            }
            selfRobotGuideDao.insert(guides);
        }
        //将作品应用关键词加到社群书应用
        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);
        selfRobotGuideDao.deleteByKeywordId(selfRobotKeyword.getId());
        List<SelfRobotGuide> guides = selfRobotKeyword.getGuideList();
        if (!ListUtils.isEmpty(guides)){
            guides.forEach(selfRobotGuide -> {
                selfRobotGuide.setKeywordId(selfRobotKeyword.getId());
                selfRobotGuide.setCreateUser(partyId);
            });
        }
        selfRobotGuideDao.insert(guides);
        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);
        selfRobotGuideDao.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
    @ParamLog(value = "根据类型获取引导语列表",isAfterReturn = false)
    public List<RobotSkill4H5> getGuideWordListByType(Integer type, Long labelId, String wxUserId) {
        List<GuideWordVO> list = new ArrayList<>();
        if (null == type){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"type为空");
        }
        List<RobotSkill4H5> skillList = null;
        if (type.equals(1)){
            //读书计划
            skillList = pcloudSkillDao.getSkillList4TimeController(type,labelId,wxUserId);
            if (!ListUtils.isEmpty(skillList) && null != labelId){
                setSubscribeState(skillList,wxUserId);
            }
        }else  if (type.equals(2)){
            //共读活动
            skillList = pcloudSkillDao.getSkillList4Activity(type,labelId);
        }else if (type.equals(3)){
            //配套资料
            skillList = pcloudSkillDao.getSkillList4Resource(type,labelId);
        }

        // 截取字符串
        if(!ListUtils.isEmpty(skillList)){
            for(RobotSkill4H5 robotSkill4H5 : skillList){
                String filterStr = StringUtilParent.replaceHtml(robotSkill4H5.getRelSkillIntroduce());
                String subStr = filterStr.length() > 100 ? filterStr.substring(0, 100) + "..." : filterStr;
                robotSkill4H5.setRelSkillIntroduce(subStr);
            }
        }

        return skillList;
    }

    private void setSubscribeState(List<RobotSkill4H5> skillList, String wxUserId) {
        skillList.stream().forEach(e ->{
            TimeControlTaskSubscribe timeControlTaskSubscribe = timeControlTaskSubscribeMapper.getSubscribe(wxUserId,null,e.getRelSkillId());
            if (null != timeControlTaskSubscribe){
                e.setState(timeControlTaskSubscribe.getState());
            }else {
                e.setState(0);
            }
        });

    }


    @Override
    public List<LabelVO> listLabelByType(Integer type) {
        List<LabelVO> list = new ArrayList<>();
        if (null == type){
            throw new BookBizException(BookBizException.PARAM_IS_NULL,"type为空");
        }
        List<Long> labelIds = new ArrayList<>();
        if (type == 1){
            //时间管理
            labelIds = pcloudSkillDao.getLabelList4TimeController(type);
        }
        if (type == 2) {
            //共读活动
            labelIds = pcloudSkillDao.getLabelList4Activity(type);
        }
        if (type == 3){
            //配套资料
            labelIds = pcloudSkillDao.getLabelList4Resource(type);
        }
        if (!ListUtils.isEmpty(labelIds)){
            labelIds.forEach(depLabelId -> {
                LabelVO labelVO = new LabelVO();
                labelVO.setLabelId(depLabelId);
                String labelName = ResponseHandleUtil.parseResponse(labelService.getLabelName(depLabelId), String.class);
                labelVO.setLabelName(labelName);
                list.add(labelVO);
            });
        }
        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 = taskBiz.listTaskByLabelIds4User(wxUserId, labelId);
            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 = taskBiz.listTaskByKey4User(wxUserId, keyWord);
            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 = taskBiz.listTaskByIds4User(wxUserId, taskIds);
            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);
        }
    }

    @Override
    public List<SelfRobotKeyword> getListByBookGroupId(Long bookGroupId) {
        List<SelfRobotKeyword> list = selfRobotKeywordDao.getListByBookGroupId(bookGroupId);
        if (!ListUtils.isEmpty(list)){
            for (SelfRobotKeyword keyword : list){
                List<SelfRobotGuide> guides = selfRobotGuideDao.getListByKeywordId(keyword.getId());
                if (!ListUtils.isEmpty(guides)){
                    keyword.setGuideList(guides);
                }
            }
        }
        return list;
    }

    @Override
    public Boolean hasKeyword(Long bookGroupId) {
        List<SelfRobotKeyword> list = selfRobotKeywordDao.getListByBookGroupId(bookGroupId);
        if (ListUtils.isEmpty(list)){
            return false;
        }else {
            return true;
        }
    }

    @Override
    public SelfRobotKeyword getById(Long id) {
        SelfRobotKeyword keyword = selfRobotKeywordDao.getById(id);
        if (null == keyword){
            return new SelfRobotKeyword();
        }
        fillSelfRobotKeyword(Arrays.asList(keyword));
        return keyword;
    }

    @Override
    public RobotSkillDetail getSkillDetail(Integer type, Integer relSkillId, String wxUserId,String robotWxId,Integer skillId) {
        if (null == type || null == relSkillId){
            throw new BizException(BizException.PARAM_IS_NULL.getCode(),"type为空或者relSkillId为空");
        }
        RobotSkillDetail robotSkillDetail = new RobotSkillDetail();
        if (SkillTypeEnum.TIME_MANAGE.value == type){
            TaskDto taskDto  = taskBiz.getTaskById(relSkillId);
            if (null != taskDto){
                TimeControlTaskSubscribe timeControlTaskSubscribe  = timeControlTaskSubscribeMapper.getSubscribe(wxUserId,null,relSkillId);
                if (null != timeControlTaskSubscribe){
                    robotSkillDetail.setState(timeControlTaskSubscribe.getState());
                }else {
                    robotSkillDetail.setState(0);
                }
                robotSkillDetail.setRelSkillId(taskDto.getTaskId());
                robotSkillDetail.setRelSkillName(taskDto.getTaskName());
                robotSkillDetail.setRelSkillIntroduce(taskDto.getTaskIntroduce());
            }
        }else if (SkillTypeEnum.READING.value == type){
            PcloudGroupActivity pcloudGroupActivity = pcloudGroupActivityDao.getById(relSkillId);
            if (null != pcloudGroupActivity){
                robotSkillDetail.setRelSkillId(Integer.valueOf(pcloudGroupActivity.getId().toString()));
                robotSkillDetail.setRelSkillName(pcloudGroupActivity.getName());
                robotSkillDetail.setRelSkillIntroduce(pcloudGroupActivity.getDesc());
            }
        }else if (SkillTypeEnum.RESOURCE.value == type){
            QueryPcloudResponseVO queryPcloudResponseVO = pcloudResourceDao.getPcloudResource(Long.valueOf(relSkillId.toString()));
            if (null != queryPcloudResponseVO){
                robotSkillDetail.setRelSkillId(Integer.valueOf(queryPcloudResponseVO.getId().toString()));
                robotSkillDetail.setRelSkillName(queryPcloudResponseVO.getName());
                robotSkillDetail.setRelSkillIntroduce(queryPcloudResponseVO.getDescription());
            }

        }
        //新增技能获取记录
        PcloudSkillRecord pcloudSkillRecord = pcloudSkillRecordDao.getBySkillIdAndWxId(skillId, wxUserId);
        if (null == pcloudSkillRecord) {
            PcloudSkillRecord pcloudSkillRecordNew = new PcloudSkillRecord();
            if (SkillTypeEnum.TIME_MANAGE.value == type){
                //先查询订阅状态
                TimeControlTaskSubscribe timeControlTaskSubscribe =  taskSubscribeBiz.getSubscribeState(wxUserId,relSkillId);
                if (null != timeControlTaskSubscribe){
                    pcloudSkillRecordNew.setState(timeControlTaskSubscribe.getState());
                }else {
                    pcloudSkillRecordNew.setState(0);
                }
            }else if (SkillTypeEnum.READING.value == type || SkillTypeEnum.RESOURCE.value == type){
                pcloudSkillRecordNew.setState(0);
            }
            pcloudSkillRecordNew.setRobotWxId(robotWxId);
            pcloudSkillRecordNew.setWxUserId(wxUserId);
            pcloudSkillRecordNew.setSkillId(skillId);
            pcloudSkillRecordNew.setSkillType(type);
            pcloudSkillRecordNew.setCreateTime(new Date());
            pcloudSkillRecordNew.setUpdateTime(new Date());
            pcloudSkillRecordDao.insertSelective(pcloudSkillRecordNew);
        }else {
            if (SkillTypeEnum.TIME_MANAGE.value == type){
                if (SubTypeEnum.CANCEL.value == pcloudSkillRecord.getState()){
                    pcloudSkillRecord.setState(0);
                }
            }
            pcloudSkillRecord.setUpdateTime(new Date());
            pcloudSkillRecordDao.updateByPrimaryKeySelective(pcloudSkillRecord);
        }
        PcloudSubRemind pcloudSubRemind = pcloudSubRemindDao.getByMap(relSkillId, type, wxUserId, skillId);
        if(null==pcloudSubRemind) {
            PcloudSubRemind subRemind = new PcloudSubRemind();
            subRemind.setCreateTime(new Date());
            subRemind.setRelSkillId(relSkillId);
            subRemind.setRobotWxId(robotWxId);
            subRemind.setSkillType(type);
            subRemind.setSubscribeState(0);
            subRemind.setWxUserId(wxUserId);
            subRemind.setSkillId(Long.valueOf(skillId));
            pcloudSubRemindDao.insert(subRemind);
        }

        if (null != robotSkillDetail) {
            String filterStr = StringUtilParent.replaceHtml(robotSkillDetail.getRelSkillIntroduce());
            robotSkillDetail.setCutRelSkillIntroduce(filterStr);
        }
        return robotSkillDetail;
    }

    @Override
    @ParamLog("确认任务")
    public String confirmSkill(Integer id, Integer type, Integer relSkillId, String robotId, String wxUserId, Integer state) {
        if (null == type || null == relSkillId || null == robotId || null == wxUserId){
            throw new BizException(BizException.PARAM_IS_NULL.getCode(),"type为空或者relSkillId为空");
        }
        String skillFuseReply = null;
        PcloudSkill pcloudSkill = pcloudSkillDao.getById(id);
        if (null != pcloudSkill){
            skillFuseReply = pcloudSkill.getSkillFuseReply();
        }

        if (SkillTypeEnum.TIME_MANAGE.value == type){
            //读书计划 确认某个读书计划
            if (null == state){
                taskSubscribeBiz.subscribeTask(wxUserId,null,relSkillId,robotId);
            }else {
                if (SubTypeEnum.SUCCESS.value == state){
                    taskSubscribeBiz.subscribeTask(wxUserId,null,relSkillId,robotId);
                }else if (SubTypeEnum.CANCEL.value == state){
                    taskSubscribeBiz.unSubscribeTask(wxUserId,null,relSkillId);
                }
            }
        }else if (SkillTypeEnum.READING.value == type){
            pcloudGroupActivityBiz.processGroup(wxUserId,robotId,Long.valueOf(relSkillId.toString()));
            pcloudSkillBiz.sendResource(id,wxUserId,robotId,relSkillId);
        }else if (SkillTypeEnum.RESOURCE.value == type){
            pcloudSkillBiz.sendResource(id,wxUserId,robotId,relSkillId);
        }
            //修改pcloud_skill_record 状态值
        if (SkillTypeEnum.READING.value == type || SkillTypeEnum.RESOURCE.value == type){
            state = SubTypeEnum.SUCCESS.value;
            pcloudSkillRecordDao.updateState4ResourceAndActivity(wxUserId,robotId,id,state);
        }
            //修改pcloud_sub_remind 未订阅提醒表状态
       pcloudSubRemindBiz.updateSubState(relSkillId,type,wxUserId,id);
       return skillFuseReply;
    }

    @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<SelfRobotGuide> guides = selfRobotGuideDao.getListByKeywordId(selfRobotKeyword.getId());
            if (!ListUtils.isEmpty(guides)){
                selfRobotKeyword.setGuideList(guides);
            }
            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和连接不能为空！");
            }
        }
    }

    @Override
    public PageBeanNew<SelfRobotBookRecordDTO> getSelfRobotBookRecordList(Integer currentPage, Integer numPerPage) {
        PageBeanNew<SelfRobotBookRecordDTO> pageBeanNew = selfRobotBookRecordDao.listPageNew(new PageParam(currentPage, numPerPage), null, "getSelfRobotBookRecordList");
        List<SelfRobotBookRecordDTO> recordList = pageBeanNew.getRecordList();
        if(!ListUtils.isEmpty(recordList)){
            List<String> collect = recordList.stream().map(x -> x.getWxUserId()).distinct().collect(Collectors.toList());
            Map<String, GroupUserDTO> userDTOMap = wechatGroupConsr.mapWxUserInfoByWxIdList(collect);
            if(MapUtils.isNotEmpty(userDTOMap)){
                GroupUserDTO groupUserDTO;
                for (SelfRobotBookRecordDTO selfRobotBookRecordDTO : recordList){
                    //用户信息
                    if (userDTOMap.containsKey(selfRobotBookRecordDTO.getWxUserId())) {
                        groupUserDTO = userDTOMap.get(selfRobotBookRecordDTO.getWxUserId());
                        selfRobotBookRecordDTO.setNickName(groupUserDTO.getNickName());
                        selfRobotBookRecordDTO.setHeadPic(groupUserDTO.getHeadPic());
                        selfRobotBookRecordDTO.setSex(groupUserDTO.getSex());
                    }
                }
            }
        }
        return pageBeanNew;
    }

    @Override
    public void exportSelfRobotBookRecord(String systemCode, Long partyId) {
        List<SelfRobotBookRecordDTO> list = selfRobotBookRecordDao.getAllSelfRobotBookRecordList();
        if(ListUtils.isEmpty(list)) {
            return;
        }
        List<String> collect = list.stream().map(x -> x.getWxUserId()).distinct().collect(Collectors.toList());
        Map<String, GroupUserDTO> userDTOMap = wechatGroupConsr.mapWxUserInfoByWxIdList(collect);
        if(MapUtils.isNotEmpty(userDTOMap)){
            GroupUserDTO groupUserDTO;
            for (SelfRobotBookRecordDTO selfRobotBookRecordDTO : list){
                //用户信息
                if (userDTOMap.containsKey(selfRobotBookRecordDTO.getWxUserId())) {
                    groupUserDTO = userDTOMap.get(selfRobotBookRecordDTO.getWxUserId());
                    selfRobotBookRecordDTO.setNickName(groupUserDTO.getNickName());
                    selfRobotBookRecordDTO.setHeadPic(groupUserDTO.getHeadPic());
                    selfRobotBookRecordDTO.setSex(groupUserDTO.getSex());
                }
            }
        }
        ThreadPoolUtils.EXPORT_THREAD_POOL.execute(() -> {
            String fileName = "用户书刊信息收录导出_" + DateUtils.getShortDateStr();
            String zipTitle = "用户书刊信息收录导出__" + DateUtils.getShortDateStr();
            Boolean isSuccess = true;
            String fileUrl = "";
            try {
                fileUrl = getExcelUrl4SelfRobotBookRecord(list, fileName);
            } catch (Exception e) {
                log.error("生成导出文件失败" + e.getMessage(), e);
                isSuccess = false;
            }
            // 发送消息
            if (isSuccess) {
                sendNotify(systemCode, partyId, fileUrl, zipTitle);
            }
        });
    }

    /**
     * 发送站内信
     */
    private void sendNotify(String systemCode, Long partyId, String fileUrl, String fileName) {
        JSONObject content = new JSONObject();
        content.put("commitTime", DateUtils.formatDate(new Date()));
        content.put("type", "书刊收录信息导出");
        SendNotifyDto sendNotifyDto = new SendNotifyDto();
        sendNotifyDto.setCreatedTime(new Date());
        sendNotifyDto.setFromId(partyId);
        sendNotifyDto.setToId(partyId);
        sendNotifyDto.setNotifyContent(content.toJSONString());
        sendNotifyDto.setSystemCode(systemCode);
        sendNotifyDto.setTypeCode("wechat_learn_export");
        sendNotifyDto.setResourceId(fileUrl);
        sendNotifyDto.setFileName(fileName);
        sendNotifyDto.setOriginType(NotifyOriginTypeEnum.BOOK_GROUP.value);
        try {
            messageBiz.sendLetter(sendNotifyDto);
        } catch (Exception e) {
            log.error("【站内信(消)】发送站内信.[sendLetter]:" + e.getMessage(), e);
        }
    }

    private String getExcelUrl4SelfRobotBookRecord(List<SelfRobotBookRecordDTO> list, String fileName) {
        // 字段名
        String[] rowsName = {"编号","读者信息", "书刊名称", "出版社", "书刊状态", "读者输入时间"};
        List<Object[]> dataList = new ArrayList<>();
        Object[] objs;
        for (int i = 0; i < list.size(); i++) {
            SelfRobotBookRecordDTO selfRobotBookRecordDTO = list.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = !StringUtil.isEmpty(selfRobotBookRecordDTO.getNickName()) ? selfRobotBookRecordDTO.getNickName() : "--";
            objs[2] = !StringUtil.isEmpty(selfRobotBookRecordDTO.getBookName()) ? selfRobotBookRecordDTO.getBookName() : "--";
            objs[3] = !StringUtil.isEmpty(selfRobotBookRecordDTO.getAgentName()) ? selfRobotBookRecordDTO.getAgentName() : "--";
             String bookStatus = null;
           switch (selfRobotBookRecordDTO.getStatus()){
               case  1 : bookStatus = "已收录未配置资源";break;
               case  2 : bookStatus = "未收录";break;
               case  3 : bookStatus = "已收录有资源";
           }
            objs[4] = !StringUtil.isEmpty(bookStatus) ? bookStatus : "--";
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            objs[5] = (selfRobotBookRecordDTO.getCreateTime() != null ? simpleDateFormat.format(selfRobotBookRecordDTO.getCreateTime()) : "--");
            dataList.add(objs);
        }
        String fileUrl = exportConsr.exportExcel(fileName, rowsName, dataList);
        return  fileUrl;

    }
}
