import 'package:domain/repository/sg_agency_repository.dart';
import 'package:get/get.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:plugin_platform/http/http_result.dart';
import 'package:shared/utils/util.dart';

import 'position_add_state.dart';

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

  // 编辑模式下展示对应的文本
  void _showPositionName() async {

    if (Utils.isNotEmpty(state.positionName)){
      var positionController = state.formData['position']!['controller'];
      positionController.text = state.positionName;
    }

  }

  /// 提交
  void doSubmit() async {

    var positionController = state.formData['position']!['controller'];
    String positionName = positionController.text.toString();

    //校验必填项
    if (Utils.isEmpty(positionName)) {
      ToastEngine.show("Enter Position Name".tr);
      return;
    }

    Future<HttpResult> taskFuture;
    if (Utils.isNotEmpty(state.positionId) && state.positionId != "0") {
      taskFuture = _agencyRepository.editPositionSubmit(
        positionId: state.positionId,
        name: positionName,
        cancelToken: cancelToken,
      );
    } else {
      taskFuture = _agencyRepository.addPositionSubmit(
        name: positionName,
        cancelToken: cancelToken,
      );
    }

    var result = await taskFuture;

    //处理数据
    if (result.isSuccess) {
      NotifyEngine.showSuccess("Successful".tr);

      //根据类型刷新
      state.cb?.call(state.positionId);

      Get.back();
    } else {
      ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
    }
  }

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