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

import cn.hutool.core.util.RandomUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pcloud.appcenter.assist.dto.AssistTempletDTO;
import com.pcloud.book.applet.biz.AppletGroupSearchRecordBiz;
import com.pcloud.book.applet.dao.AppletLinkClickDao;
import com.pcloud.book.applet.biz.AppletNewsBiz;
import com.pcloud.book.applet.dto.AppletGroupManageDTO;
import com.pcloud.book.applet.dto.AppletGroupStatementDTO;
import com.pcloud.book.applet.enums.AppletRecordTypeEnum;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.book.biz.BookBiz;
import com.pcloud.book.book.dao.BookDao;
import com.pcloud.book.book.dao.BookLabelDao;
import com.pcloud.book.book.dto.BookDto;
import com.pcloud.book.book.entity.BookLabel;
import com.pcloud.book.consumer.app.AssistTempletConsr;
import com.pcloud.book.consumer.label.LabelConsr;
import com.pcloud.book.consumer.reader.ReaderConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.biz.BookGroupBiz;
import com.pcloud.book.group.biz.GroupQrcodeBiz;
import com.pcloud.book.group.dao.BookClassifyBuyRecordDao;
import com.pcloud.book.group.dao.BookQrcodeUserDao;
import com.pcloud.book.group.vo.ClassifyQrcodeVO;
import com.pcloud.book.reading.biz.ReadingActivityBiz;
import com.pcloud.book.record.biz.BookBrowseRecordBiz;
import com.pcloud.book.record.entity.RegionMap;
import com.pcloud.book.rightsSetting.biz.RightsSettingBiz;
import com.pcloud.book.rightsSetting.dao.RightsNowItemDao;
import com.pcloud.book.rightsSetting.dao.RightsSettingItemDetailDao;
import com.pcloud.book.rightsSetting.entity.BaseTempletClassify;
import com.pcloud.book.rightsSetting.entity.RightsNowItem;
import com.pcloud.book.rightsSetting.entity.RightsSettingItemDetail;
import com.pcloud.book.rightsSetting.entity.RightsSettingTitle;
import com.pcloud.book.rightsSetting.enums.RightsNowItemTypeNew;
import com.pcloud.book.rightsSetting.mapper.RightsSettingTitleMapper;
import com.pcloud.book.skill.biz.PcloudGroupActivityBiz;
import com.pcloud.book.skill.dao.PcloudGroupActivityDao;
import com.pcloud.book.skill.dao.PcloudSkillDao;
import com.pcloud.book.applet.dto.GroupActivity4AppletDTO;
import com.pcloud.book.skill.dto.UpdateActivityShowStateDTO;
import com.pcloud.book.skill.entity.PcloudGroupActivity;
import com.pcloud.book.skill.entity.PcloudSkill;
import com.pcloud.book.skill.enums.ActivityGroupTypeEnum;
import com.pcloud.book.skill.enums.SkillTypeEnum;
import com.pcloud.book.skill.enums.GroupUpdateTypeEnum;
import com.pcloud.book.skill.facade.request.GroupActivityClassifyVO;
import com.pcloud.book.skill.facade.request.GroupActivityShowStateVO;
import com.pcloud.book.skill.facade.request.SaveGroupActivityRequestVO;
import com.pcloud.book.skill.facade.request.UpdateGroupActivityRequestVO;
import com.pcloud.book.skill.facade.response.ListGroupActivityResponseVO;
import com.pcloud.book.skill.facade.response.QueryGroupActivityResponseVO;
import com.pcloud.book.util.common.YesOrNoEnums;
import com.pcloud.common.constant.CacheConstant;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.NumberUtil;
import com.pcloud.common.utils.QrcodeUtils;
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.common.utils.string.StringUtilParent;
import com.pcloud.readercenter.common.enums.YesOrNoNumEnum;
import com.pcloud.usercenter.party.adviser.service.AdviserService;
import com.pcloud.usercenter.party.agent.service.AgentService;
import com.sdk.wxgroup.RobotProcessTypeEnum;
import com.sdk.wxgroup.SendGroupInviteVO;
import com.sdk.wxgroup.SendPicMessageVO;

import java.util.Arrays;
import java.util.Iterator;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.UUID;
import java.util.stream.Collectors;

@Slf4j
@Service
public class PcloudGroupActivityBizImpl implements PcloudGroupActivityBiz {

    @Resource
    private PcloudSkillDao pcloudSkillDao;
    @Resource
    private PcloudGroupActivityDao pcloudGroupActivityDao;
    @Resource
    private GroupQrcodeBiz groupQrcodeBiz;
    @Resource
    private ReadingActivityBiz readingActivityBiz;
    @Resource
    private LabelConsr labelConsr;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private RightsSettingBiz rightsSettingBiz;
    @Autowired
    private ReaderConsr readerConsr;
    @Autowired
    private BookLabelDao bookLabelDao;
    @Autowired
    private AssistTempletConsr assistTempletConsr;
    @Autowired
    private BookBiz bookBiz;
    @Autowired
    private RightsSettingTitleMapper rightsSettingTitleMapper;
    @Autowired
    private AppletGroupSearchRecordBiz appletGroupSearchRecordBiz;
    @Value("${wechat.group.link.prefix}")
    private String wechatGroupLinkPrefix;
    @Autowired
    private BookDao bookDao;
    @Autowired
    private BookClassifyBuyRecordDao bookClassifyBuyRecordDao;
    private BookQrcodeUserDao bookQrcodeUserDao;
    @Autowired
    private AdviserService adviserService;
    @Autowired
    private AgentService agentService;
    @Autowired
    private RightsNowItemDao rightsNowItemDao;
    @Autowired
    private RightsSettingItemDetailDao rightsSettingItemDetailDao;
    @Autowired
    private BookBrowseRecordBiz bookBrowseRecordBiz;
    @Autowired
    private BookGroupBiz bookGroupBiz;
    @Autowired
    private AppletNewsBiz appletNewsBiz;
    @Autowired
    private AppletLinkClickDao appletLinkClickDao;

