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

import com.alibaba.fastjson.JSONObject;
import com.pcloud.book.advertising.biz.AdvertisingSpaceBiz;
import com.pcloud.book.advertising.biz.GroupMasterTagBiz;
import com.pcloud.book.advertising.dao.AdvertisingGroupTagDao;
import com.pcloud.book.advertising.dao.AdvertisingMasterDao;
import com.pcloud.book.advertising.dto.AdvertisingMasterDTO;
import com.pcloud.book.advertising.dto.Book4AdvertisingMasterDTO;
import com.pcloud.book.advertising.dto.GroupMasterAddDTO;
import com.pcloud.book.advertising.dto.GroupMasterDTO;
import com.pcloud.book.advertising.dto.QrcodeAdvertisingSpaceCountDTO;
import com.pcloud.book.advertising.entity.AdvertisingGroupTag;
import com.pcloud.book.advertising.entity.AdvertisingMaster;
import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.common.ExportConsr;
import com.pcloud.book.consumer.label.LabelConsr;
import com.pcloud.book.consumer.user.AdviserConsr;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.biz.BookGroupClassifyBiz;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dao.GroupQrcodeDao;
import com.pcloud.book.group.vo.ClassifyVO;
import com.pcloud.common.core.biz.MessageBiz;
import com.pcloud.common.core.constant.SystemCode;
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.string.StringUtil;
import com.pcloud.usercenter.party.adviser.dto.AdviserBaseInfoDto;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.Collectors;

import lombok.extern.slf4j.Slf4j;

/**
 * @描述：微信群标记广告主
 * @作者：zhuyajie
 * @创建时间：18:48 2019/8/22
 * @版本：1.0
 */
@Slf4j
@Component("groupMasterBiz")
public class GroupMasterTagBizImpl implements GroupMasterTagBiz {
    private static final ExecutorService EXECUTOR_SINGLE_SERVICE = Executors.newSingleThreadExecutor();

    @Autowired
    private GroupQrcodeDao groupQrcodeDao;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private AdvertisingSpaceBiz advertisingSpaceBiz;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private LabelConsr labelConsr;
    @Autowired
    private AdvertisingMasterDao advertisingMasterDao;
    @Autowired
    private AdvertisingGroupTagDao advertisingGroupTagDao;
    @Autowired
    private BookGroupDao bookGroupDao;
    @Autowired
    private ExportConsr exportConsr;
    @Autowired
    private MessageBiz messageBiz;
    @Autowired
    private BookGroupClassifyBiz bookGroupClassifyBiz;

    @Override
    public PageBeanNew<GroupMasterDTO> listPageGroupMaster(Integer currentPage, Integer numPerPage, Map<String, Object> paramMap) {
        PageBeanNew<GroupMasterDTO> pageBeanNew = groupQrcodeDao.listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listPageGroupMaster");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        List<GroupMasterDTO> groupMasterDTOS = pageBeanNew.getRecordList();
        setGroupInfo(groupMasterDTOS);
        return pageBeanNew;
    }

