import os
import sys
import tkinter as tk
from tkinter import ttk, messagebox

import requests


class ServerCli:
    serve_url = 'http://127.0.0.1:5855'

    def get_folder_tree(self):
        return requests.post(self.serve_url + '/get_folder_tree').json()

    def create_cloud_file(self, local_file, folder_id):
        return requests.post(self.serve_url + '/create_cloud_file',
                             json={'local_file': local_file, 'folder_id': folder_id}).json()


def resource_path(relative_path):
    """打包后资源路径处理"""
    if hasattr(sys, '_MEIPASS'):
        return os.path.join(sys._MEIPASS, relative_path)
    return relative_path


class FolderSelector(tk.Tk):
    def __init__(self, file_path):
        super().__init__()
        self.title("选择文件夹")
        self.geometry("500x400")
        self.minsize(400, 300)
        self.local_file = file_path
        self.server = ServerCli()
        self.base_data = {}

        self.iconbitmap(resource_path("icon.ico"))

        # 加载中提示
        self.loading_label = ttk.Label(self, text="正在加载目录，请稍候...")
        self.loading_label.pack(pady=20)

        # 树控件先占位但不显示
        self.tree = ttk.Treeview(self)
        self.tree.pack(fill='both', expand=True, padx=10, pady=10)
        self.tree.pack_forget()  # 等加载完再显示

        self.tree.bind("<<TreeviewOpen>>", self.on_open_node)

        # 确定按钮
        self.confirm_btn = ttk.Button(self, text="确定", command=self.on_confirm)
        self.confirm_btn.pack(side="bottom", anchor="e", padx=10, pady=10)
        self.confirm_btn["state"] = "disabled"  # 先禁用

        # 延迟加载数据
        self.after(100, self.load_initial_data)

    def load_initial_data(self):
        try:
            self.tree_data = self.server.get_folder_tree()
            self.init_tree_data('root', self.tree_data)
            self.insert_node('', 'root', '我的文库', is_leaf=False)

            # 隐藏 loading，显示树
            self.loading_label.pack_forget()
            self.tree.pack(fill='both', expand=True, padx=10, pady=10)
            self.confirm_btn["state"] = "normal"
        except Exception as e:
            messagebox.showwarning("错误", f"办公助手未启动")
            self.destroy()  # 关闭主窗口
            sys.exit(1)  # 可选：退出程序（非必须）

    def insert_node(self, parent, node_id, text, is_leaf, prefix=''):
        self.tree.insert(parent, 'end', iid=node_id, text=prefix + text, values=(node_id,))
        if not is_leaf:
            self.tree.insert(node_id, 'end')  # 占位符，表明它可以展开

    def init_tree_data(self, parent, data):
        node_list = []
        for row in data:
            if len(row['children']) == 0:
                row['children'] = False
            else:
                self.init_tree_data(row['id'], row['children'])
                row['children'] = True

            node_list.append(row)
        self.base_data[parent] = node_list

    def on_open_node(self, event):
        node_id = self.tree.focus()
        children = self.tree.get_children(node_id)
        if len(children) == 1 and self.tree.item(children[0], 'text') == '':
            self.tree.delete(children[0])
            self.load_children(node_id)

    def load_children(self, parent_id=None):
        """通过接口获取 parent_id 下的子文件夹"""
        children_data = self.fetch_children_from_api(parent_id)
        for item in children_data:
            self.insert_node(
                parent_id,
                item['id'],
                item['name'],
                is_leaf=not item['children'],
                prefix='📁'
            )

    def on_confirm(self):
        selected = self.tree.focus()
        if selected == 'root':
            return

        try:
            res = self.server.create_cloud_file(self.local_file, selected)
            if res.get("success", True):  # 这里假设返回中有 success 字段
                messagebox.showinfo('上传到我的文库', res.get('msg', '未知错误'))
            else:
                messagebox.showerror('上传到我的文库', res.get('msg', '未知错误'))
        except Exception as e:
            messagebox.showerror('上传到我的文库', f"请求出错：{e}")
        finally:
            self.destroy()

    def fetch_children_from_api(self, folder_id):
        # 你应当用 requests 等请求实际接口
        # 这里只是模拟返回

        return self.base_data.get(folder_id, [])


if __name__ == "__main__":
    file_path = sys.argv[1]
    app = FolderSelector(file_path)
    app.mainloop()
