#include "app_debugset.h"
#include "service_debugset.h"
#include "ui_manager.h"
#include "app_set_var_list.h"
#include "app_confirm.h"
#include "components/app_input_pwd.h"
#include "components/app_datetime_set.h"
#include "data_config.h"

// Manu_str.c 中的菜单字符串
extern Para_OPTTypeDef Sys_set_opt[7];      // 7个系统设置项

// 系统设置菜单密码验证状态
static bool s_system_set_verified = false;

// 当前正在处理的设置项索引
static u8 s_current_setting_idx = 0xFF;

// 密码修改确认相关
static uint16_t s_new_password_temp = 0;  // 临时存储新密码
static bool s_password_modify_pending = false;  // 标记是否有待确认的密码修改

/**
 * @brief 根据按键输入计算左侧菜单选中索引
 * @param curstate 当前光标状态
 * @param kval 按键值
 * @return 新菜单索引
 */
static u8 app_debugset_cal_left_sel_idx(UICursorState curstate, keyValue kval)
{
    u8 menu_size = debugset_service_get_menu_len();
    u8 cur_idx = curstate.left_menu_idx;

    switch (kval)
    {
    case KEY_DATA_LEFT:
        if (cur_idx > 7)
            cur_idx = 8 * (cur_idx / 8) - 8;
        else
            cur_idx = 8 * ((menu_size - 1) / 8);
        break;
    case KEY_DATA_UP:
        if (cur_idx > 0)
            cur_idx--;
        else
            cur_idx = menu_size - 1;
        break;
    case KEY_DATA_RIGHT:
        if (cur_idx < (menu_size - menu_size % 8))
            cur_idx = 8 * (cur_idx / 8) + 8;
        else
            cur_idx = 0;
        break;
    case KEY_DATA_DOWN:
        cur_idx++;
        if (cur_idx > menu_size - 1)
            cur_idx = 0;
        break;
    default:
        break;
    }
    return cur_idx;
}

/**
 * @brief 根据按键输入计算右侧数据选中索引
 * @param curstate 当前光标状态
 * @param kval 按键值
 * @return 新数据项索引
 */
static u8 app_debugset_cal_right_sel_idx(UICursorState curstate, keyValue kval)
{
    u8 menu_len = debugset_service_get_items_len(curstate.left_menu_idx);
    u8 cur_idx = curstate.right_data_idx;

    if (kval == KEY_DATA_DOWN)
    {
        if (cur_idx < menu_len - 1)
            cur_idx++;
        else
            cur_idx = 0;
    }
    else if (kval == KEY_DATA_UP)
    {
        if (cur_idx > 0)
            cur_idx--;
        else
            cur_idx = menu_len - 1;
    }
    else if (kval == KEY_DATA_RIGHT)
    {
        if (cur_idx < (menu_len - menu_len % 8))
            cur_idx = 8 * (cur_idx / 8) + 8;
        else
            cur_idx = 0;
    }
    else if (kval == KEY_DATA_LEFT)
    {
        if (cur_idx > 7)
            cur_idx = 8 * (cur_idx / 8) - 8;
        else
            cur_idx = 8 * ((menu_len - 1) / 8);
    }

    return cur_idx;
}

/**
 * @brief 检查当前菜单是否需要密码验证
 * @param menu_idx 菜单索引 (0=状态信息, 1=系统设置)
 * @return true 需要密码, false 不需要密码
 */
static bool app_debugset_is_password_required(u8 menu_idx)
{
    // 状态信息(索引0)不需要密码
    // 系统设置(索引1)需要密码
    return (menu_idx == DEBUGSET_MENU_SYSTEM_SET);
}

/**
 * @brief 检查系统设置密码是否已验证
 * @return true 已验证, false 未验证
 */
static bool app_debugset_is_verified(void)
{
    return s_system_set_verified;
}

/**
 * @brief 设置密码验证状态
 * @param verified 验证状态
 */
static void app_debugset_set_verified(bool verified)
{
    s_system_set_verified = verified;
}

/**
 * @brief 处理开关类型设置（退出/投入）
 * @param kval 按键值
 * @return 设置结果值
 */
