import 'package:flutter/material.dart';
import 'package:qhd_prevention/customWidget/toast_util.dart';
import 'package:qhd_prevention/services/location_service.dart';
import 'package:qhd_prevention/http/ApiService.dart';
import 'package:qhd_prevention/tools/tools.dart';

class WorkAreaHelper {
  /// 检查是否需要并且能否在作业区域内继续
  static Future<bool> checkInSpecialWorkArea({
    required BuildContext context,
    required String flow,
    required String areaId,
    bool checkTapConfig = true,
    Duration timeout = const Duration(seconds: 10),
  }) async {
    // 如果是提交申请 或 配置关闭，则直接允许
    if (flow == '提交申请' || !checkTapConfig) {
      return true;
    }
    try {
      LoadingDialogHelper.show();

      // 获取经纬度（字符串形式）
      final LocationResult loc =
      await LocationService.getCurrentLocation(timeout: timeout);
      // 调用后端检查
      final result = await ApiService.checkSpecialWorkIsInPls(
        areaId ?? '',
        loc.longitude,
        loc.latitude,
      );

      if (result != null &&
          result['result'] == 'success' &&
          (result['flag'] as bool? ?? false)) {
        return true;
      } else {
        ToastUtil.showNormal(context, result?['msg'] ?? '作业区域不存在');
        return false;
      }
    } catch (e) {
      // 友好提示：定位或其他异常
      final msg = (e is LocationException) ? e.message : '检查区域失败: ${e.toString()}';
      ToastUtil.showNormal(context, msg);
      return false;
    } finally {
      LoadingDialogHelper.hide();
    }
  }
}
