shinyServer(function(input, output, session) {
  enc <- getOption("radiant.encoding", "UTF-8")

  ## source shared functions
  source("init.R", encoding = enc, local = TRUE)
  source("radiant.R", encoding = enc, local = TRUE)

  ## packages to use for example data
  options(radiant.example.data = "radiant.data")

  ## source data & analysis tools
  for (file in list.files(c("tools/app", "tools/data"), pattern = "\\.(r|R)$", full.names = TRUE)) {
    source(file, encoding = enc, local = TRUE)
  }

  # ============================================================
  # [新增功能] 企业级集成：Token鉴权 + 环境变量 + 自动加载
  # ============================================================
  observe({
    # 1. 解析 URL 参数
    query <- parseQueryString(session$clientData$url_search)

    dataset_id <- query[['datasetId']]
    token <- query[['token']]

    # 2. 仅当 ID 和 Token 均存在时执行
    if (!is.null(dataset_id) && !is.null(token)) {

      # 定义 Radiant 内部使用的数据集名称 (例如: data_10086)
      # 如果 URL 传了 name 参数就用 name，否则用 id 拼接
      ds_name <- if (!is.null(query[['name']])) query[['name']] else paste0("data_", dataset_id)

      # 3. 检查数据是否已存在 (防止重复加载)
      if (is.null(r_data[[ds_name]])) {

        withProgress(message = '正在从业务系统同步数据...', value = 0.2, {

          # 4. 获取环境变量中的 API 基地址
          api_base <- Sys.getenv("HOST_API_BASE","http://127.0.0.1:11999")

          # 5. 拼接完整 API 路径
          target_url <- paste0(api_base, "/disease-data/data/export/apply/apply/case?applyId=", dataset_id)

          # 6. 创建临时文件 (明确 .xlsx 后缀)
          tmp_file <- tempfile(fileext = ".xlsx")

          tryCatch({
            incProgress(0.3, detail = "正在鉴权并下载...")

            # 7. 发起带 Token 的 HTTP 请求
            response <- httr::POST(
              url = target_url,
              # 添加 Bearer Token (或根据你的接口要求修改 Header)
              httr::add_headers(Authorization = paste("Bearer", token)),
              # 将结果写入磁盘
              httr::write_disk(tmp_file, overwrite = TRUE)
            )

            # 检查 HTTP 状态码
            if (httr::status_code(response) != 200) {
              stop(paste("下载失败，请手动导入，HTTP状态码:", httr::status_code(response)))
            }

            incProgress(0.7, detail = "解析并导入 Radiant...")

            # 8. 复用 Radiant 核心加载函数 (manage_ui.R 中定义)
            # 这会自动完成读取、转因子、生成R代码、注册到下拉框等所有动作
            load_user_data(
              fname = paste0(ds_name, ".xlsx"), # 虚拟文件名
              uFile = tmp_file,                 # 实际文件路径
              ext = "xlsx",
              xlsx_sheet = 1,
              xlsx_header = TRUE,
              man_str_as_factor = TRUE
            )

            # 9. 界面联动：选中数据并跳转到视图
            updateSelectInput(session, "dataset", selected = ds_name)
            updateTabsetPanel(session, "nav_radiant", selected = "Data")
            updateTabsetPanel(session, "tabs_data", selected = "View") # 或者 "Visualize"

            showNotification(paste("数据集", ds_name, "加载成功！"), type = "message")

          }, error = function(e) {
            showNotification(paste("数据同步失败，请手动导入数据:", e$message), type = "error", duration = 10)
            #调试打印 print(e)
          })
        })
      }
    }
  })
  # ============================================================


  # dataviewer_proxy <- DT::dataTableProxy("dataviewer", session)

  # observe(session$setCurrentTheme(
  #   if (isTRUE(input$dark_mode)) {
  #     bslib::bs_theme(version = 4, bg = "black", fg = "white")
  #   } else {
  #     bslib::bs_theme(version = 4)
  #   }
  # ))

  ## save state on refresh or browser close
  saveStateOnRefresh(session)
})
