import 'dart:convert';
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:package_info/package_info.dart';
import 'package:sk_base_mobile/app_theme.dart';
import 'package:sk_base_mobile/models/app_bottom_nav_item.dart';
import 'package:sk_base_mobile/models/app_config.dart';
import 'package:sk_base_mobile/screens/inventory/inventory.dart';
import 'package:sk_base_mobile/screens/inventory_inout/inventory_inout.dart';
import 'package:sk_base_mobile/apis/index.dart';
import 'package:sk_base_mobile/screens/workbench/workbench.dart';
import 'package:sk_base_mobile/services/service.dart';
import 'package:sk_base_mobile/store/auth.store.dart';
import 'package:sk_base_mobile/util/convert.dart';
import 'package:sk_base_mobile/util/logger_util.dart';
import 'dart:ui' as ui;
import 'package:sk_base_mobile/config.dart';
import '../constants/constants.dart';
import '../screens/mine/mine.dart';

class AppInfoService extends GetxService {
  static AppInfoService get to => Get.find();
  final versionNumber = RxString('');
  late AppConfig appConfig;
  final scale = RxDouble(1.0);
  final isLarge = RxBool(false);
  final isCameraing = RxBool(false);
  List<AppBottomNavItem>? bottomNavItems = [
    AppBottomNavItem(
        icon: Icons.home_max_outlined,
        activeIcon: Icons.home_max_outlined,
        label: '登记',
        page: InvenotryInoutPage()),
    AppBottomNavItem(
        icon: Icons.inventory_outlined,
        activeIcon: Icons.inventory_rounded,
        label: '库存',
        page: InventoryPage()),
    AppBottomNavItem(
        icon: Icons.widgets_outlined,
        activeIcon: Icons.widgets_rounded,
        label: '工作台',
        page: WorkBenchPage()),
    AppBottomNavItem(
        icon: Icons.person_outline_outlined,
        activeIcon: Icons.person,
        label: '我的',
        page: MinePage()),
  ];
  Future<AppInfoService> init() async {
    LoggerUtil()
        .info("[service-appInfo] Register app-related information service");

    try {
      // await Future.wait(
      //     [getDeviceInfo(), getPackageInfo(), getAppConfig(), getossPolicy()]);
      requestPermission();
    } catch (e) {
      LoggerUtil().error(e);
    }
    return this;
  }

  Future<void> setIsFirstInstall() async {
    await StorageService.to
        .setBool(CacheKeys.isFirstInstall, true, isWithUser: false);
  }

  bool checkIsFirstInstall() {
    bool? isFirstInstallCache =
        StorageService.to.getBool(CacheKeys.isFirstInstall, isWithUser: false);
    return isFirstInstallCache == null || !isFirstInstallCache;
  }

  Future<void> getDeviceInfo() async {
    // DeviceInfoPlugin deviceInfo = DeviceInfoPlugin();
    // if (Platform.isIOS) {
    //   iosDeviceInfo = await deviceInfo.iosInfo;
    //   if (iosDeviceInfo != null) {
    //     await StorageService.to.setString(
    //         CacheKeys.deviceUUID, iosDeviceInfo!.identifierForVendor!,
    //         isWithUser: false);
    //     await StorageService.to.setString(
    //         CacheKeys.deviceModel, iosDeviceInfo!.name,
    //         isWithUser: false);
    //   }
    // } else {
    //   androidDeviceInfo = await deviceInfo.androidInfo;
    //   await StorageService.to.setString(
    //       CacheKeys.deviceUUID, GloablConfig.DEVICE_UUID,
    //       isWithUser: false);
    //   await StorageService.to.setString(
    //       CacheKeys.deviceModel, GloablConfig.DEVICE_MODEL,
    //       isWithUser: false);
    // }
  }

  Future<void> getPackageInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    versionNumber.value = packageInfo.version;
  }

  Future<void> getAppConfig() async {
    if (StorageService.to.getString(CacheKeys.token, isWithUser: false) !=
        null) {
      final response = await Api.getAppConfig();
      if (response.data != null) {
        appConfig = AppConfig.fromJson(response.data['data']);
        await StorageService.to.setString(
            CacheKeys.appConfig, jsonEncode(appConfig.items!),
            isWithUser: false);
        if (appConfig.ver != null) {
          await StorageService.to
              .setString(CacheKeys.ver, appConfig.ver!, isWithUser: false);
        }
      }
    }
  }

  // need token
  Future<void> getossPolicy() async {
    // if (StorageService.to.getString(CacheKeys.token, isWithUser: false) !=
    //     null) {
    //   final response = await Api.getOssPolicy();
    //   if (response.data != null) {
    //     ossPolicy = OssPolicy.fromJson(response.data['data']);
    //   }
    // }
  }

  T getConfigByCode<T>(String code) {
    List<AppConfigItem> items = appConfig.items!;
    dynamic config = items.firstWhereOrNull((element) => element.name == code);
    if (config != null) {
      return config.data as T;
    }
    return '' as T;
  }

  void changeTextScale(bool? value) {
    if (value ?? false) {
      scale(1.2);
    } else {
      scale(1.0);
    }
    isLarge.value = value ?? false;
  }

  Future<void> requestPermission() async {
    // final status = await AppTrackingTransparency.trackingAuthorizationStatus;
    // if (status != TrackingStatus.authorized) {
    //   await Future.delayed(const Duration(seconds: 2));
    //   await AppTrackingTransparency.requestTrackingAuthorization();
    // }
  }
}
