/* win_helper: Windows 小助手 — 系统工具 / 进程 / 信息 / 环境变量 / 文件夹 */
#include "eduwin.h"

#define CAT_COUNT 7

/* ── 全局 ── */
static HWND g_status;
static HWND g_tab;
static HWND g_panels[CAT_COUNT];
static int  g_active_cat;
static HWND g_win;

/* ── 进程面板控件 ── */
static HWND g_proc_list;

/* ── 环境变量面板控件 ── */
static HWND g_env_list;
static HWND g_env_name;
static HWND g_env_val;

/* ──── 工具启动 ──── */
static void launch(const WCHAR *exe, const WCHAR *arg)
{
    HANDLE h = run_process(exe, arg, 1);
    if (!h)
        statusbar_set_text(g_status, L"启动失败");
    else {
        wait_process(h);
        statusbar_set_text(g_status, L"进程已退出");
    }
}

static void launch_noret(const WCHAR *exe, const WCHAR *arg)
{
    if (!run_process(exe, arg, 1))
        statusbar_set_text(g_status, L"启动失败");
    else
        statusbar_set_text(g_status, L"已启动");
}

/* ──── 工具按钮回调 ──── */
static void on_notepad(void *d)   { launch(L"C:\\Windows\\System32\\notepad.exe", NULL); }
static void on_calc(void *d)      { launch(L"C:\\Windows\\System32\\calc.exe", NULL); }
static void on_cmd(void *d)       { launch_noret(L"C:\\Windows\\System32\\cmd.exe", NULL); }
static void on_regedit(void *d)   { launch_noret(L"C:\\Windows\\System32\\regedt32.exe", NULL); }
static void on_mspaint(void *d)   { launch(L"C:\\Windows\\System32\\mspaint.exe", NULL); }
static void on_taskmgr(void *d)   { launch_noret(L"C:\\Windows\\System32\\Taskmgr.exe", NULL); }

static void on_devmgmt(void *d)   { launch_noret(L"C:\\Windows\\System32\\devmgmt.msc", NULL); }
static void on_diskmgmt(void *d)  { launch_noret(L"C:\\Windows\\System32\\diskmgmt.msc", NULL); }
static void on_services(void *d)  { launch_noret(L"C:\\Windows\\System32\\services.msc", NULL); }
static void on_eventvwr(void *d)  { launch_noret(L"C:\\Windows\\System32\\eventvwr.msc", NULL); }

static void on_cleanmgr(void *d)  { launch(L"C:\\Windows\\System32\\cleanmgr.exe", NULL); }
static void on_defrag(void *d)    { launch(L"C:\\Windows\\System32\\dfrgui.exe", NULL); }

/* ──── 打开文件夹 ──── */
static void open_folder(int fid)
{
    WCHAR path[MAX_PATH];
    if (get_special_folder(fid, path, MAX_PATH) == 0) {
        WCHAR cmd[MAX_PATH + 20];
        str_format(cmd, MAX_PATH + 20, L"\"%s\"", path);
        launch_noret(L"C:\\Windows\\explorer.exe", cmd);
    } else {
        statusbar_set_text(g_status, L"获取文件夹路径失败");
    }
}

static void on_folder_desktop(void *d)    { open_folder(FOLDER_DESKTOP); }
static void on_folder_docs(void *d)       { open_folder(FOLDER_DOCUMENTS); }
static void on_folder_downloads(void *d)  { open_folder(FOLDER_DOWNLOADS); }
static void on_folder_pictures(void *d)   { open_folder(FOLDER_PICTURES); }
static void on_folder_music(void *d)      { open_folder(FOLDER_MUSIC); }
static void on_folder_videos(void *d)     { open_folder(FOLDER_VIDEOS); }
static void on_folder_appdata(void *d)    { open_folder(FOLDER_APPDATA); }

/* ──── 进程管理 ──── */
static void refresh_processes(void)
{
    process_entry_t *procs = NULL;
    int count = 0;
    if (enum_processes(&procs, &count) != 0) {
        statusbar_set_text(g_status, L"枚举进程失败");
        return;
    }

    listview_delete_all(g_proc_list);

    for (int i = 0; i < count; i++) {
        WCHAR pid_str[16];
        str_format(pid_str, 16, L"%u", procs[i].pid);
        listview_add_text(g_proc_list, pid_str);
        listview_set_text(g_proc_list, i, 1, procs[i].name);
    }

    free(procs);
    statusbar_set_text(g_status, L"就绪");
}

static void kill_selected_process(void)
{
    int idx = listview_selected_index(g_proc_list);
    if (idx < 0) {
        statusbar_set_text(g_status, L"请先选择一个进程");
        return;
    }

    WCHAR pid_str[16] = {0};
    listview_get_text(g_proc_list, idx, 0, pid_str, 16);

    DWORD pid = _wtoi(pid_str);
    if (kill_process_pid(pid) == 0)
        statusbar_set_text(g_status, L"进程已终止");
    else
        statusbar_set_text(g_status, L"终止失败（权限不足）");
    refresh_processes();
}