    /**
     * 填充群信息
     * @param groupMasterDTOS
     */
    private void setGroupInfo(List<GroupMasterDTO> groupMasterDTOS) {
        List<Long> adviserIds = groupMasterDTOS.stream().filter(s -> s.getAdviserId() != null).map(GroupMasterDTO::getAdviserId).distinct().collect(Collectors.toList());
        List<Long> qrcodeIds = groupMasterDTOS.stream().filter(s -> s.getGroupQrcodeId() != null).map(GroupMasterDTO::getGroupQrcodeId).distinct().collect(Collectors.toList());
        List<Long> labelIds = new ArrayList<>();
        List<Long> proLabels = groupMasterDTOS.stream().filter(s -> s.getProLabelId() != null).map(GroupMasterDTO::getProLabelId).distinct().collect(Collectors.toList());
        List<Long> depLabels = groupMasterDTOS.stream().filter(s -> s.getDepLabelId() != null).map(GroupMasterDTO::getDepLabelId).distinct().collect(Collectors.toList());
        List<Long> purLabels = groupMasterDTOS.stream().filter(s -> s.getPurLabelId() != null).map(GroupMasterDTO::getPurLabelId).distinct().collect(Collectors.toList());
        if (!ListUtils.isEmpty(proLabels)) {
            labelIds.addAll(proLabels);
        }
        if (!ListUtils.isEmpty(depLabels)) {
            labelIds.addAll(depLabels);
        }
        if (!ListUtils.isEmpty(purLabels)) {
            labelIds.addAll(purLabels);
        }
        Map<Long, AdviserBaseInfoDto> baseInfoDtoMap = new HashMap<>();
        Map<Long, String> adviserNameMap = new HashMap<>();
        Map<Long, QrcodeAdvertisingSpaceCountDTO> advertisingSpaceNumMap = new HashMap<>();
        Map<Long, String> labelMap = new HashMap<>();
        Map<Long, Integer> activeCountMap = new HashMap<>();
        if (!ListUtils.isEmpty(adviserIds)) {
            baseInfoDtoMap = adviserConsr.getAdviserId2AdviserInfoDtoMap(adviserIds);
            adviserNameMap = adviserConsr.getNames(adviserIds);
        }
        if (!ListUtils.isEmpty(qrcodeIds)) {
            advertisingSpaceNumMap = advertisingSpaceBiz.mapAdvertisingSpaceNum(qrcodeIds);
            activeCountMap = wechatGroupConsr.get7DayActiveCountByQrcode(qrcodeIds);
        }
        if (!ListUtils.isEmpty(labelIds)) {
            labelMap = labelConsr.getLabelName(labelIds);
        }
        for (GroupMasterDTO groupMasterDTO : groupMasterDTOS) {
            //出版社信息
            if (!MapUtils.isEmpty(baseInfoDtoMap) && null != groupMasterDTO.getAdviserId()) {
                AdviserBaseInfoDto adviserBaseInfoDto = baseInfoDtoMap.get(groupMasterDTO.getAdviserId());
                if (null != adviserBaseInfoDto) {
                    groupMasterDTO.setAgentName(adviserBaseInfoDto.getAgentName());
                }
            }
            //编辑名称
            if (!MapUtils.isEmpty(adviserNameMap) && null != groupMasterDTO.getAdviserId()) {
                groupMasterDTO.setAdviserName(adviserNameMap.get(groupMasterDTO.getAdviserId()));
            }
            //获取广告位数量
            Integer spaceNum = 0;
            if (!MapUtils.isEmpty(advertisingSpaceNumMap) && null != groupMasterDTO.getGroupQrcodeId()) {
                QrcodeAdvertisingSpaceCountDTO dto = advertisingSpaceNumMap.get(groupMasterDTO.getGroupQrcodeId());
                if (null != dto) {
                    spaceNum = dto.getAdvertisingSpaceNum();
                }
            }
            groupMasterDTO.setAdvertisingSpaceNum(spaceNum);
            //标签名称
            if (!MapUtils.isEmpty(labelMap)) {
                if (null != groupMasterDTO.getProLabelId() && labelMap.containsKey(groupMasterDTO.getProLabelId())) {
                    groupMasterDTO.setProLabelName(labelMap.get(groupMasterDTO.getProLabelId()));
                }
                if (null != groupMasterDTO.getDepLabelId() && labelMap.containsKey(groupMasterDTO.getDepLabelId())) {
                    groupMasterDTO.setDepLabelName(labelMap.get(groupMasterDTO.getDepLabelId()));
                }
                if (null != groupMasterDTO.getPurLabelId() && labelMap.containsKey(groupMasterDTO.getPurLabelId())) {
                    groupMasterDTO.setPurLabelName(labelMap.get(groupMasterDTO.getPurLabelId()));
                }
            }
            //群活跃度
            Integer activeCount = 0;
            if (!MapUtils.isEmpty(activeCountMap) && null != groupMasterDTO.getGroupQrcodeId()) {
                activeCount = activeCountMap.get(groupMasterDTO.getGroupQrcodeId());
            }
            groupMasterDTO.setActiveCount(activeCount);
            //广告主名称
            List<AdvertisingMaster> masterList = advertisingMasterDao.getByGroup(groupMasterDTO.getGroupQrcodeId());
            if (!ListUtils.isEmpty(masterList)) {
                groupMasterDTO.setMasterList(masterList);
            }
        }
    }