static float app_debugset_handle_switch_setting(keyValue kval)
{
    float val = 0;
    
    if (kval == KEY_DATA_ENTER)
    {
        // 获取当前设置值
        val = ui_manager_comp_get_valist_spinbox_value();
        printf("%s: Switch setting confirmed, value = %f\n", __FUNCTION__, val);
        
        // 调用service层保存设置
        if (s_current_setting_idx != 0xFF)
        {
            debugset_service_set_item_value(s_current_setting_idx, (uint32_t)val);
            
            // 根据设置项执行相应操作
            if (val == 1)  // 投入状态
            {
                switch (s_current_setting_idx)
                {
                    case SYSSET_ITEM_FACTORY_RESET:
                        debugset_service_factory_reset();
                        break;
                    case SYSSET_ITEM_CLEAR_HISTORY:
                        debugset_service_clear_history();
                        break;
                    case SYSSET_ITEM_CLEAR_ENERGY:
                        debugset_service_clear_energy();
                        break;
                    default:
                        break;
                }
            }
        }
    }
    else
    {
        // 处理上下键切换选项
        val = app_set_var_list_handle_event(kval);
    }
    
    return val;
}

/**
 * @brief 处理数值类型设置
 * @param kval 按键值
 * @return 设置结果值
 */
static float app_debugset_handle_number_setting(keyValue kval)
{
    float val = 0;
    
    if (kval == KEY_DATA_ENTER)
    {
        // 获取当前设置值
        val = ui_manager_comp_get_valist_spinbox_value();
        printf("%s: Number setting confirmed, value = %f\n", __FUNCTION__, val);
        
        // 调用service层保存设置
        if (s_current_setting_idx != 0xFF)
        {
            debugset_service_set_item_value(s_current_setting_idx, (uint32_t)val);
        }
    }
    else
    {
        // 处理上下键调整数值
        val = app_set_var_list_handle_event(kval);
    }
    
    return val;
}

/**
 * @brief 处理时间设置
 * @param kval 按键值
 * @return 操作结果
 */
static uint32_t app_debugset_handle_datetime_setting(keyValue kval)
{
    uint32_t result = app_datetime_set_handle_event(kval);
    
    if (result == DATETIME_OP_OK)
    {
        // 获取设置的时间值
        datetime_value_t new_time = app_datetime_set_get_value();
        printf("%s: Datetime setting confirmed: %04d-%02d-%02d %02d:%02d:%02d\n", __FUNCTION__,
               new_time.year, new_time.month, new_time.day,
               new_time.hour, new_time.minute, new_time.second);
        
        // 调用service层保存时间
        debugset_service_set_datetime(&new_time);
    }
    
    return result;
}

/**
 * @brief 处理密码设置
 * @param kval 按键值
 * @return 设置结果值
 */
static float app_debugset_handle_password_setting(keyValue kval)
{
    float val = 0;

    if (kval == KEY_DATA_ENTER)
    {
        // 获取当前设置值
        val = ui_manager_comp_get_valist_spinbox_value();
        printf("%s: Password setting enter pressed, value = %04d\n", __FUNCTION__, (int)val);

        // 验证密码范围
        if (val >= 0 && val <= 9999)
        {
            // 临时存储新密码，等待用户确认
            s_new_password_temp = (uint16_t)val;
            s_password_modify_pending = true;

            // 弹出确认对话框
            confirm_dialog_config_t pwd_confirm_config = {
                .title = "系统设置",
                .message = "您确定要修改当前密码吗？"
            };

            UICursorState curstate = ui_manager_get_cursor();
            curstate.cursor_pos = CURSOR_CONFIRM_SAVE;
            ui_manager_cursor_set_value(curstate);
            ui_manager_comp_create_confirm_save_with_config(&pwd_confirm_config);
        }
    }
    else
    {
        // 处理上下键调整数值
        val = app_set_var_list_handle_event(kval);
    }

    return val;
}

/**
 * @brief 处理系数校准确认对话框
 * @param kval 按键值
 * @return 确认结果
 */
static bool app_debugset_handle_calibration_confirm(keyValue kval)
{
    bool result = false;
    
    if (kval == KEY_DATA_ENTER)
    {
        result = ui_manager_comp_get_confirm_save_result();
        printf("%s: Calibration confirm result = %d\n", __FUNCTION__, result);
        
        if (result)
        {
            // 执行校准
            debugset_service_calibrate();
        }
    }
    else if (kval == KEY_DATA_LEFT || kval == KEY_DATA_RIGHT)
    {
        // 切换焦点
        ui_manager_comp_switch_confirm_save_focus();
    }
    
    return result;
}

