import 'package:domain/entity/response/contract_detail_entity.dart';
import 'package:domain/entity/response/index_option_entity.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/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 'contract_add_state.dart';

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

  // 获取添加或者编辑的详情
  void _fetchAddEditIndexDetail() async {
    // //获取到数据
    Future<HttpResult<ContractDetailEntity>> taskFuture;
    if (state.type != 0) {
      //编辑
      taskFuture = _agencyRepository.fetchContractEditDetail(contractId: state.contractId, cancelToken: cancelToken);
    } else {
      //新增
      taskFuture = _agencyRepository.fetchContractAddOption(cancelToken: cancelToken);
    }

    var result = await taskFuture;

    //处理数据
    if (result.isSuccess) {
      state.detailOption = result.data;

      state.agencyList = state.detailOption?.agencyList ?? [];
      state.selectedAgencyId = state.detailOption?.agencyList.firstWhere((e) => e.selected == "selected", orElse: () => IndexOptionEntity()).value;
      state.selectedAgencyTxt = state.detailOption?.agencyList.firstWhere((e) => e.selected == "selected", orElse: () => IndexOptionEntity()).txt;

      if (state.type == 1){
        state.selectedStartTime = result.data?.row?.startDate == null ? null : DateTimeUtils.getDateTime(result.data!.row!.startDate!);
        state.selectedEndTime = result.data?.row?.endDate == null ? null : DateTimeUtils.getDateTime(result.data!.row!.endDate!);
      }

      if (Utils.isNotEmpty(state.detailOption?.row?.file) && state.type == 1) {
        List<String> images = [state.detailOption!.row!.file!];
        state.selectedPaths = images;
      }

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

  /// 提交
  void doSubmit() async {

    if (state.selectedAgencyId == null) {
      ToastEngine.show("Please Select Agency".tr);
      return;
    }

    if (state.selectedStartTime == null) {
      ToastEngine.show("Please Select Start Time".tr);
      return;
    }

    if (state.selectedEndTime == null) {
      ToastEngine.show("Please Select End Time".tr);
      return;
    }

    Future<HttpResult> taskFuture;
    if (state.type == 0) {
      taskFuture = _agencyRepository.addContractSubmit(
        agencyId: state.selectedAgencyId,
        startDate: DateTimeUtils.formatDate(state.selectedStartTime!, format: 'yyyy-MM-dd'),
        endDate: DateTimeUtils.formatDate(state.selectedEndTime!, format: 'yyyy-MM-dd'),
        paths: state.selectedPaths,
        cancelToken: cancelToken,
      );

    } else if (state.type == 1){
      taskFuture = _agencyRepository.editContractSubmit(
        contractId: state.contractId,
        agencyId: state.selectedAgencyId,
        startDate: DateTimeUtils.formatDate(state.selectedStartTime!, format: 'yyyy-MM-dd'),
        endDate: DateTimeUtils.formatDate(state.selectedEndTime!, format: 'yyyy-MM-dd'),
        paths: state.selectedPaths,
        cancelToken: cancelToken,
      );
    }else{
      taskFuture = _agencyRepository.renewContractSubmit(
        contractId: state.contractId,
        agencyId: state.selectedAgencyId,
        startDate: DateTimeUtils.formatDate(state.selectedStartTime!, format: 'yyyy-MM-dd'),
        endDate: DateTimeUtils.formatDate(state.selectedEndTime!, format: 'yyyy-MM-dd'),
        paths: state.selectedPaths,
        cancelToken: cancelToken,
      );
    }

    var result = await taskFuture;

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

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

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

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

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

  // 选择结束时间
  void pickEndTime() {
    DatePickerUtil.showCupertinoDatePicker(
      selectedDateTime: state.selectedEndTime ?? state.selectedStartTime,
      mode: CupertinoDatePickerMode.date,
      onDateTimeChanged: (date) {
        state.selectedEndTime = date;
        update();
      },
      title: "End Time".tr,
    );
  }

  // 选择中介商
  void pickAgency() {
    if (state.detailOption == null) return;

    int selectedIndex;
    if (state.selectedAgencyId == null) {
      selectedIndex = 0;
    } else {
      selectedIndex = state.detailOption!.agencyList.indexWhere((bean) => bean.value.toString() == state.selectedAgencyId);
    }

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

    OptionPickerUtil.showCupertinoOptionPicker(
      items: state.detailOption!.agencyList.map((e) => e.txt!.tr).toList(growable: false),
      initialSelectIndex: selectedIndex,
      onPickerChanged: (_, index) {
        state.selectedAgencyId = state.detailOption!.agencyList[index].value!.toString();
        state.selectedAgencyTxt = state.detailOption!.agencyList[index].txt!.toString();
        update();
      },
    );
  }

  //设置选中的文件路径数组
  void setDocList(List<String> list) {
    state.selectedPaths = list;
    update();
  }
}
