import 'package:domain/repository/labour_sg_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_edit_state.dart';

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

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

    LoadingEngine.dismiss();

    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'];

      int genderOptionType = 0; //使用哪一种类型限制
      if (state.editDetailEntity?.labReq?.sexLimit == 1) {
        state.genderOptionType = 1;
        needMallController.text = state.editDetailEntity?.labReq?.maleLimit?.toString();
        needFemaleController.text = state.editDetailEntity?.labReq?.femaleLimit?.toString();
        needNumController.text = '';
      } else {
        state.genderOptionType = 0;
        needMallController.text = '';
        needFemaleController.text = '';
        needNumController.text = state.editDetailEntity?.labReq?.hiringNum?.toString();
      }

      remarkController.text = state.editDetailEntity?.labReq?.description ?? '';

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

      state.selectedOutlet = state.editDetailEntity?.labReq?.outletName;
      state.selectedOutletId = state.editDetailEntity?.labReq?.outletId?.toString();

      state.selectRequestTypeId = state.editDetailEntity?.labReq?.requestType?.toString();
      state.selectPositionId = state.editDetailEntity?.labReq?.positionId?.toString();
      state.selectPositionName = state.editDetailEntity?.labReq?.positionName?.toString();

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

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

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

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

  // 选择结束时间
  void pickEndTime() {
    if (state.editDetailEntity == 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.editDetailEntity == null) {
      return;
    }

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

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

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

  // 提交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'];

    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;
      }
    }

    if (state.selectRequestTypeId == "1") {
      if (Utils.isEmpty(state.selectPositionId)) {
        ToastEngine.show("Select Position".tr);
        return;
      }
    }

    HttpResult result;
    if (state.pageType == 1) {
      result = await _labourRepository.editLabourRequestSubmit(
        requestId: state.requestId,
        startTime: DateTimeUtils.formatDate(state.selectedStartTime),
        endTime: DateTimeUtils.formatDate(state.selectedEndTime),
        outletId: state.selectedOutletId,
        sexLimit: state.genderOptionType,
        maleLimit: maleNo,
        femaleLimit: femaleNo,
        needNum: needNo,
        requestType: state.selectRequestTypeId,
        positionId: state.selectPositionId,
        remark: remark,
        cancelToken: cancelToken,
      );
    } else {
      // state.pageType == 3 这是 LabourRequestReview 的编辑提交
      result = await _labourRepository.editLabourRequestReviewSubmit(
        requestId: state.requestId,
        startTime: DateTimeUtils.formatDate(state.selectedStartTime),
        endTime: DateTimeUtils.formatDate(state.selectedEndTime),
        outletId: state.selectedOutletId,
        sexLimit: state.genderOptionType,
        maleLimit: maleNo,
        femaleLimit: femaleNo,
        needNum: needNo,
        requestType: state.selectRequestTypeId,
        positionId: state.selectPositionId,
        remark: remark,
        cancelToken: cancelToken,
      );
    }

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

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

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

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

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

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

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

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