import 'dart:io';
import 'package:device_info_plus/device_info_plus.dart';
import 'package:flutter/widgets.dart';
import 'package:get/get.dart';
import 'package:making_school_asignment_app/common/job/app_version.dart';
import 'package:making_school_asignment_app/common/mixins/request_tool_mixin.dart';
import 'package:making_school_asignment_app/common/store/user_store.dart';
import 'package:making_school_asignment_app/common/utils/permission_describe_util.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:permission_handler/permission_handler.dart';

import 'UpdateDialog.dart';
import 'model/UpdateAppEvent.dart';

class UpgradeLogic extends GetxController with RequestToolMixin {
  Rx<bool> showUpgrade = false.obs; // 是否已经显示升级弹窗
  Rx<bool> loadingApk = false.obs; // 是否已经显示升级弹窗
  Rx<double> downloadRatio = 0.0.obs; // 下载比例

  // @override
  // void onInit() {

  //   super.onInit();
  // }

  Future<UpdateAppEvent?> getUpdateAppEvent() async {
    // 获取设备信息
    String deviceInfo;
    int deviceType;
    if (Platform.isAndroid) {
      deviceInfo = "android";
      deviceType = 1;
    } else if (Platform.isIOS) {
      deviceInfo = "ios";
      deviceType = 2;
    } else if (Platform.isWindows) {
      deviceInfo = "windows";
      deviceType = 3;
    } else {
      return null;
    }

    AppVersion? result = await getClient().getLastAppVersion('making_school_asignment_app', deviceType);
    if (result == null) return null;

    //获取当前版本
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    //获取当前版本
    String localVersion = packageInfo.version;
    String appName = packageInfo.appName; //应用名称
    String packageName = packageInfo.packageName; //包名称
    // String buildNumber = packageInfo.buildNumber; //小版本号

    Map json = {
      'downloadPath': Platform.isWindows ? '' : result.appFileUrl,
      'version': result.version,
      'systemType': deviceType,
      'description': result.description ?? 'APP新版本更新',
    };
    return UpdateAppEvent.fromJson(json, localVersion, deviceInfo, appName, packageName, typeName: 'systemType');
  }

  Future<void> getAppUpgrade(BuildContext context) async {
    if (!const bool.fromEnvironment('dart.vm.product')) return;

    try {
      showUpgrade.value = true;
      
      final names = [
        UserStore.to.userDetailInfo.value?.name,
        UserStore.to.userDetailInfo.value?.account,
      ].whereType<String>().where((name) => name.isNotEmpty).toList();
      if (names.contains('AppleTester')) return;

      UpdateAppEvent? updateAppEvent = await getUpdateAppEvent();
      if (updateAppEvent != null && updateAppEvent.upgrade) {
        if (Platform.isAndroid) {
          DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
          AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
          Permission storagePermission;
          if (androidInfo.version.sdkInt >= 33) {
            storagePermission = Permission.manageExternalStorage;
          } else {
            storagePermission = Permission.storage;
          }
          await PermissionDescribeUtil.instance.toLaunchPermissionRequest(
            Get.context ?? context,
            title: '储存权限请求',
            describe: "为了提供更好的服务，需要获取到存储权限用于保存APP升级文件APK，进行升级",
            permissions: [storagePermission],
          );
        }

        await UpdateDialog.showUpdateDialog(
          Get.context ?? context,
          updateAppEvent,
        );
      }
      /** 
      // 获取设备信息
      String deviceInfo;
      int deviceType;
      if (Platform.isAndroid) {
        deviceInfo = "android";
        deviceType = 1;
      } else if (Platform.isIOS) {
        deviceInfo = "ios";
        deviceType = 2;
      } else if (Platform.isWindows) {
        deviceInfo = "windows";
        deviceType = 3;
      } else {
        return false;
      }

      if (result != null) {
        //获取当前版本
        PackageInfo packageInfo = await PackageInfo.fromPlatform();
        //获取当前版本
        String localVersion = packageInfo.version;
        String appName = packageInfo.appName; //应用名称
        String packageName = packageInfo.packageName; //包名称
        // String buildNumber = packageInfo.buildNumber; //小版本号

        Map json = {'downloadPath': Platform.isWindows ? '' : result.appFileUrl, 'version': result.version, 'systemType': deviceType, 'description': result.description ?? 'APP新版本更新'};
        UpdateAppEvent updateAppEvent = UpdateAppEvent.fromJson(json, localVersion, deviceInfo, appName, packageName, typeName: 'systemType');
        if (updateAppEvent.upgrade) {
          if (Platform.isAndroid) {
            DeviceInfoPlugin deviceInfoPlugin = DeviceInfoPlugin();
            AndroidDeviceInfo androidInfo = await deviceInfoPlugin.androidInfo;
            Permission storagePermission;
            if (androidInfo.version.sdkInt >= 33) {
              storagePermission = Permission.manageExternalStorage;
            } else {
              storagePermission = Permission.storage;
            }
            await PermissionDescribeUtil.instance.toLaunchPermissionRequest(
              Get.context ?? context,
              title: '储存权限请求',
              describe: "为了提供更好的服务，需要获取到存储权限用于保存APP升级文件APK，进行升级",
              permissions: [storagePermission],
            );
          }

          await UpdateDialog.showUpdateDialog(
            Get.context ?? context,
            updateAppEvent,
          );
        }
      }
      */
    } finally {
      showUpgrade.value = false;
    }
  }
}
