import 'package:domain/entity/response/contract_position_option_entity.dart';
import 'package:domain/entity/response/contract_position_table_entity.dart';
import 'package:domain/repository/sg_agency_repository.dart';
import 'package:get/get.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/dio/dio_cancelable_mixin.dart';
import 'package:plugin_platform/http/http_result.dart';
import 'package:widgets/load_state_layout.dart';
import 'package:widgets/widget_export.dart';

import '../contract_rate_edit_list/contract_rate_edit_list_page.dart';
import '../contract_rate_setting/contract_rate_setting_page.dart';
import 'contract_rate_list_state.dart';

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

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

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

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

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

    // 并发执行两个请求
    var futures = [
      _agencyRepository.fetchContractPositionTable(
        curPage: _curPage,
        contractId: state.contractId,
        cancelToken: cancelToken,
      ),
      state.indexOptions == null
          ? _agencyRepository.fetchContractPositionOption(
              contractId: state.contractId,
              cancelToken: cancelToken,
            )
          : Future(() => HttpResult(isSuccess: true).convert(data: state.indexOptions!)),
    ];

    //拿到结果
    var results = await Future.wait(futures);
    var listResult = results[0] as HttpResult<ContractPositionTableEntity>;
    var optionResult = results[1] as HttpResult<ContractPositionOptionEntity>;

    //选项数据
    if (state.indexOptions == null && optionResult.isSuccess) {
      state.indexOptions = optionResult.data!;
    }

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

    // 最后赋值
    _needShowPlaceholder = false;
  }

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

  @override
  void onClose() {
    state.cb?.call(state.contractId);
    state.datas.clear();
    super.onClose();
  }

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

  //去编辑页面
  void gotoEditPage(ContractPositionTableRows data) {
    SGContractRateEditListPage.startInstance(state.contractId, data.positionId, (result) {
      if (result != null) {
        fetchItemByIdAndRefreshItem(data.positionId);
      }
    });
  }

  /// 根据ID获取Item对象，用于刷新
  void fetchItemByIdAndRefreshItem(String? id) async {
    var result = await _agencyRepository.fetchContractPositionTable(
      curPage: 1,
      contractId: state.contractId,
      positionId: 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);
    }
  }

}
