#include "app_real_time_data.h"
#include "ui_manager.h"
#include "data_config.h"
#include "components/app_set_var_list.h"
#include "components/app_input_pwd.h"
#include "service_real_time_data.h"
#include "core/lvgl/lvgl.h"

/* ============================================================================
 * 实时数据自动刷新功能
 * ----------------------------------------------------------------------------
 * 功能说明：
 *   为UI实时数据模块添加自动刷新功能，当界面处于遥信(SUB_RTD_YX)、
 *   一次遥测(SUB_RTD_OYC)、二次遥测(SUB_RTD_SYC)三个子菜单内时，
 *   能够自动检测数据变化并刷新UI显示。
 *
 * 设计要点：
 *   1. 使用LVGL原生定时器机制，周期500ms
 *   2. 刷新条件判断：当前页面+子菜单范围+光标位置
 *   3. 定时器生命周期与页面生命周期绑定
 *   4. 不影响遥控(YK)功能的认证流程
 * ============================================================================ */

/* 自动刷新配置宏 */
#define RTD_REFRESH_PERIOD_MS   500U        /* 刷新周期（毫秒） */
#define RTD_REFRESH_MENU_MIN    0U         /* 需要刷新的子菜单起始索引（遥信） */
#define RTD_REFRESH_MENU_MAX    2U         /* 需要刷新的子菜单结束索引（二次遥测） */
#define RTD_REFRESH_MENU_COUNT  3U         /* 需要刷新的子菜单数量 */

/* 静态变量定义 */
static lv_task_t *s_rtd_refresh_task = NULL;  /* LVGL定时器句柄 */
static bool s_yk_authenticated = false;       /* 遥控认证状态标志 */

/* ============================================================================
 * 自动刷新功能实现
 * ============================================================================ */

/**
 * @brief 检查当前是否满足自动刷新条件
 * @return true 满足条件，需要刷新
 * @return false 不满足条件
 * @note 刷新条件：
 *        1. 当前页面为实时数据页面
 *        2. 当前子菜单索引在[0,2]范围内（遥信、一次遥测、二次遥测）
 *        3. 光标位置在左侧菜单或右侧数据区（非输入/修改状态）
 */
static bool rtd_should_auto_refresh(void)
{
    PageType cur_page = ui_manager_get_curpage();
    if (cur_page != PAGE_REAL_TIME_DATA) {
        return false;
    }

    UICursorState cursor = ui_manager_get_cursor();

    /* 检查子菜单范围：仅对遥信、一次遥测、二次遥测进行自动刷新 */
    if (cursor.left_menu_idx < RTD_REFRESH_MENU_MIN ||
        cursor.left_menu_idx > RTD_REFRESH_MENU_MAX) {
        return false;
    }

    /* 检查光标位置：仅在左右区域时刷新，输入类状态不刷新 */
    if (cursor.cursor_pos != CURSOR_LEFT_MENU &&
        cursor.cursor_pos != CURSOR_RIGHT_DATA) {
        return false;
    }

    return true;
}

/**
 * @brief LVGL定时器回调函数
 * @param task LVGL任务句柄（未使用但保留接口）
 * @note 在LVGL任务上下文中执行，可直接操作UI
 *       使用方案A（全局刷新），确保数据一致性
 */
static void rtd_refresh_timer_cb(lv_task_t *task)
{
    (void)task;

    if (!rtd_should_auto_refresh()) {
        return;
    }

    UICursorState cursor = ui_manager_get_cursor();
    GeneralListPageConfig_t config = {0};

    /* 获取最新数据 */
    rtd_service_get_ui_data(cursor.cursor_pos,
                           cursor.left_menu_idx,
                           cursor.right_data_idx,
                           &config,
                           s_yk_authenticated);

    /* 刷新UI显示 */
    ui_manager_refresh_list(cursor, &config);
}

/**
 * @brief 启动自动刷新定时器
 * @note 页面创建时调用，避免重复创建
 *       使用LV_TASK_PRIO_LOW确保不影响其他UI响应
 */
static void rtd_start_auto_refresh(void)
{
    if (s_rtd_refresh_task != NULL) {
        return;
    }

    printf("%s create task!\n", __FUNCTION__);
    s_rtd_refresh_task = lv_task_create(rtd_refresh_timer_cb,
                                        RTD_REFRESH_PERIOD_MS,
                                        LV_TASK_PRIO_LOW,
                                        NULL);
}