/**
 * @brief 处理组件级事件(密码输入、数值修改、确认保存)
 * @param kval 按键值
 */
void app_debugset_process_compenents_handle_event(keyValue kval)
{
    UICursorState curstate = ui_manager_get_cursor();
    float val = 0;
    GeneralListPageConfig_t config = {0};
    PageCtx dev_info_ctx = {0};
    bool confirm_result = false;

    switch (curstate.cursor_pos)
    {
    case CURSOR_INPUT_PWD:
        // 处理密码输入
        val = app_input_pwd_handle_event(kval);
        if (kval == KEY_DATA_ENTER)
        {
            printf("%s touch enter key, left menu index = %d, pwd = %f\n", __FUNCTION__, curstate.left_menu_idx, val);
            // 验证密码(使用与设备设置相同的密码)
            if (val == SUPER_PWD || val == Password_opt[2].value)
            {
                // 密码正确,标记为已验证并显示系统设置
                app_debugset_set_verified(true);
                curstate.cursor_pos = CURSOR_RIGHT_DATA;
                curstate.right_data_idx = 0;
                ui_manager_cursor_set_value(curstate);
                debugset_service_get_show_ui_data(ui_manager_get_page_ctx(), curstate.left_menu_idx, curstate.right_data_idx, &config, app_debugset_is_verified());
                ui_manager_select_list_data(curstate, &config);
            }
            else
            {
                // 密码错误,返回菜单选择
                curstate.cursor_pos = CURSOR_LEFT_MENU;
                ui_manager_cursor_set_value(curstate);
                debugset_service_get_show_ui_data(ui_manager_get_page_ctx(), curstate.left_menu_idx, curstate.right_data_idx, &config, app_debugset_is_verified());
                ui_manager_select_list_data(curstate, &config);
            }
        }
        else if (kval == KEY_DATA_BACK || kval == KEY_DATA_CANCEL)
        {
            // 取消密码输入,返回菜单选择
            curstate.cursor_pos = CURSOR_LEFT_MENU;
            ui_manager_cursor_set_value(curstate);
            debugset_service_get_show_ui_data(ui_manager_get_page_ctx(), curstate.left_menu_idx, curstate.right_data_idx, &config, app_debugset_is_verified());
            ui_manager_select_list_data(curstate, &config);
        }
        break;

    case CURSOR_CHANGE_VAL:
        // 处理数值修改(用于系统设置)
        if (s_current_setting_idx != 0xFF)
        {
            if (debugset_service_is_switch_type(s_current_setting_idx))
            {
                val = app_debugset_handle_switch_setting(kval);
            }
            else if (debugset_service_is_number_type(s_current_setting_idx))
            {
                val = app_debugset_handle_number_setting(kval);
            }
            else if (s_current_setting_idx == SYSSET_ITEM_PASSWORD)
            {
                val = app_debugset_handle_password_setting(kval);
            }
        }
        
        if (kval == KEY_DATA_ENTER || kval == KEY_DATA_BACK || kval == KEY_DATA_CANCEL)
        {
            // 密码设置按ENTER后进入确认对话框，不在此处返回
            if (kval == KEY_DATA_ENTER && s_current_setting_idx == SYSSET_ITEM_PASSWORD)
            {
                // 密码设置已弹出确认对话框，不执行返回操作
                // 确认结果在 CURSOR_CONFIRM_SAVE 中处理
            }
            else
            {
                // 返回数据选择
                curstate.cursor_pos = CURSOR_RIGHT_DATA;
                ui_manager_cursor_set_value(curstate);
                s_current_setting_idx = 0xFF;  // 清除当前设置项
                debugset_service_get_show_ui_data(ui_manager_get_page_ctx(), curstate.left_menu_idx, curstate.right_data_idx, &config, app_debugset_is_verified());
                ui_manager_select_list_data(curstate, &config);
            }
        }
        break;

    case CURSOR_SET_IP:
        // 处理时间设置
        if (s_current_setting_idx == SYSSET_ITEM_DATETIME)
        {
            uint32_t result = app_debugset_handle_datetime_setting(kval);
            
            if (result == DATETIME_OP_OK || result == DATETIME_OP_CANCEL || 
                kval == KEY_DATA_BACK || kval == KEY_DATA_CANCEL)
            {
                // 返回数据选择
                curstate.cursor_pos = CURSOR_RIGHT_DATA;
                ui_manager_cursor_set_value(curstate);
                s_current_setting_idx = 0xFF;  // 清除当前设置项
                debugset_service_get_show_ui_data(ui_manager_get_page_ctx(), curstate.left_menu_idx, curstate.right_data_idx, &config, app_debugset_is_verified());
                ui_manager_select_list_data(curstate, &config);
            }
        }
        break;

    case CURSOR_CONFIRM_SAVE:
        // 处理确认对话框（系数校准、恢复出厂设置、清除历史记录、电度清除、密码修改）
        if (s_current_setting_idx == SYSSET_ITEM_CALIBRATION ||
            s_current_setting_idx == SYSSET_ITEM_FACTORY_RESET ||
            s_current_setting_idx == SYSSET_ITEM_CLEAR_HISTORY ||
            s_current_setting_idx == SYSSET_ITEM_CLEAR_ENERGY ||
            s_current_setting_idx == SYSSET_ITEM_PASSWORD)
        {
            if (kval == KEY_DATA_ENTER)
            {
                confirm_result = ui_manager_comp_get_confirm_save_result();
                printf("%s: Confirm result = %d for item %d\n", __FUNCTION__, confirm_result, s_current_setting_idx);

                if (confirm_result)
                {
                    // 根据设置项执行相应操作
                    switch (s_current_setting_idx)
                    {
                        case SYSSET_ITEM_FACTORY_RESET:
                            debugset_service_factory_reset();
                            break;
                        case SYSSET_ITEM_CLEAR_HISTORY:
                            debugset_service_clear_history();
                            break;
                        case SYSSET_ITEM_CLEAR_ENERGY:
                            debugset_service_clear_energy();
                            break;
                        case SYSSET_ITEM_CALIBRATION:
                            debugset_service_calibrate();
                            break;
                        case SYSSET_ITEM_PASSWORD:
                            // 执行密码更新操作
                            if (s_password_modify_pending)
                            {
                                debugset_service_set_password(s_new_password_temp);
                                printf("%s: Password updated to %04d\n", __FUNCTION__, s_new_password_temp);
                                s_password_modify_pending = false;
                                s_new_password_temp = 0;
                            }
                            break;
                        default:
                            break;
                    }
                }
                else
                {
                    // 用户取消密码修改，清除临时状态
                    if (s_current_setting_idx == SYSSET_ITEM_PASSWORD && s_password_modify_pending)
                    {
                        printf("%s: Password modification cancelled\n", __FUNCTION__);
                        s_password_modify_pending = false;
                        s_new_password_temp = 0;
                    }
                }

                // 返回数据选择
                curstate.cursor_pos = CURSOR_RIGHT_DATA;
                ui_manager_cursor_set_value(curstate);
                s_current_setting_idx = 0xFF;  // 清除当前设置项
                debugset_service_get_show_ui_data(ui_manager_get_page_ctx(), curstate.left_menu_idx, curstate.right_data_idx, &config, app_debugset_is_verified());
                ui_manager_select_list_data(curstate, &config);
            }
            else if (kval == KEY_DATA_BACK || kval == KEY_DATA_CANCEL)
            {
                // 取消，返回数据选择
                // 如果是密码修改，清除临时状态
                if (s_current_setting_idx == SYSSET_ITEM_PASSWORD && s_password_modify_pending)
                {
                    printf("%s: Password modification cancelled by back/cancel key\n", __FUNCTION__);
                    s_password_modify_pending = false;
                    s_new_password_temp = 0;
                }

                curstate.cursor_pos = CURSOR_RIGHT_DATA;
                ui_manager_cursor_set_value(curstate);
                s_current_setting_idx = 0xFF;
                debugset_service_get_show_ui_data(ui_manager_get_page_ctx(), curstate.left_menu_idx, curstate.right_data_idx, &config, app_debugset_is_verified());
                ui_manager_select_list_data(curstate, &config);
            }
            else if (kval == KEY_DATA_LEFT || kval == KEY_DATA_RIGHT)
            {
                // 切换焦点
                ui_manager_comp_switch_confirm_save_focus();
            }
        }
        break;

    default:
        break;
    }
}