    @Override
    public List<AdvertisingMasterDTO> getBrandMaster() throws BizException {
        List<AdvertisingMasterDTO> list = advertisingMasterDao.getBrandMaster();
        return list;
    }

    @Override
    public void setGroupMaster(GroupMasterAddDTO groupMasterAddDTO) {
        //多个微信群标记多个广告主
        if (!ListUtils.isEmpty(groupMasterAddDTO.getGroupQrcodeIdList())) {
            for (Long groupQrcodeId : groupMasterAddDTO.getGroupQrcodeIdList()) {
                advertisingGroupTagDao.deleteByGroupQrcodeId(groupQrcodeId);
                if (!ListUtils.isEmpty(groupMasterAddDTO.getMasterIdList())) {
                    List<AdvertisingGroupTag> tagList = new ArrayList<>();
                    Long bookId = groupQrcodeDao.getBookIdByGroupQrcodeId(groupQrcodeId);
                    for (Long masterId : groupMasterAddDTO.getMasterIdList()) {
                        AdvertisingGroupTag groupTag = new AdvertisingGroupTag();
                        groupTag.setGroupQrcodeId(groupQrcodeId);
                        groupTag.setMasterId(masterId);
                        groupTag.setTagBookId(bookId);
                        tagList.add(groupTag);
                    }
                    advertisingGroupTagDao.insert(tagList);
                }
            }
            return;
        }
        //一个广告主标记多本书下的微信群
        if (null != groupMasterAddDTO.getMasterId()) {
            //已标记的
            List<Long> beforeBookIds = advertisingGroupTagDao.getBookIdsByMasterId(groupMasterAddDTO.getMasterId());
            if (!ListUtils.isEmpty(groupMasterAddDTO.getBookIdList())) {
                List<Long> addIds = new ArrayList<>();
                List<Long> deleteIds = new ArrayList<>();
                if (ListUtils.isEmpty(beforeBookIds)) {
                    addIds.addAll(groupMasterAddDTO.getBookIdList());
                } else {
                    addIds.addAll(groupMasterAddDTO.getBookIdList());
                    addIds.removeAll(beforeBookIds);
                    deleteIds.addAll(beforeBookIds);
                    deleteIds.removeAll(groupMasterAddDTO.getBookIdList());
                }
                this.addBookTag(addIds, groupMasterAddDTO.getMasterId());
                this.deleteBookTag(deleteIds, groupMasterAddDTO.getMasterId());
            } else {
                this.deleteBookTag(beforeBookIds, groupMasterAddDTO.getMasterId());
            }
        }
    }

    /**
     * 添加图书标记
     */
    private void addBookTag(List<Long> bookIds, Long masterId) {
        if (ListUtils.isEmpty(bookIds)) {
            return;
        }
        List<AdvertisingGroupTag> tagList = new ArrayList<>();
        for (Long bookId : bookIds) {
            AdvertisingGroupTag groupTag = new AdvertisingGroupTag();
            groupTag.setTagBookId(bookId);
            groupTag.setMasterId(masterId);
            groupTag.setGroupQrcodeId(0L);
            tagList.add(groupTag);
        }
        advertisingGroupTagDao.insert(tagList);
        //书下每个群添加记录
        EXECUTOR_SINGLE_SERVICE.execute(() -> {
            List<Long> beforeQrcodeIds = advertisingGroupTagDao.getGroupQrcodeIdsByMasterId(masterId);
            for (Long bookId : bookIds) {
                List<AdvertisingGroupTag> addList = new ArrayList<>();
                List<Long> qrcodeIds = groupQrcodeDao.getIdsByBookId(bookId);
                if (ListUtils.isEmpty(qrcodeIds)) {
                    continue;
                }
                if (!ListUtils.isEmpty(beforeQrcodeIds)) {//去除已标记的
                    qrcodeIds.removeAll(beforeQrcodeIds);
                }
                if (ListUtils.isEmpty(qrcodeIds)) {
                    continue;
                }
                for (Long qrcodeId : qrcodeIds) {
                    AdvertisingGroupTag tag = new AdvertisingGroupTag();
                    tag.setGroupQrcodeId(qrcodeId);
                    tag.setTagBookId(bookId);
                    tag.setMasterId(masterId);
                    addList.add(tag);
                }
                advertisingGroupTagDao.insert(addList);
            }
        });
    }

