import 'dart:io';
import 'dart:typed_data';

import 'package:domain/entity/response/t_h_o_a_labour_detail_entity.dart';
import 'package:domain/repository/th_oa_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 'package:file_picker/file_picker.dart';
import 'labour_request_add_state.dart';

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

  // 获取添加选项数据
  void fetchLabourRequestEditDetail() async {
    HttpResult<THOALabourDetailEntity> result;
    if (Utils.isEmpty(state.requestId)) {
      result = await _thRepository.fetchLabourRequestAddOption(
        cancelToken: cancelToken,
      );
    } else {
      result = await _thRepository.fetchLabourRequestEditDetail(
        state.requestId,
        cancelToken: cancelToken,
      );
    }

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

      if (state.editDetailEntity?.labReq != null) {
        //有详情数据
        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'];
        var eventController = state.formData['event']!['controller'];
        var eventTypeController = state.formData['event_type']!['controller'];
        var eventPaxController = state.formData['event_pax']!['controller'];
        var revenueController = state.formData['revenue']!['controller'];
        var positionController = state.formData['position']!['controller'];
        var totalCostController = state.formData['total_cost']!['controller'];

        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 ?? '';
        eventController.text = state.editDetailEntity?.labReq?.eventName ?? "";
        eventTypeController.text = state.editDetailEntity?.labReq?.eventType ?? "";
        eventPaxController.text = state.editDetailEntity?.labReq?.passengers ?? "";
        revenueController.text = state.editDetailEntity?.labReq?.estRevenue ?? "";
        positionController.text = state.editDetailEntity?.labReq?.position ?? "";
        totalCostController.text = state.editDetailEntity?.labReq?.estCost ?? "";

        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.selectedJobTitleId = state.editDetailEntity?.labReq?.jobTitleId?.toString();
        state.selectedJobTitleName = state.editDetailEntity?.labReq?.jobTitle;

        state.selectedTypeId = state.editDetailEntity?.labReq?.employmentType?.toString();
        state.selectedType = state.editDetailEntity?.employmentList.firstWhereOrNull((element) => element.value == state.selectedTypeId)?.txt;

        state.attFilePath = state.editDetailEntity?.labReq?.attUrl;

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

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

  //选择开始时间
  void pickStartTime() {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: state.selectedStartTime,
      mode: CupertinoDatePickerMode.dateAndTime,
      onDateTimeChanged: (date) {
        state.selectedStartTime = date;
        update();
      },
      title: "Start Time".tr,
    );
  }

  // 选择结束时间
  void pickEndTime() {
    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((entity) => entity.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'];
    var eventController = state.formData['event']!['controller'];
    var eventTypeController = state.formData['event_type']!['controller'];
    var eventPaxController = state.formData['event_pax']!['controller'];
    var revenueController = state.formData['revenue']!['controller'];
    var positionController = state.formData['position']!['controller'];
    var totalCostController = state.formData['total_cost']!['controller'];

    String maleNo = maleNoController.text.toString();
    String femaleNo = femaleNoController.text.toString();
    String needNo = needNoController.text.toString();
    String remark = remarkController.text.toString();
    String event = eventController.text.toString();
    String eventType = eventTypeController.text.toString();
    String eventPax = eventPaxController.text.toString();
    String revenue = revenueController.text.toString();
    String position = positionController.text.toString();
    String totalCost = totalCostController.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;
      }
    }

    HttpResult result;
    if (state.pageType == 1 && Utils.isNotEmpty(state.requestId)) {
      //编辑
      result = await _thRepository.editLabourRequestSubmit(
        isReviewEdit: state.isReviewEdit,
        requestId: state.requestId,
        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,
        sexLimit: state.genderOptionType,
        maleLimit: maleNo,
        femaleLimit: femaleNo,
        needNum: needNo,
        description: remark,
        employmentType: state.selectedTypeId,
        eventName: event,
        eventType: eventType,
        passengers: eventPax,
        estRevenue: revenue,
        position: position,
        estCost: totalCost,
        cancelToken: cancelToken,
      );
    } else {
      //新增
      result = await _thRepository.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,
        sexLimit: state.genderOptionType,
        maleLimit: maleNo,
        femaleLimit: femaleNo,
        needNum: needNo,
        description: remark,
        employmentType: state.selectedTypeId,
        eventName: event,
        eventType: eventType,
        passengers: eventPax,
        estRevenue: revenue,
        position: position,
        estCost: totalCost,
        attUrl: state.attFilePath,
        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 pickJobTitle() {
    if (state.editDetailEntity == null) {
      return;
    }

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

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

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

  //选择性别限制类型
  void pickLimitType() {
    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.genderOptions,
      initialSelectIndex: state.genderOptionType,
      onPickerChanged: (_, index) {
        state.genderOptionType = index;
        update();
      },
    );
  }

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

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

  //选择类型
  void pickType() {
    if (state.editDetailEntity == null) {
      return;
    }

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

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

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

  // 选择单个文件
  void pickAttFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles(
      allowMultiple: false,
      type: FileType.custom,
      allowedExtensions: ['jpg', 'png', 'jpeg', 'pdf', 'docx'],
    );

    if (result != null) {
      PlatformFile file = result.files.first;
      Log.d("path:${file.path} name:${file.name}");

      final fileResult = await _thRepository.uploadFile(file.path);

      if (fileResult.isSuccess) {
        state.attFilePath = fileResult.data?.path;
        update();
      } else {
        ToastEngine.show(fileResult.errorMsg ?? "Network Load Error".tr);
      }
    }
  }
}
