#define _CRT_SECURE_NO_WARNINGS
#include "eduwin.h"

static sqlite3 *db = NULL;
static HWND listview;
static HWND statusbar;
static HWND input_name, input_email, input_phone;
static HWND btn_add, btn_delete;
static int editing_id = 0;

static void refresh_list(const char *filter)
{
    while (listview_count(listview) > 0)
        SendMessageW(listview, 0x1008, 0, 0);

    char sql[512];
    if (filter && filter[0])
        snprintf(sql, sizeof(sql),
                 "SELECT id, name, email, phone FROM users "
                 "WHERE name LIKE '%%%s%%' OR email LIKE '%%%s%%' ORDER BY id",
                 filter, filter);
    else
        strcpy(sql, "SELECT id, name, email, phone FROM users ORDER BY id");

    sqlite3_stmt *stmt = NULL;
    if (sqlite3_prepare_v2(db, sql, -1, &stmt, NULL) != SQLITE_OK)
        return;

    int row = 0;
    while (sqlite3_step(stmt) == SQLITE_ROW)
    {
        const char *name = (const char *)sqlite3_column_text(stmt, 1);
        const char *email = (const char *)sqlite3_column_text(stmt, 2);
        const char *phone = (const char *)sqlite3_column_text(stmt, 3);

        WCHAR buf[128];
        MultiByteToWideChar(65001, 0, name ? name : "", -1, buf, 128);
        listview_add_text(listview, buf);

        MultiByteToWideChar(65001, 0, email ? email : "", -1, buf, 128);
        listview_set_text(listview, row, 1, buf);

        MultiByteToWideChar(65001, 0, phone ? phone : "", -1, buf, 128);
        listview_set_text(listview, row, 2, buf);

        row++;
    }
    sqlite3_finalize(stmt);
}

static void clear_inputs(void)
{
    set_text(input_name, L"");
    set_text(input_email, L"");
    set_text(input_phone, L"");
    editing_id = 0;
    set_text(btn_add, L"添加");
    set_enable(btn_delete, 0);
}

