# coding=utf-8
# 用于MQ的各类操作
import time
import os

from base_framework.public_business.common.UBRD.kw.promotion_keyword import obj_log
from base_framework.public_tools.read_config import ReadConfig, get_current_env, get_current_config
from base_framework.public_tools.runner import Runner
from base_framework.public_tools.custom_error import BusinessError
obj_runner = Runner()


class RocketMQ:

    def __init__(self, env=''):
        self.need_login = True  # 是否需要登录
        self.team = get_current_config(section="run_evn_name", key="current_team")
        if not env:
            env = get_current_env().lower()
        if env.lower() == 'sim':
            if self.team in ['XUEDAU']:
                self.mq_host = ""
                self.need_login = False
            else:
                self.mq_host = "https://mq-console.sim.huohua.cn"
        else:
            if self.team in ['XUEDAU']:
                self.mq_host = "http://10.250.200.3:19876"
                self.need_login = False
            else:
                self.mq_host = "https://mq-console.qa.huohua.cn"

    def mq_query_msg_info(self, topic, begin_time, end_time):
        """查询mq消息"""
        msg_id_list = self.__query_msg_id_list(topic=topic, begin_time=begin_time, end_time=end_time)
        msg_info = []
        for msg_id in msg_id_list:
            m_info = self.__query_msg_detail_by_id(topic=topic, msg_id=msg_id)
            msg_info.append(m_info)
        return msg_info

    def mq_query_msg_info_by_sub_str(self, topic, begin_time, end_time, sub_str=None):
        """查询mq消息，并返回匹配的消息内容"""
        msg_info = self.mq_query_msg_info(topic=topic, begin_time=begin_time, end_time=end_time)
        if sub_str:
            sub_msg = []
            for msg in msg_info:
                if str(sub_str) in str(msg["msg_body"]):
                    sub_msg.append(msg)
            return sub_msg
        else:
            return msg_info

    def __query_msg_id_list(self, topic, begin_time, end_time):
        """查询mq的id列表"""
        mq_url = "{}/message/queryMessageByTopic.query".format(self.mq_host)
        post_data = {"topic": topic,
                     "begin": str(time.mktime(time.strptime(str(begin_time), '%Y-%m-%d %H:%M'))).split('.')[0] + '000',
                     "end": str(time.mktime(time.strptime(str(end_time), '%Y-%m-%d %H:%M'))).split('.')[0] + '000'}
        if self.need_login:
            resp = obj_runner.call_rest_api(user=None, API_URL=mq_url, req_type="GET", params=post_data)
        else:
            resp = obj_runner.call_rest_api(user=None, API_URL=mq_url, req_type="GET", token=False, params=post_data)
        if resp['status'] == 0:
            msg_id_list = []
            for item in resp['data']:
                msg_id_list.append(item['msgId'])
            return msg_id_list
        else:
            raise Exception("查询MQ消息列表失败：{}".format(resp))

    def __query_msg_detail_by_id(self, topic, msg_id):
        """查询mq消息明细"""
        mq_url = "{}/message/viewMessage.query".format(self.mq_host)
        post_data = {"topic": topic, "msgId": msg_id}
        if self.need_login:
            resp = obj_runner.call_rest_api(user=None, API_URL=mq_url, req_type="GET", params=post_data)
        else:
            resp = obj_runner.call_rest_api(user=None, API_URL=mq_url, req_type="GET", token=False, params=post_data)
        if resp['status'] == 0:
            msg_tag = resp['data']['messageView']['properties'].get('TAGS', None)
            msg_key = resp['data']['messageView']['properties'].get('KEYS', None)
            msg_env = resp['data']['messageView']['properties'].get('podenv', None)
            msg_body = resp['data']['messageView'].get('messageBody', None)
            return {"msg_id": msg_id, "msg_tag": msg_tag, "msg_key": msg_key, "msg_env": msg_env, "msg_body": msg_body}
        else:
            raise Exception("查询MQ消息明细失败：{}".format(resp))

    def mq_send_msg(self, topic, message_body, tag=None, key=None, pro=None, **kwargs):
        """mq消息发送"""
        mq_url = "{}/topic/sendTopicMessage.do".format(self.mq_host)
        post_data = {'topic': topic,
                     'tag': tag,
                     'key': key,
                     'messageBody': str(message_body).replace("'", "\"")
                     }
        if not pro:
            # 添加启动文件中的独立环境编号
            cfg_path = os.path.dirname(os.path.dirname(os.path.dirname(__file__)))
            ini_path = cfg_path + '/base_framework/base_config/env_choose.ini'
            jira_id = ReadConfig(ini_path).get_value(sections='run_jira_id', options='huohua-podenv')
            if jira_id:
                post_data['pro'] = jira_id
            else:
                post_data['pro'] = 'qa'
        else:
            post_data['pro'] = pro

        if self.team.lower() == "xuedau":
            resp = obj_runner.call_rest_api(user=None, API_URL=mq_url, req_type="POST", json=post_data, **kwargs)
        else:
            resp = obj_runner.call_rest_api(user=None, API_URL=mq_url, req_type="POST", json=post_data)

        try:
            obj_log.info("发送mq消息返回：{}".format(resp))
            if resp and 'errMsg' in resp and 'timeout' in str(resp['errMsg']):
                time.sleep(1)  # 如果接口返回超时，就再发送一次
                resp = obj_runner.call_rest_api(user=None, API_URL=mq_url, req_type="POST", json=post_data)
            elif resp and 'message' in resp and '无效的token' in str(resp['message']):
                time.sleep(1)  # 如果token过期，就再发送一次
                resp = obj_runner.call_rest_api(user=None, API_URL=mq_url, req_type="POST", json=post_data)
            elif resp and resp['status'] == 0 and resp['data']['sendStatus'] == 'SEND_OK':
                return True
            else:
                raise Exception("发送mq消息失败：{}".format(resp))
        except Exception as e:
            obj_log.info("发送mq消息体：{}".format(post_data))
            raise Exception("发送mq消息失败：{}|{}".format(e, resp))


if __name__ == '__main__':

    mq = RocketMQ()
    mb = {"platformId": 2, "eventType": "user.join", "roleType": 200, "roleId": 48711, "appId": "", "source": "SparkEnglish", "classroomCode": "", "classroomType": 1, "scheduleCode": "ECR666358307917090884", "joinTime": 1747189786903, "classSizeType": 1, "isFirst": "", "subChannelCodeList": "", "deviceId": "20200830-9CFC-E8BE-8D68-9CFCE8BE8D6C", "classroomVersion": "25.5.3-qa.2212381", "appVersion": "25.4.7-stable.2172220"}
    rsp = mq.mq_send_msg(topic='CP_CLASSROOM_STATUS_SYNC', message_body=mb, tag='TAG_ROLE_JOIN_TIME', pro='QA', xuedau="")
    print(rsp)


