import 'package:cpt_th/modules/job_er/job_list_er/job_list_er_page.dart';
import 'package:cpt_th/modules/labour_er/labour_request_er_add/labour_request_er_add_page.dart';
import 'package:domain/entity/response/labour_request_e_r_entity.dart';
import 'package:domain/repository/th_er_repository.dart';
import 'package:domain/entity/response/labour_request_list_entity.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:shared/utils/date_time_utils.dart';
import 'package:shared/utils/event_bus.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/picker/date_picker_util.dart';
import 'package:widgets/widget_export.dart';
import 'labour_request_list_state.dart';

class LabourRequestListController extends GetxController with DioCancelableMixin {
  final THERRepository _erRepository = Get.find();
  final LabourRequestListState state = LabourRequestListState();

  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 {
    fetchLabourRequestList();
  }

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

  /// 获取列表数据
  Future fetchLabourRequestList() async {
    if (_needShowPlaceholder) {
      changeLoadingState(LoadState.State_Loading);
    }

    final listResult = await _erRepository.fetchERLabourRequest(
      DateTimeUtils.formatDate(state.selectedDate, format: "yyyy-MM-dd"),
      cancelToken: cancelToken,
    );

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

    // 最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void handleList(List<LabourRequestERSourceList>? 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();
    fetchLabourRequestList();

    registerEventBus();
  }

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

  // EventBus 的事件接收
  Subscription? subscribe;

  void registerEventBus() {
    subscribe = bus.on(AppConstant.eventLabourRequestRefresh, (arg) {
        refreshController.callRefresh();
    });
  }

  void unregisterEventBus() {
    bus.off(AppConstant.eventLabourRequestRefresh, subscribe);
  }

  //跳转到添加页面
  void gotoAddLabourPage() {
    LabourRequestERAddPage.startInstance(0, "", (result) {
      //添加成功之后的刷新
      refreshController.callRefresh();
    });
  }

  // 去工作列表的指定日期
  void gotoJobPage(String? date) {
    JobListERPage.startInstance(date, (result) {
      refreshController.callRefresh();
    });
  }

  void showDatePicker() {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: state.selectedDate,
      mode: CupertinoDatePickerMode.date,
      onDateTimeChanged: (date) {
        state.selectedDate = date;
        update();
        refreshController.callRefresh();
      },
      title: "Select Date".tr,
    );
  }
}
