import 'dart:io';
import 'package:elysia/page/HomePage.dart';
import 'package:flutter/material.dart';
import 'package:package_info_plus/package_info_plus.dart';
import 'package:path_provider/path_provider.dart';

import '../plugin/C.dart';
import '../plugin/HTTP.dart';
import '../plugin/HiverCache.dart';
import '../plugin/Notify.dart';
import 'LoginPage.dart';
import '../plugin/WebSocketService.dart';

class LoadingPage extends StatefulWidget {
  @override
  _LoadingPageState createState() => _LoadingPageState();
}

class _LoadingPageState extends State<LoadingPage> {
  @override
  void initState() {
    super.initState();
    _clearUpdateCache();
    checkAuthToken();
  }

  Future<void> _getVersionInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    try {
      dynamic json = await HTTP
          .create("${C.BASE_URL}/server/latest-version")
          .execute();
      int currentCode = int.tryParse(packageInfo.buildNumber) ?? 99999999;
      if (json["code"] != 200) {
      } else {
        bool _hasUpdate =
            int.parse(json["data"]["versionCode"].toString()) > currentCode;
        if (_hasUpdate) {
          Notify.showNotification(
            channel: NotifyChannel.update,
            title: "发现新版本：${json["data"]["version"].toString()}",
            body: json["data"]["updateInfo"].toString(),
            payload: {"type": C.NOTIFY_VERSION},
          );
        }
      }
    } catch (_) {}
  }

  Future<void> checkAuthToken() async {
    final appDocDir = await getApplicationDocumentsDirectory();
    final configDir = Directory('${appDocDir.path}/config');
    final file = File('${configDir.path}/auth.token');

    // 确保目录存在
    if (!await configDir.exists()) {
      await configDir.create(recursive: true);
    }
    if (!await file.exists()) {
      // 跳转到登录页
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (_) => LoginPage()),
      );
    } else {
      C.TOKEN = {"Authorization": await file.readAsString()};
      // 跳转到首页
      dynamic result = await HTTP
          .create('${C.BASE_URL}/authorization/profile')
          .setHeader(C.TOKEN)
          .setContentType(ContentType.json)
          .setRequestType(RequestType.POST)
          .execute();
      if (result['code'] == 200) {
        C.PROFILE = result['data'];
        C.socket = WebSocketService();
        C.socket.init();
        await C.socket.connect(
          "${C.BASE_WS_URL}/socket/chat?authorization=${C.TOKEN["Authorization"].toString().replaceAll(" ", "%20")}",
        );
        await HiverCache.init(result["data"]["userName"]);
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (_) => HomePage()),
        );
      } else {
        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (_) => LoginPage()),
        );
      }
    }
  }

  Future<void> _clearUpdateCache() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    int code = int.tryParse(packageInfo.buildNumber) ?? 0;
    final savePath = await _getLocalFilePath(code);
    final file = File(savePath);
    if (await file.exists()) {
      await file.delete();
    }
  }

  Future<String> _getLocalFilePath(int code) async {
    final directory = await getTemporaryDirectory();
    String path = '${directory.path}/download/';
    final Directory folder = Directory(path);
    if (!(await folder.exists())) {
      await folder.create(recursive: true);
    }
    return '${directory.path}/download/$code.apk';
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: Center(child: CircularProgressIndicator()));
  }
}
