import tkinter as tk
from tkinter import ttk, filedialog, messagebox
from tkinter import Toplevel
from PIL import Image, ImageTk
from ttkbootstrap import Style
import numpy as np
import cv2
import os
from .image_operations import locate_license_plate, recognize_characters

edge = None

processed_win = None

def select_image(root, img_container):
    global edge

    img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.jpeg;*.bmp")])
    if img_path:
        img_path_fixed = os.path.normpath(img_path)
        img_container['file_path'] = img_path_fixed

        src_temp = cv2.imdecode(np.fromfile(img_path_fixed, dtype=np.uint8), cv2.IMREAD_UNCHANGED)
        if src_temp is None:
            messagebox.showerror("错误", "无法读取图片，请选择有效的图片路径")
            return

        src = cv2.cvtColor(src_temp, cv2.COLOR_BGR2RGB)
        img_container['image'] = src

        if 'img_label' not in img_container or not isinstance(img_container['img_label'], tk.Label):
            img_container['img_label'] = tk.Label(root)
            img_container['img_label'].pack(side=tk.TOP, pady=10)

        img = Image.fromarray(src)
        img.thumbnail((200, 200))
        img_tk = ImageTk.PhotoImage(img)
        img_container['img_label'].configure(image=img_tk)
        img_container['img_label'].image = img_tk

        edge = Image.fromarray(src)
    else:
        messagebox.showerror("错误", "没有选择图片路径")

def show_selected_image(root, img_container):
    if 'file_path' in img_container:
        img_path = img_container['file_path']
        img = Image.open(img_path)
        img.thumbnail((800, 800))
        img_tk = ImageTk.PhotoImage(img)
        if 'img_label' not in img_container:
            img_container['img_label'] = tk.Label(root)
            img_container['img_label'].pack(side=tk.TOP, pady=10)
        img_container['img_label'].configure(image=img_tk)
        img_container['img_label'].image = img_tk
    else:
        messagebox.showerror("错误", "没有选择图片路径")

def change_size(event, img, label_pic):
    img_aspect = img.shape[1] / img.shape[0]
    new_aspect = event.width / event.height

    if new_aspect > img_aspect:
        new_width = int(event.height * img_aspect)
        new_height = event.height
    else:
        new_width = event.width
        new_height = int(event.width / img_aspect)

    resized_image = cv2.resize(img, (new_width, new_height))
    image_tk = ImageTk.PhotoImage(Image.fromarray(resized_image))
    label_pic.image = image_tk
    label_pic['image'] = image_tk

def savefile():
    global edge

    filename = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG files", "*.jpg"), ("PNG files", "*.png"), ("BMP files", "*.bmp")])
    if not filename:
        return

    if edge is not None:
        try:
            edge.save(filename)
            messagebox.showinfo("保存成功", "图片保存成功！")
        except Exception as e:
            messagebox.showerror("保存失败", f"无法保存图片: {e}")
    else:
        messagebox.showerror("保存失败", "没有图像可保存")

def detect_and_show_processed_image(root, img_container):
    global processed_win, edge

    # 判断是否已经选取图片
    if 'file_path' not in img_container or not img_container['file_path']:
        messagebox.showerror("错误", "没有选择图片！")
        return

    file_path = img_container['file_path']
    print(f"File path: {file_path}")  # 调试输出文件路径

    # 调用图像处理函数
    processed_img = locate_license_plate(file_path)

    # 识别字符
    recognized_text = recognize_characters(processed_img)

    # 转换为RGB格式
    processed_img_rgb = cv2.cvtColor(processed_img, cv2.COLOR_BGR2RGB)

    # 更新 edge 变量
    edge = Image.fromarray(processed_img_rgb)

    # 创建Toplevel窗口
    try:
        processed_win.destroy()
    except Exception:
        print("NVM")
    finally:
        processed_win = Toplevel(root)
        processed_win.attributes('-topmost', True)
    processed_win.geometry("360x340")
    processed_win.resizable(True, True)  # 可缩放
    processed_win.title("处理后的图像")

    # 显示图像
    label_pic = tk.Label(processed_win, text="IMG", width=360, height=240)
    image_tk = ImageTk.PhotoImage(Image.fromarray(processed_img_rgb))
    label_pic.image = image_tk
    label_pic['image'] = image_tk

    label_pic.bind('<Configure>', lambda event: change_size(event, processed_img_rgb, label_pic))
    label_pic.pack(fill=tk.BOTH, expand=tk.YES)

    # 显示识别结果
    result_label = tk.Label(processed_win, text=f"识别结果: {recognized_text}")
    result_label.pack(side=tk.TOP, pady=10)

    # 添加保存按钮
    btn_save = tk.Button(processed_win, text="保存", bg='#add8e6', fg='black', font=('Helvetica', 14), width=20,
                             command=savefile)
    btn_save.pack(pady=10)

    return