
package com.gic.haoban.manage.api.util.notify;

import com.alibaba.fastjson.JSONObject;
import com.gic.commons.util.GICMQClientUtil;
import com.gic.haoban.manage.api.dto.notify.qdto.NoticeMessageQDTO;
import com.gic.haoban.manage.api.enums.NoticeMessageTypeEnum;
import com.gic.mq.sdk.GicMQClient;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * Created 2021/12/17.
 *
 * @author hua
 */
public class NoticeMessageUtil {

    private static final Logger logger = getLogger(NoticeMessageUtil.class);

    //com.gic.haoban.manage.api.service.notify.NoticeMessageApiService#run
    private static final String NOTICE_MESSAGE = "haobanNoticeMessage";

    private static final String NOTICE_MESSAGE_BATCH = "haobanNoticeMessageBatch";

    /**
     * 发送消息
     *
     * @param enterpriseId 企业id
     * @param clerkId      执行人导购
     * @param messageType  消息类型 NoticeMessageTypeEnum
     * @param optTargetId 操作对象
     * @param fieldMap     解析模板的字段
     * @param extendField  拓展字段给前端使用 没有可以为null
     */
    public static void sendNoticeMessage(String enterpriseId, String clerkId, int messageType, String optTargetId, Map<String, String> fieldMap, Map<String, Object> extendField) {
        if (StringUtils.isAnyBlank(enterpriseId, clerkId)) {
            throw new RuntimeException("必传参数没传");
        }
        NoticeMessageTypeEnum messageTypeEnum = NoticeMessageTypeEnum.getByType(messageType);
        if (messageTypeEnum == null) {
            throw new RuntimeException("消息类型不存在");
        }
        NoticeMessageQDTO noticeMessageQDTO = new NoticeMessageQDTO();
        noticeMessageQDTO.setEnterpriseId(enterpriseId);
        noticeMessageQDTO.setClerkId(clerkId);
        noticeMessageQDTO.setMessageType(messageType);
        noticeMessageQDTO.setContentMap(fieldMap);
        noticeMessageQDTO.setExtendContent(extendField);
        noticeMessageQDTO.setOptTargetId(optTargetId);
        String ret = JSONObject.toJSONString(noticeMessageQDTO);
        logger.info("发送消息：{}", ret);
        GicMQClient clientInstance = GICMQClientUtil.getClientInstance();
        try {
            clientInstance.sendMessage(NOTICE_MESSAGE, ret);
        } catch (Exception e) {
            logger.info("发送消息异常：{}", e);
        }
    }


    /**
     * 发送消息 对象里面的字段 解析
     *   enterpriseId 企业id
     *   clerkId      执行人导购
     *   messageType  消息类型 NoticeMessageTypeEnum
     *   optTargetId 操作对象
     *   fieldMap     解析模板的字段
     *   extendField  拓展字段给前端使用 没有可以为null
     * @param list
     */
    public static void sendNoticeMessageBatch(List<NoticeMessageQDTO> list) {
        if (CollectionUtils.isEmpty(list)) {
            logger.info("没有哦需要发送的消息");
            return;
        }
        List<String> ret = new ArrayList<String>();
        for (NoticeMessageQDTO noticeMessageQDTO : list) {
            String retStr = JSONObject.toJSONString(noticeMessageQDTO);
            if (StringUtils.isAnyBlank(noticeMessageQDTO.getEnterpriseId(), noticeMessageQDTO.getClerkId())) {
                logger.info("参数不存在：{}", retStr);
                throw new RuntimeException("必传参数没传:" + noticeMessageQDTO.getClerkId());
            }
            NoticeMessageTypeEnum messageTypeEnum = NoticeMessageTypeEnum.getByType(noticeMessageQDTO.getMessageType());
            if (messageTypeEnum == null) {
                logger.info("类型不存在：{}", retStr);
                throw new RuntimeException("消息类型不存在");
            }
            ret.add(retStr);
            logger.info("发送消息单条：{}", retStr);
        }
        logger.info("批量发送消息：{}", ret.size());
        GicMQClient clientInstance = GICMQClientUtil.getClientInstance();
        try {
            clientInstance.sendBatchMessages(NOTICE_MESSAGE, ret);
        } catch (Exception e) {
            logger.info("发送消息异常：{}", e);
        }
    }



    /**
     * 发送消息 使用staffId发送
     *
     * @param enterpriseId 企业id
     * @param staffId      发送人
     * @param clerkId      执行人导购
     * @param messageType  消息类型 NoticeMessageTypeEnum
     * @param optTargetId  操作对象
     * @param fieldMap     解析模板的字段
     * @param extendField  拓展字段给前端使用 没有可以为null
     */
    public static void sendNoticeMessageByStaff(String enterpriseId, String staffId, String clerkId, int messageType, String optTargetId, Map<String, String> fieldMap, Map<String, Object> extendField) {
        if (StringUtils.isAnyBlank(enterpriseId, clerkId, staffId)) {
            throw new RuntimeException("必传参数没传");
        }
        NoticeMessageTypeEnum messageTypeEnum = NoticeMessageTypeEnum.getByType(messageType);
        if (messageTypeEnum == null) {
            throw new RuntimeException("消息类型不存在");
        }
        NoticeMessageQDTO noticeMessageQDTO = new NoticeMessageQDTO();
        noticeMessageQDTO.setEnterpriseId(enterpriseId);
        noticeMessageQDTO.setStaffId(staffId);
        noticeMessageQDTO.setClerkId(clerkId);
        noticeMessageQDTO.setMessageType(messageType);
        noticeMessageQDTO.setContentMap(fieldMap);
        noticeMessageQDTO.setExtendContent(extendField);
        noticeMessageQDTO.setOptTargetId(optTargetId);
        String ret = JSONObject.toJSONString(noticeMessageQDTO);
        logger.info("发送消息：{}", ret);
        GicMQClient clientInstance = GICMQClientUtil.getClientInstance();
        try {
            clientInstance.sendMessage(NOTICE_MESSAGE, ret);
        } catch (Exception e) {
            logger.info("发送消息异常：{}", e);
        }
    }

    /**
     * 构建小程序跳转url
     * @param messageTypeEnum
     * @param data
     * @return
     */
    public static String buildMiniAppUrl(NoticeMessageTypeEnum messageTypeEnum, String data) {
        if (StringUtils.isNotBlank(data)) {
            try {
                data = URLEncoder.encode(data, StandardCharsets.UTF_8.name());
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage());
            }
        }
        String appUrl = messageTypeEnum.getPageUrl();
        if (StringUtils.isNotBlank(messageTypeEnum.getPageType())) {
            appUrl += messageTypeEnum.getPageType();
        }
        appUrl += "&data=" + data;
        return appUrl;
    }
}
