import 'package:domain/entity/response/t_h_o_a_attachment_entity.dart';
import 'package:domain/repository/th_oa_repository.dart';
import 'package:plugin_basic/basic_export.dart';
import 'package:plugin_platform/engine/dialog/dialog_engine.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';
import 'package:file_picker/file_picker.dart';

class OaAttachListController extends GetxController with DioCancelableMixin {
  final THOARepository _thRepository = Get.find();

  String? requestId;
  List<THOAAttachmentRows> datas = [];
  var _curPage = 1;
  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: true,
  );

  // Refresh 刷新事件
  Future onRefresh() async {
    _curPage = 1;
    fetchAllStaffList();
  }

  // Refresh 加载事件
  Future loadMore() async {
    _curPage++;
    fetchAllStaffList();
  }

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

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

    // 获取 Staff 列表
    var listResult = await _thRepository.fetchAttachmentTable(
      requestId: requestId,
      curPage: _curPage,
      cancelToken: cancelToken,
    );

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

    // 最后赋值
    _needShowPlaceholder = false;
  }

  // 处理数据与展示的逻辑
  void handleList(List<THOAAttachmentRows>? list) {
    if (list != null && list.isNotEmpty) {
      //有数据，判断是刷新还是加载更多的数据
      if (_curPage == 1) {
        //刷新的方式
        datas.clear();
        datas.addAll(list);
        refreshController.finishRefresh();

        //更新展示的状态
        changeLoadingState(LoadState.State_Success);
      } else {
        //加载更多
        datas.addAll(list);
        refreshController.finishLoad();
        update();
      }
    } else {
      if (_curPage == 1) {
        //展示无数据的布局
        datas.clear();
        changeLoadingState(LoadState.State_Empty);
        refreshController.finishRefresh();
      } else {
        //展示加载完成，没有更多数据了
        refreshController.finishLoad(IndicatorResult.noMore);
      }
    }
  }

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

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

  void pickAttFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      allowMultiple: false,
      type: FileType.custom,
      allowedExtensions: ['jpg', 'png', 'jpeg', 'pdf', 'docx'],
    );

    if (result != null) {
      PlatformFile file = result.files.first;
      Log.d("path:${file.path} name:${file.name}");

      final fileResult = await _thRepository.uploadFile(file.path);

      if (fileResult.isSuccess) {
        String? filePath = fileResult.data?.path;

        _requestAddAttachment(filePath);
      } else {
        ToastEngine.show(fileResult.errorMsg ?? "Network Load Error".tr);
      }
    }
  }

  //调用接口添加附件，成功之后刷新列表
  void _requestAddAttachment(String? filePath) async {
    final result = await _thRepository.addAttachmentSubmit(requestId: requestId, attUrl: filePath);

    if (result.isSuccess) {
      refreshController.callRefresh();
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

  //执行删除操作
  void doDeleteAction(String attachmentId, int index) {
    DialogEngine.show(
        widget: AppDefaultDialog(
          title: "Confirmation".tr,
          message: "Are you sure you want to delete this attachment?".tr,
          confirmAction: () {
            _requestDeactivate(attachmentId, index);
          },
        ));
  }

  // 请求接口删除Job
  void _requestDeactivate(String attachmentId, int index) async {
    var result = await _thRepository.deleteAttachmentSubmit(attId: attachmentId, cancelToken: cancelToken);

    if (result.isSuccess) {
      NotifyEngine.showSuccess("Successful".tr);

      if (datas.length <= 1) {
        refreshController.callRefresh();
      } else {
        datas.removeAt(index);
        update();
      }
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }


}
