import os
from tqdm import tqdm 
from utils.logger_config import setup_logger
from utils.tools import read_excel, create_sku_excel, add_sku_to_excel, add_suffix, read_json_file
from utils.monitor import monitor_directory
from services.order_fusion_services import large_order_service
from concurrent.futures import ThreadPoolExecutor, as_completed
from modules.export_excel import export_to_excel
import pandas as pd
from openpyxl import load_workbook, Workbook
from openpyxl.styles import Alignment, Font, PatternFill
import os

import pandas as pd
from openpyxl import load_workbook
from openpyxl.styles import Font, Alignment, Border, Side
import os

import openpyxl
from openpyxl.drawing.image import Image
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
import os

def copy_cell_style(src_cell, dest_cell):
    """
    复制单元格样式
    """
    if src_cell.has_style:
        dest_cell.font = Font(
            name=src_cell.font.name,
            size=src_cell.font.size,
            bold=src_cell.font.bold,
            italic=src_cell.font.italic,
            color=src_cell.font.color
        )
        dest_cell.alignment = Alignment(
            horizontal=src_cell.alignment.horizontal,
            vertical=src_cell.alignment.vertical,
            wrap_text=src_cell.alignment.wrap_text
        )
        dest_cell.border = Border(
            left=src_cell.border.left,
            right=src_cell.border.right,
            top=src_cell.border.top,
            bottom=src_cell.border.bottom
        )
        dest_cell.fill = PatternFill(
            start_color=src_cell.fill.start_color,
            end_color=src_cell.fill.end_color,
            fill_type=src_cell.fill.fill_type
        )
        # 复制数字格式（如果有）
        dest_cell.number_format = src_cell.number_format

def copy_row_height(src_ws, dest_ws, row_idx):
    """
    复制行高
    """
    dest_ws.row_dimensions[row_idx].height = src_ws.row_dimensions[row_idx].height

def copy_column_width(src_ws, dest_ws, col_idx):
    """
    复制列宽
    """
    col_letter = openpyxl.utils.get_column_letter(col_idx)
    dest_ws.column_dimensions[col_letter].width = src_ws.column_dimensions[col_letter].width

# 修改 copy_images 函数，添加错误处理
def copy_images(ws, merged_ws):
    for img in ws._images:
        try:
            # 方法1：直接复制整个图片对象
            # 注意：需要确保图片数据可用
            merged_ws.add_image(img, img.anchor)
            
        except Exception as e:
            print(f"方法1失败: {e}")
            try:
                # 方法2：通过反射获取内部图片数据
                if hasattr(img, 'ref') and img.ref:
                    # 使用图片引用重新创建
                    from openpyxl.drawing.image import Image
                    new_img = Image(img.ref)
                    new_img.anchor = img.anchor
                    merged_ws.add_image(new_img)
                else:
                    print("图片没有可用的引用")
            except Exception as e2:
                print(f"方法2也失败: {e2}")

def merge_workbooks(file_paths, output_path):
    """
    合并多个Excel工作簿到一个目标工作簿
    """
    # 创建一个新的工作簿
    merged_wb = openpyxl.Workbook()
    merged_ws = merged_wb.active
    merged_ws.title = "合并表格"

    # 当前行位置
    current_row = 1

    for file_path in file_paths:
        # 打开源工作簿
        wb = openpyxl.load_workbook(file_path, data_only=False)
        # 假设所有内容都在第一个工作表
        ws = wb.active

        # 复制每一行的内容、样式和图片
        for row in ws.iter_rows():
            for cell in row:
                # 在目标工作表中创建对应的单元格
                dest_cell = merged_ws.cell(
                    row=current_row,
                    column=cell.column,
                    value=cell.value
                )
                # 复制样式
                copy_cell_style(cell, dest_cell)

            # 复制行高
            copy_row_height(ws, merged_ws, current_row)

            # 更新当前行
            current_row += 1

        # 复制列宽
        for col in range(1, ws.max_column + 1):
            copy_column_width(ws, merged_ws, col)

        # 复制图片
        copy_images(ws, merged_ws)

        # 如果不是最后一个文件，添加空行分隔
        if file_path != file_paths[-1]:
            current_row += 2  # 增加两行空行作为分隔

    # 保存合并后的工作簿
    merged_wb.save(output_path)
    print(f"表格合并完成！输出文件: {output_path}")


def has_number_isdigit(text):
    """使用isdigit()方法检查字符串中是否包含数字"""
    return any(char.isdigit() for char in text)


if __name__ == "__main__":



    print(has_number_isdigit(str(None)))

    # # 使用示例
    # file1 = "./output/10CL6E57038H.xlsx"
    # file2 = "./output/10CL6E1U086Y.xlsx"
    # output = "merged_data.xlsx"

    # aa = {
    #     "a": True,
    #     "b": True,
    #     "c": True
    # }

    # print(all(aa.values()))


    

    # result = merge_excel_with_styles(file1, file2, output)
    # 执行合并
    # merge_workbooks([file1, file2], output)

    # file_dir = "./test/output/"
    # files = os.listdir(file_dir)
    # for file in tqdm(files):
    #     if file.endswith('json'):
    #         file_path = os.path.join(file_dir, file)
    #         large_order_service.generate_outfit_orders(file_path)

    #         json_content = read_json_file(file_path)
    #         xlsx_name = os.path.basename(file).replace('json', 'xlsx')
    #         print('xxxxxxxxxxxxxxx', xlsx_name)
    #         export_to_excel(json_content, f"{xlsx_name}")

    