    @ParamLog("批量分类")
    @Override
    public void batchUpdateClassify(GroupActivityClassifyVO groupActivityClassifyVO) {
        if (groupActivityClassifyVO == null || ListUtils.isEmpty(groupActivityClassifyVO.getIds())) {
            throw new BizException(BizException.PARAM_IS_NULL.getCode(), "参数为空");
        }
        if (!NumberUtil.isNumber(groupActivityClassifyVO.getFirstClassify())) {
            throw new BizException(BizException.PARAM_IS_NULL.getCode(), "请选择一级分类");
        }
        rightsSettingBiz.setClassifyAndLabel(groupActivityClassifyVO);
        pcloudGroupActivityDao.batchUpdateShowState(groupActivityClassifyVO);
    }


    @ParamLog("批量上下架")
    @Override
    public void batchUpdateShowState(GroupActivityShowStateVO groupActivityShowStateVO) {
        pcloudGroupActivityDao.batchUpdateShowState(groupActivityShowStateVO);
        readerConsr.deleteGroupRecore(groupActivityShowStateVO.getIds(), ActivityGroupTypeEnum.THIRD_GROUP.value, GroupUpdateTypeEnum.UPDATE.value, groupActivityShowStateVO.getShowState() ? 1 : 0);
        if (!groupActivityShowStateVO.getShowState()) {
            deleteInvalidGroupIds(groupActivityShowStateVO.getIds());
        }
    }

