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


def get_task_live(url, task_id, token, offset=0, timeout=60):
    '''
    用来获取任务实时流数据
    url: sse连接地址，如 http://xxx/api/v3/task/live
    task_id: 任务Id
    token: 凭据(access_token)
    offset: 偏移量
    timeout: 超时时间
    '''
    params = {
        'task_id': task_id,
        'offset': offset,
        'access_token': token
    }
    headers = {'Accept': 'text/event-stream'}
    oplist = []
    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:
            break
        if 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','V3_d1b7a820199d45c5955a2b09b13182d8','V3_0e6364b3ba484323856beff1aa0fea91','1aa91f3e-bee6-4284-83ec-6b0d3cb60e48'))