/**
 * @brief 停止自动刷新定时器
 * @note 页面退出时调用，防止内存泄漏
 *       多次调用安全（内部有NULL检查）
 */
static void rtd_stop_auto_refresh(void)
{
    printf("%s stop auto refresh task!\n", __FUNCTION__);
    if (s_rtd_refresh_task != NULL) {
        lv_task_del(s_rtd_refresh_task);
        s_rtd_refresh_task = NULL;
    }
}

/**
 * @brief  处理开出控制设置界面的事件
 * @param  kval 按键值
 * @return float 确认时的设置值，取消时返回-1
 * @date   2026-02-26
 */
static float app_rtd_yk_control_handle_event(keyValue kval)
{
    float value = 0.0f;
    
    switch (kval)
    {
    case KEY_DATA_UP:
        // 向上切换选项（分闸->合闸 或 合闸->分闸）
        ui_manager_comp_opera_set_valist(SPINBOX_SET_UP);
        break;
    case KEY_DATA_DOWN:
        // 向下切换选项
        ui_manager_comp_opera_set_valist(SPINBOX_SET_DOWN);
        break;
    case KEY_DATA_BACK:
    case KEY_DATA_CANCEL:
        // 取消操作，返回-1表示取消
        value = -1.0f;
        break;
    case KEY_DATA_ENTER:
        // 确认操作，获取当前值
        value = ui_manager_comp_get_valist_spinbox_value();
        break;
    default:
        break;
    }
    
    return value;
}

/**
 * @brief  处理组件级别的事件（设置界面、密码输入等）
 * @param  kval 按键值
 * @date   2026-02-26
 */
static void app_rtd_process_components_event(keyValue kval)
{
    UICursorState curstate = ui_manager_get_cursor();
    GeneralListPageConfig_t config = {0};
    float val = 0.0f;
    int pwd_val = 0;
    
    switch (curstate.cursor_pos)
    {
    case CURSOR_INPUT_PWD:  // 密码输入界面
        pwd_val = app_input_pwd_handle_event(kval);

        if (kval == KEY_DATA_ENTER)
        {
            // 处理密码确认
            if (pwd_val == SUPER_PWD || pwd_val == Password_opt[2].value)
            {
                // 密码验证通过
                s_yk_authenticated = true;
                curstate.cursor_pos = CURSOR_RIGHT_DATA;
                curstate.right_data_idx = 0;
                ui_manager_cursor_set_value(curstate);
                rtd_service_get_ui_data(curstate.cursor_pos, curstate.left_menu_idx, 
                                        curstate.right_data_idx, &config, s_yk_authenticated);
                ui_manager_select_list_data(curstate, &config);
            }
            else
            {
                // 密码验证失败
                s_yk_authenticated = false;
                curstate.cursor_pos = CURSOR_LEFT_MENU;
                ui_manager_cursor_set_value(curstate);
                rtd_service_get_ui_data(curstate.cursor_pos, curstate.left_menu_idx, 
                                        curstate.right_data_idx, &config, s_yk_authenticated);
                ui_manager_select_list_data(curstate, &config);
            }
        }
        else if (kval == KEY_DATA_BACK || kval == KEY_DATA_CANCEL)
        {
            // 处理密码输入取消
            s_yk_authenticated = false;
            curstate.cursor_pos = CURSOR_LEFT_MENU;
            ui_manager_cursor_set_value(curstate);
            rtd_service_get_ui_data(curstate.cursor_pos, curstate.left_menu_idx, 
                                    curstate.right_data_idx, &config, s_yk_authenticated);
            ui_manager_select_list_data(curstate, &config);
        }
        break;
        
    case CURSOR_CONTROL_YK:  // 开出控制设置界面
        val = app_rtd_yk_control_handle_event(kval);
        
        if (kval == KEY_DATA_ENTER)
        {
            // 确认修改，执行DO遥控操作
            printf("%s 开出控制确认，值=%f\r\n", __FUNCTION__, val);
            rtd_service_set_yk_control_value(val);
            
            // 执行实际的DO遥控操作
            // 获取当前选中的DO索引
            uint8_t do_index = curstate.right_data_idx;
            DoCtrlType ctrl_type = (val == 1.0f) ? DO_CTRL_ON : DO_CTRL_OFF;
            
            printf("%s 执行DO遥控: do_index=%d, type=%s\r\n", 
                   __FUNCTION__, do_index, (ctrl_type == DO_CTRL_ON) ? "合闸" : "分闸");
            
            // 调用service层的DO遥控接口
            DoCtrlRet ret = rtd_service_do_control(do_index, ctrl_type);
            
            // 根据结果显示操作状态
            switch (ret)
            {
            case DO_CTRL_RET_OK:
                printf("%s DO遥控操作成功\r\n", __FUNCTION__);
                break;
            case DO_CTRL_RET_PARAM_ERR:
                printf("%s DO遥控操作失败: 参数错误\r\n", __FUNCTION__);
                break;
            case DO_CTRL_RET_BS_ERR:
                printf("%s DO遥控操作失败: 气压低闭锁\r\n", __FUNCTION__);
                break;
            case DO_CTRL_RET_CFG_ERR:
                printf("%s DO遥控操作失败: 通道未配置\r\n", __FUNCTION__);
                break;
            default:
                printf("%s DO遥控操作失败: 未知错误\r\n", __FUNCTION__);
                break;
            }
            
            // 返回数据列表界面
            curstate.cursor_pos = CURSOR_RIGHT_DATA;
            ui_manager_cursor_set_value(curstate);
            rtd_service_get_ui_data(curstate.cursor_pos, curstate.left_menu_idx, 
                                    curstate.right_data_idx, &config, s_yk_authenticated);
            ui_manager_select_list_data(curstate, &config);
        }
        else if (kval == KEY_DATA_BACK || kval == KEY_DATA_CANCEL)
        {
            // 取消修改，返回数据列表界面
            printf("%s 开出控制取消\r\n", __FUNCTION__);
            curstate.cursor_pos = CURSOR_RIGHT_DATA;
            ui_manager_cursor_set_value(curstate);
            rtd_service_get_ui_data(curstate.cursor_pos, curstate.left_menu_idx, 
                                    curstate.right_data_idx, &config, s_yk_authenticated);
            ui_manager_select_list_data(curstate, &config);
        }
        break;
        
    default:
        break;
    }
}

