import 'package:domain/repository/labour_sg_repository.dart';
import 'package:domain/repository/th_er_repository.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:plugin_platform/engine/loading/loading_engine.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/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 'labour_request_er_add_state.dart';

class LabourRequestERAddController extends GetxController with DioCancelableMixin {
  final THERRepository _erRepository = Get.find();
  final LabourRequestERAddState state = LabourRequestERAddState();

  // 获取添加选项数据
  void fetchLabourRequestEditDetail() async {
    if (Utils.isNotEmpty(state.jobId)) {
      //编辑
      var result = await _erRepository.fetchERJobListDetail(
        jobId: state.jobId!,
        cancelToken: cancelToken,
      );

      if (result.isSuccess) {
        state.editDetailEntity = result.data;
        var needMallController = state.formData['need_male']!['controller'];
        var needFemaleController = state.formData['need_female']!['controller'];
        var needNumController = state.formData['need_no']!['controller'];
        var remarkController = state.formData['remark']!['controller'];
        var eventNameController = state.formData['event_name']!['controller'];
        var eventTypeController = state.formData['event_type']!['controller'];

        if (state.editDetailEntity?.job?.sexLimit == '1') {
          state.genderOptionType = 1;
          needMallController.text = state.editDetailEntity?.job?.maleLimit?.toString();
          needFemaleController.text = state.editDetailEntity?.job?.femaleLimit?.toString();
          needNumController.text = '';
        } else {
          state.genderOptionType = 0;
          needMallController.text = '';
          needFemaleController.text = '';
          needNumController.text = state.editDetailEntity?.job?.hiringNum?.toString();
        }

        state.selectTitleName = state.editDetailEntity?.job?.jobTitle;
        state.selectTitleId = state.editDetailEntity?.job?.jobTitleId;

        state.selectOutletName = state.editDetailEntity?.job?.outletName;
        state.selectOutletId = state.editDetailEntity?.job?.outletId;

        state.selectedStartTime = DateTimeUtils.getDateTime(state.editDetailEntity!.startTime!);
        state.selectedEndTime = DateTimeUtils.getDateTime(state.editDetailEntity!.endTime!);

        remarkController.text = state.editDetailEntity?.job?.description ?? '';
        eventNameController.text = state.editDetailEntity?.job?.eventName ?? '';
        eventTypeController.text = state.editDetailEntity?.job?.eventType ?? '';
      } else {
        ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      }
    } else {
      //新增
      var result = await _erRepository.fetchERLabourRequestAddOption(
        cancelToken: cancelToken,
      );

      if (result.isSuccess) {
        state.editDetailEntity = result.data;
      } else {
        ToastEngine.show(result.errorMsg ?? "Network Load Error".tr);
      }
    }

    update();
  }

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

  //选择开始时间
  void pickStartTime() {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: state.selectedStartTime,
      mode: CupertinoDatePickerMode.dateAndTime,
      onDateTimeChanged: (date) {
        state.selectedStartTime = date;
        update();
      },
      title: "Start Time".tr,
    );
  }

  // 选择结束时间
  void pickEndTime() {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: state.selectedEndTime ?? state.selectedStartTime,
      mode: CupertinoDatePickerMode.dateAndTime,
      onDateTimeChanged: (date) {
        state.selectedEndTime = date;
        update();
      },
      title: "End Time".tr,
    );
  }

  // 提交LabourRequest表单
  void doEditSubmit() 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'];
    var eventNameController = state.formData['event_name']!['controller'];
    var eventTypeController = state.formData['event_type']!['controller'];

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

    if (state.selectTitleId == null) {
      ToastEngine.show("Select Job Title".tr);
      return;
    }

    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.selectOutletId)) {
      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;
      }
    }

    HttpResult result;
    if (state.pageType == 1 && state.jobId != null) {
      //编辑
      result = await _erRepository.editLabourRequestERSubmit(
        jobId: state.jobId!,
        jobTitleId: state.selectTitleId!,
        startTime: DateTimeUtils.formatDate(state.selectedStartTime),
        endTime: DateTimeUtils.formatDate(state.selectedEndTime),
        outletId: state.selectOutletId!,
        sexLimit: state.genderOptionType.toString(),
        maleLimit: maleNo,
        femaleLimit: femaleNo,
        needNum: needNo,
        eventName: eventName,
        eventType: evenType,
        remark: remark,
        cancelToken: cancelToken,
      );
    } else {
      //新增
      result = await _erRepository.addLabourRequestERSubmit(
        jobTitleId: state.selectTitleId!,
        startTime: DateTimeUtils.formatDate(state.selectedStartTime),
        endTime: DateTimeUtils.formatDate(state.selectedEndTime),
        outletId: state.selectOutletId!,
        repeatStart: DateTimeUtils.formatDate(state.selectedRepeatStartTime, format: 'yyyy-MM-dd'),
        repeatEnd: DateTimeUtils.formatDate(state.selectedRepeatEndTime, format: 'yyyy-MM-dd'),
        sexLimit: state.genderOptionType.toString(),
        maleLimit: maleNo,
        femaleLimit: femaleNo,
        needNum: needNo,
        eventName: eventName,
        eventType: evenType,
        remark: 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);
    }
  }

  //选择性别限制类型
  void pickLimitType() {
    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.genderOptions,
      initialSelectIndex: state.genderOptionType,
      onPickerChanged: (_, index) {
        state.genderOptionType = index;
        update();
      },
    );
  }

  // 选择工作模板标题
  void pickJobTitle() {
    if (state.editDetailEntity == null) {
      return;
    }

    int selectedIndex;
    if (state.selectTitleId == null) {
      selectedIndex = 0;
    } else {
      selectedIndex = state.editDetailEntity!.titleList.indexWhere((bean) => bean.value.toString() == state.selectTitleId);
    }

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

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

    OptionPickerUtil.showCupertinoOptionPicker(
      items: list,
      initialSelectIndex: selectedIndex,
      onPickerChanged: (_, index) {
        state.selectTitleId = state.editDetailEntity!.titleList[index].value!.toString();
        state.selectTitleName = state.editDetailEntity!.titleList[index].txt!.toString();
        update();
      },
    );
  }

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

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

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

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

  void pickRepeatStartTime() {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: state.selectedRepeatStartTime,
      mode: CupertinoDatePickerMode.date,
      onDateTimeChanged: (date) {
        state.selectedRepeatStartTime = date;
        update();
      },
      title: "Repeat Start Time".tr,
    );
  }

  void pickRepeatEndTime() {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: state.selectedRepeatEndTime ?? state.selectedRepeatStartTime,
      mode: CupertinoDatePickerMode.date,
      minimumDate: state.selectedRepeatStartTime,
      onDateTimeChanged: (date) {
        state.selectedRepeatEndTime = date;
        update();
      },
      title: "Repeat End Time".tr,
    );
  }
}
