# -*- coding: utf-8 -*-
import loguru
import requests
import sys
from collections import defaultdict
from datetime import datetime, timedelta
import json
import os
from loguru import logger
from concurrent.futures import ThreadPoolExecutor
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, PatternFill
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(BASE_DIR)
from aidso_geo.models.doubao_android_data_process import doubao_mobile_process_original_data
from aidso_geo.models.qianwen_android_data_process import qianwen_android_process_original_data
import aidso_geo.utils.bh_utils as bh_utils
import aidso_geo.utils.tos_utils as tos_utils


class ExcelWriter:

    def __init__(self, file_path):
        # 如果没有 .xlsx 后缀，自动补上
        if not file_path.lower().endswith(".xlsx"):
            file_path += ".xlsx"

        self.file_path = file_path

        # 自动创建父目录
        parent_dir = os.path.dirname(self.file_path)
        if parent_dir and not os.path.exists(parent_dir):
            os.makedirs(parent_dir, exist_ok=True)

        self.workbook = Workbook()
        self.worksheet = self.workbook.active
        self.worksheet.title = "Sheet1"

    def write_batch_rows(self, data_list):
        """
        批量写入数据
        :param data_list: list[dict]
        """
        if len(data_list) == 0:
            return

        # 取第一条数据的 key 作为表头
        headers = list(data_list[0].keys())

        # 写表头
        for col_idx, header in enumerate(headers, start=1):
            self.worksheet.cell(row=1, column=col_idx, value=header)

        # 写数据
        for row_idx, row_data in enumerate(data_list, start=2):
            for col_idx, header in enumerate(headers, start=1):
                self.worksheet.cell(row=row_idx, column=col_idx, value=row_data.get(header, ""))

        # 保存文件
        self.workbook.save(self.file_path)

    def close(self):
        if self.workbook:
            self.workbook.close()


def regroup_by_brand(data_list):
    brand_map = defaultdict(list)

    for item in data_list:
        brand_name = (item.get("brand_name") or "").strip()
        req_id = item.get("req_id")
        created_at = item.get("created_at")

        if not brand_name or not req_id:
            continue

        brand_map[brand_name].append({
            "req_id": req_id,
            "created_at": created_at
        })

    result = []
    for brand_name, items in brand_map.items():
        # 按 created_at 排序
        items = sorted(items, key=lambda x: x.get("created_at") or "")
        result.append({
            "brand_name": brand_name,
            "data": items
        })

    return result


plat_form_map = {
    "DP": "deepseek网页版",
    "DB": "豆包网页版",
    "TXYB": "腾讯元宝",
    "TYQW": "通义千问",
    "KIMI": "kimi",
    "WXYY": "文心一言",
    "BDAI": "百度ai",
    "DYAI": "抖音ai",
    "DOUBA": "豆包手机版",
    "DPA": "deepseek手机版",
    "TXYBA": "腾讯元宝手机版",
    "TYQWA": "通义千问手机版",
}


def to_excel(req_data_list, file_name, output_dir):
    if not req_data_list:
        print(f"{file_name} 没有可导出的 req 数据")
        return

    # 1. 构造 req_id -> created_at 映射
    req_time_map = {}
    req_ids = []

    for item in req_data_list:
        req_id = item.get("req_id")
        created_at = item.get("created_at")
        if not req_id:
            continue
        req_ids.append(req_id)
        req_time_map[req_id] = created_at

    if not req_ids:
        print(f"{file_name} 没有有效 req_id")
        return

    # 去重，避免 SQL 重复
    req_ids = list(dict.fromkeys(req_ids))

    # 2. 拼 SQL IN
    req_id_sql = ",".join([f"'{req_id}'" for req_id in req_ids])

    query_sql = f"select * from geo_commit_task where reqId in ({req_id_sql}) and platform in ('DB','DOUBA','TYQW','TXYB')"

    query_list = bh_utils.query_data(query_sql)

    if not query_list:
        print(f"{file_name} 查询不到 geo_commit_task 数据")
        return

    plat_form_map = {
        "DP": "deepseek网页版",
        "DB": "豆包网页版",
        "TXYB": "腾讯元宝",
        "TYQW": "通义千问",
        "KIMI": "kimi",
        "WXYY": "文心一言",
        "BDAI": "百度ai",
        "DYAI": "抖音ai",
        "DOUBA": "豆包手机版",
        "DPA": "deepseek手机版",
    }

    task_list = []
    for i in query_list:
        task_list.append(
            {
                "prompt": i.get("prompt"),
                "content": tos_utils.get_string_from_tos(f"geo/{i.get('taskId')}/{i.get('platform')}/context.txt"),
                "platform": plat_form_map[i.get("platform")],
                "created_at": req_time_map.get(i.get('reqId')),
            }
        )
    excel_writer = ExcelWriter(output_dir)
    excel_writer.write_batch_rows(task_list)
    excel_writer.close()

    print(f"{file_name} 数据已成功写入Excel文件: {output_dir}")


