import 'dart:io';
import 'package:autosos_flutter/api/user_api.dart';
import 'package:autosos_flutter/config/constant.dart';
import 'package:autosos_flutter/model/misc.dart';
import 'package:dio/dio.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:install_plugin/install_plugin.dart';
import 'package:open_filex/open_filex.dart';
import 'package:path_provider/path_provider.dart';

/// 应用内更新服务（对应 Android HttpUpdateVersion）
class UpdateService {
  static final UpdateService instance = UpdateService._();
  UpdateService._();

  final _dio = Dio();

  /// 检查更新
  Future<AppUpdate?> checkUpdate() async {
    try {
      final resp = await UserApi.instance.checkUpdate();
      if (!resp.isSuccess) return null;

      final update = resp.data!;
      Constant.NECUPDATE = update.forceUpdate ? 3 : 2;
      return update;
    } catch (e) {
      debugPrint('checkUpdate failed: $e');
      Constant.NECUPDATE = 5;
      return null;
    }
  }

  /// 下载并安装
  Future<void> downloadAndInstall(AppUpdate update) async {
    if (update.downloadUrl == null) {
      EasyLoading.showError('下载链接为空');
      return;
    }
    EasyLoading.showProgress(0, status: '下载中 0%');

    final dir = await getTemporaryDirectory();
    final apkPath = '${dir.path}/autosos_${update.latestVersion}.apk';

    await _dio.download(
      update.downloadUrl!,
      apkPath,
      onReceiveProgress: (received, total) {
        if (total > 0) {
          final p = received / total;
          EasyLoading.showProgress(p, status: '下载中 ${(p * 100).toStringAsFixed(0)}%');
        }
      },
    );

    EasyLoading.dismiss();

    if (Platform.isAndroid) {
      await InstallPlugin.install(apkPath);
    } else if (Platform.isIOS) {
      await OpenFilex.open(apkPath);
    }
  }
}