import 'package:domain/entity/response/device_list_entity.dart';
import 'package:domain/entity/response/s_g_dashboard_entity.dart';
import 'package:domain/repository/job_sg_repository.dart';
import 'package:get/get.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import 'dashboard_state.dart';

class DashboardController extends GetxController with DioCancelableMixin {
  final JobSGRepository _jobRepository = Get.find();
  final DashboardState state = DashboardState();

  var _needShowPlaceholder = true;

  //页面PlaceHolder的展示
  LoadState loadingState = LoadState.State_Success;
  String? errorMessage;

  //刷新页面状态
  void changeLoadingState(LoadState state) {
    loadingState = state;
    update();
  }

  // Refresh 控制器
  final EasyRefreshController refreshController = EasyRefreshController(
    controlFinishRefresh: true,
    controlFinishLoad: false,
  );

  // Refresh 刷新事件
  Future onRefresh() async {
    fetchList();
  }

  // 重试请求
  Future retryRequest() async {
    _needShowPlaceholder = true;
    fetchList();
  }

  /// 获取服务器数据，通知消息列表
  Future fetchList() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading);
    }

    // 获取 Applied 列表
    var listResult = await _jobRepository.fetchDashboardList(
      cancelToken: cancelToken,
    );

    // 处理数据
    if (listResult.isSuccess) {
      handleList(listResult.data?.agencyList);
    } else {
      errorMessage = listResult.errorMsg;
      changeLoadingState(LoadState.State_Error);
    }

    // 最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void handleList(List<SGDashboardAgencyList>? list) {
    if (list != null && list.isNotEmpty) {
      //有数据
      state.datas.clear();
      state.datas.addAll(list);
      refreshController.finishRefresh();
      //更新展示的状态
      changeLoadingState(LoadState.State_Success);
    } else {
      //展示无数据的布局
      state.datas.clear();
      changeLoadingState(LoadState.State_Empty);
      refreshController.finishRefresh();
    }
  }

  @override
  void onReady() {
    super.onReady();
    fetchList();
  }

  @override
  void onClose() {
    state.datas.clear();
    super.onClose();
  }
}
