import 'package:domain/repository/job_repository.dart';
import 'package:domain/repository/th_er_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 'applied_er_edit_state.dart';

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

  // 获取编辑的详情
  void fetchAppliedEditView() async {
    var result = await _erRepository.fetchERAppliedEditDetail(appliedId: 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?.subtractHours ?? "0";
      // totalRoomController.text = state.appliedEditView?.totalRooms.toString();
      reasonController.text = state.appliedEditView?.remark ?? "";

      state.selectedReasonType = state.appliedEditView?.applied?.reasonType;
      state.selectedStatusId = state.appliedEditView?.applied?.status;

      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.getDateTimeByMs((state.appliedEditView?.applied?.startTime ?? 0) * 1000),
      mode: CupertinoDatePickerMode.time,
      onDateTimeChanged: (date) {
        state.appliedEditView!.startTime = DateTimeUtils.formatDate(date, format: 'HH:mm:ss');
        update();
      },
      title: "Start Time".tr,
    );
  }

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

    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: DateTimeUtils.getDateTimeByMs((state.appliedEditView?.applied?.endTime ?? 0) * 1000),
      mode: CupertinoDatePickerMode.time,
      onDateTimeChanged: (date) {
        state.appliedEditView!.endTime = DateTimeUtils.formatDate(date, format: 'HH:mm:ss');
        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!.subtractHours = addHourController.text.toString();
    state.appliedEditView!.remark = reasonController.text.toString();

    //请求网络提交修改
    var result = await _erRepository.editAppliedDetailSubmit(
      appliedId: state.appliedId,
      startTime: state.appliedEditView?.startTime,
      endTime: state.appliedEditView?.endTime,
      securityIn: state.appliedEditView?.securityIn,
      securityOut: state.appliedEditView?.securityOut,
      workIn: state.appliedEditView?.workIn,
      workOut: state.appliedEditView?.workOut,
      subtractHours: state.appliedEditView?.subtractHours,
      reasonType: state.selectedReasonType,
      status: state.selectedStatusId,
      remark: state.appliedEditView?.remark,
      cancelToken: cancelToken,
    );

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