package com.pcloud.book.mq.topic;

import com.alibaba.druid.util.StringUtils;
import com.google.common.collect.Lists;
import com.pcloud.book.book.biz.BookBiz;
import com.pcloud.book.book.constant.BookConstant;
import com.pcloud.book.book.dto.BookDto;
import com.pcloud.book.consumer.channel.QrcodeSceneConsr;
import com.pcloud.book.consumer.message.TemplateConsr;
import com.pcloud.book.consumer.user.AdviserConsr;
import com.pcloud.book.consumer.user.AgentConsr;
import com.pcloud.book.group.dao.BookGroupDao;
import com.pcloud.book.group.dao.BookGroupServeDao;
import com.pcloud.book.group.dto.BookGroupDTO;
import com.pcloud.book.group.enums.JoinGroupTypeEnum;
import com.pcloud.book.keywords.dao.BookKeywordDao;
import com.pcloud.book.keywords.dao.SelfRobotKeywordDao;
import com.pcloud.book.mq.config.MQTopicConumer;
import com.pcloud.book.util.properties.BookProps;
import com.pcloud.channelcenter.base.constants.ChannelConstants;
import com.pcloud.channelcenter.wechat.dto.AccountSettingDto;
import com.pcloud.channelcenter.wechat.dto.JsonDataAndTempletId;
import com.pcloud.channelcenter.wechat.entity.SpecialUser;
import com.pcloud.channelcenter.wechat.enums.UserSendTypeEnum;
import com.pcloud.channelcenter.qrcode.dto.QrcodeSceneDto;
import com.pcloud.common.core.aspect.ParamLog;
import com.pcloud.common.core.biz.MessageBiz;
import com.pcloud.common.core.biz.TemplateQueueBiz;
import com.pcloud.common.core.constant.SceneCode;
import com.pcloud.common.core.constant.SendType;
import com.pcloud.common.core.constant.SystemCode;
import com.pcloud.common.core.constant.WechatCode;
import com.pcloud.common.core.dto.SendEmailDto;
import com.pcloud.common.core.dto.TemplateMessageDto;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.utils.ListUtils;
import com.pcloud.common.utils.string.StringUtil;
import org.apache.commons.collections.MapUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Description社群码扫码人数达到一定数量
 * @Author ruansiyuan
 * @Date 2019/12/5 16:34
 **/