def export_all_brand_excel(data_list, phone, begin):
    """
    按品牌批量导出 Excel
    """
    grouped_data = regroup_by_brand(data_list)

    if not grouped_data:
        print("没有可分组导出的数据")
        return

    for item in grouped_data:
        brand_name = item.get("brand_name")
        req_data_list = item.get("data", [])
        out_date = f"{begin.replace('-', '')}"
        output_dir = f"/Users/yaowentong/Desktop/original_{out_date}/{phone}/{out_date}/{brand_name}_{out_date}_original"
        to_excel(req_data_list, brand_name, output_dir=output_dir)


def get_req_id(phone, begin, end):
    url = f"https://openapi.aidso.com/openapi/ywt/geoReqList?phone={phone}&begin={begin} 00:00:00&end={end} 23:59:59"

    payload = {}
    headers = {
        'Authorization': ''
    }

    response = requests.request("GET", url, headers=headers, data=payload, timeout=30)
    return response.json().get('data')


def get_url_top40(user_id, brand_library_id, begin, end, p, question_list=None):
    url = "https://openapi.aidso.com/openapi/ywt/trends"

    if isinstance(p, str):
        p = [p]
    payload_data = {
        "brand_library_id": brand_library_id,
        "user_id": user_id,
        "begin_time": f'{begin} 00:00:00',
        "end_time": f'{end} 23:59:59',
        "limit": 40,
        "platform_list": p
    }
    if question_list is not None:
        payload_data["question_list"] = question_list
    payload = json.dumps(payload_data)
    headers = {
        'Authorization': '',
        'Content-Type': 'application/json'
    }

    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get('data')


def export_base_info(phone, begin, end):
    data_list = get_req_id(phone, begin, end)
    export_all_brand_excel(data_list, phone, begin)


def generate_date_list(start_date: str, end_date: str):
    start = datetime.strptime(start_date, "%Y-%m-%d")
    end = datetime.strptime(end_date, "%Y-%m-%d")

    if start > end:
        return []

    result = []
    current = start

    while current <= end:
        result.append(current.strftime("%Y-%m-%d"))
        current += timedelta(days=1)

    return result


def get_refer_rate_heatmap(brand_library_id, user_id, begin_time, end_time, question_list=None):
    url = "https://openapi.aidso.com/openapi/ywt/platforms"

    payload_data = {
        "brand_library_id": brand_library_id,
        "user_id": user_id,
        "begin_time": f"{begin_time} 00:00:00",
        "end_time": f"{end_time} 23:59:59"
    }
    if question_list is not None:
        payload_data["question_list"] = question_list
    payload = json.dumps(payload_data)
    headers = {
        'Content-Type': 'application/json'
    }

    try:
        response = requests.post(
            url,
            headers=headers,
            data=payload,
            timeout=15
        )
        response.raise_for_status()
        result = response.json()

        if result.get("code") == 200:
            return result.get("data", {})

        return []

    except requests.RequestException as e:
        print(f"请求失败: {e}")
        return []
    except ValueError as e:
        print(f"返回结果不是合法 JSON: {e}")
        return []
        # print(response.text)


def get_platforms(brand_library_id, user_id, begin_time, end_time, question_list=None):
    url = "https://openapi.aidso.com/openapi/ywt/platforms"

    payload_data = {
        "brand_library_id": brand_library_id,
        "user_id": user_id,
        "begin_time": f"{begin_time} 00:00:00",
        "end_time": f"{end_time} 23:59:59"
    }
    if question_list is not None:
        payload_data["question_list"] = question_list
    payload = json.dumps(payload_data)
    headers = {
        'Content-Type': 'application/json'
    }

    try:
        response = requests.post(
            url,
            headers=headers,
            data=payload,
            timeout=15
        )
        response.raise_for_status()
        result = response.json()

        if result.get("code") == 200:
            return result.get("data", {})

        return []

    except requests.RequestException as e:
        print(f"请求失败: {e}")
        return []
    except ValueError as e:
        print(f"返回结果不是合法 JSON: {e}")
        return []
        # print(response.text)


