import 'package:domain/entity/response/job_template_edit_index_entity.dart';
import 'package:domain/repository/labour_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 'labour_template_add_state.dart';

class LabourTemplateAddController extends GetxController with DioCancelableMixin {
  final LabourRepository _labourRepository = Get.find();
  final LabourTemplateAddState state = LabourTemplateAddState();

  // 获取添加或者编辑的详情
  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 noteController = state.formData['note']!['controller'];
      templateNameController.text = state.indexEntity?.jobTitle ?? "";
      descController.text = state.indexEntity?.description ?? "";
      noteController.text = state.indexEntity?.note ?? "";

      //默认赋值
      state.optionLanguageList = state.indexEntity?.languageList.map((e) => e.txt!).toList() ?? [];
      Log.d("当前语言的选项为：${state.optionLanguageList}");

      state.selectedAgeList = state.indexEntity?.ageList.where((e) => e.checked == "checked").map((e) => e.value!).toList() ?? [];
      Log.d("当前选中的年龄：${state.selectedAgeList}");
      state.selectedLanguageList = state.indexEntity?.languageList.where((e) => e.checked == "checked").map((e) => e.value!).toList() ?? [];
      Log.d("当前选中的语言：${state.selectedLanguageList}");

      if (state.indexEntity?.sexList != null) {
        state.gender = state.indexEntity!.sexList.firstWhere((e) => e.checked == "checked", orElse: () => JobTemplateEditIndexSexList(),).value;
      } else {
        state.gender = null;
      }
      Log.d("当前选中的性别：${state.gender}");

      //刷新
      update(["language","all"]);

    } 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 noteController = state.formData['note']!['controller'];

    String templateName = templateNameController.text.toString();
    String desc = descController.text.toString();
    String note = noteController.text.toString();

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

    Future<HttpResult> taskFuture;
    if (Utils.isNotEmpty(state.templateId) && state.templateId != "0") {
      taskFuture = _labourRepository.editLabourTemplateSubmit(
        state.templateId,
        templateName,
        desc,
        note,
        state.selectedAgeList.join(","),
        state.gender,
        state.selectedLanguageList.join(","),
        cancelToken: cancelToken,
      );
    } else {
      taskFuture = _labourRepository.addLabourTemplateSubmit(
        templateName,
        desc,
        note,
        state.selectedAgeList.join(","),
        state.gender,
        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();
  }
}
