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

import com.pcloud.book.base.exception.BookBizException;
import com.pcloud.book.consumer.wechatgroup.WechatGroupConsr;
import com.pcloud.book.group.biz.GroupAnnouncementBiz;
import com.pcloud.book.group.biz.WeixinQrcodeBiz;
import com.pcloud.book.group.dao.GroupAnnouncementDao;
import com.pcloud.book.group.dao.GroupQrcodeDao;
import com.pcloud.book.group.dao.WeixinQrcodeDao;
import com.pcloud.book.group.dto.BookWxQrcodeDTO;
import com.pcloud.book.group.entity.GroupAnnouncement;
import com.pcloud.book.group.entity.WeixinQrcode;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.string.StringUtil;
import com.sdk.wxgroup.GroupInfoVO;
import com.sdk.wxgroup.ModifyNoticeVO;
import com.sdk.wxgroup.WxGroupSDK;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Description
 * @Author ruansiyuan
 * @Date 2019/5/24 16:27
 **/
@Component("groupAnnouncementBiz")
public class GroupAnnouncementBizImpl implements GroupAnnouncementBiz {

    private static final Logger LOGGER = LoggerFactory.getLogger(GroupAnnouncementBiz.class);

    @Autowired
    private GroupAnnouncementDao groupAnnouncementDao;
    @Autowired
    private GroupQrcodeDao groupQrcodeDao;
    @Autowired
    private WechatGroupConsr wechatGroupConsr;
    @Autowired
    private WeixinQrcodeDao weixinQrcodeDao;
    @Autowired
    private WeixinQrcodeBiz weixinQrcodeBiz;