/**
 * @brief  计算光标值
 * @param  curstate         光标数据
 * @param  kval             按键值
 * @return u8 
 * @date 2026-01-12
 */
u8 app_rtd_cal_right_sel_idx(UICursorState curstate , keyValue kval)
{
    
    u8 manu_len=0;
    u8 cur_idx = curstate.right_data_idx; // 获取当前下标
    switch (curstate.left_menu_idx)      //通过左侧选项判断使用哪个数组显示数据
    {
    case SUB_RTD_YX: // 设备参数
        manu_len = SUBMENU_TELESIGMAL_NUM;  
        break;
    case SUB_RTD_OYC:
    case SUB_RTD_SYC:
        manu_len = SUBMENU_TELEMET_NUM;
        break;
    case SUB_RTD_YK:  // 遥控
        manu_len = g_equ_config->do_num;
        if (manu_len > SUBMENU_REMOTCRTL_NUM)
            manu_len = SUBMENU_REMOTCRTL_NUM;
        break;
    default:
        break;
    }

    if (curstate.left_menu_idx == SUB_RTD_YK)   // 遥控界面需要特殊处理
    {
        switch (kval)
        {
        case KEY_DATA_LEFT:
            if (cur_idx > 7)
                cur_idx = 8 * (cur_idx / 8) - 8;
            else
                cur_idx = 8 * ((manu_len - 1) / 8);
            break;
        case KEY_DATA_UP:
            if (cur_idx > 0)
                cur_idx--;
            else
                cur_idx = manu_len - 1;
            break;
        case KEY_DATA_RIGHT:
            if (cur_idx < (manu_len - manu_len % 8))
                cur_idx = 8 * (cur_idx / 8) + 8;
            else
                cur_idx = 0;
        case KEY_DATA_DOWN:
            cur_idx++;
            if (cur_idx > manu_len - 1)
                cur_idx = 0;

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

    return cur_idx;
}

/**
 * @brief  实时数据页面处理按键事件
 * @param  kval             按键值
 * @date 2026-01-12
 */
void app_real_time_data_handle_event(keyValue kval)
{
    UICursorState curstate = ui_manager_get_cursor();
    PageCtx dev_info_ctx = {0};
    GeneralListPageConfig_t config = {0};

    // 处理组件级别事件（密码输入、设置界面等）
    // CURSOR_INPUT_PWD(2), CURSOR_CHANGE_VAL(3), CURSOR_CONFIRM_SAVE(4), CURSOR_CONTROL_YK(5)
    if (curstate.cursor_pos > CURSOR_RIGHT_DATA)
    {
        app_rtd_process_components_event(kval);
        return;
    }

    switch (kval)
    {
    case KEY_DATA_BACK:
        if (curstate.cursor_pos == CURSOR_LEFT_MENU)
        {
            /* 停止自动刷新定时器 - 页面退出时必须停止以防止内存泄漏 */
            rtd_stop_auto_refresh();
            ui_manager_switch_to_main_menu(MAIN_MENU_REAL_TIME_DATA); //回去菜单页
        }
        else if (curstate.cursor_pos == CURSOR_RIGHT_DATA)
        {
            curstate.cursor_pos = CURSOR_LEFT_MENU; //光标回左边
            curstate.right_data_idx = 0;            //下标值清空
            // 处理遥控界面特殊情况
            if (curstate.left_menu_idx == SUB_RTD_YK)
            {
                s_yk_authenticated = false;
            }
            rtd_service_get_ui_data(curstate.cursor_pos , curstate.left_menu_idx , curstate.right_data_idx, &config, s_yk_authenticated);
            ui_manager_select_list_data(curstate , &config);
        }
        break;
    case KEY_DATA_ENTER:
        if (curstate.cursor_pos == CURSOR_LEFT_MENU)
        {
            // 按确定进去数据区
            if (curstate.left_menu_idx == SUB_RTD_YK)
            {
                // 进入密码输入状态
                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;
                rtd_service_get_ui_data(curstate.cursor_pos, curstate.left_menu_idx, curstate.right_data_idx, &config, s_yk_authenticated);
                ui_manager_select_list_data(curstate, &config);
            }
        }
        else if(curstate.cursor_pos == CURSOR_RIGHT_DATA)
        {
            // 遥控界面（开出控制）- 弹出设置界面
            if (curstate.left_menu_idx == SUB_RTD_YK && s_yk_authenticated)
            {
                // printf("%s 进入开出控制设置界面，选中项=%d\r\n", __FUNCTION__, curstate.right_data_idx);
                
                // 切换到开出控制设置状态
                curstate.cursor_pos = CURSOR_CONTROL_YK;
                ui_manager_cursor_set_value(curstate);
                
                // 创建设置界面，传入开出控制的UiSetValueOptDef
                UiSetValueOptDef* yk_opt = rtd_service_get_yk_set_opt();
                ui_manager_comp_create_set_valist(yk_opt);
            }
        }
        break;
    case KEY_DATA_DOWN:
    case KEY_DATA_RIGHT:
        //计算下标
        if (curstate.cursor_pos == CURSOR_LEFT_MENU)
        {

            curstate.left_menu_idx++;
            if (curstate.left_menu_idx > MENU_RealTimeData_NUM - 1)
                curstate.left_menu_idx = 0;
            // 处理遥控界面特殊情况
            s_yk_authenticated = false;
        }
        else if (curstate.cursor_pos == CURSOR_RIGHT_DATA)
        {

            curstate.right_data_idx = app_rtd_cal_right_sel_idx(curstate , kval);

        }
        rtd_service_get_ui_data(curstate.cursor_pos , curstate.left_menu_idx , curstate.right_data_idx, &config, s_yk_authenticated);
        ui_manager_select_list_data(curstate , &config);
        break;
    case KEY_DATA_UP:
    case KEY_DATA_LEFT:
        //计算下标
        if (curstate.cursor_pos == CURSOR_LEFT_MENU)
        {

            if (curstate.left_menu_idx > 0)
                curstate.left_menu_idx--;
            else
                curstate.left_menu_idx = MENU_RealTimeData_NUM - 1;
        }
        else if (curstate.cursor_pos == CURSOR_RIGHT_DATA)
        {
            curstate.right_data_idx = app_rtd_cal_right_sel_idx(curstate , kval);
        }

        rtd_service_get_ui_data(curstate.cursor_pos , curstate.left_menu_idx , curstate.right_data_idx, &config, s_yk_authenticated);
        ui_manager_select_list_data(curstate , &config);

        break;
    default:
        break;
    }
}



void app_rtd_create_list_data(PageCtx *ctx , u8 manu_sel_idx , u8 item_sel_idex)
{
    GeneralListPageConfig_t config = {0};

    rtd_service_get_ui_data(ctx->cursor_state.cursor_pos, 0, 0, &config, false);

    ui_manager_gerneral_list(ctx , &config);

    /* 启动自动刷新定时器 - 页面创建时启动 */
    rtd_start_auto_refresh();
}