import 'package:domain/repository/job_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/dio/dio_cancelable_mixin.dart';
import 'package:shared/utils/date_time_utils.dart';
import 'package:shared/utils/event_bus.dart';
import 'package:widgets/picker/date_picker_util.dart';

import 'job_applied_edit_state.dart';

class JobAppliedEditController extends GetxController with DioCancelableMixin {
  final JobRepository _jobRepository = Get.find();
  final JobAppliedEditState state = JobAppliedEditState();

  // 获取编辑的详情
  void fetchAppliedEditView() async {
    var result = await _jobRepository.fetchAppliedEditView(state.appliedId, cancelToken: cancelToken);

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

      var addHourController = state.formData['add_hours']!['controller'];
      var totalRoomController = state.formData['total_room']!['controller'];
      var reasonController = state.formData['reason']!['controller'];

      addHourController.text = state.appliedEditView?.adjustHours ?? "0";
      totalRoomController.text = state.appliedEditView?.totalRooms.toString();
      reasonController.text = state.appliedEditView?.coReason ?? "";

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

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

  /// 选择时间
  void pickStartTime() {
    if (state.appliedEditView == null) return;

    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: DateTimeUtils.getDateTime(state.appliedEditView!.startTime ?? ""),
      mode: CupertinoDatePickerMode.dateAndTime,
      onDateTimeChanged: (date) {
        state.appliedEditView!.startTime = DateTimeUtils.formatDate(date);
        update();
      },
      title: "Start Time".tr,
    );
  }

  /// 选择时间
  void pickEndTime() {
    if (state.appliedEditView == null) return;

    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: DateTimeUtils.getDateTime(state.appliedEditView!.endTime ?? ""),
      mode: CupertinoDatePickerMode.dateAndTime,
      onDateTimeChanged: (date) {
        state.appliedEditView!.endTime = DateTimeUtils.formatDate(date);
        update();
      },
      title: "End Time".tr,
    );
  }

  /// 选择时间
  void pickSecurityInTime() {
    if (state.appliedEditView == null) return;

    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: DateTimeUtils.getDateTime(state.appliedEditView!.securityIn ?? ""),
      mode: CupertinoDatePickerMode.dateAndTime,
      onDateTimeChanged: (date) {
        state.appliedEditView!.securityIn = DateTimeUtils.formatDate(date);
        update();
      },
      title: "Security In".tr,
    );
  }

  /// 选择时间
  void pickSecurityOutTime() {
    if (state.appliedEditView == null) return;

    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: DateTimeUtils.getDateTime(state.appliedEditView!.securityOut ?? ""),
      mode: CupertinoDatePickerMode.dateAndTime,
      onDateTimeChanged: (date) {
        state.appliedEditView!.securityOut = DateTimeUtils.formatDate(date);
        update();
      },
      title: "Security Out".tr,
    );
  }

  /// 选择时间
  void pickWorkInTime() {
    if (state.appliedEditView == null) return;

    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: DateTimeUtils.getDateTime(state.appliedEditView!.workIn ?? ""),
      mode: CupertinoDatePickerMode.dateAndTime,
      onDateTimeChanged: (date) {
        state.appliedEditView!.workIn = DateTimeUtils.formatDate(date);
        update();
      },
      title: "Work In".tr,
    );
  }

  /// 选择时间
  void pickWorkOutTime() {
    if (state.appliedEditView == null) return;

    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: DateTimeUtils.getDateTime(state.appliedEditView!.workOut ?? ""),
      mode: CupertinoDatePickerMode.dateAndTime,
      onDateTimeChanged: (date) {
        state.appliedEditView!.workOut = DateTimeUtils.formatDate(date);
        update();
      },
      title: "Work Out".tr,
    );
  }

  /// 提交修改
  void doSubmit() async {
    if (state.appliedEditView == null) return;

    //输入框的数据赋值
    TextEditingController totalRoomController = state.formData['total_room']!['controller'];
    TextEditingController addHourController = state.formData['add_hours']!['controller'];
    TextEditingController reasonController = state.formData['reason']!['controller'];
    // 获取文本并尝试转换为整数
    String totalRoomText = totalRoomController.text;
    if (totalRoomText.isNotEmpty) {
      try {
        // 尝试将文本转换为整数
        int totalRooms = int.parse(totalRoomText);
        // 赋值给 state.appliedEditView!.totalRooms
        state.appliedEditView!.totalRooms = totalRooms;
      } catch (e) {
        // 如果转换失败，可以进行错误处理
        print('Error parsing totalRooms: $e');
      }
    } else {
      // 文本为空时的处理逻辑，例如设置默认值或提示用户
      print('Total rooms input is empty');
    }

    state.appliedEditView!.adjustHours = addHourController.text.toString();
    state.appliedEditView!.coReason = reasonController.text.toString();

    //请求网络提交修改
    var result = await _jobRepository.editAppliedSingleStaffInfo(state.appliedId, state.appliedEditView!);

    if (result.isSuccess) {
      NotifyEngine.showSuccess("Successful".tr);

      bus.emit(AppConstant.eventAppliedListRefresh, state.appliedId);

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