import os
import random
import shutil
import string

from datetime import datetime
from openpyxl import load_workbook


def clear_blank_rows(sheet):
    last_row = sheet.max_row
    for row in range(last_row, 1, -1):
        if all(cell.value is None or cell.value == '' for cell in sheet[row]):
            sheet.delete_rows(row)


def copy_data(source_sheet, target_sheet, start_row):
    for row in range(start_row, source_sheet.max_row + 1):
        a_cell_value = source_sheet.cell(row=row, column=1).value
        if isinstance(a_cell_value, (int, float)) and any(
                source_sheet.cell(row=row, column=col).value for col in range(4, source_sheet.max_column + 1)):
            target_sheet.append(
                [source_sheet.cell(row=row, column=col).value for col in range(1, source_sheet.max_column + 1)])


def run_conformity(file_path, print_path):
    try:
        # 加载模板文件
        template_path = os.path.join('app', 'utils', 'excelmerge', '国网上海电力整合模版.xlsx')
        template_excel = load_workbook(template_path)
        template_sheets = {sheet.title: sheet for sheet in template_excel}
        source_files = [f for f in os.listdir(file_path) if f.endswith('.xlsx') and not f.startswith('~$')]

        for file in source_files:
            source_path = os.path.join(file_path, file)
            source_excel = load_workbook(source_path)

            # 动态获取工作表
            source_sheets = {sheet.title: sheet for sheet in source_excel}

            for name in template_sheets:
                if name in source_sheets:
                    clear_blank_rows(source_sheets[name])

            for name, start_row in [('技术监督工作统计表', 4), ('技术监督告（预）警单统计表', 3),
                                    ('投产前技术监督报告统计表', 3), ('技术监督细则完善建议', 4),
                                    ('典型经验交流', 3)]:
                if name in source_sheets and name in template_sheets:
                    copy_data(source_sheets[name], template_sheets[name], start_row)

            source_excel.close()

        for name, start_row in [('技术监督工作统计表', 4), ('技术监督告（预）警单统计表', 3),
                                ('投产前技术监督报告统计表', 3), ('技术监督细则完善建议', 4),
                                ('典型经验交流', 3)]:
            if name in template_sheets:
                last_row = template_sheets[name].max_row
                for i in range(start_row, last_row + 1):
                    template_sheets[name].cell(row=i, column=1).value = i - start_row + 1

        timestamp = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
        random_string = ''.join(random.choice(string.ascii_letters + string.digits) for i in range(5))
        file_name = f'{random_string}_{timestamp}'
        output_path = os.path.join(print_path, f'{file_name}.xlsx')
        template_excel.save(output_path)
        template_excel.close()

        try:
            for filename in os.listdir(file_path):
                file_path_full = os.path.join(file_path, filename)
                if os.path.isfile(file_path_full) or os.path.islink(file_path_full):
                    os.unlink(file_path_full)
                elif os.path.isdir(file_path_full):
                    shutil.rmtree(file_path_full)
            os.rmdir(file_path)
        except Exception as e:
            print(f"删除文件时发生错误: {e}")

        return file_name
    except Exception as e:
        print(f"读取数据发生错误: {e}")
        return None
