import 'dart:io';

import 'package:flutter/material.dart';
import 'package:loopin/IM/im_core.dart';
import 'package:loopin/api/common_api.dart';
import 'package:loopin/service/http.dart';
import 'package:package_info_plus/package_info_plus.dart';

import 'upgrade_dialog.dart';
import 'upgrade_util.dart';

class UpgradeService {
  static Future<void> checkUpgrade(State state) async {
    final info = await PackageInfo.fromPlatform();
    if (!state.mounted) return;

    logger.i('App version: ${info.version}');
    logger.i('version_code: ${info.buildNumber}');
    final res = await Http.post(CommonApi.checkVersion, data: {
      'platformType': Platform.isAndroid ? 'android' : 'ios',
      'status': 1,
    });
    if (!state.mounted) return;

    logger.e('版本：$res');
    final result = res['data']['records'] as List;
    if (result.isEmpty) return;
    final data = result.first;
    final currentVersion = info.buildNumber;
    if (int.parse(data['versionCode'] ?? 0) > int.parse(currentVersion)) {
      // 版本号不一致
      // 0 表示 false非强制，非 0 表示 true强制
      // final bool force = (data['isForceUpdate'] ?? 0) != 0;
      final bool force = true;
      // 弹窗
      showDialog(
        context: state.context,
        barrierDismissible: !force,
        builder: (_) => UpgradeDialog(
          version: data['versionName']?.toString() ?? '',
          content: (data['releaseNotes'] as String).split(',').map((e) => e.trim()).toList(),
          force: force,
          onConfirm: () {
            if (Platform.isAndroid) {
              Navigator.pop(state.context);
              UpgradeUtil.downloadAndInstallAPK(state.context, data['downloadUrl']?.toString() ?? '');
            } else if (Platform.isIOS) {
              UpgradeUtil.launchAppStore(data['downloadUrl']?.toString() ?? '');
            }
          },
        ),
      );
    }
    // final data = {
    //   "version": "4.1.0",
    //   "content": [
    //     "新增火箭弹窗",
    //     "修复若干 Bug",
    //     "优化界面动画",
    //   ],
    //   "force": 0,
    //   "apkUrl": "https://wuzhongjie.com.cn/download/wzj.apk",
    //   "iosUrl": "https://apps.apple.com/cn/app/无终街/id6479185362",
    // };
  }
}
