import 'package:cpt_sg/modules/agency/contract_add/contract_add_page.dart';
import 'package:cpt_sg/modules/agency/contract_rate_list/contract_rate_list_page.dart';
import 'package:domain/entity/response/contract_option_entity.dart';
import 'package:domain/entity/response/contract_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/picker/option_pick_util.dart';
import 'package:widgets/widget_export.dart';
import 'contract_list_state.dart';

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

  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 futures = [
      _agencyRepository.fetchContractTable(
        status: state.selectedStatusId,
        agencyId: state.selectedAgencyId,
        curPage: _curPage,
        cancelToken: cancelToken,
      ),
      state.indexOptions == null
          ? _agencyRepository.fetchContractOption(
              cancelToken: cancelToken,
            )
          : Future(() => HttpResult(isSuccess: true).convert(data: state.indexOptions!)),
    ];

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

    //选项数据
    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<ContractTableRows>? 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);
      }
    }
  }

  // 清空搜索条件
  void resetFiltering() {
    state.selectedAgencyId = null;
    state.selectedStatusId = null;

    //赋值之后刷新
    refreshController.callRefresh();
  }

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

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

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

  //跳转到添加页面
  void gotoAddPage() {
    SGContractAddPage.startInstance("", 0, (result) {
      if (result != null) {
        refreshController.callRefresh();
      }
    });
  }

  //去详情页面
  void gotoDetailPage(ContractTableRows data) {
    SGContractRateListPage.startInstance(data.id, (result) {
      if (result != null) {
        fetchItemByIdAndRefreshItem(data.id);
      }
    });
  }

  //去编辑页面
  void gotoEditPage(ContractTableRows data) {
    SGContractAddPage.startInstance(data.id, 1, (result) {
      if (result != null) {
        fetchItemByIdAndRefreshItem(data.id.toString());
      }
    });
  }

  //去Renew页面
  void gotoRenewPage(ContractTableRows data) {
    SGContractAddPage.startInstance(data.id, 2, (result) {
      if (result != null) {
        fetchItemByIdAndRefreshItem(data.id.toString());
      }
    });
  }

  /// 选择状态
  void pickStatus() {
    if (state.indexOptions == null) return;

    int selectedIndex;
    if (state.selectedStatusId == null) {
      selectedIndex = 0;
    } else {
      selectedIndex = state.indexOptions!.statusList.indexWhere((bean) => bean.value.toString() == state.selectedStatusId);
    }

    if (selectedIndex < 0) {
      selectedIndex = 0;
    }

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.indexOptions!.statusList.map((e) => e.txt!.tr).toList(growable: false),
      initialSelectIndex: selectedIndex,
      onPickerChanged: (_, index) {
        state.selectedStatusId = state.indexOptions!.statusList[index].value!.toString();
        state.selectedStatusTxt = state.indexOptions!.statusList[index].txt!.toString();
        update();

        refreshController.callRefresh();
      },
    );
  }

  /// 选择中介
  void pickAgency() {
    if (state.indexOptions == null) return;

    int selectedIndex;
    if (state.selectedAgencyId == null) {
      selectedIndex = 0;
    } else {
      selectedIndex = state.indexOptions!.agencyList.indexWhere((bean) => bean.value.toString() == state.selectedAgencyId);
    }

    if (selectedIndex < 0) {
      selectedIndex = 0;
    }

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.indexOptions!.agencyList.map((e) => e.txt!.tr).toList(growable: false),
      initialSelectIndex: selectedIndex,
      onPickerChanged: (_, index) {
        state.selectedAgencyId = state.indexOptions!.agencyList[index].value!.toString();
        state.selectedAgencyTxt = state.indexOptions!.agencyList[index].txt!.toString();
        update();

        refreshController.callRefresh();
      },
    );
  }
}
