import tools.utils as utils

from PIL import Image
import os


class ImageSpilt:

    def __init__(self,header_height:int=30,row_height:int=23,row_count:int=5):

        self._logger = utils.get_logger()

        self._header_height = header_height

        self._row_height = row_height

        self._row_count = row_count

    def split(self,image_name:str, output_dir:str=None):

        self._logger.info(f"开始处理图片{image_name}")
        if output_dir is None:
            output_dir = f"./temp_files/images/output/img/{image_name}"
        # 确保输出目录存在
        os.makedirs(output_dir, exist_ok=True)

        image_path = f"./temp_files/images/source/{image_name}.png"
        # 打开并读取图片
        image = Image.open(image_path)
        width, height = image.size
        self._logger.info(f"图片尺寸为{width}x{height}")
        # 提取表头部分
        header = image.crop((0, 0, width, self._header_height))
        # 计算总行数
        content_height = height - self._header_height
        total_rows = content_height // self._row_height
        
        # 计算需要生成的图片数量
        image_count = (total_rows + self._row_count - 1) // self._row_count
        self._logger.info(f"总行数：{total_rows}，需要生成{image_count}张图片")

        # 按图片切割
        for img_index in range(image_count):
            # 计算当前图片包含的行范围
            start_row = img_index * self._row_count
            end_row = min((img_index + 1) * self._row_count, total_rows)
            current_rows = end_row - start_row

            # 创建新图片（表头高度 + 当前行数 * 行高）
            new_image = Image.new('RGB', (width, self._header_height + current_rows * self._row_height))
            
            # 粘贴表头
            new_image.paste(header, (0, 0))
            
            # 粘贴每一行内容
            for row in range(current_rows):
                # 计算原图中的行位置
                src_start_y = self._header_height + (start_row + row) * self._row_height
                src_end_y = src_start_y + self._row_height
                # 提取行内容
                row_image = image.crop((0, src_start_y, width, src_end_y))
                # 粘贴到新图片中
                new_image.paste(row_image, (0, self._header_height + row * self._row_height))

            # 保存切割后的图片
            file_name = f"part_{img_index + 1}.png" if img_index>=9 else f"part_0{img_index + 1}.png"
            output_path = os.path.join(output_dir, file_name)
            new_image.save(output_path)
            self._logger.info(f"已保存第{img_index + 1}张图片（包含{current_rows}行）: {output_path}")

        self._logger.info(f"图片处理完成，共生成{image_count}张图片")
        