def get_all_word_rank(brand_library_id, user_id, begin_time, end_time, question_list=None):
    url = "https://openapi.aidso.com/openapi/ywt/all_word_rank"

    payload_data = {
        "brand_library_id": brand_library_id,
        "user_id": user_id,
        "begin_time": f"{begin_time} 00:00:00",
        "end_time": f"{end_time} 23:59:59",
        "last": True
    }
    if question_list is not None:
        payload_data["question_list"] = question_list
    payload = json.dumps(payload_data)
    headers = {
        'Content-Type': 'application/json'
    }

    try:
        response = requests.post(
            url,
            headers=headers,
            data=payload,
            timeout=15
        )
        response.raise_for_status()
        result = response.json()

        if result.get("code") == 200:
            return result.get("data", [])

        return []

    except requests.RequestException as e:
        print(f"请求失败: {e}")
        return []
    except ValueError as e:
        print(f"返回结果不是合法 JSON: {e}")
        return []


def get_sentiment_overview(brand_library_id, user_id, begin_time, end_time, question_list=None):
    url = "https://openapi.aidso.com/openapi/ywt/overview"

    payload_data = {
        "brand_library_id": brand_library_id,
        "user_id": user_id,
        "begin_time": f"{begin_time} 00:00:00",
        "end_time": f"{end_time} 23:59:59"
    }
    if question_list is not None:
        payload_data["question_list"] = question_list
    payload = json.dumps(payload_data)
    headers = {
        'Content-Type': 'application/json'
    }

    try:
        response = requests.post(
            url,
            headers=headers,
            data=payload,
            timeout=15
        )
        response.raise_for_status()
        result = response.json()

        if result.get("code") == 200:
            return result.get("data", {})

        return []

    except requests.RequestException as e:
        print(f"请求失败: {e}")
        return []

    # response = requests.request("POST", url, headers=headers, data=payload)
    #
    # print(response.text)


def get_platforms_sentiment(brand_library_id, user_id, begin_time, end_time, question_list=None):
    url = "https://openapi.aidso.com/openapi/ywt/platforms/sentiment"

    payload_data = {
        "brand_library_id": brand_library_id,
        "user_id": user_id,
        "begin_time": f"{begin_time} 00:00:00",
        "end_time": f"{end_time} 23:59:59",
        "last": True
    }
    if question_list is not None:
        payload_data["question_list"] = question_list
    payload = json.dumps(payload_data)
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        response = requests.post(
            url,
            headers=headers,
            data=payload,
            timeout=15
        )
        response.raise_for_status()
        result = response.json()

        if result.get("code") == 200:
            return result.get("data", {})

        return []

    except requests.RequestException as e:
        print(f"请求失败: {e}")
        return []


def get_site_category(brand_library_id, user_id, begin_time, end_time, p, question_list=None):
    url = "https://openapi.aidso.com/openapi/ywt/statistics/site_category"
    if isinstance(p, str):
        p = [p]
    payload_data = {
        "brand_library_id": brand_library_id,
        "user_id": user_id,
        "begin_time": f"{begin_time} 00:00:00",
        "end_time": f"{end_time} 23:59:59",
        "platform_list": p,
    }
    if question_list is not None:
        payload_data["question_list"] = question_list
    payload = json.dumps(payload_data)
    headers = {
        'Content-Type': 'application/json'
    }

    try:
        response = requests.post(
            url,
            headers=headers,
            data=payload,
            timeout=15
        )
        response.raise_for_status()
        result = response.json()

        if result.get("code") == 200:
            return result.get("data", [])

        return []

    except requests.RequestException as e:
        print(f"请求失败: {e}")
        return []


def get_quote_mention_word_cloud(brand_library_id, user_id, begin_time, end_time, question_list=None):
    url = "https://openapi.aidso.com/openapi/ywt/quote_mention_word_cloud"

    payload_data = {
        "brand_library_id": brand_library_id,
        "user_id": user_id,
        "begin_time": f"{begin_time} 00:00:00",
        "end_time": f"{end_time} 23:59:59"
    }
    if question_list is not None:
        payload_data["question_list"] = question_list
    payload = json.dumps(payload_data)
    headers = {
        'Content-Type': 'application/json'
    }

    try:
        response = requests.post(
            url,
            headers=headers,
            data=payload,
            timeout=15
        )
        response.raise_for_status()
        result = response.json()

        if result.get("code") == 200:
            return result.get("data", {})

        return []

    except requests.RequestException as e:
        print(f"请求失败: {e}")
        return []


def get_quto_statistics(brand_library_id, user_id, begin_time, end_time, question_list=None):
    url = "https://openapi.aidso.com/openapi/ywt/statistics"

    payload_data = {
        "brand_library_id": brand_library_id,
        "user_id": user_id,
        "begin_time": f"{begin_time} 00:00:00",
        "end_time": f"{end_time} 23:59:59"
    }
    if question_list is not None:
        payload_data["question_list"] = question_list
    payload = json.dumps(payload_data)
    headers = {
        'Content-Type': 'application/json'
    }

    try:
        response = requests.post(
            url,
            headers=headers,
            data=payload,
            timeout=15
        )
        response.raise_for_status()
        result = response.json()

        if result.get("code") == 200:
            return result.get("data", {})

        return []

    except requests.RequestException as e:
        print(f"请求失败: {e}")
        return []


