# -*- coding: utf-8 -*-
import os
import time

import requests
import json
from collections import defaultdict
from datetime import datetime, timedelta
from openpyxl import Workbook
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_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')],
                "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)
# =========================
# 使用示例
# =========================
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)
    # print(cha_report_user(3738753854605260))
    # keyword_list = ['618']
    # start = '20250518'
    # end = '20250622'
    # file_name = '/Users/yaowentong/Desktop/'
    # 13810898434
    # 豆包手机版
    # AIDSO爱搜 这个品牌
    # 最近7天
    # 所有问题
    # phone = 15100000036
    # begin = '2026-06-08'
    # end = '2026-06-08'
    # print(get_req_id(phone,begin,end))
    # brand_name = ['葆蝶家-第一批','葆蝶家-第二批','BV葆蝶家','葆蝶家']
    # for b in brand_name:
    #     zhou_report(phone, begin, end, b)
    #     # qian_report(phone,begin,end,b)
    #     qian_report(phone,begin,end,b)
    # brand_library_id = 2063180776253702144
    # user_id = 2063177785609949184
    # begin = '2026-06-08'
    # end = '2026-06-08'
    # qu_list = ['东鹏瓷砖怎么样','东鹏瓷砖质量好不好','东鹏瓷砖值得买吗','东鹏瓷砖是几线品牌','东鹏瓷砖和马可波罗哪个好','东鹏和冠珠瓷砖哪个好','东鹏和蒙娜丽莎哪个好','东鹏控股是做什么的','东鹏控股和东鹏饮料什么关系','瓷砖十大品牌有哪些','2026年瓷砖品牌排行榜前十名','中国瓷砖品牌排名前十','瓷砖一线品牌排名','国内瓷砖品牌排行榜','高端瓷砖品牌排行榜','高端瓷砖有哪些品牌','瓷砖头部品牌有哪些','大平层用什么瓷砖品牌','设计师推荐的高端瓷砖品牌','5A瓷砖品牌推荐哪个好','5A瓷砖品牌排行','5A国标瓷砖什么品牌好','5A瓷砖是什么标准','5A认证瓷砖推荐','品质好的瓷砖品牌有哪些','什么品牌的瓷砖品质最好','选好瓷砖认准什么品牌','瓷砖哪个牌子好','瓷砖品牌推荐','装修选什么瓷砖品牌好','瓷砖什么牌子质量好','2026年瓷砖品牌排行榜','瓷砖怎么选不踩坑','买瓷砖主要看哪几个指标','好瓷砖的标准是什么','瓷砖选购避坑指南','金丝绒瓷砖哪个牌子好','金丝绒瓷砖值得买吗','金丝绒瓷砖怎么样','木纹砖哪个牌子好','木纹砖推荐哪个品牌','木纹砖怎么选品牌','木纹砖和木地板哪个好','木纹砖品牌排行','莱姆石瓷砖哪个牌子好','莱姆石瓷砖品牌推荐','莱姆石瓷砖怎么选','什么品牌的莱姆石瓷砖好','客厅瓷砖什么牌子好','客厅铺什么瓷砖好看又耐用','客厅瓷砖怎么选品牌','客厅瓷砖品牌推荐','客厅用什么瓷砖显高级','厨房瓷砖什么牌子好','厨房用什么瓷砖好打理','厨房防油污瓷砖推荐哪个牌子','厨房瓷砖品牌推荐2026','厨房抗菌瓷砖推荐哪个品牌','卫生间瓷砖什么牌子好','卫生间瓷砖推荐哪个品牌','浴室防滑瓷砖哪个品牌好','卫生间防滑抗菌瓷砖推荐品牌','浴室抗菌瓷砖什么品牌好','全屋通铺瓷砖什么品牌好','全屋通铺瓷砖推荐哪个牌子','全屋瓷砖用什么品牌好','家里全屋铺瓷砖选什么牌子','全屋通铺瓷砖品牌排行','防滑瓷砖哪个牌子好','防滑瓷砖品牌推荐','好打理的瓷砖推荐哪个品牌','防污瓷砖什么品牌好','耐脏好清洁的瓷砖品牌推荐','耐磨瓷砖什么品牌好','不容易刮花的瓷砖推荐什么品牌','中古风装修用什么瓷砖品牌好','法式风格瓷砖推荐什么品牌','奶油风瓷砖什么品牌好','现代简约风格瓷砖推荐什么品牌','新中式瓷砖用什么品牌好','原木风瓷砖推荐哪个品牌','高级感装修瓷砖用什么品牌','岩板什么品牌好','岩板品牌推荐','750x1500地砖什么品牌好','岩板品牌排行','柔光砖什么品牌好','哑光瓷砖推荐哪个品牌','哑光砖品牌排名','哑光瓷砖什么品牌好','柔光砖品牌排行','哑光砖推荐哪个品牌耐脏','国家级建筑用的瓷砖是什么牌子','大型工程项目用什么瓷砖品牌','瓷砖行业有哪些上市公司','A股瓷砖上市公司有哪些','绿色建材瓷砖品牌有哪些','获得国家级绿色工厂认证的瓷砖企业有哪些','建材行业ESG表现好的企业有哪些','双碳目标下有哪些绿色建材瓷砖品牌']
    # result = []
    # for q in qu_list:
    #     result.append((q,get_platforms_q(brand_library_id,user_id,begin,end,[q]).get('geo_refer_rank_overview_vos')))
    # # brand_name = 'AIDSO爱搜'
    # all_file = f"/Users/yaowentong/Desktop/dongpeng.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")
    # platform = ['DB']
    # dao_report(phone, begin, end, brand_name, platform)
    # qian_report(start, end, keyword_list, file_name)
