import 'package:domain/entity/response/labour_request_edit_index_entity.dart';
import 'package:domain/repository/labour_repository.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:plugin_basic/constants/app_constant.dart';
import 'package:plugin_platform/engine/notify/notify_engine.dart';
import 'package:plugin_platform/engine/toast/toast_engine.dart';
import 'package:plugin_platform/http/http_result.dart';
import 'package:shared/utils/date_time_utils.dart';
import 'package:shared/utils/event_bus.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_add_state.dart';

class LabourRequestAddController extends GetxController {
  final LabourRepository _labourRepository = Get.find();
  final LabourRequestAddState state = LabourRequestAddState();

  /// 获取首页的数据
  void fetchRequestDetail() async {
    //获取到数据
    Future<HttpResult<LabourRequestEditIndexEntity>> taskFuture;
    if (state.pageType != 0 && Utils.isNotEmpty(state.appliedId) && state.appliedId != "0") {
      taskFuture = _labourRepository.fetchLabourRequestEditDetail(state.appliedId);
    } else {
      taskFuture = _labourRepository.fetchLabourRequestAddOption();
    }

    var result = await taskFuture;

    //处理数据
    if (result.isSuccess) {
      state.labReqOption = result.data;
      state.selectedStartTime = state.labReqOption?.jobStart == null ? null : DateTimeUtils.getDateTime(state.labReqOption!.jobStart!);
      state.selectedEndTime = state.labReqOption?.jobEnd == null ? null : DateTimeUtils.getDateTime(state.labReqOption!.jobEnd!);
      state.noStaff = state.labReqOption?.needNum.toString() == "0" ? "" : state.labReqOption?.needNum.toString();
      var needNumController = state.formData['no_of_staff']!['controller'];
      needNumController.text = state.noStaff;
      var amountController = state.formData['amount']!['controller'];
      amountController.text = state.labReqOption?.amount ?? "";
      state.selectedTemplateId = state.labReqOption?.templateId;
      state.selectedDepartmentId = state.labReqOption?.departmentId;

      state.chargeOptionId = state.labReqOption?.chargeList.firstWhere((element) => element.checked == "checked").value;

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

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

  /// 提交
  void doSubmit() async {
    var needNumController = state.formData['no_of_staff']!['controller'];
    var amountController = state.formData['amount']!['controller'];
    String needNum = needNumController.text.toString();
    String amount = amountController.text.toString();

    if (Utils.isEmpty(state.selectedTemplateId)) {
      ToastEngine.show("Choose Job Title".tr);
      return;
    } else if (state.selectedStartTime == null) {
      ToastEngine.show("Choose Start Date".tr);
      return;
    } else if (state.selectedEndTime == null) {
      ToastEngine.show("Choose End Date".tr);
      return;
    } else if (Utils.isEmpty(state.selectedDepartmentId)) {
      ToastEngine.show("Choose Outlet".tr);
      return;
    } else if (Utils.isEmpty(needNum)) {
      ToastEngine.show("Enter No. of Staff".tr);
      return;
    } else if (state.labReqOption?.serviceType == 1 && Utils.isEmpty(amount)) {
      ToastEngine.show("Enter Amount".tr);
      return;
    }

    Future<HttpResult> taskFuture;
    if (state.pageType != 0 && Utils.isNotEmpty(state.appliedId) && state.appliedId != "0") {
      taskFuture = _labourRepository.editLabourRequestSubmit(
        state.appliedId,
        state.selectedTemplateId,
        DateTimeUtils.formatDate(state.selectedStartTime),
        DateTimeUtils.formatDate(state.selectedEndTime),
        state.selectedDepartmentId,
        needNum,
        state.chargeOptionId,
        state.labReqOption?.serviceType == 1 ? amount : null,
      );
    } else {
      taskFuture = _labourRepository.addLabourRequestSubmit(
        state.selectedTemplateId,
        DateTimeUtils.formatDate(state.selectedStartTime),
        DateTimeUtils.formatDate(state.selectedEndTime),
        state.selectedDepartmentId,
        needNum,
        state.chargeOptionId,
        state.labReqOption?.serviceType == 1 ? amount : null,
      );
    }

    var result = await taskFuture;

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

      //根据类型刷新

      if (state.pageType != 0 && Utils.isNotEmpty(state.appliedId) && state.appliedId != "0") {
        //编辑就发送指定的 requestId
        bus.emit(AppConstant.eventLabourRequestRefresh, state.appliedId);
      } else {
        //新增的就发送空
        bus.emit(AppConstant.eventLabourRequestRefresh, "");
      }

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

  // 筛选工作模板
  void pickJobTitle() {
    if (state.labReqOption == null || state.pageType == 2) {
      return;
    }

    int selectedTemplateIndex;
    if (state.selectedTemplateId == null) {
      selectedTemplateIndex = 0;
    } else {
      selectedTemplateIndex = state.labReqOption!.templateList.indexWhere((department) => department.value.toString() == state.selectedTemplateId);
    }

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

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.labReqOption!.templateList.map((e) => e.txt!).toList(growable: false),
      initialSelectIndex: selectedTemplateIndex,
      onPickerChanged: (_, index) {
        state.selectedTemplateId = state.labReqOption!.templateList[index].value!.toString();
        update();
      },
    );
  }

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

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

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

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

  // 筛选部门
  void pickDepartment() {
    if (state.labReqOption == null || state.pageType == 2) {
      return;
    }

    int selectedDepartmentIndex;
    if (state.selectedDepartmentId == null) {
      selectedDepartmentIndex = 0;
    } else {
      selectedDepartmentIndex = state.labReqOption!.departmentList.indexWhere((department) => department.value.toString() == state.selectedDepartmentId);
    }

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

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.labReqOption!.departmentList.map((e) => e.txt!).toList(growable: false),
      initialSelectIndex: selectedDepartmentIndex,
      onPickerChanged: (_, index) {
        state.selectedDepartmentId = state.labReqOption!.departmentList[index].value!.toString();
        update();
      },
    );
  }
}
