import sys
import os
import time
from openpyxl import load_workbook

def get_resource_path(relative_path):
    """ 获取资源绝对路径，兼容开发环境和 PyInstaller 打包环境 """
    if hasattr(sys, '_MEIPASS'):
        # PyInstaller 打包后的临时解压路径
        return os.path.join(sys._MEIPASS, relative_path)
    # 开发环境下的路径
    base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    return os.path.join(base_dir, relative_path)

def append_to_template(products, output_path, status_callback=None):
    """
    将产品数据追加写入到指定的 Excel 文件中。
    增加文件占用检测：如果文件被打开，则暂停任务直到关闭。
    """
    # 1. 使用增强的路径获取函数寻找模板
    template_path = get_resource_path(os.path.join('templates', '【进价】产品信息空表.xlsx'))
    
    if not os.path.exists(template_path):
        # 兜底：如果打包路径没找到，尝试当前目录
        template_path = os.path.join('templates', '【进价】产品信息空表.xlsx')

    if not os.path.exists(template_path):
        raise FileNotFoundError(f"未找到核心模板文件: {template_path}")

    # 2. 加载文件
    if os.path.exists(output_path):
        wb = load_workbook(output_path)
    else:
        os.makedirs(os.path.dirname(output_path), exist_ok=True)
        wb = load_workbook(template_path)
    
    ws = wb.active
    
    # 3. 寻找起始行 (品类或名称为空的行)
    start_row = 3
    for r in range(3, ws.max_row + 2):
        val_cat = ws.cell(row=r, column=2).value
        val_name = ws.cell(row=r, column=4).value
        if (val_cat is None or str(val_cat).strip() == "") and \
           (val_name is None or str(val_name).strip() == ""):
            start_row = r
            break
    else:
        start_row = ws.max_row + 1
    
    # 4. 写入本批次数据
    for i, product in enumerate(products):
        row = start_row + i
        ws.cell(row=row, column=1, value=row - 2) 
        ws.cell(row=row, column=2, value=product.get('category', ''))
        ws.cell(row=row, column=3, value=product.get('brand', ''))
        ws.cell(row=row, column=4, value=product.get('name', ''))
        ws.cell(row=row, column=5, value=product.get('color', ''))
        ws.cell(row=row, column=6, value=product.get('spec', ''))
        ws.cell(row=row, column=7, value=product.get('material', ''))
        ws.cell(row=row, column=8, value=product.get('price', ''))
        ws.cell(row=row, column=9, value=product.get('moq', ''))
        ws.cell(row=row, column=10, value=product.get('wholesale_price', ''))
        ws.cell(row=row, column=11, value=product.get('link', '')) 
        ws.cell(row=row, column=12, value=product.get('supplier', ''))

    # 5. 核心改进：占用检测保存循环
    while True:
        try:
            wb.save(output_path)
            if status_callback:
                status_callback(False, "写入成功")
            break
        except PermissionError:
            msg = "文件被占用，请关闭 Excel"
            print(f"[!] {msg}: {output_path}")
            if status_callback:
                status_callback(True, msg)
            time.sleep(3)
