
// 初始化界面
import 'dart:ffi';

import 'package:flutter/material.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import '../basic/Method.dart';
import '../basic/Test.dart';
import 'AppScreen.dart';
import 'LoginScreen.dart';
import '../basic/Global.dart' as glob;
import '../basic/Encrypt.dart';

class InitScreen extends StatefulWidget {
  const InitScreen({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _InitScreenState();
}

class _InitScreenState extends State<InitScreen> {
  var _authenticating = false;

  @override
  initState() {
    _init();
    super.initState();
  }

  Future<dynamic> _init() async {
    encryptTest();
    await glob.init();
    await method.init();
    if (_authenticating) {
      _goAuthentication();
    } else {
      _goApplication();
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_authenticating) {
      return Scaffold(
        appBar: AppBar(
          title: const Text("身份验证"),
        ),
        body: Center(
          child: Container(
            padding: const EdgeInsets.all(20),
            child: MaterialButton(
              onPressed: () {
                _goAuthentication();
              },
              child:
              const Text('您在之前使用APP时开启了身份验证, 请点这段文字进行身份核查, 核查通过后将会进入APP'),
            ),
          ),
        ),
      );
    }
    return const Scaffold(
      backgroundColor: Colors.white,
      /*body: ConstrainedBox(
        constraints: const BoxConstraints.expand(),
        child: Image.asset(
          "lib/assets/init.jpg",
          fit: BoxFit.contain,
        ),
      ),*/
    );
  }

  Future _goApplication() async {
    // 登录, 如果token失效重新登录, 网络不好的时候可能需要1分钟
    // Todo: 直接进入AppScreen
    if (await method.authorized) {
      // 如果token或username+password有效则直接进入登录好的界面
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => const AppScreen()),
      );
    } else {
      // 否则跳转到登录页
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => const LoginScreen()),
      );
    }
  }

  Future _goAuthentication() async {
    _goApplication();
  }
}