    /**
     * 删除图书标记
     */
    private void deleteBookTag(List<Long> bookIds, Long masterId) {
        if (ListUtils.isEmpty(bookIds)) {
            return;
        }
        advertisingGroupTagDao.deleteByBook(bookIds, masterId);
    }

    @Override
    public PageBeanNew<Book4AdvertisingMasterDTO> listPageBook4AdMaster(Integer currentPage, Integer numPerPage, String name) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", StringUtil.isEmpty(name) ? null : name);
        PageBeanNew<Book4AdvertisingMasterDTO> pageBeanNew = bookGroupDao.listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listPageBook4AdMaster");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        for (Book4AdvertisingMasterDTO dto : pageBeanNew.getRecordList()) {
            Map<String, Object> map = groupQrcodeDao.getGroupCountUserCountByBookId(dto.getBookId());
            Integer groupCount = 0;
            Integer userNum = 0;
            if (!MapUtils.isEmpty(map)) {
                groupCount = Integer.valueOf(map.get("groupCount").toString());
                userNum = Integer.valueOf(map.get("userNum").toString());
            }
            dto.setGroupCount(groupCount);
            dto.setGroupUserNum(userNum);
        }
        return pageBeanNew;
    }

    @Override
    public PageBeanNew<GroupMasterDTO> listPageGroupList4Master(Long userId, Integer currentPage, Integer numPerPage, Map<String, Object> paramMap) {
        Long masterId = advertisingMasterDao.getIdByUserLoginId(userId);
        if (null == masterId) {
            throw new BookBizException(BookBizException.ERROR, "广告主不存在");
        }
        paramMap.put("masterId", masterId);
        PageBeanNew<GroupMasterDTO> pageBeanNew = groupQrcodeDao.listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listPageGroupMaster");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        List<GroupMasterDTO> groupMasterDTOS = pageBeanNew.getRecordList();
        setLabelName(groupMasterDTOS);
        return pageBeanNew;
    }

    /**
     * 填充标签名称
     * @param groupMasterDTOS
     */
    private void setLabelName(List<GroupMasterDTO> groupMasterDTOS) {
        List<Long> labelIds = new ArrayList<>();
        List<Long> proLabels = groupMasterDTOS.stream().filter(s -> s.getProLabelId() != null).map(GroupMasterDTO::getProLabelId).distinct().collect(Collectors.toList());
        List<Long> depLabels = groupMasterDTOS.stream().filter(s -> s.getDepLabelId() != null).map(GroupMasterDTO::getDepLabelId).distinct().collect(Collectors.toList());
        List<Long> purLabels = groupMasterDTOS.stream().filter(s -> s.getPurLabelId() != null).map(GroupMasterDTO::getPurLabelId).distinct().collect(Collectors.toList());
        if (!ListUtils.isEmpty(proLabels)) {
            labelIds.addAll(proLabels);
        }
        if (!ListUtils.isEmpty(depLabels)) {
            labelIds.addAll(depLabels);
        }
        if (!ListUtils.isEmpty(purLabels)) {
            labelIds.addAll(purLabels);
        }
        Map<Long, String> labelMap = new HashMap<>();
        if (!ListUtils.isEmpty(labelIds)) {
            labelMap = labelConsr.getLabelName(labelIds);
        }
        for (GroupMasterDTO groupMasterDTO : groupMasterDTOS) {
            //标签名称
            if (!MapUtils.isEmpty(labelMap)) {
                if (null != groupMasterDTO.getProLabelId() && labelMap.containsKey(groupMasterDTO.getProLabelId())) {
                    groupMasterDTO.setProLabelName(labelMap.get(groupMasterDTO.getProLabelId()));
                }
                if (null != groupMasterDTO.getDepLabelId() && labelMap.containsKey(groupMasterDTO.getDepLabelId())) {
                    groupMasterDTO.setDepLabelName(labelMap.get(groupMasterDTO.getDepLabelId()));
                }
                if (null != groupMasterDTO.getPurLabelId() && labelMap.containsKey(groupMasterDTO.getPurLabelId())) {
                    groupMasterDTO.setPurLabelName(labelMap.get(groupMasterDTO.getPurLabelId()));
                }
            }
        }
    }

    @Override
    public void exportGroupMaster(String name, Long proLabelId, Long depLabelId, Long purLabelId, Long masterId, Long partyId) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", StringUtil.isEmpty(name) ? null : name);
        paramMap.put("proLabelId", proLabelId);
        paramMap.put("depLabelId", depLabelId);
        paramMap.put("purLabelId", purLabelId);
        paramMap.put("masterId", masterId);
        List<GroupMasterDTO> list = groupQrcodeDao.listPageGroupMaster(paramMap);
        if (ListUtils.isEmpty(list)) {
            return;
        }
        EXECUTOR_SINGLE_SERVICE.execute(() -> {
            String fileName = "微信群导出_" + DateUtils.getShortDateStr();
            Boolean isSuccess = true;
            String fileUrl = "";
            try {
                setGroupInfo(list);
                fileUrl = exportGroupMastefile(list, fileName);
            } catch (Exception e) {
                log.error("生成导出文件失败" + e.getMessage(), e);
                isSuccess = false;
            }
            // 发送消息
            if (isSuccess) {
                sendNotify(partyId, fileUrl, fileName);
            }
        });
    }

    @Override
    public void exportGroupList4Master(Long partyId, Map<String, Object> paramMap, Long userId) {
        Long masterId = advertisingMasterDao.getIdByUserLoginId(userId);
        if (null == masterId) {
            throw new BookBizException(BookBizException.ERROR, "广告主不存在");
        }
        paramMap.put("masterId", masterId);
        List<GroupMasterDTO> list = groupQrcodeDao.listPageGroupMaster(paramMap);
        if (ListUtils.isEmpty(list)) {
            return;
        }
        EXECUTOR_SINGLE_SERVICE.execute(() -> {
            String fileName = "微信群导出_" + DateUtils.getShortDateStr();
            Boolean isSuccess = true;
            String fileUrl = "";
            try {
                setLabelName(list);
                fileUrl = exportGroupList4Master(list, fileName);
            } catch (Exception e) {
                log.error("生成导出文件失败" + e.getMessage(), e);
                isSuccess = false;
            }
            // 发送消息
            if (isSuccess) {
                sendNotify(partyId, fileUrl, fileName);
            }
        });
    }

    /**
     * 广告主分配微信群导出
     */
    private String exportGroupMastefile(List<GroupMasterDTO> list, String fileName) {
        // 字段名
        String[] rowsName = {"序号", "群名称", "群分类名称", "社群标签（专业）", "社群标签（深度）", "社群标签（目的）", "社群书", "所属出版社",
                "创建编辑", "近7天活跃度", "当前群人数", "广告位数量", "群二维码", "标签", "群创建时间"};
        List<Object[]> dataList = new ArrayList<>();
        Object[] objs;
        for (int i = 0; i < list.size(); i++) {
            GroupMasterDTO dto = list.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = dto.getGroupName();
            objs[2] = dto.getClassify();
            objs[3] = dto.getProLabelName();
            objs[4] = dto.getDepLabelName();
            objs[5] = dto.getPurLabelName();
            objs[6] = dto.getBookName();
            objs[7] = dto.getAgentName();
            objs[8] = dto.getAdviserName();
            objs[9] = dto.getActiveCount() == null ? 0 : dto.getActiveCount();
            objs[10] = dto.getUserNumber();
            objs[11] = dto.getAdvertisingSpaceNum() == null ? 0 : dto.getAdvertisingSpaceNum();
            String qrcodeUrl = "";
            if (!StringUtil.isEmpty(dto.getQrcodeUrl())) {
                qrcodeUrl = dto.getQrcodeUrl().replace("oss.5rs.me", "file.5rs.me");
            }
            objs[12] = qrcodeUrl;
            String masterName = "";
            List<AdvertisingMaster> masterList = dto.getMasterList();
            if (!ListUtils.isEmpty(masterList)) {
                for (AdvertisingMaster master : masterList) {
                    if (StringUtil.isEmpty(masterName)) {
                        masterName = master.getMasterName();
                    } else {
                        masterName = masterName + "; " + master.getMasterName();
                    }
                }
            }
            objs[13] = masterName;
            objs[14] = DateUtils.formatDate(dto.getCreateTime(), DateUtils.DATE_FORMAT_DATEONLY);
            dataList.add(objs);
        }
        return exportConsr.exportExcel(fileName, rowsName, dataList);
    }

    /**
     * 广告主-微信群导出
     */
    private String exportGroupList4Master(List<GroupMasterDTO> list, String fileName) {
        // 字段名
        String[] rowsName = {"序号", "群名称", "群分类名称", "社群书", "社群标签（专业）", "社群标签（深度）", "社群标签（目的）",
                "当前群人数", "群二维码", "群创建时间", "分配时间"};
        List<Object[]> dataList = new ArrayList<>();
        Object[] objs;
        for (int i = 0; i < list.size(); i++) {
            GroupMasterDTO dto = list.get(i);
            objs = new Object[rowsName.length];
            objs[0] = i + 1;
            objs[1] = dto.getGroupName();
            objs[2] = dto.getClassify();
            objs[3] = dto.getBookName();
            objs[4] = dto.getProLabelName();
            objs[5] = dto.getDepLabelName();
            objs[6] = dto.getPurLabelName();
            objs[7] = dto.getUserNumber();
            String qrcodeUrl = "";
            if (!StringUtil.isEmpty(dto.getQrcodeUrl())) {
                qrcodeUrl = dto.getQrcodeUrl().replace("oss.5rs.me", "file.5rs.me");
            }
            objs[8] = qrcodeUrl;
            objs[9] = DateUtils.formatDate(dto.getCreateTime(), DateUtils.DATE_FORMAT_DATEONLY);
            objs[10] = DateUtils.formatDate(dto.getTagTime(), DateUtils.DATE_FORMAT_DATEONLY);
            dataList.add(objs);
        }
        return exportConsr.exportExcel(fileName, rowsName, dataList);
    }

    /**
     * 发送站内信
     */
    private void sendNotify(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.pcloud.code);
        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);
        }
    }
    @Override
    public List<String> getTagWxGroupIdsByUserId(Long userId) {
        Long masterId = advertisingMasterDao.getIdByUserLoginId(userId);
        if (null == masterId) {
            return new ArrayList<>();
        }
        List<String> groupIds = advertisingGroupTagDao.getTagWxGroupIdsByMasterId(masterId);
        return groupIds;
    }

    @Override
    public PageBeanNew<GroupMasterDTO> listPageGroupBaseInfo4Master(Integer currentPage, Integer numPerPage, String name, Long userId) {
        Long masterId = advertisingMasterDao.getIdByUserLoginId(userId);
        if (null == masterId) {
            throw new BookBizException(BookBizException.ERROR, "广告主不存在");
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("query", name);
        paramMap.put("masterId", masterId);
        PageBeanNew<GroupMasterDTO> pageBeanNew = groupQrcodeDao.listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listPageGroupMaster");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        return pageBeanNew;
    }

    @Override
    public void updateMasterLoginId(Long masterId, Long loginId) {
        advertisingMasterDao.updateMasterLoginId(masterId, loginId);
    }

    @Override
    public List<Long> getTagBookIds4AdMatser(Long masterId) {
        List<Long> bookIds = advertisingGroupTagDao.getBookIdsByMasterId(masterId);
        return bookIds;
    }

    @Override
    public void addTagByBookGroup(Long classifyId, Long qrcodeId) {
        ClassifyVO classifyVO = bookGroupClassifyBiz.getClassify(classifyId);
        if (null == classifyVO){
            return;
        }
        Long bookId = classifyVO.getBookId();
        List<Long> masterIds = advertisingGroupTagDao.getMasterIdsByBookId(bookId);
        if (ListUtils.isEmpty(masterIds)) {
            return;
        }
        List<AdvertisingGroupTag> list = new ArrayList<>();
        for (Long masterId : masterIds) {
            AdvertisingGroupTag tag = new AdvertisingGroupTag();
            tag.setGroupQrcodeId(qrcodeId);
            tag.setTagBookId(bookId);
            tag.setMasterId(masterId);
            list.add(tag);
        }
        advertisingGroupTagDao.insert(list);
    }
}