def cha_report(phone_list, begin, end):
    for ph in phone_list:
        for de in generate_date_list(begin, end):
            data_list = get_req_id(ph, de, de)
            out_date = f"{de.replace('-', '')}"

            export_base_info(ph, de, de)
            print(f"ph:{ph}---de{de}开始执行")
            result = []
            seen = set()
            if data_list:
                for i in data_list:
                    item = {
                        "user_id": i.get("user_id"),
                        "brand_library_id": i.get("brand_library_id"),
                        "brand_name": i.get("brand_name")
                    }

                    key = (item["user_id"], item["brand_library_id"], item["brand_name"])
                    if key not in seen:
                        seen.add(key)
                        result.append(item)

                for r in result:
                    # platforms = ["DB", "DOUBA", "TYQW", "TXYB"]
                    platforms = ["DB", "DOUBA", "TYQW", "TXYB", "DP", "DPA", "TXYBA", "TYQWA", "BDAI", "WXYY", "KIMI",
                                 "DYAI"]
                    for p in platforms:
                        t_data = get_url_top40(r.get('user_id'), r.get('brand_library_id'), de, de, p)
                        fields = ["site_name", "log_count", "quote_ratio_percent"]
                        result = [{k: item.get(k) for k in fields} for item in t_data]
                        out_path = f"/Users/yaowentong/Desktop/source_{out_date}/{ph}/{out_date}{p}_source/{r.get('brand_name')}_{out_date}_source"
                        writer = ExcelWriter(out_path)
                        writer.write_batch_rows(result)
                        writer.close()


def zhou_report_suggestion(phone, begin, end, brand_name, platform=None):
    req_list = get_req_id(phone, begin, end)

    req_time_map = {}
    req_ids = []
    for item in req_list:
        print(item)
        if item.get('brand_name') == brand_name:
            req_id = item.get("req_id")
            created_at = item.get("created_at")
            req_ids.append(req_id)
            req_time_map[req_id] = created_at
    req_id_sql = ",".join([f"'{req_id}'" for req_id in req_ids])
    if platform:
        platform_list = ",".join([f"'{p}'" for p in platform])
        query_sql = f"select * from geo_commit_task where reqId in ({req_id_sql}) and platform in ({platform_list}) "
    else:
        query_sql = f"select * from geo_commit_task where reqId in ({req_id_sql})"

    query_list = bh_utils.query_data(query_sql)

    result = []
    if query_list:
        for q in query_list:
            r = {
                "prompt": q.get('prompt'),
                "platform": plat_form_map[q.get('platform')],
                "suggestions": tos_utils.get_string_from_tos(
                    f"geo/{q.get('taskId')}/{q.get('platform')}/suggestions.txt"),
                "created_at": req_time_map[q.get('reqId')],
            }
            result.append(r)
        all_file = f"/Users/yaowentong/Desktop/{brand_name}_all.txt"
        with open(all_file, "w", encoding="utf-8") as f:
            for item in result:
                f.write(json.dumps(item, ensure_ascii=False) + "\n\n\n")


def qian_report(phone, begin, end, brand_name, platform=None):
    req_list = get_req_id(phone, begin, end)
    req_ids = []
    req_time_map = {}
    for item in req_list:
        if item.get('brand_name') == brand_name:
            req_id = item.get("req_id")
            created_at = item.get("created_at")
            req_ids.append(req_id)
            req_time_map[req_id] = created_at

    req_id_sql = ",".join([f"'{req_id}'" for req_id in req_ids])
    if platform:
        platform_list = ",".join([f"'{p}'" for p in platform])
        query_sql = f"select * from geo_commit_task where reqId in ({req_id_sql}) and platform in ({platform_list}) "
    else:
        query_sql = f"select * from geo_commit_task where reqId in ({req_id_sql})"
    query_list = bh_utils.query_data(query_sql)

    result = []
    if query_list:
        for q in query_list:
            r = {
                "prompt": q.get('prompt'),
                "reqId": q.get('reqId'),
                "platform": plat_form_map[q.get('platform')],
                "content": tos_utils.get_string_from_tos(f"geo/{q.get('taskId')}/{q.get('platform')}/context.txt"),
                "quote": tos_utils.get_string_from_tos(f"geo/{q.get('taskId')}/{q.get('platform')}/quote.txt"),
                "created_at": req_time_map[q.get('reqId')]
            }
            result.append(r)
        all_file = f"/Users/yaowentong/Desktop/{brand_name}_all.txt"
        lite_file = f"/Users/yaowentong/Desktop/{brand_name}_lite.txt"
        with open(all_file, "w", encoding="utf-8") as f:
            for item in result:
                f.write(json.dumps(item, ensure_ascii=False) + "\n\n\n")

        remove_keys = {"site_icon", "task_id", "quto_id"}
        data = []
        with open(all_file, "r", encoding="utf-8") as f:
            for line in f:
                line = line.strip()
                if not line:
                    continue

                item = json.loads(line)

                quote = item.get("quote")
                if quote:
                    quote_list = json.loads(quote)  # 把 quote 字符串转成 list

                    for one in quote_list:  # one 是每个 dict
                        if isinstance(one, dict):
                            for k in remove_keys:
                                one.pop(k, None)

                    item["quote"] = json.dumps(quote_list, ensure_ascii=False)
                data.append(item)

        with open(lite_file, "w", encoding="utf-8") as f:
            for item in data:
                f.write(json.dumps(item, ensure_ascii=False) + "\n\n\n")


