import requests
import sseclient
import time
import json


def get_ablId(url,sessionId,streamId,token,timeout=180):
    '''
    用来获取探索id，返回的是探索会话的id
    url:sse连接地址；
    sessionId：会话Id
    streamId：本次对话Id
    token：凭据
    '''
    params = {
        'sessionId':sessionId,
        'streamId':streamId,
        'access_token':token
    }
    headers = {'Accept': 'text/event-stream'}
    opdata = []
    response = requests.get(url=url,params=params,headers=headers,stream=True)
    client = sseclient.SSEClient(response)
    starttime = time.time()
    for msg in client.events():
        # 处理每个接收到的消息
        localtime = time.time()
        if localtime > starttime + timeout:
            opdata = "获取探索id超时"
            break
        if 'ABL' in msg.data:
            # print("Received Message:", msg.data)
            opdata = json.loads(msg.data)
            break
    return opdata

def get_message(url,sessionId,streamId,token,timeout=180):
    '''
    用来获取普通的message消息，返回的是一个消息列表
    url:sse连接地址；
    sessionId：会话Id
    streamId：本次对话Id
    token：凭据
    '''
    params = {
        'sessionId':sessionId,
        'streamId':streamId,
        'access_token':token
    }
    headers = {'Accept': 'text/event-stream'}
    oplist = []
    response = requests.get(url=url,params=params,headers=headers,stream=True)
    client = sseclient.SSEClient(response)
    for msg in client.events():
        # 处理每个接收到的消息
        if msg.data:
            # print("Received Message:", msg.data)
            oplist.append(msg.data)
    return oplist


# print(get_expId('http://bitagent.sit.ninetechone.com/api/chat/read','CB_2a7714d1e41e4d0891fc5c13a39a4063','CB_a556efbc8502461ba473d789da439c55','Bearer c1391926-e8ba-46c0-a0d1-c5e3c38503da'))
# print(get_expId('http://bitagent.sit.ninetechone.com/api/chat/read','CB_e48bea09fe1e4c8388883ff11384bef8','CB_0e7c9c99d6494d9f977b0c2fbb73e2e3','Bearer c1391926-e8ba-46c0-a0d1-c5e3c38503da'))
# print(get_message('http://bitagent.sit.ninetechone.com/api/chat/read','CB_e268fb27e7d146009d18e0912c23be58','CB_bc6ed32cc3e0476d90c7b243c75cf2a9','Bearer c1391926-e8ba-46c0-a0d1-c5e3c38503da'))
