import re
from aidso_geo.utils import bh_utils,ai_utils



def process_eco_product_relation(
    eco_result,
    keyword,
    batch_size=500,
):
    """
    每100条商品调用一次AI，并将识别结果合并到原商品数据中。
    produce_name只用于匹配，不写入最终结果。
    """

    def normalize_title(value):
        return " ".join(
            str(value or "").strip().split()
        )

    final_result = []

    for start_index in range(
        0,
        len(eco_result),
        batch_size,
    ):
        batch = eco_result[
            start_index:start_index + batch_size
        ]

        product_list = [
            str(item.get("eco_title") or "").strip()
            for item in batch
        ]
        try:
            ai_result = (
                ai_utils.ai_get_product_relation_spu(
                    product_list,
                    keyword,
                )
            )
            print(ai_result)
        except Exception as exc:
            print(
                f"AI商品识别失败: "
                f"batch={start_index // batch_size + 1}, "
                f"error={exc}"
            )
            ai_result = []

        if not isinstance(ai_result, list):
            ai_result = []

        # produce_name只用于建立匹配关系。
        ai_result_map = {}

        for ai_item in ai_result:
            if not isinstance(ai_item, dict):
                continue

            produce_name = str(
                ai_item.get("produce_name") or ""
            ).strip()

            normalized_name = normalize_title(
                produce_name
            )
            if not normalized_name:
                continue

            if normalized_name not in ai_result_map:
                ai_result_map[normalized_name] = ai_item

        for original_item in batch:
            eco_title = str(
                original_item.get("eco_title") or ""
            ).strip()

            matched_item = ai_result_map.get(
                normalize_title(eco_title)
            )

            # 未匹配时的默认值。
            relation_data = {
                "brand": eco_title,
                "spu_name": "",
                "current": 0,
            }

            if isinstance(matched_item, dict):
                brand = str(
                    matched_item.get("brand")
                    or eco_title
                ).strip()

                spu_name = str(
                    matched_item.get("spu_name")
                    or ""
                ).strip()

                try:
                    current = int(
                        matched_item.get("current", 0)
                    )
                except (TypeError, ValueError):
                    current = 0

                if brand == spu_name:
                    spu_name = brand
                else:
                    spu_name = brand+" "+spu_name

                relation_data = {
                    "brand": brand,
                    "search_goods_word":keyword,
                    "spu_name": spu_name,
                    "current": (
                        1 if current == 1 else 0
                    ),
                }

            final_result.append(
                {
                    **original_item,
                    **relation_data,
                }
            )
    print(final_result)
    for item in final_result:
        item["isCalculateSearchWord"] = 1
    bh_utils.insert_data('geo_eco_data', final_result)
    return final_result


def extract_price(price):
    if not price:
        return ''

    price = str(price).strip()

    # 提取“元”前面的整数或小数
    match = re.search(r'(\d+(?:\.\d+)?)\s*元', price)

    return match.group(1) if match else ''
def qianwen_android_process_taobao_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        if item.get('card_type') =='single_product':
            raw_data = {
                "eco_id": item.get('item_id', ''),
                "eco_url": item.get('auctionURL', '') or item.get('jump_url',''),
                "eco_title": item.get('title', ''),
                "eco_index": index+1,
                "eco_pic": item.get('pic_path', ''),
                "eco_price": item.get('price', ''),
                "eco_source": 'taobao',
                "platform": platform,
                "task_id": task_id,
                "req_id": req_id,
                "prompt": prompt
            }
            eco_result.append(raw_data)

    return eco_result

def qianwen_android_process_damai_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('id', ''),
            "eco_url": item.get('webURL', '') ,
            "eco_title": item.get('name', ''),
            "eco_index": index+1,
            "eco_pic": item.get('verticalPic', ''),
            "eco_price": item.get('priceShowText', ''),
            "eco_source": 'damai',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result


def qianwen_android_process_gaode_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('poi_id', ''),
            "eco_url": item.get('url', '') ,
            "eco_title": item.get('name', ''),
            "eco_index": index+1,
            "eco_pic": item.get('photos', ''),
            "eco_price": item.get('cost', ''),
            "eco_source": 'gaode',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result

def doubao_android_process_douyin_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('pid', ''),
            "eco_url": item.get('jump_url', '') ,
            "eco_title": item.get('text', ''),
            "eco_index": index+1,
            "eco_pic": item.get('image_url', ''),
            "eco_price": item.get('priceShowText', ''),
            "eco_source": 'dyeco',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result

def doubao_android_process_douyin_poi_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('poi_id', ''),
            "eco_url": item.get('poi_url', '') ,
            "eco_title": item.get('poi_name', ''),
            "eco_index": index+1,
            "eco_pic": item.get('image_list', [])[0].get('large_url','') or item.get('image_list', [])[0].get('small_url',''),
            "eco_price": extract_price(item.get('price', '')),
            "eco_source": 'dypoi',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result



