import 'package:domain/entity/response/job_list_edit_index_s_g_entity.dart';
import 'package:domain/repository/labour_sg_repository.dart';
import 'package:flutter/cupertino.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:shared/utils/date_time_utils.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/picker/date_picker_util.dart';
import 'package:widgets/picker/option_pick_util.dart';

import 'job_list_edit_state.dart';

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

  // 获取添加选项数据
  void fetchLabourRequestEditIndex() async {
    var result = await _labourRepository.fetchJobListEditIndex(
      state.jobId,
      cancelToken: cancelToken,
    );

    if (result.isSuccess) {
      state.editEntity = result.data;

      TextEditingController maleNoController = state.formData['need_male']!['controller'];
      TextEditingController femaleNoController = state.formData['need_female']!['controller'];
      TextEditingController needNoController = state.formData['need_no']!['controller'];
      TextEditingController remarkController = state.formData['remark']!['controller'];

      //赋值展示
      state.selectedOutlet = state.editEntity?.outletList.firstWhere((e) => e.selected == "selected", orElse: () => JobListEditIndexOption()).txt;
      state.selectedOutletId = state.editEntity?.outletList.firstWhere((e) => e.selected == "selected", orElse: () => JobListEditIndexOption()).value;
      state.genderOptionType = state.editEntity?.sexLimit ?? 0;
      state.selectRequestTypeId = state.editEntity?.requestType.firstWhere((e) => e.checked == "checked").value;
      state.selectPositionName = state.editEntity?.positionList.firstWhere((e) => e.selected == "selected", orElse: () => JobListEditIndexOption()).txt;
      state.selectPositionId = state.editEntity?.positionList.firstWhere((e) => e.selected == "selected", orElse: () => JobListEditIndexOption()).value;

      Log.d("selectRequestTypeId:${state.selectRequestTypeId}，selectPositionId：${state.selectPositionId}");

      //时间赋值
      state.selectedStartTime = state.editEntity?.startTime == null ? null : DateTimeUtils.getDateTime(state.editEntity?.startTime ?? "");
      state.selectedEndTime = state.editEntity?.endTime == null ? null : DateTimeUtils.getDateTime(state.editEntity?.endTime ?? "");

      state.isOtherFormDisEnable = Utils.isEmpty(state.editEntity?.disabled);

      maleNoController.text = state.editEntity?.maleLimit == 0 ? "" : state.editEntity?.maleLimit.toString() ?? "";
      femaleNoController.text = state.editEntity?.femaleLimit == 0 ? "" : state.editEntity?.femaleLimit.toString() ?? "";
      needNoController.text = state.editEntity?.needNum == 0 ? "" : state.editEntity?.needNum.toString() ?? "";
      remarkController.text = state.editEntity?.remark ?? "";


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

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

  //选择开始时间
  void pickStartTime() {
    if (state.editEntity == null) {
      return;
    }

    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: state.selectedStartTime,
      mode: CupertinoDatePickerMode.dateAndTime,
      onDateTimeChanged: (date) {
        state.selectedStartTime = date;
        update();
      },
      title: "Start Time".tr,
    );
  }

  // 选择结束时间
  void pickEndTime() {
    if (state.editEntity == null) {
      return;
    }

    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: state.selectedEndTime ?? state.selectedStartTime,
      mode: CupertinoDatePickerMode.dateAndTime,
      onDateTimeChanged: (date) {
        state.selectedEndTime = date;
        update();
      },
      title: "End Time".tr,
    );
  }

  //选择部门
  void pickOutlet() {
    if (state.editEntity == null) {
      return;
    }

    int selectedIndex;
    if (state.selectedOutletId == null) {
      selectedIndex = 0;
    } else {
      selectedIndex = state.editEntity!.outletList.indexWhere((department) => department.value.toString() == state.selectedOutletId);
    }

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

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.editEntity!.outletList.map((e) => e.txt!).toList(growable: false),
      initialSelectIndex: selectedIndex,
      onPickerChanged: (_, index) {
        state.selectedOutletId = state.editEntity!.outletList[index].value!.toString();
        state.selectedOutlet = state.editEntity!.outletList[index].txt!.toString();
        update();
      },
    );
  }

  //选择常规职位
  void pickRegularPosition() {
    if (state.editEntity == null) {
      return;
    }

    int selectedIndex;
    if (state.selectPositionId == null) {
      selectedIndex = 0;
    } else {
      selectedIndex = state.editEntity!.positionList.indexWhere((bean) => bean.value.toString() == state.selectPositionId);
    }

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

    List<String> list = [];
    list.addAll(state.editEntity!.positionList.map((e) => e.txt!).toList(growable: false));

    OptionPickerUtil.showCupertinoOptionPicker(
      items: list,
      initialSelectIndex: selectedIndex,
      onPickerChanged: (_, index) {
          state.selectPositionId = state.editEntity!.positionList[index].value!.toString();
          state.selectPositionName = state.editEntity!.positionList[index].txt!.toString();
        update();
      },
    );
  }

  // 提交表单
  void doSubmit() async {
    var maleNoController = state.formData['need_male']!['controller'];
    var femaleNoController = state.formData['need_female']!['controller'];
    var needNoController = state.formData['need_no']!['controller'];
    var remarkController = state.formData['remark']!['controller'];

    String maleNo = maleNoController.text.toString();
    String femaleNo = femaleNoController.text.toString();
    String needNo = needNoController.text.toString();
    String remark = remarkController.text.toString();

    if (state.selectedStartTime == null) {
      ToastEngine.show("Select Job Start Time".tr);
      return;
    }

    if (state.selectedEndTime == null) {
      ToastEngine.show("Select Job End Time".tr);
      return;
    }

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

    if (state.genderOptionType == 0) {
      if (Utils.isEmpty(needNo)) {
        ToastEngine.show("Enter No. of Staff".tr);
        return;
      }
    } else {
      if (Utils.isEmpty(maleNo) || Utils.isEmpty(femaleNo)) {
        ToastEngine.show("Enter No. of Staff of The Corresponding Gender".tr);
        return;
      }
    }

    var result = await _labourRepository.editJobListSubmit(
      state.jobId,
      DateTimeUtils.formatDate(state.selectedStartTime),
      DateTimeUtils.formatDate(state.selectedEndTime),
      state.selectedOutletId,
      state.genderOptionType,
      maleNo,
      femaleNo,
      needNo,
      state.selectRequestTypeId,
      state.selectPositionId,
      remark,
      cancelToken: cancelToken,
    );

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

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

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