import json

import httpx
import requests

from Log import logger


class BasicService:
    def __init__(self, base_url: str):
        self.base_url = base_url

    def _check_response(self, response: httpx.Response):
        """检查响应并处理错误"""
        if response.status_code not in [200, 201]:
            # raise Exception(f"Failed to fetch data from API: {response.status_code}")
            logger.error(f"Failed to fetch data from API:")
            logger.error(response.status_code)
        response_data = response.json()
        return response_data

    async def download_from_url(self, url, params=None):
        async with httpx.AsyncClient() as client:
            async with client.stream('GET', url, params=params) as response:
                if response.status_code == 200:
                    # 获取文件名
                    content_disposition = response.headers.get('Content-Disposition')
                    if content_disposition:
                        filename = content_disposition.split('filename=')[1].strip('"')
                    else:
                        filename = 'unknown_filename'

                    # 获取内容类型
                    content_type = response.headers.get('Content-Type')

                    # 读取文件内容
                    content = await response.aread()
                    return content, filename, content_type
                else:
                    raise Exception(f"Failed to download: {response.status_code}")

    async def excel_talk_image_download(self, file_id: str):
        url = f"{self.base_url}/exceltalk/download/image"
        return await self.download_from_url(url, params={'images_name': file_id})

    async def excel_talk_excel_download(self, file_id: str):
        url = f"{self.base_url}/exceltalk/download/excel"
        return await self.download_from_url(url, params={'excel_name': file_id})

    async def excel_talk_upload(self, chat_id: str, files):
        url = f"{self.base_url}/exceltalk/upload/files"
        params = {'chat_id': chat_id, 'is_col': '0'}

        async with httpx.AsyncClient(timeout=300) as client:
            response = await client.post(
                url,
                files=files,
                params=params
            )
            return self._check_response(response)

    async def excel_talk(self, question: str, chat_id: str):
        url = f"{self.base_url}/exceltalk/talk"
        params = {'chat_id': chat_id}
        data = {"query": question}
        headers = {'Content-Type': 'application/json'}
        with requests.post(url, headers=headers, json=data, params=params, timeout=60,
                           stream=True) as response:
            for line in response.iter_lines():
                if line:
                    decoded_line = line.decode("utf-8")
                    try:
                        if decoded_line.startswith("data:"):
                            decoded_line = decoded_line[5:]
                        answer = json.loads(decoded_line)
                        answer["type"] = "message"
                        yield answer
                    except GeneratorExit as e:
                        logger.error("------------except GeneratorExit as e:---------------------")
                        logger.error(e)
                        print(e)
                        yield {"message": "内部错误", "type": "close"}
                    # finally:
                    #     # 在所有数据接收完毕后返回close
                    #     yield {"message": "", "type": "close"}

                else:
                    continue
                    # yield f"Error: {response.status_code}"
            else:
            # 在所有数据接收完毕后返回close
                yield {"message": "", "type": "close"}

    async def questions_talk(self, question, chat_id: str):
        logger.error("---------------questions_talk--------------------------")
        url = f"{self.base_url}/questions/talk"
        params = {'chat_id': chat_id}
        headers = {'Content-Type': 'text/plain'}
        async with httpx.AsyncClient(timeout=1800) as client:
            response = await client.post(
                url,
                data=question,
                headers=headers,
                params=params
            )
            return self._check_response(response)

    async def questions_talk_word_download(self, file_id: str):
        url = f"{self.base_url}/questions/download/word"
        return await self.download_from_url(url, params={'word_name': file_id})