    @ParamLog("新增群公告")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long createGroupAnnouncement(GroupAnnouncement groupAnnouncement) {
        if (StringUtil.isEmpty(groupAnnouncement.getAnnouncementContent())) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "公告内容不能为空！");
        }
        if (groupAnnouncement.getBookGroupId() == null && groupAnnouncement.getBookGroupClassifyId() == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "社群书id和分类id不能同时为空！");
        }
        Long bookGroupId = groupAnnouncement.getBookGroupId();
        Long classifyId = groupAnnouncement.getBookGroupClassifyId();
        //新增之前判断是否重复添加
        if (bookGroupId != null && groupAnnouncementDao.getByGroupBookId(bookGroupId) != null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "该社群码下已有公告，请勿重复添加！");
        }
        if (classifyId != null && groupAnnouncementDao.getByClassifyId(classifyId) != null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "该群分类下已有公告，请勿重复添加！");
        }
        //新增群发
        groupAnnouncementDao.insert(groupAnnouncement);

        String content = groupAnnouncement.getAnnouncementContent();
        List<String> wechatGroupIds = new ArrayList<>();
        //根据书群发
        if (bookGroupId != null && classifyId == null) {
            //根据书查询群id集合
            wechatGroupIds = groupQrcodeDao.getWeixinGroupIdsByBookGroupId(bookGroupId);
        }
        //根据分类群发
        if (bookGroupId == null && classifyId != null) {
            //根据分类查询群id集合
            wechatGroupIds = groupQrcodeDao.getWeixinGroupIdsByClassifyId(classifyId);
        }
        dealAnnouncement(wechatGroupIds, content);
        return groupAnnouncement.getId();
    }

    @ParamLog("修改群公告")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateGroupAnnouncement(GroupAnnouncement groupAnnouncement) {
        if (StringUtil.isEmpty(groupAnnouncement.getAnnouncementContent())) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "公告内容不能为空！");
        }
        if (groupAnnouncement.getId() == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "公告id不能为空！");
        }
        GroupAnnouncement groupAnnouncementOld = groupAnnouncementDao.getById(groupAnnouncement.getId());
        if (groupAnnouncementOld == null) {
            throw new BookBizException(BookBizException.PARAM_IS_ERROR, "该公告不存在！");
        }
        Long bookGroupId = groupAnnouncementOld.getBookGroupId();
        Long classifyId = groupAnnouncementOld.getBookGroupClassifyId();
        String content = groupAnnouncement.getAnnouncementContent();
        //如果群公告一样就不修改
        if (groupAnnouncement.getAnnouncementContent().equals(groupAnnouncementOld.getAnnouncementContent())){
            return;
        }
        groupAnnouncementDao.updateContentById(content, groupAnnouncement.getId());
        List<String> wechatGroupIds = new ArrayList<>();


        //如果是按照分类修改，则直接修改
        if (bookGroupId == null && classifyId != null) {
            //根据分类查询群id集合
            wechatGroupIds = groupQrcodeDao.getWeixinGroupIdsByClassifyId(classifyId);
        }
        //如果是按照社群书修改，则判断下该社群书下的分类是否已经创建了群公告，如果有，则不修改这部分分类下的群公告
        if (bookGroupId != null && classifyId == null) {
            //根据书查询群id集合
            wechatGroupIds = groupQrcodeDao.getWeixinGroupIdsByBookGroupId(bookGroupId);
            if (!ListUtils.isEmpty(wechatGroupIds)) {
                //根据社群码id获取已经设置过公告的微信群id集合
                List<String> hasAnnWechatGroupIds = groupAnnouncementDao.getHasAnnGroupIdsByBookGroupId(bookGroupId);
                if (!ListUtils.isEmpty(hasAnnWechatGroupIds)) {
                    wechatGroupIds.removeAll(hasAnnWechatGroupIds);
                }
            }
        }
        dealAnnouncement(wechatGroupIds, content);
    }

    @Override
    public GroupAnnouncement getGroupAnnouncement(Long classifyId, Long bookGroupId) {
        if (classifyId==null&&bookGroupId==null){
            throw new BookBizException(BookBizException.PARAM_IS_ERROR,"社群码id和群分类id不能同时为空！");
        }
        GroupAnnouncement groupAnnouncement = null;
        if (bookGroupId!=null){
            groupAnnouncement=groupAnnouncementDao.getByGroupBookId(bookGroupId);
        }
        if (classifyId!=null){
            groupAnnouncement=groupAnnouncementDao.getByClassifyId(classifyId);
        }
        if (groupAnnouncement == null) {
            groupAnnouncement = new GroupAnnouncement();
        }
        return groupAnnouncement;
    }

    /**
     * 按照微信群设置群公告
     *
     * @param bookGroupId
     * @param classifyId
     * @param weixinGroupId
     */
    @ParamLog("按照微信群设置群公告")
    @Override
    public void setAnForGroup(Long bookGroupId, Long classifyId, String weixinGroupId) {
        if (bookGroupId == null && classifyId == null) {
            return;
        }
        GroupAnnouncement groupAnnouncement = null;
        if (classifyId != null) {
            groupAnnouncement = groupAnnouncementDao.getByClassifyId(classifyId);
        }
        if (groupAnnouncement == null) {
            groupAnnouncement = groupAnnouncementDao.getByGroupBookId(bookGroupId);
        }
        if (groupAnnouncement != null) {
            List<String> wechatGroupIds = new ArrayList<>();
            wechatGroupIds.add(weixinGroupId);
            dealAnnouncement(wechatGroupIds, groupAnnouncement.getAnnouncementContent());
        }
    }

    /**
     * 设置群公告
     */
    private void dealAnnouncement(List<String> wechatGroupIds, String content) {
        if (!ListUtils.isEmpty(wechatGroupIds)) {
            //循环设置群公告
            for (String wechatGroupId : wechatGroupIds) {
                ModifyNoticeVO modifyNoticeVO = new ModifyNoticeVO();
                modifyNoticeVO.setContent(content);
                modifyNoticeVO.setWxGroupId(wechatGroupId);
                // 调内部接口获取群主微信号
                LOGGER.info("开始拿群主信息" + wechatGroupId);
                String masterId = wechatGroupConsr.getMasterIdByGroupId(wechatGroupId);
                LOGGER.info("结束拿群主信息" + masterId);
                if (StringUtil.isEmpty(masterId)){
                    continue;
                }
                modifyNoticeVO.setMasterId(masterId);
                modifyNoticeVO.setIp(findIp(wechatGroupId));
                //设置群公告
                LOGGER.info("设置群公告开始"+modifyNoticeVO.toString());
                WxGroupSDK.modifyNotice(modifyNoticeVO);
                LOGGER.info("设置群公告结束"+modifyNoticeVO.toString());
            }
        }
    }

    @ParamLog("获取ip")
    private String findIp(String wechatGroupId) {
        Map<String, BookWxQrcodeDTO> groupVersion = weixinQrcodeBiz.getGroupVersion(Collections.singletonList(wechatGroupId));
        String ip = Optional.ofNullable(groupVersion.get(wechatGroupId)).orElse(new BookWxQrcodeDTO()).getWechatGroupIp();
        return ip;
    }

}
