import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../../common/api/index.dart';
import '../../../common/models/index.dart';
import '../../../common/services/index.dart';
import '../../../common/utils/index.dart';
import '../../../common/values/o2.dart';
import '../../apps/cms/cms_document/index.dart';
import '../../common/process_webview/index.dart';
import 'index.dart';

class SearchController extends GetxController {
  SearchController();

  final state = SearchState();


  // 登录用户名的控制器
  final TextEditingController searchController = TextEditingController();
  final FocusNode searchNode = FocusNode();

  final refreshController = RefreshController();
  int page = 1; // 分页查询
  bool isLoading = false; // 防止重复刷新

  

  /// 在 widget 内存中分配后立即调用。
  @override
  void onInit() {
    super.onInit();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    state.historyList.clear();
    state.historyList.addAll(SharedPreferenceService.to.getList(SharedPreferenceService.searchHistoryKey));
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
  }

  /// dispose 释放内存
  @override
  void dispose() {
    super.dispose();
  }

  /// 清除历史
  void cleanHistory() {
    state.historyList.clear();
    saveHistory();
  }
  /// 搜索
  void onSearch(String key) {
    OLogger.d("搜索关键字：$key");
    searchController.text = key;
    state.searchKey = key;
    if (key.isNotEmpty && !state.historyList.contains(key)) {
      state.historyList.add(key);
      saveHistory();
    }
    // 请求后台搜索
    if (key.isNotEmpty) {
      refreshSearchList();
    }
  }

  refreshSearchList() async {
    if (isLoading) return;
    page = 1;
    isLoading = true;
    state.resultList.clear();
    final form = O2SearchV2Form(page: page, query: state.searchKey, size: O2.o2DefaultPageSize);
    final result = await QueryAssembleSurfaceService.to.searchV2(form);
    if (result != null ) {
      state.resultList.addAll(result.documentList ?? []);
    }
    refreshController.refreshCompleted();
    state.hasMoreData = (result?.documentList?.length ?? 0) == O2.o2DefaultPageSize;
    isLoading = false;
  }
  loadMoreSearchList() async {
    if (isLoading) return;
    if (!state.hasMoreData) {
      refreshController.loadComplete();
      return;
    }
    isLoading = true;
    page++;
    final form = O2SearchV2Form(page: page, query: state.searchKey, size: O2.o2DefaultPageSize);
    final result = await QueryAssembleSurfaceService.to.searchV2(form);
    if (result != null) {
      state.resultList.addAll(result.documentList ?? []);
    }
    refreshController.loadComplete();
    state.hasMoreData = (result?.documentList?.length ?? 0) == O2.o2DefaultPageSize;
    isLoading = false;
  }

  tapEntry(O2SearchV2Entry entry) {
    if (entry.category == 'cms') {
      CmsDocumentPage.open(entry.id!, title: entry.title??'');
    } else {
      // 这个 job id
      ProcessWebviewPage.openJob(entry.id ?? '');
    }
  }

  /// 持久化 history
  saveHistory() async {
    await SharedPreferenceService.to.putList(SharedPreferenceService.searchHistoryKey, state.historyList.toList());
  }
}
