import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
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 {
  // --- 定义 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 kg'.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 = "";

  @override
  void onInit() {
    super.onInit();

    final args = Get.arguments as Map<String, dynamic>;
    stationName = args['stationName'] as String;
    fetchHistoryData();
  }

  Future<void> getAllOrderCounts() async {
    var response = await HttpService.to.post(
      "appointment/orderAddHyd/getAllOrderCounts",
      data: {
        // --- 直接使用 DateFormat 来格式化日期 ---
        'startTime': _apiDateFormat.format(startDate.value),
        'endTime': _apiDateFormat.format(endDate.value),
        'plateNumber': plateNumberController.text,
        'stationName': stationName, // 加氢站名称
      },
    );
    if (response == null || response.data == null) {
      totalHydrogen.value = '0 kg';
      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} kg';
      totalCompletions.value = '${dataMap['orderCompleteCount'] ?? 0} 次';
    } catch (e) {
      totalHydrogen.value = '0 kg';
      totalCompletions.value = '0 次';
    }
  }

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

    //获取数据
    getAllOrderCounts();

    try {
      var response = await HttpService.to.post(
        "appointment/orderAddHyd/sitOrderPage",
        data: {
          // --- 直接使用 DateFormat 来格式化日期 ---
          'startTime': _apiDateFormat.format(startDate.value),
          'endTime': _apiDateFormat.format(endDate.value),
          'plateNumber': plateNumberController.text,
          'pageNum': 1,
          'pageSize': 50,
          'stationName': stationName, // 加氢站名称
        },
      );

      if (response == null || response.data == null) {
        showToast('无法获取历史记录');
        _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 {
        showToast(baseModel.message);
        _resetData();
      }
    } catch (e) {
      showToast('获取历史记录失败: $e');
      _resetData();
    } finally {
      isLoading.value = false;
    }
  }

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

  void pickDate(BuildContext context, bool isStartDate) {
    //  确定当前操作的日期和临时存储变量
    final DateTime initialDate = isStartDate ? startDate.value : endDate.value;
    DateTime tempDate = initialDate;

    //  定义全局的最早可选日期
    final DateTime globalMinimumDate = DateTime(2025, 12, 1);

    //  动态计算当前选择器的最小/最大日期范围
    DateTime minimumDate;
    DateTime? maximumDate; // 声明为可空，因为两个日期都可能没有最大限制

    if (isStartDate) {
      // 当选择【开始日期】时 它的最小日期就是全局最小日期
      minimumDate = globalMinimumDate;
      // 最大日期没有限制
      maximumDate = null;
    } else {
      // 当选择【结束日期】时 它的最小日期不能早于当前的开始日期
      minimumDate = startDate.value;
      //  确认结束日期没有最大限制 ---
      //最大日期没有限制
      maximumDate = null;
    }

    Get.bottomSheet(
      Container(
        height: 300,
        decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(16),
            topRight: Radius.circular(16),
          ),
        ),
        child: Column(
          children: [
            // 顶部的取消和确认按钮
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  TextButton(
                    onPressed: () => Get.back(),
                    child: const Text('取消', style: TextStyle(color: Colors.grey)),
                  ),
                  TextButton(
                    onPressed: () {
                      // 4. 确认后，更新对应的日期变量
                      if (isStartDate) {
                        startDate.value = tempDate;
                        // 如果新的开始日期晚于结束日期，自动将结束日期调整为同一天
                        if (tempDate.isAfter(endDate.value)) {
                          endDate.value = tempDate;
                        }
                      } else {
                        endDate.value = tempDate;
                      }
                      Get.back();

                      // 选择日期后自动刷新数据
                      fetchHistoryData();
                    },
                    child: const Text(
                      '确认',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                  ),
                ],
              ),
            ),
            const Divider(height: 1),
            // 日期选择器
            Expanded(
              child: CupertinoDatePicker(
                mode: CupertinoDatePickerMode.date,
                initialDateTime: initialDate,
                // 应用动态计算好的最小/最大日期
                minimumDate: minimumDate,
                maximumDate: maximumDate,
                onDateTimeChanged: (DateTime newDate) {
                  tempDate = newDate;
                },
              ),
            ),
          ],
        ),
      ),
      backgroundColor: Colors.transparent, // 使底部工作表外的区域透明
    );
  }

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