import time, json
from django.core.management import BaseCommand
from rocketmq.client import PushConsumer, ConsumeStatus
from concurrent.futures import ThreadPoolExecutor
from automated_main.models.api_automation.api_test_task import APITestTask
from automated_main.view.api_automation.api_test_task.extend.new_task_thread import TaskThread

pool = ThreadPoolExecutor(5, 'publish')

"""
    以扩展命令的方式执行方法, 进行监听消息
    python manage.py init_data
"""
class Command(BaseCommand):
    """
        The actual logic of the command. Subclasses must implement
        this method.
    """

    def handle(self, *args, **options):
        print(" ---- 启动发布消息监听 ---- ")
        consumer = PushConsumer(group_id='GID_test_automated_group', message_model=1)
        consumer.set_name_server_address('rocketmq-dev.rd.com:9876')
        consumer.subscribe('test_publish_topic', callback)
        consumer.start()
        while True:
            time.sleep(60 * 60 * 24)  # 一睡就是一天


"""
    监听到消息之后, 执行的回调方法
"""
def callback(msg):
    try:
        msg_body_str = str(msg.body, "utf-8")
        body = json.loads(msg_body_str)
        if not isinstance(body, dict):
            print(" 非发布消息格式, 暂不处理! ")
        else:
            # 将消息丢到异步线程处理
            task = pool.submit(do_consumer, body)
            # 如果需要拿到消息结果, 则使用task.result()拿结果
            # all_task.append(task)
    except Exception:
        return ConsumeStatus.CONSUME_SUCCESS
    return ConsumeStatus.CONSUME_SUCCESS


def do_consumer(param):
    # 消息内容{"projectName":"sms-base-service","moduleName":"sms-base-starter","env":"prod","branch":"master-27839-1654070365-tag","channel":"QIKE","mode":2,"defaultBranch":"prod","emailToUserList":"yanfuchang@qike366.com,chentaolian@qike366.com","publishId":4812,"publishUserName":"liubo"}
    # 提取消息中的项目名称
    project_name = param.get('projectName', None)
    if project_name is None or project_name == '':
        print(" --- 消息内容不完整, 不处理 --- ")
        return
    print(project_name)
    task = APITestTask.objects.filter(api_test_task_name=project_name).first()
    print("查询到的任务: ", json.dumps(task))
    if task.status == 1:
        print("当前该任务正在执行!")
        return
    else:
        task.status = 1
        task.save()
        # 通过多线程运行测试任务
        TaskThread(task.id).run()
        print("任务开始执行!")
        return