static void on_add_click(void *data)
{
    const WCHAR *wname = get_text(input_name);
    if (wname[0] == L'\0')
    {
        alert(L"提示", L"请输入姓名");
        return;
    }
    const WCHAR *wemail = get_text(input_email);
    const WCHAR *wphone = get_text(input_phone);

    if (editing_id > 0)
    {
        char *name8 = wtou8(wname);
        char *email8 = wtou8(wemail);
        char *phone8 = wtou8(wphone);
        sqlite3_stmt *stmt = NULL;
        sqlite3_prepare_v2(db,
                           "UPDATE users SET name=?, email=?, phone=? WHERE id=?",
                           -1, &stmt, NULL);
        sqlite3_bind_text(stmt, 1, name8, -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(stmt, 2, email8, -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(stmt, 3, phone8, -1, SQLITE_TRANSIENT);
        sqlite3_bind_int(stmt, 4, editing_id);
        if (sqlite3_step(stmt) == SQLITE_DONE)
            statusbar_set_text(statusbar, L"修改成功");
        sqlite3_finalize(stmt);
        free(name8);
        free(email8);
        free(phone8);
    }
    else
    {
        char *name8 = wtou8(wname);
        char *email8 = wtou8(wemail);
        char *phone8 = wtou8(wphone);
        sqlite3_stmt *stmt = NULL;
        sqlite3_prepare_v2(db,
                           "INSERT INTO users (name, email, phone) VALUES (?, ?, ?)",
                           -1, &stmt, NULL);
        sqlite3_bind_text(stmt, 1, name8, -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(stmt, 2, email8, -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(stmt, 3, phone8, -1, SQLITE_TRANSIENT);
        if (sqlite3_step(stmt) == SQLITE_DONE)
            statusbar_set_text(statusbar, L"添加成功");
        sqlite3_finalize(stmt);
        free(name8);
        free(email8);
        free(phone8);
    }

    refresh_list(NULL);
    clear_inputs();
}

static void on_delete_click(void *data)
{
    if (editing_id <= 0)
        return;
    if (!confirm(L"确认", L"确定要删除该用户吗？"))
        return;

    sqlite3_stmt *stmt = NULL;
    sqlite3_prepare_v2(db, "DELETE FROM users WHERE id=?", -1, &stmt, NULL);
    sqlite3_bind_int(stmt, 1, editing_id);
    if (sqlite3_step(stmt) == SQLITE_DONE)
        statusbar_set_text(statusbar, L"已删除");
    sqlite3_finalize(stmt);

    refresh_list(NULL);
    clear_inputs();
}

static void on_search_click(void *data)
{
    const WCHAR *kw = get_text(input_name);
    char *kw8 = wtou8(kw);
    refresh_list(kw8);
    free(kw8);
    statusbar_set_text(statusbar, L"搜索完成");
}

static void on_clear_click(void *data)
{
    clear_inputs();
    refresh_list(NULL);
    statusbar_set_text(statusbar, L"已重置");
}

static void on_list_dblclick(void *data)
{
    int sel = listview_selected_index(listview);
    if (sel < 0)
        return;

    sqlite3_stmt *stmt = NULL;
    sqlite3_prepare_v2(db,
                       "SELECT id, name, email, phone FROM users ORDER BY id LIMIT 1 OFFSET ?",
                       -1, &stmt, NULL);
    sqlite3_bind_int(stmt, 1, sel);

    if (sqlite3_step(stmt) == SQLITE_ROW)
    {
        editing_id = sqlite3_column_int(stmt, 0);
        const char *name = (const char *)sqlite3_column_text(stmt, 1);
        const char *email = (const char *)sqlite3_column_text(stmt, 2);
        const char *phone = (const char *)sqlite3_column_text(stmt, 3);

        WCHAR buf[128];
        MultiByteToWideChar(65001, 0, name ? name : "", -1, buf, 128);
        set_text(input_name, buf);
        MultiByteToWideChar(65001, 0, email ? email : "", -1, buf, 128);
        set_text(input_email, buf);
        MultiByteToWideChar(65001, 0, phone ? phone : "", -1, buf, 128);
        set_text(input_phone, buf);

        set_text(btn_add, L"修改");
        set_enable(btn_delete, 1);
    }
    sqlite3_finalize(stmt);
}

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

    if (sqlite3_open("users.db", &db) != SQLITE_OK)
    {
        alert(L"错误", L"无法打开数据库 users.db");
        return 1;
    }

    char *err = NULL;
    sqlite3_exec(db,
                 "CREATE TABLE IF NOT EXISTS users ("
                 "id INTEGER PRIMARY KEY AUTOINCREMENT, "
                 "name TEXT NOT NULL, "
                 "email TEXT, "
                 "phone TEXT)",
                 NULL, NULL, &err);
    if (err)
    {
        sqlite3_free(err);
        sqlite3_close(db);
        alert(L"错误", L"建表失败");
        return 1;
    }

    HWND win = create_window(L"用户信息管理 — SQLite + eduwin", 800, 520);
    if (!win)
        return 1;

    create_label(win, L"用户列表（双击编辑）：", 15, 10, 200, 20);
    listview = create_listview(win, 15, 30, 420, 400);
    listview_add_column(listview, L"姓名", 120);
    listview_add_column(listview, L"邮箱", 150);
    listview_add_column(listview, L"电话", 130);

    create_groupbox(win, L"用户信息", 460, 10, 315, 400);

    create_label(win, L"姓名：", 470, 35, 60, 22);
    input_name = create_text(win, L"", 530, 33, 230, 24);

    create_label(win, L"邮箱：", 470, 70, 60, 22);
    input_email = create_text(win, L"", 530, 68, 230, 24);

    create_label(win, L"电话：", 470, 105, 60, 22);
    input_phone = create_text(win, L"", 530, 103, 230, 24);

    btn_add = create_button(win, L"添加", 470, 150, 90, 30);
    on_button_click(btn_add, on_add_click, NULL);

    HWND btn_search = create_button(win, L"搜索", 570, 150, 90, 30);
    on_button_click(btn_search, on_search_click, NULL);

    btn_delete = create_button(win, L"删除", 470, 190, 90, 30);
    on_button_click(btn_delete, on_delete_click, NULL);
    set_enable(btn_delete, 0);

    HWND btn_clear = create_button(win, L"重置", 570, 190, 90, 30);
    on_button_click(btn_clear, on_clear_click, NULL);

    create_label(win, L"使用说明：\n"
                      L"• 填入信息后点击[添加]新增\n"
                      L"• 双击列表行回填，[添加]变[修改]\n"
                      L"• 选中后点[删除]移除该用户\n"
                      L"• 输入关键词后点[搜索]过滤\n"
                      L"• 点[重置]清空输入并显示全部",
                 470, 240, 300, 150);

    statusbar = create_statusbar(win);
    statusbar_set_text(statusbar, L"就绪 — 数据库: users.db");

    on_listview_dblclick(listview, on_list_dblclick, NULL);

    refresh_list(NULL);

    show_window(win);
    run_app();

    sqlite3_close(db);
    return 0;
}