def yuanbao_android_process_jd_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('sku', ''),
            "eco_url": item.get('pc_url', '') ,
            "eco_title": item.get('sku_name', ''),
            "eco_index": index+1,
            "eco_pic": item.get('image_url', ''),
            "eco_price": item.get('price', ''),
            "eco_source": 'jdeco',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result

def yuanbao_process_jd_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('sku', ''),
            "eco_url": item.get('pc_url', '') ,
            "eco_title": item.get('sku_name', ''),
            "eco_index": index+1,
            "eco_pic": item.get('image_url', ''),
            "eco_price": item.get('price', ''),
            "eco_source": 'jdeco',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result

def yuanbao_process_txmap_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('poiId', ''),
            "eco_url": item.get('jumpUrl', '') ,
            "eco_title": item.get('title', ''),
            "eco_index": index+1,
            "eco_pic": item.get('image_url', 'https://tcdn.aidso.com/dso/pc/aiDialoguePng/112_112.jpg?v=2'),
            "eco_price": item.get('avgPrice', ''),
            "eco_source": 'txmap',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result

def yuanbao_android_process_txmap_eco(data,eco_list):
    eco_result = []
    task_id = data.get('taskId')
    platform = data.get('platform')
    req_id = data.get('reqId')
    prompt = data.get('prompt')
    for index, item in enumerate(eco_list):
        raw_data = {
            "eco_id": item.get('poiId', ''),
            "eco_url": item.get('jumpUrl', '') ,
            "eco_title": item.get('title', ''),
            "eco_index": index+1,
            "eco_pic": item.get('image_url', 'https://tcdn.aidso.com/dso/pc/aiDialoguePng/112_112.jpg?v=2'),
            "eco_price": item.get('avgPrice', ''),
            "eco_source": 'txmap',
            "platform": platform,
            "task_id": task_id,
            "req_id": req_id,
            "prompt": prompt
        }
        eco_result.append(raw_data)

    return eco_result

def save_eco_data_to_bh(data,eco_type,eco_list):

    platform = data.get('platform')
    search_goods_word = data.get('searchGoodsWord')

    eco_result = []
    if platform == 'TYQWA':
        if eco_type == 'taobao':
            eco_result = qianwen_android_process_taobao_eco(data,eco_list)
        if eco_type == 'damai':
            eco_result = qianwen_android_process_damai_eco(data, eco_list)
        if eco_type == 'gaode':
            eco_result = qianwen_android_process_gaode_eco(data, eco_list)
    if platform == 'DOUBA':
        if eco_type == 'dypoi':
            eco_result = doubao_android_process_douyin_poi_eco(data, eco_list)
        if eco_type == 'dyeco':
            eco_result =doubao_android_process_douyin_eco(data,eco_list)
    if platform == 'TXYBA':
        if eco_type == 'jdeco':
            eco_result =yuanbao_android_process_jd_eco(data,eco_list)
        if eco_type == 'txmap':
            eco_result = yuanbao_android_process_txmap_eco(data,eco_list)
    if platform == 'TXYB':
        if eco_type == 'jdeco':
            eco_result =yuanbao_process_jd_eco(data,eco_list)
        if eco_type == 'txmap':
            eco_result = yuanbao_process_txmap_eco(data,eco_list)

    if search_goods_word:
        eco_result = process_eco_product_relation(eco_result, search_goods_word)
        for item in eco_result:
            item["isCalculateSearchWord"] = None
    # eco_result = process_eco_product_relation(eco_result, search_goods_word)
    bh_utils.insert_data('geo_eco_data',eco_result)
