import 'package:domain/entity/agency_need_number.dart';
import 'package:domain/repository/labour_sg_repository.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.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/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 'AgencyNeedNumberWidget.dart';
import 'labour_request_add_state.dart';

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

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

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

      state.agencyKeys.clear();
      state.agencyWidgets.clear();

      state.agencyWidgets = state.indexEntity!.agencyList.map((e) {
        final key = GlobalKey<AgencyNeedNumberState>();
        state.agencyKeys.add(key); // 存储 key
        return AgencyNeedNumberWidget(
          key: key,
          agencyId: e.agencyId,
          agencyName: e.agencyName,
        );
      }).toList(growable: true);

      // 添加 InHouse 的 AgencyNeedNumberWidget
      final inHouseKey = GlobalKey<AgencyNeedNumberState>();
      state.agencyKeys.add(inHouseKey);
      final inHouseWidget = AgencyNeedNumberWidget(
        key: inHouseKey,
        agencyId: "0",
        agencyName: "In House",
      );
      state.agencyWidgets.add(inHouseWidget);

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

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

  // 选择工标题
  void pickJobTitle() {
    if (state.indexEntity == null) {
      return;
    }

    int selectedTemplateIndex;
    if (state.selectedJobTitleId == null) {
      selectedTemplateIndex = 0;
    } else {
      selectedTemplateIndex = state.indexEntity!.titleList.indexWhere((department) => department.value.toString() == state.selectedJobTitleId);
    }

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

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

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

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

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

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

  void pickRepeatStartTime() {
    if (state.indexEntity == null) {
      return;
    }

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

  void pickRepeatEndTime() {
    if (state.indexEntity == null) {
      return;
    }

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

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

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

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

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

  // 提交LabourRequest表单
  void doSubmit() async {
    TextEditingController remarkController = state.formData['remark']!['controller'];
    String? remark = remarkController.text;

    if (Utils.isEmpty(state.selectedJobTitleId)) {
      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.selectedOutletId)) {
      ToastEngine.show("Choose Outlet".tr);
      return;
    }

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

    // 获取所有 AgencyNeedNumberEntity
    List<AgencyNeedNumberEntity> agencyEntities = state.agencyKeys.map((key) {
      return key.currentState!.getAgencyNeedNumberEntity();
    }).toList();
    Log.d("agencyEntities：$agencyEntities");

    var result = await _labourRepository.addLabourRequestSubmit(
      jobTitleId: state.selectedJobTitleId,
      startTime: DateTimeUtils.formatDate(state.selectedStartTime),
      endTime: DateTimeUtils.formatDate(state.selectedEndTime),
      repeatStart: DateTimeUtils.formatDate(state.selectedRepeatStartTime, format: "yyyy-MM-dd"),
      repeatEnd: DateTimeUtils.formatDate(state.selectedRepeatEndTime, format: "yyyy-MM-dd"),
      outletId: state.selectedOutletId,
      requestType: state.selectRequestTypeId,
      positionId: state.selectPositionId,
      remark: remark,
      list: agencyEntities,
      cancelToken: cancelToken,
    );

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

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

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

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

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

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

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

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