package com.customization.yll.liuzhoucitycollege.integration;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudstore.dev.api.bean.MessageBean;
import com.customization.yll.common.util.Md5Util;
import com.customization.yll.liuzhoucitycollege.api.JinzhiApiManager;
import com.customization.yll.liuzhoucitycollege.api.JinzhiTokenManager;
import com.customization.yll.liuzhoucitycollege.config.JinzhiConfiguraton;
import com.engine.msgcenter.entity.MsgSubInterface;
import com.engine.msgcenter.entity.MsgSubParam;
import com.weaver.base.msgcenter.sub.StandardSub;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yaolilin
 * @desc 消息推送到金智，用消息订阅方式实现，适用于金智接口 3.6.1.Beta2+ 版本
 * @date 2024/12/1
 **/
public class MessagePushToJz extends StandardSub {
    private final Logger log = LoggerFactory.getLogger(this.getClass());
    private final JinzhiTokenManager tokenManager = new JinzhiTokenManager();
    private final JinzhiApiManager apiManager = new JinzhiApiManager();

    /**
     * 对原始消息订阅参数进行修改
     */
    @Override
    public Map<String, Object> getSubMsgParams(MessageBean messageBean, MsgSubInterface msgSubInterface,
                                               List<MsgSubParam> list) {
        Map<String, Object> params = super.getSubMsgParams(messageBean, msgSubInterface, list);
        log.info("原始参数：" + params);
        params.put("sign", getSign(params));
        if (params.get("receiverType") == null ||
                params.get("receiverType") != null && "1".equals(params.get("receiverType"))){
            params.put("receivers", getReceivers(params));
        }
        log.info("修改后参数："+params);
        return params;
    }

    /**
     * 重写消息推送逻辑，将消息推送到金智
     */
    @Override
    public String doSub(MessageBean messageBean, MsgSubInterface msgSubInterface, List<MsgSubParam> list) {
        String apiAddress = msgSubInterface.getInterfaceAds();
        apiAddress += "?appId=" + JinzhiConfiguraton.getAppId() + "&accessToken=" + tokenManager.getToken();
        log.info("接口地址："+apiAddress);
        Map<String, Object> params = getSubMsgParams(messageBean, msgSubInterface, list);
        JSONObject body = new JSONObject(params);
        log.info("推送参数："+ body.toJSONString());
        String result = apiManager.callApi(apiAddress, body.toJSONString());
        if (StrUtil.isEmpty(result)) {
            log.error("消息发送失败，接口请求错误，消息id：" + messageBean.getMessageId());
            return "";
        }
        log.info("消息推送结果：" + result);
        JSONObject resultJson = JSON.parseObject(result);
        if (!"200".equals(resultJson.getString("status"))) {
            log.error("消息发送失败");
            return "";
        }
        log.info("消息推送成功，消息id："+messageBean.getMessageId());
        return "SUCCESS";
    }

    /**
     * 将原始的接收者参数转换成金智接口的接收者参数
     */
    private List<Map<String, Object>> getReceivers(Map<String, Object> params) {
        if (params.get("receivers") == null) {
            return new ArrayList<>();
        }
        List<Map<String, Object>> result = new ArrayList<>();
        @SuppressWarnings("unchecked")
        List<String > receivers = (List<String >) params.get("receivers");
        for (String loginId : receivers) {
            Map<String, Object> user = new HashMap<>();
            user.put("userId", loginId);
            result.add(user);
        }
        return result;
    }

    private String getSign(Map<String, Object> params) {
        String firstUserId = "";
        if (params.get("receivers") != null) {
            @SuppressWarnings("unchecked")
            List<String > receivers = (List<String >) params.get("receivers");
            if (!receivers.isEmpty()) {
                firstUserId = receivers.get(0);
            }
        }
        String accessToken = tokenManager.getToken();
        return Md5Util.createMd5(accessToken + firstUserId);
    }
}
