import 'dart:convert';

import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_book/services/index.dart';
import 'package:flutter_book/store/index.dart';
import 'package:flutter_book/utils/index.dart';
import 'package:get/get.dart';

import 'apis/index.dart';
class Global {
  static Future<void> init() async {
    // 确保 Flutter 绑定已经初始化
    WidgetsFlutterBinding.ensureInitialized();
    // 设置应用程序的首选屏幕方向
    await SystemChrome.setPreferredOrientations([DeviceOrientation.portraitUp]);
    // 初始化数据库
    SqlManager.init();
    // 检测网络变化
    Connectivity().onConnectivityChanged.listen((ConnectivityResult result) {
      Console.log('网络变化--------------------------------$result');
      if(result !=ConnectivityResult.none && UserStore.to.isLogin){
        upload();
      }
    });
    // 监测app生命周期
    // WidgetsBinding.instance?.addObserver(AppLifecycleObserver());

    await Future.wait([
      // 配置存储
      Get.putAsync<StorageService>(() => StorageService().init()),
    ]).whenComplete(() {

      // 网络
      Get.put<HttpService>(HttpService());
      //配置基本设置
      Get.put<ConfigStore>(ConfigStore());
      //
      Get.put<UserStore>(UserStore());

    });
  }

  static void upload() async{
    List<Map<String, dynamic>> data = await SqlManager.queryNoUploadData();
    List<Map<String, dynamic>> finalData = List<Map<String, dynamic>>.from(data);
    Console.log('Sql-----查询到的数据-----------------------$data');
    if(data.isNotEmpty){
      for (int i = 0; i < data.length; i ++){
        Map<String, dynamic> temp = data[i];
        // for (Map<String, dynamic> temp in data){

        // 如果是笔记
        if (temp['types'] == 3){
          // 存储url的数组
          List<String> finalAudios = [];
          // 存储url的数组
          List<String> finalImages = [];

          Map<String,dynamic> contentMap =  jsonDecode(temp['note_content']);
          List<dynamic> audios = contentMap['audio'];
          if(audios.isNotEmpty){
            for(String path in audios){
              final url = await uploadSource(path: path);
              finalAudios.add(url);
            }
          }
          List<dynamic> images = contentMap['image'];
          if(images.isNotEmpty){
            for(String path in images){
              final url = await uploadSource(path: path);
              finalImages.add(url);
            }
          }
          Map<String,dynamic> finalContentMap = {
            'text':contentMap['text'],
            'audio': finalAudios,
            'image': finalImages
          };
          finalData[i] = Map<String,dynamic>.from(temp);
          finalData[i]['note_content'] = jsonEncode(finalContentMap);
        }
      }
      String noteStr = jsonEncode(finalData);
      final result = await LibraryAPI.uploadOffline(node: noteStr);
      // 上传成功后 更新数据库中的字段
      if (result.isNotEmpty) {
        // SqlManager.updateUploadStatus();
        SqlManager.updateNotesId(result);
      }
    }

  }
  // 上传文件
  static Future<String> uploadSource({
    required String path
  }) async {
    // String result  = await CommonAPI.upload(path:path,fileTypes: 'comment');
    // return result;
    OssTool tool = OssTool('zxts-comment-file');
    final response = await tool.putObjectFile(path);
    Console.log('------response--------------------------${response.realUri}');
    return response.realUri.toString();
  }

}

/// 生命周期类
class AppLifecycleObserver extends WidgetsBindingObserver {
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    if (state == AppLifecycleState.paused || state == AppLifecycleState.detached) {
      SqlManager.closeDatabase(); // 应用进入后台时关闭数据库连接
    }
  }
}