import 'package:domain/entity/response/index_option_entity.dart';
import 'package:domain/entity/response/job_template_edit_index_entity.dart';
import 'package:domain/repository/labour_sg_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/log_utils.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/picker/option_pick_util.dart';

import 'job_template_add_state.dart';

class JobTemplateAddController extends GetxController with DioCancelableMixin {
  final LabourSGRepository _labourRepository = Get.find();
  final JobTemplateAddState state = JobTemplateAddState();

  // 获取添加或者编辑的详情
  void _fetchAddEditIndexDetail() async {
    //获取到数据
    Future<HttpResult<JobTemplateEditIndexEntity>> taskFuture;
    if (Utils.isNotEmpty(state.templateId) && state.templateId != "0") {
      //编辑
      taskFuture = _labourRepository.fetchJobTemplateEditIndex(state.templateId, cancelToken: cancelToken);
    } else {
      //新增
      taskFuture = _labourRepository.fetchJobTemplateAddIndex(cancelToken: cancelToken);
    }

    var result = await taskFuture;

    //处理数据
    if (result.isSuccess) {
      state.indexEntity = result.data;

      var templateNameController = state.formData['template_name']!['controller'];
      var descController = state.formData['desc']!['controller'];
      var contactController = state.formData['contact']!['controller'];
      var contactNoController = state.formData['contact_no']!['controller'];
      var noteController = state.formData['note']!['controller'];
      templateNameController.text = state.indexEntity?.name ?? "";
      descController.text = state.indexEntity?.description ?? "";
      contactController.text = state.indexEntity?.contact ?? "";
      contactNoController.text = state.indexEntity?.contactNo ?? "";
      noteController.text = state.indexEntity?.note ?? "";

      //默认赋值
      state.selectedAgeList = state.indexEntity?.ageList.where((e) => e.checked == "checked").map((e) => e.value!).toList() ?? [];
      Log.d("当前选中的年龄1：${state.selectedAgeList}");
      state.selectedLanguageList = state.indexEntity?.languageList.where((e) => e.checked == "checked").map((e) => e.value!).toList() ?? [];
      Log.d("当前选中的语言1：${state.selectedLanguageList}");
      state.foodCert = state.indexEntity?.withFoodCert.toString();
      // state.gender = state.indexEntity?.sexList.firstWhere((e) => e.checked == "checked").value;

      state.positionList = state.indexEntity?.positionList ?? [];
      state.positionId = state.indexEntity?.positionList.firstWhere((e) => e.selected == "selected", orElse: () => IndexOptionEntity()).value ?? "";
      state.positionName = state.indexEntity?.positionList.firstWhere((e) => e.selected == "selected", orElse: () => IndexOptionEntity()).txt ?? "";

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

  /// 提交
  void doSubmit() async {
    var templateNameController = state.formData['template_name']!['controller'];
    var descController = state.formData['desc']!['controller'];
    var contactController = state.formData['contact']!['controller'];
    var contactNoController = state.formData['contact_no']!['controller'];
    var noteController = state.formData['note']!['controller'];

    String templateName = templateNameController.text.toString();
    String desc = descController.text.toString();
    String contact = contactController.text.toString();
    String contactNo = contactNoController.text.toString();
    String note = noteController.text.toString();

    //只校验模版的名称
    if (Utils.isEmpty(templateName)) {
      ToastEngine.show("Enter Job Template Name".tr);
      return;
    }

    if (Utils.isEmpty(state.positionId)) {
      ToastEngine.show("Choose Position".tr);
      return;
    }

    Future<HttpResult> taskFuture;
    if (Utils.isNotEmpty(state.templateId) && state.templateId != "0") {
      taskFuture = _labourRepository.editJobTemplateSubmit(
        state.templateId,
        templateName,
        state.positionId,
        contact,
        contactNo,
        desc,
        note,
        state.selectedAgeList.join(","),
        state.gender,
        state.foodCert,
        state.selectedLanguageList.join(","),
        cancelToken: cancelToken,
      );
    } else {
      taskFuture = _labourRepository.addJobTemplateSubmit(
        templateName,
        state.positionId,
        contact,
        contactNo,
        desc,
        note,
        state.selectedAgeList.join(","),
        state.gender,
        state.foodCert,
        state.selectedLanguageList.join(","),
        cancelToken: cancelToken,
      );
    }

    var result = await taskFuture;

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

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

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

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

  // 选择职位
  void pickPosition() {
    int selectedIndex;
    if (state.positionId == null) {
      selectedIndex = 0;
    } else {
      selectedIndex = state.positionList.indexWhere((department) => department.value.toString() == state.positionId);
    }

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

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.positionList.map((e) => e.txt!).toList(growable: false),
      initialSelectIndex: selectedIndex,
      onPickerChanged: (_, index) {
        state.positionName = state.positionList[index].txt;
        state.positionId = state.positionList[index].value;
        update();
      },
    );
  }
}
