part of splash_page;

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

  @override
  State<SplashPage> createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  bool _navigated = false;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _startLaunchFlow();
    });
  }

  Future<void> _startLaunchFlow() async {
    final accepted = await _showPrivacyNoticeIfNeeded();
    if (!accepted) {
      await SystemNavigator.pop();
      return;
    }
    if (!mounted || _navigated) return;

    await Future.delayed(const Duration(seconds: 2));
    if (!mounted || _navigated) return;

    final netStatus = await Tools.checkCurrentNetStatus();
    if (!mounted || _navigated) return;

    if (netStatus) {
      final ads = await CommonAPI.list(type: '1');
      if (!mounted || _navigated) return;
      if (ads.isNotEmpty) {
        _navigated = true;
        context.pushReplacementNamed(Routes.ad, extra: ads);
        return;
      }
    }

    _navigated = true;
    context.pushReplacementNamed(Routes.main);
  }

  Future<bool> _showPrivacyNoticeIfNeeded() async {
    if (StorageService.to.getBool(kLocalPrivacyNoticeShown)) {
      return true;
    }

    final agreed = await showDialog<bool>(
      context: context,
      barrierDismissible: false,
      builder: (dialogContext) {
        return AlertDialog(
          scrollable: true,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          title: const Text(
            '隐私声明',
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 18,
              fontWeight: FontWeight.w600,
              color: Colours.c3,
            ),
          ),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                RichText(
                  text: TextSpan(
                    style: const TextStyle(
                      fontSize: 14,
                      height: 1.6,
                      color: Colours.c6,
                    ),
                    children: [
                      const TextSpan(
                        text: '欢迎使用清控紫荆数智学堂。为保障你的个人信息安全，我们会按照',
                      ),
                      TextSpan(
                        text: '《用户协议》',
                        style: const TextStyle(color: Color(0xFF2A82D9)),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            context.pushNamed(
                              Routes.terms,
                              queryParameters: {
                                'url': kUserAgreement,
                                'title': '用户协议',
                              },
                            );
                          },
                      ),
                      const TextSpan(text: '和'),
                      TextSpan(
                        text: '《隐私政策》',
                        style: const TextStyle(color: Color(0xFF2A82D9)),
                        recognizer: TapGestureRecognizer()
                          ..onTap = () {
                            context.pushNamed(
                              Routes.terms,
                              queryParameters: {
                                'url': kUserPriAgreement,
                                'title': '隐私政策',
                              },
                            );
                          },
                      ),
                      const TextSpan(
                        text: '处理账号信息、设备信息、学习记录等内容。',
                      ),
                    ],
                  ),
                ),
              ],
            ),
          ),
          actions: [
            Row(
              children: [
                Expanded(
                  child: TextButton(
                    onPressed: () {
                      Navigator.of(dialogContext).pop(false);
                    },
                    child: const Text('不同意'),
                  ),
                ),
                Expanded(
                  child: TextButton(
                    onPressed: () async {
                      await StorageService.to
                          .setBool(kLocalPrivacyNoticeShown, true);
                      if (dialogContext.mounted) {
                        Navigator.of(dialogContext).pop(true);
                      }
                    },
                    child: const Text('同意'),
                  ),
                ),
              ],
            ),
          ],
        );
      },
    );

    return agreed ?? false;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        extendBodyBehindAppBar: true,
        // appBar: AppBar(),
        body: SizedBox(
          height: double.infinity,
          width: double.infinity,
          child: Image.asset(
            'assets/images/splash.png',
            fit: BoxFit.cover,
          ),
        )
        // const Column(
        //   crossAxisAlignment: CrossAxisAlignment.stretch,
        //   mainAxisAlignment: MainAxisAlignment.center,
        //   children: [
        //     Expanded(
        //         flex: 5,
        //         child: Center(
        //           child: CustomEmpty(
        //             icon: CustomImage.asset(
        //                 url: 'assets/images/logo.png',
        //                 fit: BoxFit.contain,
        //             ),
        //             title: Text('清控紫荆数智学堂'),
        //           ),
        //         )
        //     ),
        //     // Expanded(
        //     //   flex: 2,
        //     //   child: Center(child: CupertinoActivityIndicator(),),
        //     // )
        //   ],
        // ),
        );
  }
}