@Component("someUserScanBookGroupListener")
@RabbitListener(queues = MQTopicConumer.CONSUMER_SOME_USER_SCAN_BOOK_GROUP)
public class SomeUserScanBookGroupListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(SomeUserScanBookGroupListener.class);
    @Autowired
    private BookGroupDao bookGroupDao;
    @Autowired
    private BookKeywordDao bookKeywordDao;
    @Autowired
    private BookGroupServeDao bookGroupServeDao;
    @Autowired
    private TemplateConsr templateConsr;
    @Autowired
    private SelfRobotKeywordDao selfRobotKeywordDao;
    @Autowired
    private QrcodeSceneConsr qrcodeSceneConsr;
    @Autowired
    private BookProps bookProps;
    @Autowired
    private TemplateQueueBiz templateQueueBiz;
    @Autowired
    private MessageBiz messageBiz;
    @Autowired
    private AdviserConsr adviserConsr;
    @Autowired
    private AgentConsr agentConsr;
    @Autowired
    private BookBiz bookBiz;

    @ParamLog("接收社群码扫码人数达到一定数量topic")
    @RabbitHandler
    public void onMessage(Long bookGroupId) throws BizException {
        if (bookGroupId == null) {
            return;
        }
        BookGroupDTO dto = bookGroupDao.getDTOById(bookGroupId);
        if (dto == null) {
            LOGGER.error("没有找到该社群码" + bookGroupId);
            return;
        }
        Integer joinGroupType = dto.getJoinGroupType();
        Boolean isSend = false;
        if (JoinGroupTypeEnum.GROUP_QRCODE.getCode().equals(joinGroupType)) {
            //普通群查询有没有配置关键词
            Integer keywordCount = bookKeywordDao.getKeywordCount(bookGroupId, null);
            if (keywordCount <= 0) {
                isSend = true;
            }
        }
        if (JoinGroupTypeEnum.ROBOT.getCode().equals(joinGroupType)) {
            //1v1查询有没有配置资源服务
            Integer count = bookGroupServeDao.getCountByBookGroupId(bookGroupId);
            if (count <= 0) {
                isSend = true;
            }
        }
        if (JoinGroupTypeEnum.AI_ROBOT.getCode().equals(joinGroupType)) {
            //1v1查询有没有配置资源服务
            Integer count = selfRobotKeywordDao.getCountByBookGroupId(bookGroupId);
            if (count <= 0) {
                isSend = true;
            }
        }
        if (isSend) {
            //发送模板消息
            sendTemplate(dto);
            //配置资源为空则推送模板消息和发送邮件
            sendTemplataAndEmail(dto);
        }
    }

    private void sendTemplataAndEmail(BookGroupDTO dto) {
        LOGGER.info("配置资源为空则推送模板消息和发送邮件：{}", dto);
        Map<String, String> temParam = getStringStringMap(dto);
        //获取待发送的openId
        List<SpecialUser> specialUsers =  qrcodeSceneConsr.getAllSpcialUser();
        if (ListUtils.isEmpty(specialUsers)) {
            return;
        }
        List<String> openIds = specialUsers.stream().filter(e -> Objects.equals(UserSendTypeEnum.OPENID.value, e.getSendType())).
                map(m -> m.getOpenid()).collect(Collectors.toList());
        List<String> emails = specialUsers.stream().filter(e -> Objects.equals(UserSendTypeEnum.EMAIL.value, e.getSendType())).
                map(m -> m.getEmail()).collect(Collectors.toList());
        if (!ListUtils.isEmpty(openIds)) {
            openIds.stream().forEach(openid -> {
                sendTemplate4Openid(dto, openid);
            });
        }
        if (!ListUtils.isEmpty(emails)) {
            sendEmail(emails, dto);
        }
    }

    private void sendEmail(List<String> emails, BookGroupDTO bookGroupDTO) {
        SendEmailDto sendEmailDto   = new SendEmailDto();
        if (emails.size() > 1) {
            sendEmailDto.setToEmail(emails.get(0));
            emails = emails.subList(1, emails.size());
            String ccEmail = String.join(",", emails);
//            sendEmailDto.setCcEmail(ccEmail);
        } else {
            sendEmailDto.setToEmail(emails.get(0));
        }
        sendEmailDto.setTypeCode(BookConstant.NO_RESOURCE_REMIND);
        Map<String, Object> content = new HashMap<>();
        content.put("sceneName", bookGroupDTO.getGroupQrcodeName());

        if (null != bookGroupDTO.getCreateUser()) {
            String adviserName = adviserConsr.getNameById(bookGroupDTO.getCreateUser());
            content.put("adviserName", adviserName);
        }
        if (null != bookGroupDTO.getAgentId()) {
            Map<Long, String> agentMap = agentConsr.getNames(Lists.newArrayList(bookGroupDTO.getAgentId()));
            if (MapUtils.isNotEmpty(agentMap) && agentMap.containsKey(bookGroupDTO.getAgentId())) {
                content.put("agentName", agentMap.get(bookGroupDTO.getAgentId()));
            }
        }
        if (null != bookGroupDTO.getBookId()) {
            BookDto bookDto = bookBiz.getBaseById(bookGroupDTO.getBookId());
            if (null != bookDto) {
                content.put("bookName", bookDto.getBookName());
            }
        }
        sendEmailDto.setContent(content);
        LOGGER.info("发送邮件sendEmailDto：{}", sendEmailDto);
        messageBiz.sendEmail(sendEmailDto);
    }


    private void sendTemplate4Openid(BookGroupDTO dto, String openid) {
        try {

            Map<String, String> temParam = getStringStringMap(dto);
            // 组装参数对象
            TemplateMessageDto templateMessageDto = new TemplateMessageDto();
            templateMessageDto.setSceneCode(SceneCode.PROJECT_TASK_SCENE.value);
            templateMessageDto.setAccountSettingId(bookProps.getManageOfficialId());
            templateMessageDto.setSendPartyId(bookProps.getOurManagerAccountId());
            templateMessageDto.setSendPartyRole(WechatCode.AGENT.value);
            templateMessageDto.setTemParam(temParam);
            templateMessageDto.setSendType(SendType.SEND_BY_OPENID.value);
            templateMessageDto.setOpenId(openid);
            templateMessageDto.setIsApp(false);
            try {
                templateQueueBiz.sendMessageQueue(templateMessageDto);
            } catch (Exception e) {
                LOGGER.error("【模板消息(消)】发送模板消息topic(管理公众号),<ERROR>.[sendMessageQueue]:" + e.getMessage(), e);
            }

            LOGGER.info("资源未配置发送模板消息temParam="+temParam.toString()+"dto="+dto.toString());
        } catch (Exception e) {
            LOGGER.error("编辑管理--删除副编辑,发送模板消息失败<ERROR>" + e.getMessage());
        }
    }



    private Map<String, String> getStringStringMap(BookGroupDTO bookGroupDTO) {
        Map<String, String> temParam = new HashMap<>();
        String word="已有读者扫码！您的二维码“" + bookGroupDTO.getGroupQrcodeName() + "”还未配置任何资源服务。请及时完善该二维码资源服务。";
        temParam.put("first", word);
        temParam.put("keyword1", "【提醒】您的二维码还未配置资源服务");
        temParam.put("keyword2", "请前往编辑端为二维码配置相关资源或服务");
        temParam.put("remark", "请及时处理");
        return temParam;
    }

    @ParamLog("发送模板消息")
    private void sendTemplate(BookGroupDTO dto) {
        try {
            Map<String, String> temParam = getStringStringMap(dto);
            templateConsr.sendManage(SceneCode.PROJECT_TASK_SCENE.value, dto.getAgentId(), dto.getCreateUser(),
                    SystemCode.adviser.code, "", temParam, SendType.SEND_BY_PARTY_ID.value, false);
            LOGGER.info("资源未配置发送模板消息temParam="+temParam.toString()+"dto="+dto.toString());
        } catch (Exception e) {
            LOGGER.error("编辑管理--删除副编辑,发送模板消息失败<ERROR>" + e.getMessage());
        }
    }

}
