import 'package:domain/entity/response/contract_position_rate_table_entity.dart';
import 'package:domain/repository/sg_agency_repository.dart';
import 'package:get/get.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:widgets/dialog/app_default_dialog.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import '../contract_rate_setting/contract_rate_setting_page.dart';
import '../contract_rate_specific_day/contract_rate_specific_page.dart';
import 'contract_rate_edit_list_state.dart';
import 'dialog/dialog_edit_rate.dart';

class ContractRateEditListController extends GetxController with DioCancelableMixin {
  final SGAgencyRepository _agencyRepository = Get.find();
  final ContractRateEditListState state = ContractRateEditListState();

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

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

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

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

    // 并发执行两个请求

    var listResult = await _agencyRepository.fetchContractPositionRateTable(
      curPage: _curPage,
      contractId: state.contractId,
      positionId: state.positionId,
      cancelToken: cancelToken,
    );

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

    // 最后赋值
    _needShowPlaceholder = false;
  }

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

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

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

  @override
  void onClose() {
    state.cb?.call(state.positionId); //只要是进入当前页面，关闭的时候都刷新上一个页面
    state.datas.clear();
    super.onClose();
  }

  //去详情页面
  void gotoSettingPage() {
    ContractRateSettingPage.startInstance(state.contractId, state.positionId, (result) {
      if (result != null) {
        refreshController.callRefresh();
      }
    });
  }

  //去设置特殊的日期
  void gotoAddSpecificPage() {
    SGContractRateSpecificPage.startInstance(state.contractId, state.positionId, (result) {
      if (result != null) {
        refreshController.callRefresh();
      }
    });
  }

  /// 展示这个日期的编辑弹窗
  void showEditDialog(ContractPositionRateTableRows data) {
    DialogEngine.show(
      widget: EditRateDialog(
        rate: data.amount,
        confirmAction: (rate) {
          _requestAmountModify(data.id, rate);
        },
      ),
    );
  }

  /// 删除的确认弹窗
  void showDeleteDialog(ContractPositionRateTableRows data, int index) {
    DialogEngine.show(
        widget: AppDefaultDialog(
      title: "Confirmation".tr,
      message: "Are you sure you want to delete this Rate?".tr,
      confirmAction: () {
        _submitDeleteRequest(data.id, index);
      },
    ));
  }

  // 执行删除的网络请求
  void _submitDeleteRequest(String? id, int index) async {
    var result = await _agencyRepository.deleteContractPositionRate(rateId: id, cancelToken: cancelToken);

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

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

  // 执行更新金额的请求
  void _requestAmountModify(String? rateId, String? rate) async {
    var result = await _agencyRepository.editContractPositionRateAmountEdit(rateId: rateId, amount: rate, cancelToken: cancelToken);

    if (result.isSuccess) {
      NotifyEngine.showSuccess("Successful".tr);
      fetchItemByIdAndRefreshItem(rateId);
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

  /// 根据ID获取Item对象，用于刷新
  void fetchItemByIdAndRefreshItem(String? id) async {
    var result = await _agencyRepository.fetchContractPositionRateTable(
      curPage: 1,
      contractId: state.contractId,
      positionId: state.positionId,
      rateId: id,
      cancelToken: cancelToken,
    );

    //处理数据
    if (result.isSuccess) {
      var data = result.data;
      if (data != null && data.rows.isNotEmpty) {
        final requestItem = data.rows[0]; //只找第一个

        //找到当前数据中的此 requestId，并替换对象，再刷新
        var index = state.datas.indexWhere((element) => element.id == requestItem.id);
        if (index >= 0) {
          state.datas[index] = requestItem;
          update();
        }
      }
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }
}
