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.GroupTagBiz;
import com.pcloud.book.advertising.dao.AdvertisingBrandDao;
import com.pcloud.book.advertising.dao.AdvertisingGroupTagDao;
import com.pcloud.book.advertising.dao.AdvertisingMasterDao;
import com.pcloud.book.advertising.dto.AdvertisingBrandDTO;
import com.pcloud.book.advertising.dto.Book4AdvertisingTagDTO;
import com.pcloud.book.advertising.dto.GroupTagAddDTO;
import com.pcloud.book.advertising.dto.GroupTagDTO;
import com.pcloud.book.advertising.dto.OldBrandMasterDTO;
import com.pcloud.book.advertising.dto.QrcodeAdvertisingSpaceCountDTO;
import com.pcloud.book.advertising.entity.AdvertisingBrand;
import com.pcloud.book.advertising.entity.AdvertisingGroupTag;
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.user.PartyConsr;
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.book.util.common.ThreadPoolUtils;
import com.pcloud.common.core.aspect.ParamLog;
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.entity.UploadResultInfo;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBean;
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.QrcodeUtils;
import com.pcloud.common.utils.SessionUtil;
import com.pcloud.common.utils.cache.redis.JedisClusterUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.pcloud.common.utils.zip.CompressUtils;
import com.pcloud.usercenter.party.adviser.dto.AdviserBaseInfoDto;
import com.pcloud.usercenter.user.entity.UserLogin;
import com.pcloud.wechatgroup.message.dto.BrandParamDTO;
import com.pcloud.wechatgroup.message.dto.GroupStatistics;

import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
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.stream.Collectors;

import lombok.extern.slf4j.Slf4j;

/**
 * @描述：微信群标记品牌方
 * @作者：zhuyajie
 * @创建时间：18:48 2019/8/22
 * @版本：1.0
 */
@Slf4j
@Component("groupTagBiz")
public class GroupTagBizImpl implements GroupTagBiz {

    @Autowired
    private GroupQrcodeDao groupQrcodeDao;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private AdvertisingSpaceBiz advertisingSpaceBiz;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private LabelConsr labelConsr;
    @Autowired
    private AdvertisingGroupTagDao advertisingGroupTagDao;
    @Autowired
    private BookGroupDao bookGroupDao;
    @Autowired
    private ExportConsr exportConsr;
    @Autowired
    private MessageBiz messageBiz;
    @Autowired
    private BookGroupClassifyBiz bookGroupClassifyBiz;
    @Value("${wechat.group.link.prefix}")
    private String wechatLinkPrefix;
    /**
     * 品牌方扫码进入指定群链接缓存
     */
    private static final String BRAND_QRCODE_URL_REDIS = "BRAND_QRCODE_URL_REDIS";
    @Autowired
    private AdvertisingBrandDao advertisingBrandDao;
    @Autowired
    private AdvertisingMasterDao advertisingMasterDao;
    @Autowired
    private PartyConsr partyConsr;

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