    @ParamLog("批量删除共读模板")
    @Override
    public void deleteByIds(List<Long> ids) {
        if (ListUtils.isEmpty(ids)) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数有误！");
        }
        pcloudGroupActivityDao.deleteByIds(ids);
        readerConsr.deleteGroupRecore(ids, ActivityGroupTypeEnum.THIRD_GROUP.value, GroupUpdateTypeEnum.DELETE.value, null);
        deleteInvalidGroupIds(ids);
    }


    @ParamLog("保存共读活动")
    @Override
    public void saveGroupActivity(SaveGroupActivityRequestVO vo) {
        if (null == vo.getAgentId()){
            vo.setAgentId(0L);
        }
        //校验编号是否重复
        if(!StringUtil.isEmpty(vo.getNumber())){
            Integer count = pcloudGroupActivityDao.getCountByNumber(vo.getNumber(),vo.getAgentId());
            if (count>0){
                throw new BookBizException(BookBizException.PARAM_IS_ERROR,"参数有误，编号已存在！");
            }
        }

        vo.checkParam();
        PcloudGroupActivity entity = vo.getEntity();
        Date now = new Date();
        entity.setCreateUser(vo.getUserId());
        entity.setCreateTime(now);
        entity.setUpdateUser(vo.getUserId());
        entity.setUpdateTime(now);
        entity.setIsDelete(0);
        entity.setAgentId(vo.getAgentId());
        rightsSettingBiz.setClassifyAndLabel(entity);
        pcloudGroupActivityDao.insert(entity);

    }

    @Override
    public void updateGroupActivity(UpdateGroupActivityRequestVO vo) {
        vo.checkParam();

        PcloudGroupActivity activity = pcloudGroupActivityDao.getById(vo.getId());
        if (null == activity) {
            throw new BookBizException(BookBizException.ID_NOT_EXIST, "共读活动不存在");
        }

        //校验编号是否重复
        if(!StringUtil.isEmpty(vo.getNumber())){
            Integer count = pcloudGroupActivityDao.getCountByNumber(vo.getNumber(),activity.getAgentId());
            if (count > 0 && (!vo.getNumber().equals(activity.getNumber()))) {
                throw new BookBizException(BookBizException.PARAM_IS_ERROR, "参数有误，编号已存在！");
            }
        }
        PcloudGroupActivity entity = vo.getEntity();
        Date now = new Date();
        entity.setUpdateUser(vo.getUserId());
        entity.setUpdateTime(now);
        rightsSettingBiz.setClassifyAndLabel(entity);
        if (ActivityGroupTypeEnum.THIRD_GROUP.value.equals(vo.getGroupType()) && !Objects.equals(activity.getGroupExtLink(), entity.getGroupExtLink())) {
            String link = entity.getGroupExtLink();
            String url = QrcodeUtils.create(link);
            entity.setMediaId(activity.getMediaId());
            bookGroupBiz.updateMediaId4Activity(url, entity);
        }
        pcloudGroupActivityDao.updateByPrimaryKeySelective(entity);
    }

    @Override
    public void deleteGroupActivity(Long id, Long partyId) {
        if (Objects.isNull(id)) {
            throw new BookBizException(BookBizException.PARAM_IS_NULL, "该共读活动不存在！");
        }
        PcloudSkill byRelId = pcloudSkillDao.getByRelId(id.intValue(), SkillTypeEnum.READING.value);
        if (Objects.nonNull(byRelId)) {
            throw new BookBizException(BookBizException.PARAM_IS_EXIST, "该共读活动已经关联技能，无法删除！");
        }
        pcloudGroupActivityDao.deleteById(id);
        readerConsr.deleteGroupRecore(Lists.newArrayList(id), ActivityGroupTypeEnum.THIRD_GROUP.value, GroupUpdateTypeEnum.DELETE.value, null);
        deleteInvalidGroupIds(Lists.newArrayList(id));
    }

    @Override
    @ParamLog("[processGroup]")
    public void processGroup(String wxId, String robotWxId, Long id) {
        PcloudGroupActivity byId = pcloudGroupActivityDao.getById(id);
        if (Objects.isNull(byId)) {
            log.error("[processGroup] error 共读不存在");
            return;
        }
        Integer count= 1;
        String messageGroup =  UUID.randomUUID().toString();
        Integer index = 0;
        if (0 == byId.getJoinType()) {
            // 更新获取群二维码的方式
            String groupQrCode = groupQrcodeBiz.getChangeGroupQrCode(byId.getBookGroupClassifyId());
            ClassifyQrcodeVO groupQrcodeInfo = groupQrcodeBiz.getGroupQrcodeInfo(groupQrCode, byId.getBookGroupClassifyId());
            if (Objects.isNull(groupQrcodeInfo)) {
                log.error("[processGroup] error 共读对应社群不存在");
                return;
            }
            SendGroupInviteVO vo = new SendGroupInviteVO();
            vo.setWxId(wxId);
            vo.setAltId(robotWxId);
            vo.setIp(readingActivityBiz.getIP(robotWxId));
            vo.setWxGroupId(groupQrcodeInfo.getWeixinGroupId());
            vo.setCounts(count);
            vo.setMessageGroupId(messageGroup);
            vo.setIndex(index);
            vo.setRobotProcessType(RobotProcessTypeEnum.SKILL_REPLY);
            wechatGroupConsr.sendMessage(JSON.toJSONString(vo));
            log.info("[processGroup] sendGroupInvite:{}", vo);
        }
        if (1 == byId.getJoinType()) {
            SendPicMessageVO vo = new SendPicMessageVO();
            // 更新获取群二维码的方式
            vo.setPicUrl(groupQrcodeBiz.getChangeGroupQrCode(byId.getBookGroupClassifyId()));
            vo.setWxGroupId(wxId);
            vo.setAltId(robotWxId);
            vo.setIp(readingActivityBiz.getIP(robotWxId));
            vo.setCounts(count);
            vo.setMessageGroupId(messageGroup);
            vo.setIndex(index);
            vo.setRobotProcessType(RobotProcessTypeEnum.SKILL_REPLY);
            wechatGroupConsr.sendMessage(JSON.toJSONString(vo));
        }
    }

    @Override
    public PageBeanNew<QueryGroupActivityResponseVO> queryGroupActivity(String name, Long proLabelId, Long purLabelId, Long depLabelId, Integer joinType, Long firstClassify,
                                                                        Long secondClassify, Long thirdClassify,
                                                                        Long gradeLabelId,
                                                                        Long subjectLabelId, Integer numPerPage, Integer currentPage, String cityCode, Long agentId, Integer isChoose) {

        PageParam pageParam = new PageParam(currentPage, numPerPage);
        BaseTempletClassify baseTempletClassify =new BaseTempletClassify();
        baseTempletClassify.setFirstClassify(firstClassify);
        baseTempletClassify.setSecondClassify(secondClassify);
        baseTempletClassify.setThirdClassify(thirdClassify);
        baseTempletClassify.setSubjectLabelId(subjectLabelId);
        baseTempletClassify.setGradeLabelId(gradeLabelId);
        if (null != baseTempletClassify.getFirstClassify()){
            rightsSettingBiz.setClassifyAndLabel(baseTempletClassify);
        }
        Map<String, Object> paraMap = Maps.newHashMap();
        paraMap.put("name", name);
        paraMap.put("proLabelId", proLabelId);
        paraMap.put("purLabelId", purLabelId);
        paraMap.put("depLabelId", depLabelId);
        paraMap.put("joinType", joinType);
        paraMap.put("firstClassify", baseTempletClassify.getFirstClassify());
        paraMap.put("secondClassify", baseTempletClassify.getSecondClassify());
        paraMap.put("thirdClassify", baseTempletClassify.getThirdClassify());
        paraMap.put("gradeLabelId", baseTempletClassify.getGradeLabelId());
        paraMap.put("subjectLabelId", baseTempletClassify.getSubjectLabelId());
        paraMap.put("cityCode", cityCode);
        paraMap.put("agentId", agentId);
        paraMap.put("isChoose", isChoose);
        PageBeanNew<QueryGroupActivityResponseVO> queryGroupActivity = pcloudGroupActivityDao.listPageNew(pageParam, paraMap, "queryGroupActivity");
        if (null == queryGroupActivity || CollectionUtils.isEmpty(queryGroupActivity.getRecordList())) {
            return queryGroupActivity;
        }
        // 组装标签名称
        List<Long> labelId = Lists.newArrayList();
        for (QueryGroupActivityResponseVO responseVO : queryGroupActivity.getRecordList()) {
            labelId.add(responseVO.getProLabelId());
            labelId.add(responseVO.getPurLabelId());
            labelId.add(responseVO.getDepLabelId());
        }
        Map<Long, String> labelName = labelConsr.getLabelName(labelId);
        for (QueryGroupActivityResponseVO responseVO : queryGroupActivity.getRecordList()) {
            responseVO.setPurLabelName(labelName.get(responseVO.getPurLabelId()));
            responseVO.setProLabelName(labelName.get(responseVO.getProLabelId()));
            responseVO.setDepLabelName(labelName.get(responseVO.getDepLabelId()));
        }
        //设置分类名称
        setLabelContent(queryGroupActivity.getRecordList());
        // 处理属性值
        for(QueryGroupActivityResponseVO vo : queryGroupActivity.getRecordList()){
            // 截取字符串
            String filterStr = StringUtilParent.replaceHtml(vo.getDesc());
            String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
            vo.setCutDesc(subStr);
        }
        //设置城市名称
        setCityNames(queryGroupActivity.getRecordList());
        return queryGroupActivity;
    }

    private void setCityNames(List<QueryGroupActivityResponseVO> recordList) {
        if (ListUtils.isEmpty(recordList)) {
            return;
        }
        List<String> cityCodes = recordList.stream().map(e -> e.getCityCode()).collect(Collectors.toList());
        if (ListUtils.isEmpty(cityCodes)) {
            return;
        }
        Map<String, RegionMap> regionMapMap = bookBrowseRecordBiz.getCitysByCodes(cityCodes);
        if (MapUtils.isEmpty(regionMapMap)) {
            return;
        }
        //过滤掉第三方社群
        recordList.stream().filter(e -> !YesOrNoNumEnum.YES.getValue().equals(e.getGroupType())).forEach(queryGroupActivityResponseVO -> {
            RegionMap regionMap = regionMapMap.get(queryGroupActivityResponseVO.getCityCode());
            if (null != regionMap) {
                queryGroupActivityResponseVO.setCityName(regionMap.getRegionName());
            }
        });
    }

    private void setLabelContent(List<QueryGroupActivityResponseVO> rightsSettingDtos) {
        log.info("权益设置标签具体内容");
        if (ListUtils.isEmpty(rightsSettingDtos)){
            return;
        }
        List<Long> firstClassifyIds = new ArrayList<>();
        List<Long> secondClassifyIds = new ArrayList<>();
        List<Long> thirdClassifyIds = new ArrayList<>();
        List<Long> classifyIds = new ArrayList<>();
        List<Long> gradeLabelIds = new ArrayList<>();
        List<Long> subjectLabelIds = new ArrayList<>();
        List<Long> labelIds = new ArrayList<>();
        for (QueryGroupActivityResponseVO queryGroupActivityResponseVO:rightsSettingDtos) {
            firstClassifyIds.add(queryGroupActivityResponseVO.getFirstClassify());
            secondClassifyIds.add(queryGroupActivityResponseVO.getSecondClassify());
            thirdClassifyIds.add(queryGroupActivityResponseVO.getThirdClassify());
            gradeLabelIds.add(queryGroupActivityResponseVO.getGradeLabelId());
            subjectLabelIds.add(queryGroupActivityResponseVO.getSubjectLabelId());
        }
        if (!ListUtils.isEmpty(firstClassifyIds)){
            classifyIds.addAll(firstClassifyIds);
        }
        if (!ListUtils.isEmpty(secondClassifyIds)){
            classifyIds.addAll(secondClassifyIds);
        }
        if (!ListUtils.isEmpty(thirdClassifyIds)){
            classifyIds.addAll(thirdClassifyIds);
        }
        if (!ListUtils.isEmpty(gradeLabelIds)){
            labelIds.addAll(gradeLabelIds);
        }
        if (!ListUtils.isEmpty(subjectLabelIds)){
            labelIds.addAll(subjectLabelIds);
        }
        Map<Long, AssistTempletDTO> classifyMap = new HashMap<>();
        Map<Long, BookLabel>  labelMap= new HashMap<>();
        if (!ListUtils.isEmpty(classifyIds)){
            classifyMap = assistTempletConsr.mapByIds4Classify(classifyIds);
        }
        if (!ListUtils.isEmpty(labelIds)){
            labelMap = bookLabelDao.getMapByIds(labelIds);
        }
        for (QueryGroupActivityResponseVO rightsSettingDto : rightsSettingDtos){
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingDto.getFirstClassify())){
                rightsSettingDto.setFirstClassifyName(classifyMap.get(rightsSettingDto.getFirstClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingDto.getSecondClassify())){
                rightsSettingDto.setSecondClassifyName(classifyMap.get(rightsSettingDto.getSecondClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(classifyMap) && classifyMap.containsKey(rightsSettingDto.getThirdClassify())){
                rightsSettingDto.setThirdClassifyName(classifyMap.get(rightsSettingDto.getThirdClassify()).getTempletName());
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingDto.getGradeLabelId())){
                rightsSettingDto.setGradeLabelName(labelMap.get(rightsSettingDto.getGradeLabelId()).getName());
            }
            if (!MapUtils.isEmpty(labelMap) && labelMap.containsKey(rightsSettingDto.getSubjectLabelId())){
                rightsSettingDto.setSubjectLabelName(labelMap.get(rightsSettingDto.getSubjectLabelId()).getName());
            }
        }
    }

    @Override
    public PageBeanNew<ListGroupActivityResponseVO> listGroupActivity(String name, Integer joinType, Integer numPerPage, Integer currentPage,Long agentId) {
        PageParam pageParam = new PageParam(currentPage, numPerPage);
        // 根据数命查bookid
        List<Long> bookIds = new ArrayList<>();
        if (!StringUtil.isEmpty(name)){
            bookIds = bookDao.getBookIdsByBookName(name);
        }
        Map<String, Object> paraMap = Maps.newHashMap();
        paraMap.put("name", StringUtil.isEmpty(name) ? null : name);
        paraMap.put("bookIds", bookIds);
        paraMap.put("joinType", joinType);
        paraMap.put("agentId", agentId);
        PageBeanNew<ListGroupActivityResponseVO> listGroupActivity = pcloudGroupActivityDao.listPageNew(pageParam, paraMap, "listGroupActivity");
        if (null == listGroupActivity || CollectionUtils.isEmpty(listGroupActivity.getRecordList())) {
            return listGroupActivity;
        }
        for(ListGroupActivityResponseVO vo : listGroupActivity.getRecordList()){
            if(vo.getGroupType() != null && vo.getGroupType() == 0){
                // 处理群分类短连接
                String groupClassifyUrl = wechatGroupLinkPrefix + "/group/info2?classify_id=" + vo.getClassifyId() + "&book_group_id=" + vo.getBookGroupId();
                vo.setGroupClassifyUrl(UrlUtils.getShortUrl4Own(groupClassifyUrl));
            }
            if(!StringUtil.isEmpty(vo.getDescription())){
                String filterStr = StringUtilParent.replaceHtml(vo.getDescription());
                vo.setCutDescription(filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr);
            }
        }
        return listGroupActivity;
    }

    @Override
    public GroupActivity4AppletDTO getGroupActivity4Applet(Long rightSettingId, Long adviserId, Long bookId, Long channelId, Integer readType) {
        BookDto adviserBook = bookBiz.getAdviserBook(bookId, adviserId, channelId, null);
        BookDto dto = Optional.ofNullable(adviserBook).orElseThrow(() -> new BookBizException(BookBizException.ID_NOT_EXIST, "未找到相关书刊"));
        // 处理分类和标签
        BaseTempletClassify baseTempletClassify = new BaseTempletClassify();
        baseTempletClassify.setFirstClassify(dto.getTempletId());
        baseTempletClassify.setSecondClassify(dto.getSecondTempletId());
        baseTempletClassify.setThirdClassify(dto.getThirdTempletId());
        baseTempletClassify.setGradeLabelId(dto.getGraLabelId());
        baseTempletClassify.setSubjectLabelId(dto.getSubLabelId());
        baseTempletClassify.setVolLabelId(dto.getVolLabelId());
        rightsSettingBiz.setClassifyAndLabel(baseTempletClassify);

        GroupActivity4AppletDTO groupActivity4AppletDTO = pcloudGroupActivityDao.getGroupActivity4Applet(baseTempletClassify.getFirstClassify(),
                baseTempletClassify.getSecondClassify(),baseTempletClassify.getGradeLabelId(),baseTempletClassify.getSubjectLabelId(), baseTempletClassify.getThirdClassify());
        if(groupActivity4AppletDTO == null){
            return new GroupActivity4AppletDTO();
        }
        // 是否开启社群服务开关
        RightsSettingTitle right = rightsSettingTitleMapper.getByRightSettingIdAndType(rightSettingId, RightsNowItemTypeNew.GROUP_SERVICE.value,readType);
        if (null == right){
            return new GroupActivity4AppletDTO();
        }
        groupActivity4AppletDTO.setOpenStatus(Objects.isNull(right.getOpenState()) ? false : right.getOpenState());
        groupActivity4AppletDTO.setRightsSettingTitle(right.getRightsSettingTitle());
        groupActivity4AppletDTO.setRightsSettingDesc(right.getRightsSettingDesc());
        String filterStr = StringUtilParent.replaceHtml(groupActivity4AppletDTO.getDesc());
        String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
        groupActivity4AppletDTO.setCutDesc(subStr);
        //头像列表从缓存里取
        // 通过 classifyId 获取群二维码链接
        String groupQrCode = groupQrcodeBiz.getChangeGroupQrCode(groupActivity4AppletDTO.getClassifyId());
        // 通过群二维码链接反查群ID
        ClassifyQrcodeVO groupQrcodeInfo = groupQrcodeBiz.getGroupQrcodeInfo(groupQrCode, groupActivity4AppletDTO.getClassifyId());
        List<String> headUrlList = appletGroupSearchRecordBiz.getHeadUrlList(groupQrcodeInfo.getUserNumber(),groupQrcodeInfo.getId());
        groupActivity4AppletDTO.setHeadUrlList(headUrlList);
        List<AppletGroupStatementDTO> statementDTOS = appletGroupSearchRecordBiz.getStatementList(groupQrcodeInfo.getUserNumber(),headUrlList,groupQrcodeInfo.getId());
        groupActivity4AppletDTO.setStatementDTOList(statementDTOS);
        return groupActivity4AppletDTO;
    }

    @Override
    public Map<Long, GroupActivity4AppletDTO> getByIds(List<Long> ids) {
        if (ListUtils.isEmpty(ids)) {
            return new HashMap<>();
        }
        List<Long> adviserGroupIds = rightsSettingItemDetailDao.getAdviserGroupIds(ids);
        List<Long> adviserGroupIds4Save = Lists.newArrayList(adviserGroupIds);
        List<Long> activityGroupIds = getActivityGroupIds(ids,adviserGroupIds);
        // 合并
        return getGroupMap(adviserGroupIds4Save, activityGroupIds);
    }

    private List<Long> getActivityGroupIds(List<Long> ids, List<Long> adviserGroupIds) {
        if (!ListUtils.isEmpty(adviserGroupIds)) {
            Iterator<Long> it4Ids = ids.iterator();
            log.info("it4Ids : {}, adviserGroupIds {}",ids,adviserGroupIds);
            while (it4Ids.hasNext()) {
                Long serverId = it4Ids.next();
                Iterator<Long> it4Group = adviserGroupIds.iterator();
                while (it4Group.hasNext()) {
                    Long serverId4Group = it4Group.next();
                    if (serverId.equals(serverId4Group)) {
                        it4Group.remove();
                        if (ids.contains(serverId4Group)){
                            it4Ids.remove();
                        }
                    }
                }
            }
        }
        return ids;
    }

    private Map<Long, GroupActivity4AppletDTO> getGroupMap(List<Long> adviserGroupIds, List<Long> activityGroupIds) {
        log.info("获取群数据adviserGroupIds：{}，activityGroupIds", adviserGroupIds, activityGroupIds);
        Map<Long, GroupActivity4AppletDTO> mapDto = new HashMap<Long, GroupActivity4AppletDTO>();
        Map<Long, GroupActivity4AppletDTO> editDtoThree = new HashMap<>();
        Map<Long, GroupActivity4AppletDTO> localMap = new HashMap<>();
        if (!ListUtils.isEmpty(adviserGroupIds)){
            editDtoThree = pcloudGroupActivityDao.getGroupClassifyByIds(adviserGroupIds);  //查询第编辑端群
        }
        if (!ListUtils.isEmpty(activityGroupIds)) {
            localMap = pcloudGroupActivityDao.getByIds(activityGroupIds, null);
        }
        if (MapUtils.isNotEmpty(localMap)) {
            mapDto.putAll(localMap);
        }
        if (MapUtils.isNotEmpty(editDtoThree)) {
            mapDto.putAll(editDtoThree);
        }
        if(mapDto.isEmpty()){
            return mapDto;
        }
        for(GroupActivity4AppletDTO groupActivity4AppletDTO: mapDto.values()){
            String filterStr = StringUtilParent.replaceHtml(groupActivity4AppletDTO.getDesc());
            String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
            groupActivity4AppletDTO.setCutDesc(subStr);
        }
        return mapDto;
    }

    @Override
    public PageBeanNew<AppletGroupManageDTO> getGroupListByBookTemplet(Long wechatUserId, Long firstClassify, Long secondClassify, Long gradeLabelId, Long subjectLabelId, Integer currentPage, Integer numPerPage, Long agentId, Long thirdClassify) {
        // 处理分类和标签
        if (null == firstClassify && null == secondClassify && null == thirdClassify && null == gradeLabelId && null == subjectLabelId) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        BaseTempletClassify baseTempletClassify = new BaseTempletClassify();
        baseTempletClassify.setFirstClassify(firstClassify);
        baseTempletClassify.setSecondClassify(secondClassify);
        baseTempletClassify.setThirdClassify(thirdClassify);
        baseTempletClassify.setGradeLabelId(gradeLabelId);
        baseTempletClassify.setSubjectLabelId(subjectLabelId);
        rightsSettingBiz.setClassifyAndLabel(baseTempletClassify);
        Map<String, Object> map = new HashMap<>();
        map.put("firstClassify", baseTempletClassify.getFirstClassify());
        map.put("secondClassify", baseTempletClassify.getSecondClassify());
        map.put("thirdClassify", baseTempletClassify.getThirdClassify());
        map.put("gradeLabelId", baseTempletClassify.getGradeLabelId());
        map.put("subjectLabelId", baseTempletClassify.getSubjectLabelId());
        map.put("agentId", agentId);
        PageBeanNew<AppletGroupManageDTO> list = pcloudGroupActivityDao.listPageNew(new PageParam(currentPage,numPerPage),map,"getGroupListByBookTemplet");
        if (null == list || ListUtils.isEmpty(list.getRecordList())) {
            return new PageBeanNew<>(currentPage,numPerPage,0,new ArrayList<>());
        }
        for (AppletGroupManageDTO activity4AppletDTO : list.getRecordList()) {
            activity4AppletDTO.setStatus(0);
            // 付费群 查询用户是否已经购买过该群分类
            if (activity4AppletDTO.getPrice() != null && activity4AppletDTO.getPrice().compareTo(BigDecimal.ZERO) > 0) {
                if (bookClassifyBuyRecordDao.checkUserBuy(wechatUserId, activity4AppletDTO.getClassifyId())) {
                    activity4AppletDTO.setStatus(1);
                }
            }
            String filterStr = StringUtilParent.replaceHtml(activity4AppletDTO.getDesc());
            String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
            activity4AppletDTO.setCutDesc(subStr);
            // 通过 classifyId 获取群二维码链接
            String groupQrCode = groupQrcodeBiz.getChangeGroupQrCode(activity4AppletDTO.getClassifyId());
            // 通过群二维码链接反查群ID

            if (activity4AppletDTO.getGroupType() == null|| activity4AppletDTO.getGroupType()!=1){
                ClassifyQrcodeVO groupQrcodeInfo = groupQrcodeBiz
                        .getGroupQrcodeInfo(groupQrCode, activity4AppletDTO.getClassifyId());

                //头像、对话
                if(groupQrcodeInfo != null && groupQrcodeInfo.getId()!= null){
                    List<String> headUrlList = appletGroupSearchRecordBiz
                            .getHeadUrlList(groupQrcodeInfo.getUserNumber(), groupQrcodeInfo.getId());
                    activity4AppletDTO.setHeadUrlList(headUrlList);
                    List<AppletGroupStatementDTO> statementDTOS = appletGroupSearchRecordBiz
                            .getStatementList(groupQrcodeInfo.getUserNumber(), headUrlList, groupQrcodeInfo.getId());
                    activity4AppletDTO.setStatementDTOList(statementDTOS);
                }
            }else{
               fillThirdGroupHeadList(activity4AppletDTO);
            }

        }
        return list;
    }

    @Override
    public void fillThirdGroupHeadList(AppletGroupManageDTO activity4AppletDTO) {
        //头像列表从缓存里取
        String key = CacheConstant.BOOK + "THIRD_GROUP:" + activity4AppletDTO.getGroupActivityId();
        Integer userNum;
        if (StringUtil.isEmpty(JedisClusterUtils.get(key))) {
            userNum = RandomUtil.randomInt(10, 30);
            JedisClusterUtils.set(key, userNum.toString(), 3600);
        } else {
            userNum = Integer.valueOf(JedisClusterUtils.get(key));
        }
        List<String> headUrlList = appletGroupSearchRecordBiz
                .getHeadUrlList(userNum, 3L);
        activity4AppletDTO.setHeadUrlList(headUrlList);
        List<AppletGroupStatementDTO> statementDTOS = appletGroupSearchRecordBiz
                .getStatementList(userNum, headUrlList, activity4AppletDTO.getId());
        activity4AppletDTO.setStatementDTOList(statementDTOS);
        activity4AppletDTO.setUserNumber(userNum);
    }

    @Override
    public List<GroupActivity4AppletDTO> getTishBookSchoolListWrap(BaseTempletClassify baseTempletClassify, Integer limit) {
        List<GroupActivity4AppletDTO> list = pcloudGroupActivityDao.getTishBookSchoolList(baseTempletClassify, limit);
        if (!ListUtils.isEmpty(list)) {
            for (GroupActivity4AppletDTO dto : list) {
                Long classifyId = dto.getClassifyId();
                if (null != classifyId && 0!= classifyId){
                // 通过 classifyId 获取群二维码链接
                String groupQrCode = groupQrcodeBiz.getChangeGroupQrCode(classifyId);
                // 通过群二维码链接反查群ID
                ClassifyQrcodeVO groupQrcodeInfo = groupQrcodeBiz.getGroupQrcodeInfo(groupQrCode, classifyId);
                if (groupQrcodeInfo != null) {
                    dto.setBookGroupQrcodeId(groupQrcodeInfo.getId());
                    dto.setGroupName(groupQrcodeInfo.getGroupName());
                    dto.setGroupPic(groupQrcodeInfo.getQrcodeUrl());
                    dto.setUserNumber(groupQrcodeInfo.getUserNumber());
                }
                }
            }
        }
        return list;
    }

    @Override
    public void updateActivityShowState(UpdateActivityShowStateDTO showStateDTO) {
        PcloudGroupActivity byId = pcloudGroupActivityDao.getById(showStateDTO.getId());
        if (byId==null || byId.getId() == null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"不存在的共读活动！");
        }
        byId.setIsShow(showStateDTO.getIsShow());
        pcloudGroupActivityDao.updateByPrimaryKeySelective(byId);
        if (YesOrNoEnums.NO.getValue().equals(showStateDTO.getIsShow())) {
            deleteInvalidGroupIds(Lists.newArrayList(showStateDTO.getId()));
        }
        readerConsr.deleteGroupRecore(Lists.newArrayList(byId.getId()), ActivityGroupTypeEnum.THIRD_GROUP.value, GroupUpdateTypeEnum.UPDATE.value, showStateDTO.getIsShow());
    }

    private void deleteInvalidGroupIds(List<Long> activityIds) {
        if (ListUtils.isEmpty(activityIds)) {
            return;
        }
        //查询该资讯关联了多少权益
        List<RightsNowItem> rightsNowItems = rightsNowItemDao.getByActivityGroupIds(activityIds);
        List<RightsSettingItemDetail> rightsSettingItemDetails = rightsSettingItemDetailDao.getByActivityIds(activityIds);
        if (!ListUtils.isEmpty(rightsNowItems)) {
            log.info("删除无效的资源前先查询rightsNowItems:{}", rightsNowItems);
            rightsNowItemDao.deleteInvalidActivityGroups(activityIds);
        }
        if (!ListUtils.isEmpty(rightsSettingItemDetails)) {
            log.info("删除无效的资源前先查询rightsSettingItemDetails:{}", rightsSettingItemDetails);
            rightsSettingItemDetailDao.deleteInvalidActivityGroups(activityIds);
        }
    }


    @Override
    public Map<Long, GroupActivity4AppletDTO> getByIds4Now(List<Long> ids) {
        if (ListUtils.isEmpty(ids)) {
            return new HashMap<>();
        }
        List<Long> adviserGroupIds = rightsNowItemDao.getAdviserGroupIds(ids);
        List<Long> adviserGroupIds4Save = Lists.newArrayList(adviserGroupIds);
        List<Long> activityGroupIds = getActivityGroupIds(ids,adviserGroupIds);
        return getGroupMap(adviserGroupIds4Save, activityGroupIds);
    }

    @Override
    public PcloudGroupActivity getById(Long id){
        return pcloudGroupActivityDao.getById(id);
    }


    @Override
    public PageBeanNew<AppletGroupManageDTO> getLocalGroup(Long wechatUserId, Integer numPerPage, Integer currentPage, Long officialAccountsId) {
        String cityCode = readerConsr.getCityCodeByWechatUserId(wechatUserId);
        if (StringUtil.isEmpty(cityCode)) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        Long agentId = appletNewsBiz.getAgentIdByAccountId(officialAccountsId);
        Map<String, Object> map = new HashMap<>();
        map.put("cityCode", cityCode);
        map.put("agentId", agentId);
        PageBeanNew<AppletGroupManageDTO> pageBeanNew = pcloudGroupActivityDao
                .listPageNew(new PageParam(currentPage, numPerPage), map, "getLocalGroup");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, pageBeanNew.getTotalCount(), new ArrayList<>());
        }
        for (AppletGroupManageDTO activity4AppletDTO : pageBeanNew.getRecordList()) {
            activity4AppletDTO.setStatus(0);
            // 付费群 查询用户是否已经购买过该群分类
            if (activity4AppletDTO.getPrice().compareTo(BigDecimal.ZERO) > 0) {
                if (bookClassifyBuyRecordDao.checkUserBuy(wechatUserId, activity4AppletDTO.getClassifyId())) {
                    activity4AppletDTO.setStatus(1);
                }
            }
            String filterStr = StringUtilParent.replaceHtml(activity4AppletDTO.getDesc());
            String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
            activity4AppletDTO.setCutDesc(subStr);
            // 通过 classifyId 获取群二维码链接
            String groupQrCode = groupQrcodeBiz.getChangeGroupQrCode(activity4AppletDTO.getClassifyId());
            // 通过群二维码链接反查群ID
            ClassifyQrcodeVO groupQrcodeInfo = groupQrcodeBiz.getGroupQrcodeInfo(groupQrCode, activity4AppletDTO.getClassifyId());
            //头像、对话
            List<String> headUrlList = appletGroupSearchRecordBiz.getHeadUrlList(groupQrcodeInfo.getUserNumber(), groupQrcodeInfo.getId());
            activity4AppletDTO.setHeadUrlList(headUrlList);
            List<AppletGroupStatementDTO> statementDTOS = appletGroupSearchRecordBiz.getStatementList(groupQrcodeInfo.getUserNumber(), headUrlList, groupQrcodeInfo.getId());
            activity4AppletDTO.setStatementDTOList(statementDTOS);
        }
        return pageBeanNew;
    }

    @Override
    @ParamLog("修改mediaId")
    public void updateMediaId(PcloudGroupActivity pcloudGroupActivity) {
        pcloudGroupActivityDao.updateByPrimaryKeySelective(pcloudGroupActivity);
    }

    @Override
    public QueryGroupActivityResponseVO getByActivityId(Long id) {
        QueryGroupActivityResponseVO responseVO = pcloudGroupActivityDao.getByActivityId(id);
        // 组装标签名称
        List<Long> labelId = Lists.newArrayList();
        labelId.add(responseVO.getProLabelId());
        labelId.add(responseVO.getPurLabelId());
        labelId.add(responseVO.getDepLabelId());
        Map<Long, String> labelName = labelConsr.getLabelName(labelId);
        if (!MapUtils.isEmpty(labelName)){
            responseVO.setPurLabelName(labelName.get(responseVO.getPurLabelId()));
            responseVO.setProLabelName(labelName.get(responseVO.getProLabelId()));
            responseVO.setDepLabelName(labelName.get(responseVO.getDepLabelId()));
        }
        //设置分类名称
        setLabelContent(Arrays.asList(responseVO));
        return responseVO;
    }

    @Override
    public Map<Long, GroupActivity4AppletDTO> getByIds4NowRecord(List<Long> bookGroupIds, Integer groupType) {
        log.info("获取群数据adviserGroupIds：{}，activityGroupIds:{}", bookGroupIds, groupType);
        Map<Long, GroupActivity4AppletDTO> mapDto = new HashMap<Long, GroupActivity4AppletDTO>();
        if (Objects.equals(AppletRecordTypeEnum.ADVISER_GROUP.value, groupType)){
            mapDto = pcloudGroupActivityDao.getGroupClassifyByIds4Record(bookGroupIds);  //查询第编辑端群
        } else {
            mapDto = pcloudGroupActivityDao.getByIds(bookGroupIds, null);
        }

        if(mapDto.isEmpty()){
            return mapDto;
        }
        for(GroupActivity4AppletDTO groupActivity4AppletDTO: mapDto.values()){
            String filterStr = StringUtilParent.replaceHtml(groupActivity4AppletDTO.getDesc());
            String subStr = filterStr.length() > 60 ? filterStr.substring(0, 60) + "..." : filterStr;
            groupActivity4AppletDTO.setCutDesc(subStr);
        }
        rightsSettingBiz.fillGroupActivityHead(Lists.newArrayList(mapDto.values()));
        return mapDto;
    }
}
