import 'package:domain/repository/labour_sg_repository.dart';
import 'package:domain/repository/sg_agency_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:plugin_platform/http/http_result.dart';
import 'package:shared/utils/log_utils.dart';
import 'package:shared/utils/util.dart';
import 'package:widgets/picker/option_pick_util.dart';

import 'contract_rate_setting_state.dart';

class ContractRateSettingController extends GetxController with DioCancelableMixin {
  final SGAgencyRepository _agencyRepository = Get.find();
  final ContractRateSettingState state = ContractRateSettingState();

  // 获取添加或者编辑的详情
  void _fetchAddEditIndexDetail() async {
    if (!state.isAddType) {
      //编辑
      final detailResult = await _agencyRepository.fetchContractPositionRateDetail(
        contractId: state.contractId,
        positionId: state.positionId,
        cancelToken: cancelToken,
      );

      if (detailResult.isSuccess) {
        state.editDetail = detailResult.data;

        TextEditingController agencyNameController = state.formData['agency_name']!['controller'];
        TextEditingController hourlyRateController = state.formData['hourly_rate']!['controller'];
        TextEditingController weekdaysController = state.formData['weekdays']!['controller'];
        TextEditingController weekendsController = state.formData['weekends']!['controller'];
        TextEditingController sundayController = state.formData['sunday']!['controller'];
        TextEditingController mondayController = state.formData['monday']!['controller'];
        TextEditingController tuesdayController = state.formData['tuesday']!['controller'];
        TextEditingController wednesdayController = state.formData['wednesday']!['controller'];
        TextEditingController thursdayController = state.formData['thursday']!['controller'];
        TextEditingController fridayController = state.formData['friday']!['controller'];
        TextEditingController saturdayController = state.formData['saturday']!['controller'];
        TextEditingController eveOfPHDayController = state.formData['eve_of_ph_day']!['controller'];
        TextEditingController phDaysController = state.formData['ph_days']!['controller'];

        agencyNameController.text = state.editDetail?.agencyName ?? "";
        state.positionId = state.editDetail?.positionId ?? "";
        state.positionName = state.editDetail?.position ?? "";
        hourlyRateController.text = state.editDetail?.type1 ?? "";
        weekdaysController.text = state.editDetail?.type2 ?? "";
        weekendsController.text = state.editDetail?.type3 ?? "";
        sundayController.text = state.editDetail?.type7 ?? "";
        mondayController.text = state.editDetail?.type8 ?? "";
        tuesdayController.text = state.editDetail?.type9 ?? "";
        wednesdayController.text = state.editDetail?.type10 ?? "";
        thursdayController.text = state.editDetail?.type11 ?? "";
        fridayController.text = state.editDetail?.type12 ?? "";
        saturdayController.text = state.editDetail?.type13 ?? "";
        eveOfPHDayController.text = state.editDetail?.type20 ?? "";
        phDaysController.text = state.editDetail?.type21 ?? "";
      } else {
        ToastEngine.show(detailResult.errorMsg ?? "");
      }
    } else {
      //新增
      final optionResult = await _agencyRepository.fetchContractPositionAddOption(
        contractId: state.contractId,
        cancelToken: cancelToken,
      );

      if (optionResult.isSuccess) {
        state.addOption = optionResult.data;
        state.positionList = optionResult.data?.positionList ?? [];

        TextEditingController agencyNameController = state.formData['agency_name']!['controller'];
        agencyNameController.text = state.addOption?.agencyName ?? "";
      } else {
        ToastEngine.show(optionResult.errorMsg ?? "");
      }
    }

    update();
  }

  /// 提交
  void doSubmit() async {
    var hourlyRateController = state.formData['hourly_rate']!['controller'];
    var weekdaysController = state.formData['weekdays']!['controller'];
    var weekendsController = state.formData['weekends']!['controller'];
    var mondayController = state.formData['monday']!['controller'];
    var tuesdayController = state.formData['tuesday']!['controller'];
    var wednesdayController = state.formData['wednesday']!['controller'];
    var thursdayController = state.formData['thursday']!['controller'];
    var fridayController = state.formData['friday']!['controller'];
    var saturdayController = state.formData['saturday']!['controller'];
    var sundayController = state.formData['sunday']!['controller'];
    var eveOfPHDayController = state.formData['eve_of_ph_day']!['controller'];
    var phDaysController = state.formData['ph_days']!['controller'];

    String hourlyRate = hourlyRateController.text.toString();
    String weekdays = weekdaysController.text.toString();
    String weekends = weekendsController.text.toString();
    String sunday = sundayController.text.toString();
    String monday = mondayController.text.toString();
    String tuesday = tuesdayController.text.toString();
    String wednesday = wednesdayController.text.toString();
    String thursday = thursdayController.text.toString();
    String friday = fridayController.text.toString();
    String saturday = saturdayController.text.toString();
    String eveOfPHDay = eveOfPHDayController.text.toString();
    String phDays = phDaysController.text.toString();

    if (Utils.isEmpty(state.positionId)) {
      ToastEngine.show("Select Position".tr);
      return;
    }

    if (Utils.isEmpty(hourlyRate)) {
      ToastEngine.show("Enter Hourly Rate".tr);
      return;
    }

    Future<HttpResult> taskFuture;
    if (!state.isAddType) {
      taskFuture = _agencyRepository.editContractPositionRateSubmit(
        contractId: state.contractId,
        positionId: state.positionId,
        type_1: hourlyRate,
        type_2: weekdays,
        type_3: weekends,
        type_7: sunday,
        type_8: monday,
        type_9: tuesday,
        type_10: wednesday,
        type_11: thursday,
        type_12: friday,
        type_13: saturday,
        type_20: eveOfPHDay,
        type_21: phDays,
        cancelToken: cancelToken,
      );
    } else {
      taskFuture = _agencyRepository.addContractPositionSubmit(
        contractId: state.contractId,
        positionId: state.positionId,
        type_1: hourlyRate,
        type_2: weekdays,
        type_3: weekends,
        type_7: sunday,
        type_8: monday,
        type_9: tuesday,
        type_10: wednesday,
        type_11: thursday,
        type_12: friday,
        type_13: saturday,
        type_20: eveOfPHDay,
        type_21: phDays,
        cancelToken: cancelToken,
      );
    }

    var result = await taskFuture;

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

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

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

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

  // 选择职位
  void pickPosition() {
    int selectedIndex;
    if (state.positionId == null) {
      selectedIndex = 0;
    } else {
      selectedIndex = state.positionList.indexWhere((department) => department.value.toString() == state.positionId);
    }

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

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.positionList.map((e) => e.txt!).toList(growable: false),
      initialSelectIndex: selectedIndex,
      onPickerChanged: (_, index) {
        state.positionName = state.positionList[index].txt;
        state.positionId = state.positionList[index].value;
        update();
      },
    );
  }
}