def zhou_report(phone, begin, end, brand_name):
    req_list = get_req_id(phone, begin, end)
    req_time_map = {}
    req_ids = []
    brand_id = 0
    user_id = 0
    for item in req_list:
        if item.get('brand_name') == brand_name:
            req_id = item.get("req_id")
            user_id = item.get("user_id")
            brand_id = item.get("brand_library_id")
            created_at = item.get("created_at")
            req_ids.append(req_id)
            req_time_map[req_id] = created_at

    result = []
    platform_data = get_platforms(brand_id, user_id, begin, end)
    refer_rate_heatmap = get_refer_rate_heatmap(brand_id, user_id, begin, end)
    print('---')
    print('---')
    print(refer_rate_heatmap)
    print('---')
    print('---')
    geo_refer_rank_overview_vos = platform_data.get('geo_refer_rank_overview_vos')
    brand_overview = platform_data.get('brand_overview')
    for item in geo_refer_rank_overview_vos:
        result.append({
            "平台": plat_form_map.get(item.get("platform"), item.get("platform")),
            "对话次数": item.get("ai_count"),
            "提及率": item.get("refer_rate"),
            "Top1提及率": item.get("top1_refer_rate"),
            "Top3提及率": item.get("top3_refer_rate"),
            "Top10提及率": item.get("top10_refer_rate"),
            "平均提及排名": item.get("avg_rank"),
            "提及好感度": item.get("sentiment_score"),
        })

    brand_overview_result = []
    brand_overview_result.append({
        '对话次数': brand_overview.get('ai_count'),
        '提及对话次数': brand_overview.get('valid_rank_count'),
        '提及率': brand_overview.get('refer_rate'),
        'top1提及率': brand_overview.get('top1_refer_rate'),
        'top3提及率': brand_overview.get('top3_refer_rate'),
        'top10提及率': brand_overview.get('top10_refer_rate'),
        '品牌提及次数': brand_overview.get('mention_count'),
        '平均提及排名': brand_overview.get('avg_rank'),
        '品牌提及好感度': brand_overview.get('sentiment_score'),
        '品牌得分': brand_overview.get('brand_score')
    })
    # 概览数据
    # 分平台数据

    all_word = get_all_word_rank(brand_id, user_id, begin, end)
    all_word_result = []
    for all in all_word:
        all_word_result.append({
            "品牌提及次数": all.get('ref_count'),
            "品牌名称": all.get("word"),
            "品牌得分": all.get("score"),
            "品牌提及率": all.get("rate"),
            "平均提及排名": all.get("avg_rank")
        })
    # 全部品牌词数据

    overview_result = []
    sentiment_overview = get_sentiment_overview(brand_id, user_id, begin, end)

    overview_result.append(
        {
            "提及品牌AI对话次数": sentiment_overview.get('sentiment_count'),
            "品牌提及好感度": sentiment_overview.get('sentiment_score'),
            "正面情感": sentiment_overview.get('positive_count'),
            "中性情感": sentiment_overview.get('neutral_count'),
            "负面情感": sentiment_overview.get('negative_count'),
            "全部引用文章": sentiment_overview.get('article_count'),
            "有品牌内容引用文章": sentiment_overview.get('has_brand_count'),
            # todo 负面引用文章
            "负面引用文章": sentiment_overview.get('negative_count')
        }
    )
    platform_sentiment_result = []
    platform_sentiment = get_platforms_sentiment(brand_id, user_id, begin, end)
    for pla in platform_sentiment:
        platform_sentiment_result.append({
            "平台": plat_form_map.get(pla.get("platform"), pla.get("platform")),
            "正面": round(pla.get('positive_count') / pla.get('sentiment_count'), 2),
            "中性": round(pla.get('neutral_count') / pla.get('sentiment_count'), 2),
            "负面": round(pla.get('negative_count') / pla.get('sentiment_count'), 2),
            "提及品牌次数": pla.get('brand_words_count'),
            "引用来源": pla.get('source_count'),
        })

    platform_list = ["DB", "DP", "TYQW", "TXYB", "BDAI", "DOUBA", "DPA", "DYAI", "KIMI", "WXYY"]
    url_top_40 = get_url_top40(user_id, brand_id, begin, end, platform_list)
    url_top_40_result = []
    for url in url_top_40:
        url_top_40_result.append({
            "网站名称": url.get('site_name'),
            "引用次数": url.get('log_count'),
            "引用占比": url.get('quote_ratio_percent'),
        })

    site_category = get_site_category(brand_id, user_id, begin, end, platform_list)
    site_category_result = []
    for site in site_category:
        site_category_result.append({
            "站点类型": site.get('category'),
            "站点数量": site.get('site_count'),
            "引用文章数": site.get('resource_count'),
            "引用次数": site.get('total_log_count'),
            "引用率": site.get('quote_rate'),
        })

    quote_mention_word_cloud = get_quote_mention_word_cloud(brand_id, user_id, begin, end)
    positive_top = quote_mention_word_cloud.get('positive_top')
    negative_top = quote_mention_word_cloud.get('negative_top')
    positive_top_result = []
    for positive in positive_top:
        positive_top_result.append({
            "关键词": positive.get('word'),
            "出现次数": positive.get('count'),
        })

    negative_top_result = []
    for negative in negative_top:
        negative_top_result.append({
            "关键词": negative.get('word'),
            "出现次数": negative.get('count'),
        })
    quto_statistics_result = []
    quto_statistics = get_quto_statistics(brand_id, user_id, begin, end)
    quto_statistics_result.append({
        "引用文章数": quto_statistics.get('resource_count'),
        "引用次数": quto_statistics.get('total_log_count'),
        "引用网站": quto_statistics.get('site_count'),
    })
    return {
        "brand_overview_result": brand_overview_result,
        "result": result,
        "all_word_result": all_word_result,
        "overview_result": overview_result,
        "platform_sentiment_result": platform_sentiment_result,
        "url_top_40_result": url_top_40_result,
        "site_category_result": site_category_result,
        "positive_top_result": positive_top_result,
        "negative_top_result": negative_top_result,
        "quto_statistics_result": quto_statistics_result
    }