static void on_refresh(void *d)  { refresh_processes(); }
static void on_kill(void *d)     { kill_selected_process(); }

/* ──── 环境变量面板 ──── */
static void refresh_env_list(void)
{
    listview_delete_all(g_env_list);

    struct { const WCHAR *name; } envs[] = {
        {L"PATH"}, {L"USERPROFILE"}, {L"APPDATA"}, {L"LOCALAPPDATA"},
        {L"TEMP"}, {L"TMP"}, {L"OS"}, {L"COMPUTERNAME"}, {L"USERNAME"},
        {L"ProgramFiles"}, {L"SystemRoot"}, {L"windir"},
    };

    int row = 0;
    for (int i = 0; i < sizeof(envs)/sizeof(envs[0]); i++) {
        WCHAR val[4096] = {0};
        if (get_env(envs[i].name, val, 4096) == 0) {
            listview_add_text(g_env_list, (WCHAR*)envs[i].name);
            listview_set_text(g_env_list, row, 1, val);
            row++;
        }
    }
}

static void on_env_set(void *d)
{
    const WCHAR *name = get_text(g_env_name);
    const WCHAR *val  = get_text(g_env_val);
    if (!name || !name[0]) {
        statusbar_set_text(g_status, L"请输入变量名");
        return;
    }

    if (set_env(name, val) == 0) {
        refresh_env_list();
        statusbar_set_text(g_status, L"环境变量已设置（仅当前进程）");
    } else {
        statusbar_set_text(g_status, L"设置失败");
    }
}

/* ──── 面板创建 ──── */

static HWND add_tool_btn(HWND parent, const WCHAR *text, void (*cb)(void*), int row, int col)
{
    int x = 20 + col * 200;
    int y = 20 + row * 50;
    HWND btn = create_button(parent, text, x, y, 180, 40);
    on_button_click(btn, cb, NULL);
    return btn;
}

/* 0: 系统工具 */
static HWND create_panel_system(HWND parent)
{
    HWND p = create_groupbox(parent, L"系统工具", 0, 0, 100, 100);
    add_tool_btn(p, L"记事本", on_notepad, 0, 0);
    add_tool_btn(p, L"计算器", on_calc, 0, 1);
    add_tool_btn(p, L"命令提示符", on_cmd, 0, 2);
    add_tool_btn(p, L"注册表编辑器", on_regedit, 1, 0);
    add_tool_btn(p, L"画图", on_mspaint, 1, 1);
    add_tool_btn(p, L"任务管理器", on_taskmgr, 1, 2);
    return p;
}

/* 1: 管理工具 */
static HWND create_panel_admin(HWND parent)
{
    HWND p = create_groupbox(parent, L"管理工具", 0, 0, 100, 100);
    add_tool_btn(p, L"设备管理器", on_devmgmt, 0, 0);
    add_tool_btn(p, L"磁盘管理", on_diskmgmt, 0, 1);
    add_tool_btn(p, L"服务管理", on_services, 0, 2);
    add_tool_btn(p, L"事件查看器", on_eventvwr, 1, 0);
    return p;
}

/* 2: 磁盘工具 */
static HWND create_panel_disk(HWND parent)
{
    HWND p = create_groupbox(parent, L"磁盘工具", 0, 0, 100, 100);
    add_tool_btn(p, L"磁盘清理", on_cleanmgr, 0, 0);
    add_tool_btn(p, L"磁盘碎片整理", on_defrag, 0, 1);
    return p;
}

/* 3: 快捷文件夹 */
static HWND create_panel_folders(HWND parent)
{
    HWND p = create_groupbox(parent, L"快捷文件夹", 0, 0, 100, 100);
    add_tool_btn(p, L"桌面", on_folder_desktop, 0, 0);
    add_tool_btn(p, L"文档", on_folder_docs, 0, 1);
    add_tool_btn(p, L"下载", on_folder_downloads, 0, 2);
    add_tool_btn(p, L"图片", on_folder_pictures, 1, 0);
    add_tool_btn(p, L"音乐", on_folder_music, 1, 1);
    add_tool_btn(p, L"视频", on_folder_videos, 1, 2);
    add_tool_btn(p, L"Roaming AppData", on_folder_appdata, 2, 0);
    return p;
}

/* 4: 进程管理 */
static HWND create_panel_processes(HWND parent)
{
    HWND p = create_groupbox(parent, L"进程管理", 0, 0, 100, 100);

    HWND refresh_btn = create_button(p, L"刷新列表", 20, 20, 100, 30);
    on_button_click(refresh_btn, on_refresh, NULL);

    HWND kill_btn = create_button(p, L"终止进程", 130, 20, 100, 30);
    on_button_click(kill_btn, on_kill, NULL);

    g_proc_list = create_listview(p, 20, 60, 780, 400);
    listview_add_column(g_proc_list, L"PID", 80);
    listview_add_column(g_proc_list, L"进程名", 680);

    return p;
}

