'''
# System --> Windows & Python3.7.0
# File ----> main.py
# Author --> Illusionna
# Create --> 2024/06/09 02:06:05
'''
# -*- Encoding: UTF-8 -*-


# (python -m venv venv)
# (conda deactivate)
# (./venv/Scripts/activate)
# >>> pip install xlwings
# >>> pip install pillow
# >>> python  main.py  -i  "A:/Illusionna/Desktop/demo.xlsx"  -o  "./demo.png"


import os
import sys
import time
import argparse
from xlwings import App
from PIL.Image import new
from PIL.ImageGrab import grabclipboard
from pythoncom import CoInitialize, CoUninitialize


class Convert:
    """
    Excel to PNG: Excel 转化成 PNG 图片类, 默认 Excel 的 "Sheet1" 表单, 如果不是, 修改表单参数.
    """

    @staticmethod
    def TransparentBackgroud(
        excelDir: str,
        pngDir:str,
        sheetName: str = 'Sheet1',
        format: str = 'PNG',
        quality: int = 95,
        dpi: tuple = (72, 72),
        compressLevel: int = 7
    ) -> None:
        try:
            os.system('taskkill  /IM  excel.exe  /F')
            CoInitialize()
            app = App(visible=False, add_book=False)
            wb = app.books.open(os.path.abspath(excelDir))
            sheet = wb.sheets(sheetName)
            all = sheet.used_range
            all.api.CopyPicture()
            sheet.api.Paste()
            pic = sheet.pictures[-1]
            pic.api.Copy()
            time.sleep(3)
            img = grabclipboard()
            img.save(
                fp = pngDir,
                quality = quality,
                dpi = dpi,
                format = format,
                compress_level = compressLevel
            )
            pic.delete()
            wb.close()
            app.quit()
            CoUninitialize()
            print('\033[92m [+] Success \033[0m')
        except:
            print('\033[91m [-] Error: 重新执行 \033[0m')

    @staticmethod
    def WhiteBackgroud(
        excelDir: str,
        pngDir:str,
        sheetName: str = 'Sheet1',
        format: str = 'PNG',
        resize: int = 1,
        quality: int = 95,
        dpi: tuple = (72, 72),
        compressLevel: int = 7
    ) -> None:
        try:
            os.system('taskkill  /IM  excel.exe  /F')
            CoInitialize()
            app = App(visible=False, add_book=False)
            wb = app.books.open(os.path.abspath(excelDir))
            sheet = wb.sheets(sheetName)
            all = sheet.used_range
            all.api.CopyPicture()
            sheet.api.Paste()
            pic = sheet.pictures[-1]
            pic.api.Copy()
            time.sleep(3)
            img = grabclipboard().convert('RGBA')
            bg = new('RGBA', img.size, (255, 255, 255, 255))
            bg.paste(img, mask=img)
            bg = bg.resize((bg.width * resize, bg.height * resize))
            bg.save(
                fp = pngDir,
                quality = quality,
                dpi = dpi,
                format = format,
                compress_level = compressLevel
            )
            pic.delete()
            wb.close()
            app.quit()
            CoUninitialize()
            print('\033[92m [+] Success \033[0m')
        except:
            print('\033[91m [-] Error: 重新执行 \033[0m')


def FrozenAppPath() -> str:
    """对程序执行路径进行路径冻结.

    Returns:
        str: 返回 App 程序真实路径字符串.
    """
    if hasattr(sys, 'frozen'):
        return os.path.dirname(sys.executable)
    return os.path.dirname(__file__)



if __name__ == '__main__':
    os.system('')
    print('\n')
    parser = argparse.ArgumentParser()
    parser.add_argument('-bg', help='透明（transparent）？白底（white）？默认白底', default='white')
    parser.add_argument('-i', help='输入 Excel 路径，最好英文双引号括起来')
    parser.add_argument('-o', help='输出 PNG 路径，最好英文双引号括起来')
    args = parser.parse_args()
    if (not args.i) or (not args.o):
        print('\033[91m [-] Error: 终端未接收到路径参数 \033[0m')
        print(f'\033[92m [+] 终端执行帮助指令 >>> {sys.argv[0]} -h \033[0m')
    else:
        if args.bg == 'transparent':
            Convert.TransparentBackgroud(args.i, args.o)
        elif args.bg == 'white':
            Convert.WhiteBackgroud(args.i, args.o)
        else:
            print('\033[91m [-] Error \033[0m')
    input('按 Enter 键退出')