def cha_report_video(videoId):
    url = f"http://172.16.1.37:8874/getVideoDetail2?videoId={videoId}"

    payload = {}
    headers = {}
    response = requests.request("GET", url, headers=headers, data=payload)
    try:
        return response.json().get('data')[0]
    except Exception as e:
        return None


def cha_report_user(uid):
    url = f"http://172.16.1.37:8873/getUserInfoUid?uid={uid}"

    payload = {}
    headers = {}

    response = requests.request("GET", url, headers=headers, data=payload)
    return response.json().get('data')


def get_detail(keyword, monday, sunday):
    url = f"http://172.16.1.37:8873/SuanShuGetRelationWord?keyword={keyword}&monday={monday}&sunday={sunday}"

    payload = {}
    headers = {}

    response = requests.request("GET", url, headers=headers, data=payload)
    try:
        response_json = response.json()

        if response_json.get('code') == 200:
            return response_json.get('data')
    except Exception as e:
        print(e)


def get_portrait(keyword, monday, sunday):
    url = f"http://172.16.1.37:8873/SuanShuGetPortrait?keyword={keyword}&monday={monday}&sunday={sunday}"

    payload = {}
    headers = {}

    response = requests.request("GET", url, headers=headers, data=payload)
    try:
        response_json = response.json()

        if response_json.get('code') == 200:
            return response_json.get('data')
    except Exception as e:
        print(e)


def get_full_weeks(start_time: str, end_time: str):
    start_date = datetime.strptime(start_time, "%Y%m%d").date()
    end_date = datetime.strptime(end_time, "%Y%m%d").date()

    if start_date > end_date:
        return []

    # 找到 >= start_date 的第一个周一
    days_to_monday = (7 - start_date.weekday()) % 7
    first_monday = start_date + timedelta(days=days_to_monday)

    result = []
    current_monday = first_monday

    while True:
        current_sunday = current_monday + timedelta(days=6)

        # 周日必须 <= end_date，才算完整包含
        if current_sunday > end_date:
            break

        result.append((
            current_monday.strftime("%Y%m%d"),
            current_sunday.strftime("%Y%m%d")
        ))

        current_monday += timedelta(days=7)

    return result