/**
 * @brief 出厂调试页面主事件处理函数
 * @param kval 按键值
 */
void app_debugset_handle_event(keyValue kval)
{
    UICursorState curstate = ui_manager_get_cursor();
    PageCtx dev_info_ctx = {0};
    GeneralListPageConfig_t config = {0};

    // 首先处理组件级事件
    if (curstate.cursor_pos > CURSOR_RIGHT_DATA)
    {
        app_debugset_process_compenents_handle_event(kval);
        return;
    }

    switch (kval)
    {
    case KEY_DATA_BACK:
        if (curstate.cursor_pos == CURSOR_LEFT_MENU)
        {
            // 检查是否有未保存的更改
            // TODO: 如需要可添加差异检查
            // 目前直接返回主菜单
            ui_manager_switch_to_main_menu(MAIN_MENU_DEBUG_TEST);
            // 离开页面时重置验证状态
            app_debugset_set_verified(false);
        }
        else if (curstate.cursor_pos == CURSOR_RIGHT_DATA)
        {
            // 返回左侧菜单
            curstate.cursor_pos = CURSOR_LEFT_MENU;
            curstate.right_data_idx = 0;
            ui_manager_cursor_set_value(curstate);
            debugset_service_get_show_ui_data(ui_manager_get_page_ctx(), curstate.left_menu_idx, curstate.right_data_idx, &config, app_debugset_is_verified());
            ui_manager_select_list_data(curstate, &config);
        }
        break;

    case KEY_DATA_ENTER:
        if (curstate.cursor_pos == CURSOR_LEFT_MENU)
        {
            // 检查此菜单是否需要密码
            if (app_debugset_is_password_required(curstate.left_menu_idx))
            {
                if (!app_debugset_is_verified())
                {
                    // 显示密码输入对话框
                    curstate.cursor_pos = CURSOR_INPUT_PWD;
                    ui_manager_cursor_set_value(curstate);
                    ui_manager_comp_create_input_pwd();
                }
                else
                {
                    // 已验证,直接进入数据
                    curstate.cursor_pos = CURSOR_RIGHT_DATA;
                    curstate.right_data_idx = 0;
                    ui_manager_cursor_set_value(curstate);
                    debugset_service_get_show_ui_data(ui_manager_get_page_ctx(), curstate.left_menu_idx, curstate.right_data_idx, &config, app_debugset_is_verified());
                    ui_manager_select_list_data(curstate, &config);
                }
            }
            else
            {
                // 不需要密码,直接进入数据
                curstate.cursor_pos = CURSOR_RIGHT_DATA;
                curstate.right_data_idx = 0;
                ui_manager_cursor_set_value(curstate);
                debugset_service_get_show_ui_data(ui_manager_get_page_ctx(), curstate.left_menu_idx, curstate.right_data_idx, &config, app_debugset_is_verified());
                ui_manager_select_list_data(curstate, &config);
            }
        }
        else if (curstate.cursor_pos == CURSOR_RIGHT_DATA)
        {
            printf("%s touch enter!!\n", __FUNCTION__);

            // 仅在系统设置菜单(索引1)且已验证时允许修改
            if (curstate.left_menu_idx == DEBUGSET_MENU_SYSTEM_SET && app_debugset_is_verified())
            {
                u8 item_idx = curstate.right_data_idx;
                s_current_setting_idx = item_idx;

                if (item_idx == SYSSET_ITEM_DATETIME)
                {
                    // 系统时间设置 - 使用datetime组件
                    datetime_value_t curr_datetime;
                    debugset_service_get_datetime(&curr_datetime);

                    curstate.cursor_pos = CURSOR_SET_IP;  // 复用IP设置的光标状态
                    ui_manager_cursor_set_value(curstate);
                    ui_manager_comp_create_datetime_set(&curr_datetime);
                }
                else if (item_idx == SYSSET_ITEM_CALIBRATION)
                {
                    // 系数校准 - 使用确认对话框（自定义标题和内容）
                    confirm_dialog_config_t calib_config = {
                        .title = "系统设置",
                        .message = "确定是否一键校准"
                    };
                    curstate.cursor_pos = CURSOR_CONFIRM_SAVE;
                    ui_manager_cursor_set_value(curstate);
                    ui_manager_comp_create_confirm_save_with_config(&calib_config);
                }
                else if (item_idx == SYSSET_ITEM_FACTORY_RESET)
                {
                    // 恢复出厂设置 - 使用确认对话框
                    confirm_dialog_config_t reset_config = {
                        .title = "系统设置",
                        .message = "确定是否恢复出厂设置"
                    };
                    curstate.cursor_pos = CURSOR_CONFIRM_SAVE;
                    ui_manager_cursor_set_value(curstate);
                    ui_manager_comp_create_confirm_save_with_config(&reset_config);
                }
                else if (item_idx == SYSSET_ITEM_CLEAR_HISTORY)
                {
                    // 清除历史记录 - 使用确认对话框
                    confirm_dialog_config_t clear_history_config = {
                        .title = "系统设置",
                        .message = "确定是否清除历史记录"
                    };
                    curstate.cursor_pos = CURSOR_CONFIRM_SAVE;
                    ui_manager_cursor_set_value(curstate);
                    ui_manager_comp_create_confirm_save_with_config(&clear_history_config);
                }
                else if (item_idx == SYSSET_ITEM_CLEAR_ENERGY)
                {
                    // 电度清除 - 使用确认对话框
                    confirm_dialog_config_t clear_energy_config = {
                        .title = "系统设置",
                        .message = "确定是否清除电度"
                    };
                    curstate.cursor_pos = CURSOR_CONFIRM_SAVE;
                    ui_manager_cursor_set_value(curstate);
                    ui_manager_comp_create_confirm_save_with_config(&clear_energy_config);
                }
                else
                {
                    // 其他设置项 - 使用set_valist组件
                    UiSetValueOptDef set_opt = {0};
                    sysset_op_result_t result = debugset_service_create_ui_config(item_idx, &set_opt);

                    if (result == SYSSET_OP_SUCCESS)
                    {
                        curstate.cursor_pos = CURSOR_CHANGE_VAL;
                        ui_manager_cursor_set_value(curstate);
                        ui_manager_comp_create_set_valist(&set_opt);
                    }
                    else
                    {
                        printf("%s: Failed to create UI config for item %d, result=%d\n",
                               __FUNCTION__, item_idx, result);
                    }
                }
            }
        }
        break;

    case KEY_DATA_UP:
    case KEY_DATA_DOWN:
    case KEY_DATA_LEFT:
    case KEY_DATA_RIGHT:
        if (curstate.cursor_pos == CURSOR_LEFT_MENU)
        {
            curstate.left_menu_idx = app_debugset_cal_left_sel_idx(curstate, kval);
            // 切换离开系统设置时重置验证
            if (curstate.left_menu_idx != DEBUGSET_MENU_SYSTEM_SET)
            {
                app_debugset_set_verified(false);
            }
        }
        else if (curstate.cursor_pos == CURSOR_RIGHT_DATA)
        {
            curstate.right_data_idx = app_debugset_cal_right_sel_idx(curstate, kval);
        }

        ui_manager_cursor_set_value(curstate);
        debugset_service_get_show_ui_data(ui_manager_get_page_ctx(), curstate.left_menu_idx, curstate.right_data_idx, &config, app_debugset_is_verified());
        ui_manager_select_list_data(curstate, &config);
        break;

    default:
        break;
    }
}

/**
 * @brief 创建出厂调试页面列表数据
 * @param ctx 页面上下文
 * @param menu_sel_idx 选中菜单索引 (0=状态信息, 1=系统设置)
 * @param item_sel_idx 菜单内选中项索引
 */
void app_debugset_create_list_data(PageCtx *ctx, u8 menu_sel_idx, u8 item_sel_idx)
{
    GeneralListPageConfig_t config = {0};

    // 创建新列表时重置验证状态(进入页面)
    app_debugset_set_verified(false);
    s_current_setting_idx = 0xFF;

    debugset_service_get_show_ui_data(ctx, menu_sel_idx, item_sel_idx, &config, app_debugset_is_verified());

    ui_manager_gerneral_list(ctx, &config);
}