/* 5: 系统信息 */
static HWND create_panel_info(HWND parent)
{
    HWND p = create_groupbox(parent, L"系统信息", 0, 0, 100, 100);

    sys_info_t info;
    if (get_sys_info(&info) != 0) {
        create_label(p, L"获取系统信息失败", 20, 20, 400, 20);
        return p;
    }

    int y = 20, lh = 28;

    create_label(p, L"计算机名", 20, y, 100, 20);
    create_label(p, info.computer_name, 130, y, 400, 20);
    y += lh;

    create_label(p, L"用户名", 20, y, 100, 20);
    create_label(p, info.user_name, 130, y, 400, 20);
    y += lh;

    create_label(p, L"操作系统", 20, y, 100, 20);
    create_label(p, info.os_version, 130, y, 500, 20);
    y += lh;

    WCHAR buf[512];
    str_format(buf, 512, L"%d 个逻辑核心", info.cpu_cores);
    create_label(p, L"CPU 核心", 20, y, 100, 20);
    create_label(p, buf, 130, y, 400, 20);
    y += lh;

    create_label(p, L"CPU 型号", 20, y, 100, 20);
    create_label(p, info.cpu_name, 130, y, 500, 20);
    y += lh;

    str_format(buf, 512, L"%llu MB（可用 %llu MB）", info.mem_total_mb, info.mem_avail_mb);
    create_label(p, L"物理内存", 20, y, 100, 20);
    create_label(p, buf, 130, y, 400, 20);
    y += lh;

    create_label(p, L"Windows 目录", 20, y, 100, 20);
    create_label(p, info.windows_dir, 130, y, 500, 20);

    return p;
}

/* 6: 环境变量 */
static HWND create_panel_env(HWND parent)
{
    HWND p = create_groupbox(parent, L"环境变量", 0, 0, 100, 100);

    create_label(p, L"变量名", 20, 20, 80, 20);
    g_env_name = create_text(p, L"PATH", 100, 18, 200, 24);

    create_label(p, L"变量值", 20, 52, 80, 20);
    g_env_val = create_text(p, L"", 100, 50, 500, 24);

    HWND set_btn = create_button(p, L"设置", 620, 50, 80, 26);
    on_button_click(set_btn, on_env_set, NULL);

    g_env_list = create_listview(p, 20, 85, 780, 380);
    listview_add_column(g_env_list, L"变量名", 180);
    listview_add_column(g_env_list, L"值", 580);

    refresh_env_list();
    return p;
}

/* ──── 创建面板工厂 ──── */
static HWND (* const g_panel_ctors[])(HWND) = {
    create_panel_system, create_panel_admin, create_panel_disk,
    create_panel_folders, create_panel_processes,
    create_panel_info, create_panel_env,
};

static const WCHAR *g_cat_names[] = {
    L"系统工具", L"管理工具", L"磁盘工具", L"快捷文件夹",
    L"进程管理", L"系统信息", L"环境变量"
};

/* ──── 类别切换 ──── */
static void switch_category(int cat)
{
    if (cat == g_active_cat) return;
    if (g_active_cat >= 0)
        hide(g_panels[g_active_cat]);
    g_active_cat = cat;
    show(g_panels[cat]);
    statusbar_set_text(g_status, g_cat_names[cat]);

    if (cat == 4) refresh_processes();
}

static void on_tab_changed(void *d)
{
    int cat = tabbar_selected_index(g_tab);
    switch_category(cat);
}

/* ──── 窗口缩放 ──── */
static void resize_content(void)
{
    int w, h;
    get_size(g_win, &w, &h);
    int tab_h = 26, bot = 24;

    set_size(g_tab, w, tab_h);
    for (int i = 0; i < CAT_COUNT; i++) {
        move(g_panels[i], 0, tab_h);
        set_size(g_panels[i], w, h - tab_h - bot);
    }
}

static void on_resize(int w, int h)
{
    resize_content();
}

static int on_close(void *d)
{
    return 1;
}

/* ──── Main ──── */
int main(void)
{
    if (init_app() != 0) {
        alert(L"错误", L"eduwin 初始化失败");
        return 1;
    }

    log_info(L"=== win_helper start ===");

    g_win = create_window(L"Windows 小助手", 1000, 600);
    if (!g_win) {
        alert(L"错误", L"创建窗口失败");
        return 1;
    }
    on_window_close(g_win, on_close, NULL);
    on_window_resize(g_win, on_resize);

    /* Tab 容器 */
    g_tab = create_tabbar(g_win, 0, 0, 850, 26);
    for (int i = 0; i < CAT_COUNT; i++)
        tabbar_add_text(g_tab, g_cat_names[i]);
    on_tabbar_select(g_tab, on_tab_changed, NULL);

    /* 面板 */
    for (int i = 0; i < CAT_COUNT; i++)
        g_panels[i] = g_panel_ctors[i](g_win);

    /* 默认隐藏所有面板，由 switch_category 控制显示 */
    for (int i = 0; i < CAT_COUNT; i++)
        hide(g_panels[i]);

    /* 状态栏 */
    g_status = create_statusbar(g_win);
    statusbar_set_text(g_status, L"Windows 小助手 - 选择工具类别");

    g_active_cat = -1;
    switch_category(0);

    show_window(g_win);
    run_app();

    log_info(L"=== win_helper end ===");
    return 0;
}