def suanshu_export(start, end, keyword_list, file_name):
    # start = "20250602"
    # end = "20250630"
    # keyword_list = ['旅游', '美食', '景点', '亲子游', '周边游', '避暑', '自驾游', '民宿', '海边', '古镇']

    data_list = get_full_weeks(start, end)

    for keyword in keyword_list:
        result = []
        for da in data_list:
            detail_result = get_detail(keyword, da[0], da[1])
            result.append({
                "type": "detail",
                "keyword": keyword,
                "start": da[0],
                "end": da[1],
                "result": detail_result
            })
        portrait_result = get_portrait(keyword, start, end)
        result.append({
            "type": "portrait",
            "keyword": keyword,
            "start": start,
            "end": end,
            "result": portrait_result
        })
        result_file = f"{file_name}/{keyword}.txt"
        with open(result_file, "w", encoding="utf-8") as f:
            for item in result:
                f.write(json.dumps(item, ensure_ascii=False) + "\n\n\n")


def dao_report(phone, begin, end, brand_name, platform=None):
    req_list = get_req_id(phone, begin, end)

    req_time_map = {}
    req_ids = []

    for item in req_list:
        if item.get('brand_name') == brand_name:
            req_id = item.get("req_id")
            created_at = item.get("created_at")
            req_ids.append(req_id)
            req_time_map[req_id] = created_at

    req_id_sql = ",".join([f"'{req_id}'" for req_id in req_ids])

    if platform:
        platform_list = ",".join([f"'{p}'" for p in platform])
        query_sql = f"select * from geo_commit_task where reqId in ({req_id_sql}) and platform in ({platform_list}) "
    else:
        query_sql = f"select * from geo_commit_task where reqId in ({req_id_sql})"
    query_list = bh_utils.query_data(query_sql)

    result = []
    if query_list:
        for q in query_list:
            r = {
                "prompt": q.get('prompt'),
                "platform": plat_form_map[q.get('platform')],
                "search_keyword": tos_utils.get_string_from_tos(
                    f"geo/{q.get('taskId')}/{q.get('platform')}/search_keyword.txt"),
                "created_at": req_time_map[q.get('reqId')],
            }
            result.append(r)
        all_file = f"/Users/yaowentong/Desktop/{brand_name}_dao_report.txt"
        with open(all_file, "w", encoding="utf-8") as f:
            for item in result:
                f.write(json.dumps(item, ensure_ascii=False) + "\n\n\n")


def get_platforms_q(brand_library_id, user_id, begin_time, end_time, question_list):
    url = "https://openapi.aidso.com/openapi/ywt/platforms"

    payload = json.dumps({
        "brand_library_id": brand_library_id,
        "user_id": user_id,
        "begin_time": f"{begin_time} 00:00:00",
        "end_time": f"{end_time} 23:59:59",
        "question_list": question_list
    })
    print(question_list)
    headers = {
        'Content-Type': 'application/json'
    }

    try:
        response = requests.post(
            url,
            headers=headers,
            data=payload,
            timeout=15
        )
        response.raise_for_status()
        result = response.json()

        if result.get("code") == 200:
            return result.get("data", {})

        return []

    except requests.RequestException as e:
        print(f"请求失败: {e}")
        return []
    except ValueError as e:
        print(f"返回结果不是合法 JSON: {e}")
        return []
        # print(response.text)


def txt_to_excel_with_type(txt_file, excel_file, req_type_map):
    """
    从 txt 读取数据，根据 reqId 补充 type 字段，写入 Excel。

    req_type_map 示例：
    {
        "reqId1": "普通任务",
        "reqId2": "搜索任务"
    }
    """

    data_list = read_txt_json_to_list(txt_file)

    wb = Workbook()
    ws = wb.active
    ws.title = "数据"

    headers = [
        "reqId",
        "type",
        "prompt",
        "platform",
        "content",
        "quote",
        "created_at"
    ]

    ws.append(headers)

    # 表头样式
    header_fill = PatternFill("solid", fgColor="D9EAF7")

    for col_idx, header in enumerate(headers, start=1):
        cell = ws.cell(row=1, column=col_idx)
        cell.font = Font(bold=True)
        cell.fill = header_fill
        cell.alignment = Alignment(horizontal="center", vertical="center")

    # 写入数据
    for item in data_list:
        req_id = item.get("reqId") or item.get("req_id") or ""

        req_type = req_type_map.get(req_id, "")

        ws.append([
            limit_excel_text(req_id),
            limit_excel_text(req_type),
            limit_excel_text(item.get("prompt", "")),
            limit_excel_text(item.get("platform", "")),
            limit_excel_text(item.get("content", "")),
            limit_excel_text(item.get("quote", "")),
            limit_excel_text(item.get("created_at", "")),
        ])

    # 设置列宽
    column_widths = {
        "A": 42,  # reqId
        "B": 18,  # type
        "C": 40,  # prompt
        "D": 18,  # platform
        "E": 80,  # content
        "F": 80,  # quote
        "G": 22,  # created_at
    }

    for col, width in column_widths.items():
        ws.column_dimensions[col].width = width

    # 自动换行 + 顶部对齐
    for row in ws.iter_rows(min_row=2):
        for cell in row:
            cell.alignment = Alignment(
                vertical="top",
                wrap_text=True
            )

    # 冻结首行
    ws.freeze_panes = "A2"

    # 开启筛选
    ws.auto_filter.ref = ws.dimensions

    # 创建目录
    dir_name = os.path.dirname(excel_file)
    if dir_name:
        os.makedirs(dir_name, exist_ok=True)

    wb.save(excel_file)

    print(f"读取 txt：{txt_file}")
    print(f"写入 Excel：{excel_file}")
    print(f"总条数：{len(data_list)}")

    return excel_file


