import requests
import sseclient
import time
import json


def get_expId(url,sessionId,streamId,token,timeout=180):
    '''
    用来获取探索id，返回的是探索会话的id
    url:sse连接地址；
    sessionId：会话Id
    streamId：本次对话Id
    token：凭据
    '''
    params = {
        'sessionId':sessionId,
        'streamId':streamId,
        'access_token':token
    }
    print(params)
    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 'EXP'  in msg.data or 'TSK' in msg.data:
            # print("Received Message:", msg.data)
            opdata = json.loads(msg.data)
            break
        elif msg.data != "":
            print(msg.data)
    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','P_CB_f21b81ef55ab48f8b87530500ced227d','P_CB_976bebae52514b39a140e38f88cd2dee','Bearer d25c4717-087b-4472-aaaa-2a1939f22680'))
# 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','P_CB_f21b81ef55ab48f8b87530500ced227d','P_CB_976bebae52514b39a140e38f88cd2dee','Bearer d25c4717-087b-4472-aaaa-2a1939f22680'))