if __name__ == '__main__':
    result = bh_utils.query_data("select * from geo_eco_data where req_id in ('0e2eacab462342e2864a85c625a9f275','0e2eacab462342e2864a85c625a9f275','0e2eacab462342e2864a85c625a9f275','10640b76d87747eaa6230d6b9f594e85','10640b76d87747eaa6230d6b9f594e85','196e4bbe93864eb6bd0293c152d46add','196e4bbe93864eb6bd0293c152d46add','196e4bbe93864eb6bd0293c152d46add','196e4bbe93864eb6bd0293c152d46add','257c85d919bf49f8b96eaa8882f773de','257c85d919bf49f8b96eaa8882f773de','257c85d919bf49f8b96eaa8882f773de','2d16246643544e4bad1131e975113a8e','2d16246643544e4bad1131e975113a8e','2d16246643544e4bad1131e975113a8e','38160b94710c4d038c6f6f8d94bb0dbe','38160b94710c4d038c6f6f8d94bb0dbe','38160b94710c4d038c6f6f8d94bb0dbe','38160b94710c4d038c6f6f8d94bb0dbe','3bb66c2799514f52995cd2511d1e3daf','3bb66c2799514f52995cd2511d1e3daf','3fe79b3a348a49fabae424e1d2e38ff8','3fe79b3a348a49fabae424e1d2e38ff8','3fe79b3a348a49fabae424e1d2e38ff8','449d52b97baa4df5b76b19299ada8260','449d52b97baa4df5b76b19299ada8260','449d52b97baa4df5b76b19299ada8260','449d52b97baa4df5b76b19299ada8260','449d52b97baa4df5b76b19299ada8260','451a1fb1af7b446eac0943824e894314','451a1fb1af7b446eac0943824e894314','451a1fb1af7b446eac0943824e894314','451a1fb1af7b446eac0943824e894314','465ab0c779d64b38b0d562e156847d6b','465ab0c779d64b38b0d562e156847d6b','465ab0c779d64b38b0d562e156847d6b','4665b0e22c054e3e82cc8410d2db2324','4665b0e22c054e3e82cc8410d2db2324','4665b0e22c054e3e82cc8410d2db2324','48e7a107ae7e4fdf99f1d3f0ea487a48','48e7a107ae7e4fdf99f1d3f0ea487a48','48e7a107ae7e4fdf99f1d3f0ea487a48','48e7a107ae7e4fdf99f1d3f0ea487a48','48e7a107ae7e4fdf99f1d3f0ea487a48','5768ef633cd54922a978fa14bca14a36','5768ef633cd54922a978fa14bca14a36','5768ef633cd54922a978fa14bca14a36','5768ef633cd54922a978fa14bca14a36','58b8e813708545dd9ffefd6444d8e218','58b8e813708545dd9ffefd6444d8e218','58b8e813708545dd9ffefd6444d8e218','58b8e813708545dd9ffefd6444d8e218','5f0d0b47b08145d597f8dfcf4726412b','5f0d0b47b08145d597f8dfcf4726412b','5f0d0b47b08145d597f8dfcf4726412b','61ad4b20cd9a4386881b7b67c21ed057','61ad4b20cd9a4386881b7b67c21ed057','61ad4b20cd9a4386881b7b67c21ed057','61ad4b20cd9a4386881b7b67c21ed057','61ad4b20cd9a4386881b7b67c21ed057','676a5a8c265340518da4e400d5f5a3b9','676a5a8c265340518da4e400d5f5a3b9','676a5a8c265340518da4e400d5f5a3b9','676a5a8c265340518da4e400d5f5a3b9','69127d4b15804ba39fb14dc2f5ae8e42','69127d4b15804ba39fb14dc2f5ae8e42','69127d4b15804ba39fb14dc2f5ae8e42','69127d4b15804ba39fb14dc2f5ae8e42','6c135f845cce4fe7b9fe3ea5faa17e75','6c135f845cce4fe7b9fe3ea5faa17e75','6c135f845cce4fe7b9fe3ea5faa17e75','6c135f845cce4fe7b9fe3ea5faa17e75','78d739b8bd1c4bb7bf1e4fad25239554','78d739b8bd1c4bb7bf1e4fad25239554','78d739b8bd1c4bb7bf1e4fad25239554','78d739b8bd1c4bb7bf1e4fad25239554','7ae879d6d7bb4b6087e75f7d4ded1ffc','7ae879d6d7bb4b6087e75f7d4ded1ffc','7ae879d6d7bb4b6087e75f7d4ded1ffc','85eef28d6aa14cafb621094c73df9911','85eef28d6aa14cafb621094c73df9911','85eef28d6aa14cafb621094c73df9911','85eef28d6aa14cafb621094c73df9911','8786a734f1554a089b8b4d08179ba0b3','8786a734f1554a089b8b4d08179ba0b3','8786a734f1554a089b8b4d08179ba0b3','8786a734f1554a089b8b4d08179ba0b3','87f373b2b340427a89a93b7293033f00','87f373b2b340427a89a93b7293033f00','87f373b2b340427a89a93b7293033f00','888f4e6e8a07446aaf569efa73259005','888f4e6e8a07446aaf569efa73259005','888f4e6e8a07446aaf569efa73259005','888f4e6e8a07446aaf569efa73259005','888f4e6e8a07446aaf569efa73259005','8cf53d76ae5740afa268f09619bcfb8e','8cf53d76ae5740afa268f09619bcfb8e','8cf53d76ae5740afa268f09619bcfb8e','8cf53d76ae5740afa268f09619bcfb8e','8d978e92b80c4f67a9b54266eb78b959','8d978e92b80c4f67a9b54266eb78b959','8d978e92b80c4f67a9b54266eb78b959','902f9a8a4c934b1c8266c9e2476cdbc0','902f9a8a4c934b1c8266c9e2476cdbc0','902f9a8a4c934b1c8266c9e2476cdbc0','90ea60112e76421eb5b74553d79278c1','90ea60112e76421eb5b74553d79278c1','90ea60112e76421eb5b74553d79278c1','94348debf16742b587bfdcc0ab195096','94348debf16742b587bfdcc0ab195096','94348debf16742b587bfdcc0ab195096','94348debf16742b587bfdcc0ab195096','989e1f32f9164a4da9d2396a6bca0ec5','989e1f32f9164a4da9d2396a6bca0ec5','989e1f32f9164a4da9d2396a6bca0ec5','989e1f32f9164a4da9d2396a6bca0ec5','989e1f32f9164a4da9d2396a6bca0ec5','9a7cba2dce884a279525431f3fa97950','9a7cba2dce884a279525431f3fa97950','9a7cba2dce884a279525431f3fa97950','9a7cba2dce884a279525431f3fa97950','a1169748b418488eb5ca4b236b2da12e','a1169748b418488eb5ca4b236b2da12e','a1169748b418488eb5ca4b236b2da12e','a1169748b418488eb5ca4b236b2da12e','a98b908d8e304b229953cd4fa51c03f5','a98b908d8e304b229953cd4fa51c03f5','a98b908d8e304b229953cd4fa51c03f5','a98b908d8e304b229953cd4fa51c03f5','ad8ef6d073a24f1fba8a086e7de0ab5c','ad8ef6d073a24f1fba8a086e7de0ab5c','ad8ef6d073a24f1fba8a086e7de0ab5c','afd02a2ee3c542ac9713e2e1ee4077a3','afd02a2ee3c542ac9713e2e1ee4077a3','afd02a2ee3c542ac9713e2e1ee4077a3','afd02a2ee3c542ac9713e2e1ee4077a3','b206185d28ba494bb22a4b2e38113dd4','b206185d28ba494bb22a4b2e38113dd4','b206185d28ba494bb22a4b2e38113dd4','b206185d28ba494bb22a4b2e38113dd4','b206185d28ba494bb22a4b2e38113dd4','b31ac2d7b69248f8bc0253c2e0d27c3b','b31ac2d7b69248f8bc0253c2e0d27c3b','b49fdfdf3f0c4ae6b46405b6b2111674','b49fdfdf3f0c4ae6b46405b6b2111674','b49fdfdf3f0c4ae6b46405b6b2111674','b6ba043b847d47699e9133204cf54978','b6ba043b847d47699e9133204cf54978','b6ba043b847d47699e9133204cf54978','b9a6165b716448d6842b21cfd6ebc77c','b9a6165b716448d6842b21cfd6ebc77c','b9a6165b716448d6842b21cfd6ebc77c','bb53d45b2f4f418e8ada0eb981871029','bb53d45b2f4f418e8ada0eb981871029','bb53d45b2f4f418e8ada0eb981871029','bb53d45b2f4f418e8ada0eb981871029','bbc59d9cb36041109d6a19d6eade9b0f','bbc59d9cb36041109d6a19d6eade9b0f','bbc59d9cb36041109d6a19d6eade9b0f','cf40224a49c740219a975242ec6f8130','cf40224a49c740219a975242ec6f8130','cf40224a49c740219a975242ec6f8130','d4d0ab9535fd4f179ce2521af945e6c9','d4d0ab9535fd4f179ce2521af945e6c9','d4d0ab9535fd4f179ce2521af945e6c9','d4d0ab9535fd4f179ce2521af945e6c9','d4d0ab9535fd4f179ce2521af945e6c9','e1e8b32050aa45a191507d438c133b01','e1e8b32050aa45a191507d438c133b01','e1e8b32050aa45a191507d438c133b01','e1e8b32050aa45a191507d438c133b01','ea2b9acd3ab644e093b4c7ce1675fa65','ea2b9acd3ab644e093b4c7ce1675fa65','ea2b9acd3ab644e093b4c7ce1675fa65','ea2b9acd3ab644e093b4c7ce1675fa65','eca988c29d304089b09f3d5956e72f39','eca988c29d304089b09f3d5956e72f39','eca988c29d304089b09f3d5956e72f39','eca988c29d304089b09f3d5956e72f39','ef126fbefb234d68b96d7e88e231561a','ef126fbefb234d68b96d7e88e231561a','ef126fbefb234d68b96d7e88e231561a','f97b2e3c391841888bc22581f8f508f8','f97b2e3c391841888bc22581f8f508f8','f97b2e3c391841888bc22581f8f508f8','f97b2e3c391841888bc22581f8f508f8')")
    eco_result = process_eco_product_relation(result, "小米洗地机")
    for item in eco_result:
        item["isCalculateSearchWord"] = None
    bh_utils.insert_data('geo_eco_data', eco_result)

