import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:ln_jq_app/common/model/base_model.dart';
import 'package:ln_jq_app/common/model/vehicle_info.dart';
import 'package:ln_jq_app/common/styles/theme.dart';
import 'package:ln_jq_app/storage_service.dart';

import '../../login/view.dart';

class MineController extends GetxController with BaseControllerMixin {
  @override
  String get builderId => 'mine';

  MineController();

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

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

  void logout() async {
    await StorageService.to.clearLoginInfo();

    Get.offAll(() => LoginPage());
  }

  String rate = "";
  String rating = "";
  String accident = "";
  String historyBreakRules = "";
  String vin = "";
  String plateNumber = "";
  String violationTotal = "0";//违章总数
  String violationScore = "0";//扣分总数
  String violationDispose = "0";//已处理
  bool isNotice = false;

  void renderData() async {
    if (StorageService.to.hasVehicleInfo) {
      VehicleInfo? bean = StorageService.to.vehicleInfo;
      if (bean == null) {
        return;
      }
      vin = bean.vin;
      plateNumber = bean.plateNumber;
    }

    try {
      showLoading("加载中");
      await Future.wait([
        _fetchCompletionRate(), // 请求1：完成率
        _fetchAccidentCount(), // 请求2：事故数
        _fetchBreakRulesCount(), // 请求3：违章数
        _rating(), // 司机评分
        msgNotice(), // 红点消息
      ]);

      await renderViolation();
    } catch (e, stackTrace) {
      showErrorToast("加载数据失败，请稍后重试 $e");
    } finally {
      dismissLoading();
      updateUi();
    }
  }

  Future<void> msgNotice() async {
    final Map<String, dynamic> requestData = {
      'appFlag': 1,
      'isRead': 1,
      'pageNum': 1,
      'pageSize': 5,
    };
    final response = await HttpService.to.get(
      'appointment/unread_notice/page',
      params: requestData,
    );
    if (response != null) {
      final result = BaseModel.fromJson(response.data);
      if (result.code == 0 && result.data != null) {
        String total = result.data["total"].toString();
        isNotice = int.parse(total) > 0;
        updateUi();
      }
    }
  }

  Future<void> _rating() async {
    final response = await HttpService.to.get('appointment/rating/driver');

    if (response != null) {
      final result = BaseModel.fromJson(response.data);
      if (result.code == 0 && result.data != null) {
        rating = result.data.toString();
      }
    }
  }

  Future<void> _fetchCompletionRate() async {
    final response = await HttpService.to.get(
      'appointment/orderAddHyd/driverAppointmentCompletionRate?phone=${StorageService.to.phone}',
    );

    if (response != null) {
      final result = BaseModel.fromJson(response.data);
      if (result.code == 0 && result.data != null) {
        rate = result.data.toString();
      }
    }
  }

  /// 获取历史事故数
  Future<void> _fetchAccidentCount() async {
    final response = await HttpService.to.get(
      'appointment/truck/historyTrafficAccidentCount?vin=${vin}',
    );
    if (response != null) {
      final result = BaseModel.fromJson(response.data);
      if (result.code == 0 && result.data != null) {
        accident = result.data.toString();
      }
    }
  }

  /// 获取历史违章数
  Future<void> _fetchBreakRulesCount() async {
    final response = await HttpService.to.get(
      'appointment/truck/historyBreakRulesCount?vin=${vin}',
    );
    if (response != null) {
      final result = BaseModel.fromJson(response.data);
      if (result.code == 0 && result.data != null) {
        historyBreakRules = result.data.toString();
      }
    }
  }

  Future<void> renderViolation() async {
    // 违章信息查询
    try {
      var responseData = await HttpService.to.get(
        "appointment/truck/queryViolationInfo_V2?plateNum=${plateNumber}",
      );

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

      var result = BaseModel.fromJson(responseData.data);

      if (result.code == 0 && result.data != null && result.data is List) {
        List<dynamic> violationList = result.data as List;
        int totalScore = 0;
        int disposeCount = 0;
        for (var item in violationList) {
          if (item is Map<String, dynamic>) {
            totalScore += (item['score'] as num?)?.toInt() ?? 0;
            if (item['isDispose'] == 1) {
              disposeCount++;
            }
          }
        }
        violationTotal = violationList.length.toString();
        violationScore = totalScore.toString();
        violationDispose = disposeCount.toString();
      }
    } catch (e) {
    } finally {
      updateUi();
    }
  }
}