    /**
     * 填充群信息
     * @param groupTagDTOS
     */
    private void setGroupInfo(List<GroupTagDTO> groupTagDTOS) {
        List<Long> adviserIds = groupTagDTOS.stream().filter(s -> s.getAdviserId() != null).map(GroupTagDTO::getAdviserId).distinct().collect(Collectors.toList());
        List<Long> qrcodeIds = groupTagDTOS.stream().filter(s -> s.getGroupQrcodeId() != null).map(GroupTagDTO::getGroupQrcodeId).distinct().collect(Collectors.toList());
        List<Long> labelIds = new ArrayList<>();
        List<Long> proLabels = groupTagDTOS.stream().filter(s -> s.getProLabelId() != null).map(GroupTagDTO::getProLabelId).distinct().collect(Collectors.toList());
        List<Long> depLabels = groupTagDTOS.stream().filter(s -> s.getDepLabelId() != null).map(GroupTagDTO::getDepLabelId).distinct().collect(Collectors.toList());
        List<Long> purLabels = groupTagDTOS.stream().filter(s -> s.getPurLabelId() != null).map(GroupTagDTO::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 (GroupTagDTO groupTagDTO : groupTagDTOS) {
            //出版社信息
            if (!MapUtils.isEmpty(baseInfoDtoMap) && null != groupTagDTO.getAdviserId()) {
                AdviserBaseInfoDto adviserBaseInfoDto = baseInfoDtoMap.get(groupTagDTO.getAdviserId());
                if (null != adviserBaseInfoDto) {
                    groupTagDTO.setAgentName(adviserBaseInfoDto.getAgentName());
                }
            }
            //编辑名称
            if (!MapUtils.isEmpty(adviserNameMap) && null != groupTagDTO.getAdviserId()) {
                groupTagDTO.setAdviserName(adviserNameMap.get(groupTagDTO.getAdviserId()));
            }
            //获取广告位数量
            Integer spaceNum = 0;
            if (!MapUtils.isEmpty(advertisingSpaceNumMap) && null != groupTagDTO.getGroupQrcodeId()) {
                QrcodeAdvertisingSpaceCountDTO dto = advertisingSpaceNumMap.get(groupTagDTO.getGroupQrcodeId());
                if (null != dto) {
                    spaceNum = dto.getAdvertisingSpaceNum();
                }
            }
            groupTagDTO.setAdvertisingSpaceNum(spaceNum);
            //标签名称
            if (!MapUtils.isEmpty(labelMap)) {
                if (null != groupTagDTO.getProLabelId() && labelMap.containsKey(groupTagDTO.getProLabelId())) {
                    groupTagDTO.setProLabelName(labelMap.get(groupTagDTO.getProLabelId()));
                }
                if (null != groupTagDTO.getDepLabelId() && labelMap.containsKey(groupTagDTO.getDepLabelId())) {
                    groupTagDTO.setDepLabelName(labelMap.get(groupTagDTO.getDepLabelId()));
                }
                if (null != groupTagDTO.getPurLabelId() && labelMap.containsKey(groupTagDTO.getPurLabelId())) {
                    groupTagDTO.setPurLabelName(labelMap.get(groupTagDTO.getPurLabelId()));
                }
            }
            //群活跃度
            Integer activeCount = 0;
            if (!MapUtils.isEmpty(activeCountMap) && null != groupTagDTO.getGroupQrcodeId()) {
                activeCount = activeCountMap.get(groupTagDTO.getGroupQrcodeId());
            }
            groupTagDTO.setActiveCount(activeCount);
            //品牌方名称
            List<AdvertisingBrandDTO> brandList = advertisingBrandDao.getByGroupQrcodeId(groupTagDTO.getGroupQrcodeId());
            if (!ListUtils.isEmpty(brandList)) {
                groupTagDTO.setBrandList(brandList);
            }
            if (new Integer(2).equals(groupTagDTO.getJoinGroupType())) {
                groupTagDTO.setCodeUrl(findCodeUrl(groupTagDTO.getBookGroupId(), groupTagDTO.getClassifyId(), groupTagDTO.getGroupQrcodeId()));
            }
        }
    }

    @ParamLog("获取品牌方进指定群链接")
    private String findCodeUrl(Long bookGroupId, Long classifyId, Long groupQrcodeId){
        //获取连接
        String codeUrl = JedisClusterUtils.hget(BRAND_QRCODE_URL_REDIS, groupQrcodeId.toString());
        if (codeUrl == null) {
            String link = wechatLinkPrefix + "/group/info?classify_id=" + classifyId + "&book_group_id=" + bookGroupId + "&group_qrcode_id=" + groupQrcodeId;
            codeUrl = QrcodeUtils.create(link);
            JedisClusterUtils.hset(BRAND_QRCODE_URL_REDIS, groupQrcodeId.toString(), codeUrl);
        }
        return codeUrl;
    }

    @Override
    public List<AdvertisingBrandDTO> getAllBrand() throws BizException {
        List<AdvertisingBrandDTO> list = advertisingBrandDao.getAllBrand();
        return list;
    }

    @Override
    public void setGroupBrand(GroupTagAddDTO groupTagAddDTO) {
        //多个微信群标记多个品牌方
        if (!ListUtils.isEmpty(groupTagAddDTO.getGroupQrcodeIdList())) {
            for (Long groupQrcodeId : groupTagAddDTO.getGroupQrcodeIdList()) {
                advertisingGroupTagDao.deleteByGroupQrcodeId(groupQrcodeId);
                if (!ListUtils.isEmpty(groupTagAddDTO.getBrandIdList())) {
                    List<AdvertisingGroupTag> tagList = new ArrayList<>();
                    Long bookId = groupQrcodeDao.getBookIdByGroupQrcodeId(groupQrcodeId);
                    for (Long brandId : groupTagAddDTO.getBrandIdList()) {
                        AdvertisingGroupTag groupTag = new AdvertisingGroupTag();
                        groupTag.setGroupQrcodeId(groupQrcodeId);
                        groupTag.setBrandId(brandId);
                        groupTag.setTagBookId(bookId);
                        tagList.add(groupTag);
                    }
                    advertisingGroupTagDao.insert(tagList);
                }
            }
            return;
        }
        //一个品牌方标记多本书下的微信群
        if (null != groupTagAddDTO.getBrandId()) {
            //已标记的
            List<Long> beforeBookIds = advertisingGroupTagDao.getBookIdsByBrandId(groupTagAddDTO.getBrandId());
            if (!ListUtils.isEmpty(groupTagAddDTO.getBookIdList())) {
                List<Long> addIds = new ArrayList<>();
                List<Long> deleteIds = new ArrayList<>();
                if (ListUtils.isEmpty(beforeBookIds)) {
                    addIds.addAll(groupTagAddDTO.getBookIdList());
                } else {
                    addIds.addAll(groupTagAddDTO.getBookIdList());
                    addIds.removeAll(beforeBookIds);
                    deleteIds.addAll(beforeBookIds);
                    deleteIds.removeAll(groupTagAddDTO.getBookIdList());
                }
                this.addBookTag(addIds, groupTagAddDTO.getBrandId());
                this.deleteBookTag(deleteIds, groupTagAddDTO.getBrandId());
            } else {
                this.deleteBookTag(beforeBookIds, groupTagAddDTO.getBrandId());
            }
        }
    }

    /**
     * 添加图书标记
     */
    private void addBookTag(List<Long> bookIds, Long brandId) {
        if (ListUtils.isEmpty(bookIds)) {
            return;
        }
        List<AdvertisingGroupTag> tagList = new ArrayList<>();
        for (Long bookId : bookIds) {
            AdvertisingGroupTag groupTag = new AdvertisingGroupTag();
            groupTag.setTagBookId(bookId);
            groupTag.setBrandId(brandId);
            groupTag.setGroupQrcodeId(0L);
            tagList.add(groupTag);
        }
        advertisingGroupTagDao.insert(tagList);
        //书下每个群添加记录
        ThreadPoolUtils.EXPORT_THREAD_POOL.execute(() -> {
            List<Long> beforeQrcodeIds = advertisingGroupTagDao.getGroupQrcodeIdsByBrandId(brandId);
            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.setBrandId(brandId);
                    addList.add(tag);
                }
                advertisingGroupTagDao.insert(addList);
            }
        });
    }

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

    @Override
    public PageBeanNew<Book4AdvertisingTagDTO> listPageBook4AdBrand(Integer currentPage, Integer numPerPage, String name) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", StringUtil.isEmpty(name) ? null : name);
        PageBeanNew<Book4AdvertisingTagDTO> pageBeanNew = bookGroupDao.listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listPageBook4AdBrand");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        for (Book4AdvertisingTagDTO 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<GroupTagDTO> listPageGroupList4Brand(Long userId, Integer currentPage, Integer numPerPage, Map<String, Object> paramMap) {
        Long brandId = advertisingBrandDao.getBrandIdByUserLoginId(userId);
        AdvertisingBrandDTO brand = advertisingBrandDao.getBrandById(brandId);
        if (null == brand) {
            throw new BookBizException(BookBizException.ERROR, "品牌方不存在");
        }
        paramMap.put("brandId", brandId);
        PageBeanNew<GroupTagDTO> pageBeanNew = groupQrcodeDao.listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listPageGroup4Brand");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        List<GroupTagDTO> groupTagDTOS = pageBeanNew.getRecordList();
        setLabelName(groupTagDTOS);
        return pageBeanNew;
    }

    /**
     * 填充标签名称
     * @param groupTagDTOS
     */
    private void setLabelName(List<GroupTagDTO> groupTagDTOS) {
        List<Long> labelIds = new ArrayList<>();
        List<Long> proLabels = groupTagDTOS.stream().filter(s -> s.getProLabelId() != null).map(GroupTagDTO::getProLabelId).distinct().collect(Collectors.toList());
        List<Long> depLabels = groupTagDTOS.stream().filter(s -> s.getDepLabelId() != null).map(GroupTagDTO::getDepLabelId).distinct().collect(Collectors.toList());
        List<Long> purLabels = groupTagDTOS.stream().filter(s -> s.getPurLabelId() != null).map(GroupTagDTO::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 (GroupTagDTO groupTagDTO : groupTagDTOS) {
            //标签名称
            if (!MapUtils.isEmpty(labelMap)) {
                if (null != groupTagDTO.getProLabelId() && labelMap.containsKey(groupTagDTO.getProLabelId())) {
                    groupTagDTO.setProLabelName(labelMap.get(groupTagDTO.getProLabelId()));
                }
                if (null != groupTagDTO.getDepLabelId() && labelMap.containsKey(groupTagDTO.getDepLabelId())) {
                    groupTagDTO.setDepLabelName(labelMap.get(groupTagDTO.getDepLabelId()));
                }
                if (null != groupTagDTO.getPurLabelId() && labelMap.containsKey(groupTagDTO.getPurLabelId())) {
                    groupTagDTO.setPurLabelName(labelMap.get(groupTagDTO.getPurLabelId()));
                }
            }
            if (new Integer(2).equals(groupTagDTO.getJoinGroupType())) {
                groupTagDTO.setCodeUrl(findCodeUrl(groupTagDTO.getBookGroupId(), groupTagDTO.getClassifyId(), groupTagDTO.getGroupQrcodeId()));
            }
        }
    }

    @Override
    public void exportGroupBrand(String name, Long proLabelId, Long depLabelId, Long purLabelId, Long brandId, 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("brandId", brandId);
        List<GroupTagDTO> list = groupQrcodeDao.listPageGroup4Brand(paramMap);
        if (ListUtils.isEmpty(list)) {
            return;
        }
        ThreadPoolUtils.EXPORT_THREAD_POOL.execute(() -> {
            String fileName = "微信群导出";
            String zipTitle = "微信群导出_" + DateUtils.getShortDateStr();
            Boolean isSuccess = true;
            String fileUrl = "";
            try {
                fileUrl = packExcelZip4GroupBrand(list, fileName, zipTitle);
            } catch (Exception e) {
                log.error("生成导出文件失败" + e.getMessage(), e);
                isSuccess = false;
            }
            // 发送消息
            if (isSuccess) {
                sendNotify(partyId, fileUrl, zipTitle);
            }
        });
    }


    /**
     * excel打包
     */
    private String packExcelZip4GroupBrand(List<GroupTagDTO> list, String fileName, String zipTitle) {
        Integer totalCount = list.size();
        // 分批Excel文件URL
        List<String[]> fileUrls = new ArrayList<String[]>();
        // 每个Excel大小
        Integer perExcelSize = 10000;
        // 单个excel文件存储
        if (totalCount <= perExcelSize) {
            setGroupInfo(list);
            this.setGroupMessageInfo(list);
            fileUrls.add(new String[]{fileName, exportGroupBrandfile(list, fileName)});
        }
        // 多个excel文件存储(//大于10000条记录)
        else {
            int excelNums = 0;
            if (totalCount % perExcelSize == 0) {
                excelNums = totalCount / perExcelSize;
            } else {
                excelNums = totalCount / perExcelSize + 1;
            }
            for (int i = 0; i < excelNums; i++) {
                List<GroupTagDTO> exportList;
                if (i == excelNums - 1) {
                    exportList = list.subList(i * perExcelSize, list.size());
                } else {
                    exportList = list.subList(i * perExcelSize, (i + 1) * perExcelSize);
                }
                setGroupInfo(exportList);
                this.setGroupMessageInfo(exportList);
                fileUrls.add(new String[]{fileName, exportGroupBrandfile(exportList, fileName)});
            }
        }
        // 压缩包url
        String resultUrl = null;
        // 压缩文件
        if (!ListUtils.isEmpty(fileUrls)) {
            log.info("压缩文件fileUrls：" + fileUrls + "为：" + zipTitle);
            UploadResultInfo uploadResultInfo = CompressUtils.zip(fileUrls, zipTitle);
            resultUrl = uploadResultInfo.getUrl();
        }
        return resultUrl;
    }

    /**
     * 填充群消息数量
     * @param groupTagDTOS
     */
    private void setGroupMessageInfo(List<GroupTagDTO> groupTagDTOS) {
        List<BrandParamDTO> paramDTOList = new ArrayList<>();
        groupTagDTOS.forEach(groupTagDTO -> {
            BrandParamDTO paramDTO = new BrandParamDTO();
            paramDTO.setWxGroupId(groupTagDTO.getWxGroupId());
            Date time = groupTagDTO.getTagTime();
            if (null != time) {
                paramDTO.setTagTime(DateUtils.formatDate(time, DateUtils.DATE_FORMAT_DATETIME));
            }
            paramDTOList.add(paramDTO);
        });
        Map<String, GroupStatistics> groupStatisticsMap = wechatGroupConsr.getGroupMessageStatistics4AdBrand(paramDTOList);
        if (MapUtils.isEmpty(groupStatisticsMap)) {
            return;
        }
        groupTagDTOS.forEach(groupTagDTO -> {
            GroupStatistics statistics = groupStatisticsMap.get(groupTagDTO.getWxGroupId());
            if (null != statistics) {
                groupTagDTO.setJoinCount(statistics.getJoinCount());
                groupTagDTO.setMsgCount(statistics.getMsgCount());
                groupTagDTO.setChatCount(statistics.getChatCount());
                groupTagDTO.setChatUserCount(statistics.getChatUserCount());
            }
        });
    }

    @Override
    public Map<String,Object> exportGroupList4Brand(Map<String, Object> paramMap, Long userId) {
        Long brandId = advertisingBrandDao.getBrandIdByUserLoginId(userId);
        AdvertisingBrandDTO brand = advertisingBrandDao.getBrandById(brandId);
        if (null == brand) {
            throw new BookBizException(BookBizException.ERROR, "品牌方不存在");
        }
        paramMap.put("brandId", brandId);
        List<GroupTagDTO> list = groupQrcodeDao.listPageGroup4Brand(paramMap);
        if (ListUtils.isEmpty(list)) {
            return new HashMap<>();
        }
        Map<String, Object> map = new HashMap<>();
        String fileName = "微信群二维码导出_" + DateUtils.getShortDateStr();
        String fileUrl = "";
        try {
            //导出二维码
            Map<String, List<String[]>> zipFileMap = new HashMap<>();
            List<String[]> qrcodePicUrls = new ArrayList<String[]>();
            Integer noName = 0;
            for (GroupTagDTO tagDTO : list) {
                String qrcodeUrl = tagDTO.getQrcodeUrl() == null ? null : tagDTO.getQrcodeUrl().replace("//oss", "//file");
                String qrcodeName;//二维码命名
                if (!StringUtil.isEmpty(tagDTO.getGroupName())) {
                    qrcodeName = tagDTO.getGroupName();
                } else {
                    noName = noName + 1;
                    qrcodeName = "未命名" + noName;
                }
                String[] qrcodePicurl = {qrcodeName, qrcodeUrl};
                qrcodePicUrls.add(qrcodePicurl);
            }
            zipFileMap.put(fileName, qrcodePicUrls);
            UploadResultInfo zipUrlInfo = CompressUtils.zipByCatalog(zipFileMap, fileName);
            fileUrl = zipUrlInfo != null ? zipUrlInfo.getUrl() : null;
        } catch (Exception e) {
            log.error("导出文件失败" + e.getMessage(), e);
        }
        map.put("fileName", fileName);
        map.put("fileUrl", fileUrl);
        return map;
    }

    /**
     * 品牌方分配微信群导出
     */
    private String exportGroupBrandfile(List<GroupTagDTO> list, String fileName) {
        // 字段名
        String[] rowsName = {"序号", "群名称", "群分类名称", "社群书", "社群标签（专业）", "社群标签（深度）", "社群标签（目的）", "所属出版社",
                "创建编辑", "近7天活跃度", "当前群人数", "广告位数量", "二维码", "品牌方", "分配日期",
                "期间进群人数", "群消息数", "发言人数（机器人除外）", "发言次数（机器人除外"};
        List<Object[]> dataList = new ArrayList<>();
        Object[] objs;
        for (int i = 0; i < list.size(); i++) {
            GroupTagDTO 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.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 (Integer.valueOf(2).equals(dto.getJoinGroupType()) && !StringUtil.isEmpty(dto.getCodeUrl())) {
                qrcodeUrl = dto.getCodeUrl().replace("//oss", "//file");
            } else if (!StringUtil.isEmpty(dto.getQrcodeUrl())) {
                qrcodeUrl = dto.getQrcodeUrl().replace("//oss", "//file");
            }
            objs[12] = qrcodeUrl;
            String brandName = "";
            List<AdvertisingBrandDTO> brandList = dto.getBrandList();
            if (!ListUtils.isEmpty(brandList)) {
                for (AdvertisingBrandDTO brandDTO : brandList) {
                    if (StringUtil.isEmpty(brandName)) {
                        brandName = brandDTO.getBrandName();
                    } else {
                        brandName = brandName + "; " + brandDTO.getBrandName();
                    }
                }
            }
            objs[13] = brandName;
            objs[14] = dto.getTagTime() == null ? "" : DateUtils.formatDate(dto.getTagTime(), DateUtils.DATE_FORMAT_DATEONLY);
            objs[15] = dto.getJoinCount();
            objs[16] = dto.getMsgCount();
            objs[17] = dto.getChatUserCount();
            objs[18] = dto.getChatCount();
            dataList.add(objs);
        }
        return exportConsr.exportExcel(fileName, rowsName, dataList);
    }

    /**
     * 品牌方-微信群导出
     */
    private String exportGroupList4Brand(List<GroupTagDTO> list, String fileName) {
        // 字段名
        String[] rowsName = {"序号", "群名称", "群分类名称", "社群书", "社群标签（专业）", "社群标签（深度）", "社群标签（目的）",
                "当前群人数", "群二维码", "群创建时间", "分配时间"};
        List<Object[]> dataList = new ArrayList<>();
        Object[] objs;
        for (int i = 0; i < list.size(); i++) {
            GroupTagDTO 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", "//file");
            }
            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 brandId = advertisingBrandDao.getBrandIdByUserLoginId(userId);
        AdvertisingBrandDTO brand = advertisingBrandDao.getBrandById(brandId);
        if (null == brand) {
            return new ArrayList<>();
        }
        List<String> groupIds = advertisingGroupTagDao.getTagWxGroupIdsByBrandId(brandId);
        return groupIds;
    }

    @Override
    public PageBeanNew<GroupTagDTO> listPageGroupBaseInfo4Brand(Integer currentPage, Integer numPerPage, String name, Long userId) {
        Long brandId = advertisingBrandDao.getBrandIdByUserLoginId(userId);
        AdvertisingBrandDTO brand = advertisingBrandDao.getBrandById(brandId);
        if (null == brand) {
            throw new BookBizException(BookBizException.ERROR, "品牌方不存在");
        }
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("query", name);
        paramMap.put("brandId", brandId);
        PageBeanNew<GroupTagDTO> pageBeanNew = groupQrcodeDao.listPageNew(new PageParam(currentPage, numPerPage), paramMap, "listPageGroup4Brand");
        if (null == pageBeanNew || ListUtils.isEmpty(pageBeanNew.getRecordList())) {
            return new PageBeanNew<>(currentPage, numPerPage, 0, new ArrayList<>());
        }
        return pageBeanNew;
    }

    @Override
    public List<Long> getTagBookIds4AdBrand(Long brandId) {
        List<Long> bookIds = advertisingGroupTagDao.getBookIdsByBrandId(brandId);
        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> brandIds = advertisingGroupTagDao.getBrandIdsByBookId(bookId);
        if (ListUtils.isEmpty(brandIds)) {
            return;
        }
        List<AdvertisingGroupTag> list = new ArrayList<>();
        for (Long brandId : brandIds) {
            AdvertisingGroupTag tag = new AdvertisingGroupTag();
            tag.setGroupQrcodeId(qrcodeId);
            tag.setTagBookId(bookId);
            tag.setBrandId(brandId);
            list.add(tag);
        }
        advertisingGroupTagDao.insert(list);
    }

    @Override
    public Long createBrand(AdvertisingBrand advertisingBrand) {
        //用户名登录名是否重复
        Boolean brandCheck = advertisingBrandDao.checkBrandNameRepeat(advertisingBrand.getBrandName());
        if (brandCheck) {
            throw new BookBizException(BookBizException.ERROR, "品牌方名称已存在");
        }
        Boolean loginNameCheck = advertisingBrandDao.checkLoginNameRepeat(advertisingBrand.getLoginName());
        if (loginNameCheck) {
            throw new BookBizException(BookBizException.ERROR, "登录名已存在");
        }
        advertisingBrand.setIsDelete(false);
        advertisingBrandDao.insert(advertisingBrand);
        return advertisingBrand.getId();
    }

    @Override
    public AdvertisingBrandDTO getBrandById(Long brandId) {
        AdvertisingBrandDTO dto = advertisingBrandDao.getBrandById(brandId);
        return dto;
    }

    @Override
    public void updateBrandPassword(AdvertisingBrand advertisingBrand) {
        advertisingBrandDao.update(advertisingBrand);
    }

    @Override
    public void deleteBrandById(Long brandId) {
        advertisingBrandDao.deleteBrand(brandId);
        //删除标记的微信群
        advertisingGroupTagDao.deleteByBrandId(brandId);
    }

    @Override
    public PageBean listPageBrand(Integer currentPage, Integer numPerPage, String name) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("name", name);
        PageBean pageBean = advertisingBrandDao.listPage(new PageParam(currentPage, numPerPage), paramMap, "listPageBrand");
        return pageBean;
    }

    @Override
    public Map<String, Object> brandLogin(AdvertisingBrandDTO advertisingBrandDTO) {
        AdvertisingBrand brand = advertisingBrandDao.getLoginInfo(advertisingBrandDTO.getLoginName());
        if (null == brand) {
            throw new BookBizException(BookBizException.ERROR, "账号不存在");
        }
        if (brand.getIsDelete()) {
            throw new BookBizException(BookBizException.ERROR, "账号已删除");
        }
        if (!advertisingBrandDTO.getPassword().equals(brand.getPassword())) {
            throw new BookBizException(BookBizException.ERROR, "密码错误");
        }
        // 登录成功，将用户的相关信息保存至redis中
        Map<String, Object> map = new HashMap<>();
        map.put(SessionUtil.USER_ID, brand.getId());
        map.put(SessionUtil.PARTY_ID, 0);
        String token = SessionUtil.writeToken2Redis(map);
        //返回登录信息
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("token", token);
        return resultMap;
    }

    @Override
    public List<Long> getBrandIdsByWxGroupId(String wxGroupId) {
        return advertisingGroupTagDao.getBrandIdsByWxGroupId(wxGroupId);
    }

    @Override
    public void dealOldBrandStatistic() {
        List<OldBrandMasterDTO> masterList = advertisingMasterDao.getMasterBrand();
        if (ListUtils.isEmpty(masterList)) {
            return;
        }
        for (OldBrandMasterDTO master : masterList) {
            UserLogin userLogin = partyConsr.getUserLoginInfo(master.getLoginId());
            if (null == userLogin) {
                continue;
            }
            AdvertisingBrand brand = new AdvertisingBrand();
            brand.setBrandName(master.getMasterName());
            brand.setLoginName(userLogin.getUserName());
            brand.setPassword(userLogin.getCurrentPassword());
            brand.setIsDelete(false);
            brand.setCreateUser(0l);
            advertisingBrandDao.insert(brand);
            Long brandId = brand.getId();
            //更新广告主登录id为空
            advertisingMasterDao.updateLoginId(master.getMasterName());
            //更新标记列表的品牌id
            Long masterId = master.getId();
            advertisingGroupTagDao.updateId(masterId, brandId);
        }
    }

    @Override
    public Map<String, Object> getBrandLoginInfo(Long userId) {
        Map<String, Object> map = new HashMap<>();
        Long brandId = advertisingBrandDao.getBrandIdByUserLoginId(userId);
        AdvertisingBrandDTO brandDTO = advertisingBrandDao.getBrandById(brandId);
        if (null != brandDTO) {
            map.put("brandName", brandDTO.getBrandName());
            map.put("loginName", brandDTO.getLoginName());
        }
        return map;
    }

}
