# coding: utf-8
# 导出退款记录
import os

import pandas as pd
from DrissionPage import ChromiumPage
from DrissionPage.errors import ElementNotFoundError

from helper import helper, excel, file, domain, logger, api

country = None
log = logger.ConsoleLog()

page = ChromiumPage()
page.set.load_mode.normal()
page.set.when_download_file_exists('overwrite')

# 下载目录
download_path = os.getcwd()
# 检查下载目录是否存在，如果不存在则创建
helper.make_dir(download_path)
# 设置下载路径，确保在打开浏览器前设置
page.set.download_path(download_path)


def page_get(url):
    host = domain.switch_domain(country)
    full_url = host + url
    page.get(full_url, timeout=3)


def export_list_read_data():
    file_name = "Return_Summary.xls"
    if not os.path.isfile(file_name):
        raise FileNotFoundError(f"{file_name},文件不存在")
        # 访问网页
        # page_get("hz/vendor/members/returns?ref_=vc_xx_subNav")
        # # 导出退货单
        # page.ele("#file-download-button").click.to_download()
        # file.wait_for_downloads(file_name)

    return pd.read_excel(file_name, engine='xlrd')


def export_item_read_data(return_id):
    file_name = f"return_goods\\{return_id}.xls"
    if not os.path.isfile(file_name):
        while True:
            try:
                # 打开退回详情下载明细
                page_get(f"katalmonsapp/vendor/members/returns/{return_id}")
                page.ele("#file-download-button").click.to_download(rename=file_name)
                file.wait_for_downloads(file_name)
                break
            except ElementNotFoundError:
                log.warning("元素未找到,刷新网页")
                page.refresh()

    # 读取回退商品详情
    return pd.read_excel(file_name, engine='xlrd')


def main():
    # 读取sku映射关系
    relations_dict = api.sku_relations()
    # 下载并读取list数据
    list_data = export_list_read_data()
    log.info(f"共计：{len(list_data)} 订单")

    new_list_data = []
    i = 0
    for _, data in list_data.iterrows():
        i += 1
        return_id = data.get('Return ID')
        log.info({"index": i, "return_id": return_id})

        # 下载退货详情表格读取数据
        item_data = export_item_read_data(return_id)
        # 按 'Purchase order' 和 'ASIN' 分组，并对 'Quantity' 和 Total amount 进行求和
        item_data_result = item_data.groupby(['Purchase order', 'ASIN'], as_index=False).agg({
            'Quantity': 'sum',
            'Total amount': 'sum',
        })

        for _, item_row in item_data_result.iterrows():
            relation = relations_dict.get(item_row.get('ASIN'))
            erp_sku = relation.get('erp_sku')
            data_dict = data.to_dict()
            data_dict.update({
                'Return Date': data_dict['Return Date'].strftime('%m/%d/%Y'),
                'Return ID': str(data_dict['Return ID']),
                'PO': item_row.get('Purchase order'),
                'ASIN': item_row.get('ASIN'),
                'SKU': erp_sku if erp_sku is not None else "",
                'Quantity': item_row.get('Quantity'),
                # 替换回会数量和金额为详情里面的值
                'Return quantity': item_row.get('Quantity'),  # 替换回会数量
                'Total cost': item_row.get('Total amount')  # 替换金额
            })
            # 追加数据
            new_list_data.append(data_dict)

    excel.save_xls(new_list_data, '退货明细.xlsx')


if __name__ == '__main__':
    try:
        country = helper.get_input_with_default("国家", "usa")
        domain.domain_page(page, country)
        main()
        page.close()
    except KeyboardInterrupt:
        pass
    except Exception as e:
        log.error(e)
        helper.print_trace("main", e)