def read_txt_json_to_list(txt_file):
    """
    读取 txt 文件中的 JSON 数据。

    兼容格式：
    1. 每条 JSON 一行
    2. 每条 JSON 后面多个空行
    """
    result = []

    with open(txt_file, "r", encoding="utf-8") as f:
        content = f.read()

    # 先按行读取，更稳。因为你原来是一条 json + 多个换行。
    for line in content.splitlines():
        line = line.strip()
        if not line:
            continue

        try:
            item = json.loads(line)
            result.append(item)
        except Exception as e:
            print(f"JSON 解析失败，跳过：{e}")
            print(f"异常内容：{line[:300]}")

    return result


def limit_excel_text(text, max_len=32000):
    """
    Excel 单个单元格最大字符数约 32767，这里做保护。
    """
    if text is None:
        return ""
    return str(text)[:max_len]


# =========================
# 使用示例
# =========================
if __name__ == "__main__":
    # result = get_req_id(18156037075,'2026-06-24','2026-06-24')
    # req_list = []
    # for i in result:
    #     req_list.append(i.get('req_id'))
    # print(req_list)
    # qian_report(15100000026,'2026-06-21','2026-06-21','oral')
    phone = 18521518364
    begin = '2026-04-15'
    end = '2026-07-13'
    req_list = get_req_id(phone, begin, end)
    brand_name1 = '王康医生'
    brand_name2 = '殷敏毅'
    req_list_result1 = []
    req_list_result2 = []
    for i in req_list :
        if i.get('brand_name') == brand_name1:
            req_list_result1.append(i.get('req_id'))
        if i.get('brand_name') == brand_name2:
            req_list_result2.append(i.get('req_id'))
    print(f"req_list_result1:{len(req_list_result1)}")

    print(req_list_result1)
    print(f"req_list_result2:{len(req_list_result2)}")
    print(req_list_result2)
    # data_list = bh_utils.query_data(
    #     f"select * from geo_commit_task where platform in ('TYQWA','DOUBA') and insertime >1780243200")
    #
    #
    # def handle_item(i):
    #     try:
    #         if i.get('comWordsMap'):
    #             i['comWordsMap'] = json.loads(i.get('comWordsMap'))
    #         if i.get('brandWords'):
    #             i['brandWords'] = json.loads(i.get('brandWords'))
    #         if i.get('comWords'):
    #             i['comWords'] = json.loads(i.get('comWords'))
    #         if i.get('keywords'):
    #             i['keywords'] = json.loads(i.get('keywords'))
    #         if i.get('productWordsMap'):
    #             i['productWordsMap'] = json.loads(i.get('productWordsMap'))
    #
    #         taskId = i.get('taskId')
    #         reqId = i.get('reqId')
    #         platform = i.get('platform')
    #         content_file_path = f'geo/{taskId}/{platform}/context.txt'
    #         result_file_path = f'geo/{taskId}/{platform}/result.json'
    #
    #         content = tos_utils.get_string_from_tos(content_file_path)
    #
    #         if 'render_ecom_card_widget_' not in content:
    #             return
    #         logger.success(f"{reqId}----{platform}更新完成")
    #         result_content = tos_utils.get_string_from_tos(result_file_path)
    #         result_content_json = json.loads(result_content)
    #         result_content_json["hasGoods"] = 1
    #
    #         tos_utils.put_string_to_tos(result_file_path, result_content_json)
    #
    #         if platform == 'TYQWA':
    #             return qianwen_android_process_original_data(i)
    #
    #         elif platform == 'DOUBA':
    #             return doubao_mobile_process_original_data(i)
    #     except Exception as e:
    #         print(f"{i.get('taskId')} error: {e}")
    #
    #
    # if data_list:
    #     with ThreadPoolExecutor(max_workers=50) as executor:
    #         list(executor.map(handle_item, data_list))
