import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:ln_jq_app/common/model/base_model.dart';
import 'package:ln_jq_app/pages/b_page/site/controller.dart'; // Reuse ReservationModel

class HistoryController extends GetxController with BaseControllerMixin {
  @override
  String get builderId => 'history';

  // --- 定义 API 需要的日期格式化器 ---
  final DateFormat _apiDateFormat = DateFormat('yyyy-MM-dd');

  // 默认查询最近7天
  final Rx<DateTime> startDate = DateTime.now().subtract(const Duration(days: 7)).obs;
  final Rx<DateTime> endDate = DateTime.now().obs;
  final TextEditingController plateNumberController = TextEditingController();

  final RxString totalHydrogen = '0'.obs;
  final RxString totalCompletions = '0'.obs;

  final RxList<ReservationModel> historyList = <ReservationModel>[].obs;
  final RxBool isLoading = true.obs;
  final RxBool hasData = false.obs;

  String get formattedStartDate => DateFormat('yyyy/MM/dd').format(startDate.value);

  String get formattedEndDate => DateFormat('yyyy/MM/dd').format(endDate.value);

  String stationName = "";

  final Map<String, String> statusOptions = {
    '': '全部',
    '100': '未预约加氢',
    '0': '待加氢',
    '1': '已加氢',
    '2': '未加氢',
    '5': '拒绝加氢',
  };

  final RxString selectedStatus = ''.obs;
  final RxString selectedDateType = ''.obs; // week, month, three_month

  @override
  void onInit() {
    super.onInit();
    final args = Get.arguments as Map<String, dynamic>;
    stationName = args['stationName'] as String? ?? "";
    refreshData();
  }

  void refreshData() {
    getAllOrderCounts();
    fetchHistoryData();
  }

  Future<void> getAllOrderCounts() async {
    var response = await HttpService.to.post(
      "appointment/orderAddHyd/getAllOrderCounts",
      data: {
        /*'startTime': _apiDateFormat.format(startDate.value),
        'endTime': _apiDateFormat.format(endDate.value),*/
        'plateNumber': plateNumberController.text,
        'stationName': stationName,
        "status": selectedStatus.value,
        "dateType": selectedDateType.value,
      },
    );
    if (response == null || response.data == null) {
      totalHydrogen.value = '0';
      totalCompletions.value = '0';
      return;
    }
    try {
      final baseModel = BaseModel<dynamic>.fromJson(response.data);
      final dataMap = baseModel.data as Map<String, dynamic>;
      totalHydrogen.value = '${dataMap['totalAddAmount'] ?? 0}';
      totalCompletions.value = '${dataMap['orderCompleteCount'] ?? 0}';
    } catch (e) {
      totalHydrogen.value = '0';
      totalCompletions.value = '0';
    }
  }

  Future<void> fetchHistoryData() async {
    isLoading.value = true;
    updateUi();

    try {
      var response = await HttpService.to.post(
        "appointment/orderAddHyd/sitOrderPage",
        data: {
          /*'startTime': _apiDateFormat.format(startDate.value),
          'endTime': _apiDateFormat.format(endDate.value),*/
          'plateNumber': plateNumberController.text,
          'pageNum': 1,
          'pageSize': 50,
          'stationName': stationName,
          "status": selectedStatus.value,
          "dateType": selectedDateType.value,
        },
      );

      if (response == null || response.data == null) {
        _resetData();
        return;
      }

      final baseModel = BaseModel<dynamic>.fromJson(response.data);
      if (baseModel.code == 0 && baseModel.data != null) {
        final dataMap = baseModel.data as Map<String, dynamic>;
        final List<dynamic> listFromServer = dataMap['records'] ?? [];
        historyList.assignAll(
          listFromServer
              .map((item) => ReservationModel.fromJson(item as Map<String, dynamic>))
              .toList(),
        );
        hasData.value = historyList.isNotEmpty;
      } else {
        _resetData();
      }
    } catch (e) {
      _resetData();
    } finally {
      isLoading.value = false;
      updateUi();
    }
  }

  void _resetData() {
    historyList.clear();
    hasData.value = false;
  }

  void onStatusSelected(String status) {
    if (selectedStatus.value == status) return;
    selectedStatus.value = status;
    refreshData();
  }

  void onDateTypeSelected(String type) {
    selectedDateType.value = type;
    refreshData();
  }

  @override
  void onClose() {
    plateNumberController.dispose();
    super.onClose();
  }
}
