import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:odf/network/NetworkConfig.dart';
import 'package:odf/tools/login/login_model.dart';
import 'package:shared_preferences/shared_preferences.dart';

import '../common/Global.dart';

class StartPage extends StatefulWidget {
  const StartPage({super.key});

  @override
  State<StartPage> createState() => _StartPageState();
}

class _StartPageState extends State<StartPage> {
  late StreamSubscription subscription;

  final LoginModel _viewmodel = LoginModel();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    subscription = _viewmodel.streamController.stream.listen((newData) {
      String code = newData['code'];
      if (code.isNotEmpty) {
        switch (code) {
          case "odf":
            Navigator.pushReplacementNamed(context, "/HomePage");
            break;
          case "login":
            Navigator.pushReplacementNamed(context, "/LoginPage");
            break;
          default:
            Navigator.pushReplacementNamed(context, "/LoginPage");
            break;
        }
      }
    });

    _loadData();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    subscription.cancel();
    super.dispose();
  }

  Future<void> _loadData() async {
    final SharedPreferences prefs = await SharedPreferences.getInstance();
    NetworkConfig.token = prefs.getString('token') ?? ""; //token
    print("token=${NetworkConfig.token}");
    if (NetworkConfig.token != "") {
      _viewmodel.odf();
    } else {
      Navigator.pushReplacementNamed(context, "/LoginPage");
    }
  }

  @override
  Widget build(BuildContext context) {
    return const Stack(
      alignment: Alignment.center,
      children: [
        Text("光缆资源管理"),
      ],
    );
  }

  // 获取原生的值
  invokeNativeMethod(String method, Map<String, dynamic> map) async {
    dynamic args;
    try {
      args = await Global.method.invokeMethod(method, map);
    } on PlatformException {}
  }
}
