import tkinter as tk
from tkinter import filedialog, messagebox
from tkinter import Toplevel
from PIL import Image, ImageTk
import numpy as np
import cv2
import os

img_path = ""  # 全局变量，用于存储图像路径
src = None  # 全局变量，用于存储已选择的图像
X = None  # 用于存储第一张图像
Y = None  # 用于存储第二张图像
img_label = None  # 全局变量，用于存储显示选择的图片的标签
edge = None

FaceWin = None

# 获取当前脚本文件的目录
base_path = os.path.dirname(os.path.abspath(__file__))

def select_image(root):
    global img_path, src, img_label, edge

    img_path = filedialog.askopenfilename(filetypes=[("Image files", "*.jpg;*.png;*.jpeg;*.bmp")])
    if img_path:
        # 确保路径中的反斜杠正确处理，并使用 UTF-8 编码处理中文路径
        img_path_fixed = os.path.normpath(img_path)

        # 图像输入
        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_label 是否存在且有效
        if img_label is None or not img_label.winfo_exists():
            img_label = tk.Label(root)
            img_label.pack(side=tk.TOP, pady=10)

        img = Image.open(img_path)
        img.thumbnail((160, 160))
        img_tk = ImageTk.PhotoImage(img)
        img_label.configure(image=img_tk)
        img_label.image = img_tk

        # 定义 edge 变量为 PIL.Image 对象，以便稍后保存
        edge = Image.fromarray(src)
    else:
        messagebox.showerror("错误", "没有选择图片路径")

def show_selected_image(root):
    global img_label
    img_label = tk.Label(root)
    img_label.pack(side=tk.TOP, pady=10)
    img = Image.open(img_path)
    img.thumbnail((160, 160))
    img_tk = ImageTk.PhotoImage(img)
    img_label.configure(image=img_tk)
    img_label.image = img_tk

def changeSize(event, img, LabelPic):
    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))
    image1 = ImageTk.PhotoImage(Image.fromarray(resized_image))
    LabelPic.image = image1
    LabelPic['image'] = image1

def savefile():
    global edge

    filename = filedialog.asksaveasfilename(defaultextension=".jpg", filetypes=[("JPEG files", "*.jpg"), ("PNG files", "*.png"), ("BMP files", "*.bmp")])
    if not filename:
        return
    # 确保 edge 变量已定义
    if edge is not None:
        try:
            edge.save(filename)
            messagebox.showinfo("保存成功", "图片保存成功！")
        except Exception as e:
            messagebox.showerror("保存失败", f"无法保存图片: {e}")
    else:
        messagebox.showerror("保存失败", "没有图像可保存")

def face_recog(root):
    global src, FaceWin, edge

    # 判断是否已经选取图片
    if src is None:
        messagebox.showerror("错误", "没有选择图片！")
        return

    # 转换为灰度图片
    gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

    # 人脸检测器
    model_path = os.path.join(base_path, 'haarcascade_frontalface_default.xml')
    face_cascade = cv2.CascadeClassifier(model_path)

    # 检查模型文件是否成功加载
    if face_cascade.empty():
        messagebox.showerror("错误", "无法加载人脸检测模型，请检查文件路径")
        return

    # 识别人脸
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    # 显示检测结果
    for (x, y, w, h) in faces:
        # 在人脸区域添加矩形框
        cv2.rectangle(src, (x, y), (x + w, y + h), (255, 0, 0), 2)

        # 提取人脸区域的灰度图像
        face_gray = gray[y:y + h, x:x + w]

        # 眼睛检测器
        eye_model_path = os.path.join(base_path, 'haarcascade_eye.xml')
        eye_cascade = cv2.CascadeClassifier(eye_model_path)
        eyes = eye_cascade.detectMultiScale(face_gray)

        # 在眼睛区域添加矩形框
        for (ex, ey, ew, eh) in eyes:
            cv2.rectangle(src, (x + ex, y + ey), (x + ex + ew, y + ey + eh), (0, 255, 0), 2)

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

    # 创建Toplevel窗口
    try:
        FaceWin.destroy()
    except Exception:
        print("NVM")
    finally:
        FaceWin = Toplevel()
        FaceWin.attributes('-topmost', True)
    FaceWin.geometry("360x300")
    FaceWin.resizable(True, True)  # 可缩放
    FaceWin.title("检测到的人脸")

    # 显示图像
    LabelPic = tk.Label(FaceWin, text="IMG", width=360, height=240)
    image = ImageTk.PhotoImage(Image.fromarray(cv2.cvtColor(src, cv2.COLOR_BGR2RGB)))
    LabelPic.image = image
    LabelPic['image'] = image

    LabelPic.bind('<Configure>', lambda event: changeSize(event, src, LabelPic))
    LabelPic.pack(fill=tk.BOTH, expand=tk.YES)

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

    return