// ignore_for_file: use_build_context_synchronously

import 'dart:convert';

import 'package:encrypt/encrypt.dart' as encrypt;
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:pointycastle/asymmetric/api.dart';
import 'package:qhd_prevention/tools/AESEncryption.dart';
import 'package:qhd_prevention/tools/tools.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'http/ApiService.dart';
import 'http/HttpManager.dart';
import 'main_tab.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '登录页面',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        inputDecorationTheme: const InputDecorationTheme(
          border: InputBorder.none,
          contentPadding: EdgeInsets.symmetric(horizontal: 8),
        ),
      ),
      home: const LoginPage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

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

  @override
  // ignore: library_private_types_in_public_api
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _phoneController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  // final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
  String _errorMessage = '';
  bool _isLoading = false;
  bool _obscurePassword = true;


  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _phoneController.text="15600000001";
    _passwordController.text="Tsaq@123456";
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Column(
          children: [
            _buildHeader(),

            Transform.translate(
              offset: const Offset(0, -20),
              child: Container(
                decoration: const BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.only(
                    topLeft: Radius.circular(30),
                    topRight: Radius.circular(30),
                  ),
                ),
                child: Padding(
                  padding: const EdgeInsets.only(top: 30),
                  child: Column(
                    children: [
                      // 手机号
                      _buildInputSection(
                        label: "手机号码",
                        controller: _phoneController,
                        hintText: "请输入手机号...",
                        keyboardType: TextInputType.phone,
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return '请输入手机号';
                          }
                          if (!RegExp(r'^1[3-9]\d{9}$').hasMatch(value)) {
                            return '请输入有效的手机号';
                          }
                          return null;
                        },
                      ),

                      Padding(padding: const EdgeInsets.symmetric(horizontal: 25),
                        child: const Divider(height: 1, thickness: 1),
                      ),
                      // 密码
                      _buildInputSection(
                        label: "密码",
                        controller: _passwordController,
                        hintText: "请输入密码...",
                        obscureText: _obscurePassword,
                        suffixIcon: IconButton(
                          icon: Icon(
                            _obscurePassword
                                ? Icons.visibility
                                : Icons.visibility_off,
                            color: Colors.grey,
                          ),
                          onPressed: () {
                            setState(() {
                              _obscurePassword = !_obscurePassword;
                            });
                          },
                        ),
                        validator: (value) {
                          if (value == null || value.isEmpty) {
                            return '请输入密码';
                          }
                          if (value.length < 6) {
                            return '密码长度至少6位';
                          }
                          return null;
                        },
                      ),
                      Padding(padding: const EdgeInsets.symmetric(horizontal: 25),
                      child: const Divider(height: 1, thickness: 1),
                      ),
                      // 登录按钮
                      Padding(
                        padding: const EdgeInsets.symmetric(
                            horizontal: 25, vertical: 24),
                        child: SizedBox(
                          width: double.infinity,
                          height: 48,
                          child: ElevatedButton(
                            onPressed: _isLoading ? null : _handleLogin,
                            style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.blue,
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(8),
                              ),
                            ),
                            child: _isLoading
                                ? const CircularProgressIndicator(
                              color: Colors.white,
                            )
                                : const Text(
                              '登录',
                              style: TextStyle(
                                fontSize: 18,
                                color: Colors.white,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ),
                        ),
                      ),
                      Padding(padding: const EdgeInsets.only(left: 30, right: 30),
                          child:Text("     本平台为互联网非涉密平台，严禁处理、传输国家秘密和工作秘密",
                              style: TextStyle(color: Colors.red))
                          )
                    ],
                  ),
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 顶部图片和文字
  Widget _buildHeader() {
    return Stack(
      alignment: Alignment.center,
      children: [
        Image.asset(
          'assets/images/login-bg.png',
          width: double.infinity,
          fit: BoxFit.fitWidth,
        ),
        Positioned(
          bottom: 40,
          left: 30,
          child: Column(
            children: [
              const Text(
                '欢迎登录',
                style: TextStyle(
                  fontSize: 28,
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                  shadows: [
                    Shadow(
                      blurRadius: 10,
                      color: Colors.black45,
                      offset: Offset(2, 2),
                    ),
                  ],
                ),
              ),
              const SizedBox(height: 8),
              Text(
                '秦皇岛市应急管局\n数智应急管理平台',
                style: TextStyle(fontSize: 18, color: Colors.white),
              ),
            ],
          ),
        ),
      ],
    );
  }
  // 输入区域组件
  Widget _buildInputSection({
    required String label,
    required TextEditingController controller,
    required String hintText,
    bool obscureText = false,
    TextInputType keyboardType = TextInputType.text,
    Widget? suffixIcon,
    String? Function(String?)? validator,
  }) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 12),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            label,
            style: const TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.w500,
              color: Colors.black87,
            ),
          ),
          const SizedBox(height: 15),
          TextFormField(
            controller: controller,
            obscureText: obscureText,
            keyboardType: keyboardType,
            validator: validator,
            // 关键属性：让文字在行内垂直居中
            textAlignVertical: TextAlignVertical.center,
            decoration: InputDecoration(
              hintText: hintText,
              suffixIcon: suffixIcon,
              // 去掉默认的上下/左右 padding，让文字贴紧外层的 25 左边距
              isDense: true,
              contentPadding: EdgeInsets.zero,
            ),
          ),
        ],
      ),
    );
  }


  // 登录处理
  Future<void> _handleLogin() async {

    // Navigator.pushReplacement(
    //   context,
    //   MaterialPageRoute(builder: (_) => const MainPage()),
    // );

    // 表单校验
    // if (!(_formKey.currentState?.validate() ?? false)) return;

    final userName = _phoneController.text.trim();
    final userPwd = _passwordController.text;


    ///aes加密
    final userNameMi = aesEncryptEcbPkcs5(plainText: userName,);
    print('userNameMi: $userNameMi');
    final userPwdMi = aesEncryptEcbPkcs5(plainText: userPwd,);
    print('userNameMi: $userPwdMi');


    // // RSA 加密：encrypt 包的用法
    // final parser = encrypt.RSAKeyParser();
    // final pub = parser.parse(ApiService.publicKey) as RSAPublicKey;
    // final encrypter = encrypt.Encrypter(encrypt.RSA(publicKey: pub));
    // final plain = 'zcloudchina$userName,zy,$userPwd';
    //
    // String keydataVal;
    // try {
    //   keydataVal = encrypter.encrypt(plain).base64;
    // } catch (e) {
    //   Fluttertoast.showToast(msg: '加密失败：$e', toastLength: Toast.LENGTH_LONG);
    //   return;
    // }
    try {
    setState(() => _isLoading = true);
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (_) => const Center(child: CircularProgressIndicator()),
    );

      final data = await ApiService.loginCheck(userNameMi,userPwdMi);
      final result = data['result'] as String? ?? '';

      if (result == 'success') {
        final token = data['token'] as String? ?? '';
        SessionService.instance.setToken(token);
        SessionService.instance.setPhone(userName);
        final dataUser = await ApiService.getUserInfo();
        final resultUser = dataUser['result'] as String? ?? '';
        if(resultUser == 'success'){
          // 存储用户信息

          SessionService.instance.setUsername(dataUser['data']['name'] as String);

          Navigator.of(context).pop(); // 关 loading
          setState(() => _isLoading = false);
            Navigator.pushReplacement(
              context,
              MaterialPageRoute(builder: (_) => const MainPage()),
            );

        }

      } else {
        // 理论上不会走这里，非 'success' 会抛 ApiException
      }

    } on ApiException catch (e) {
      // 业务错误：
      Navigator.of(context).pop();
      setState(() => _isLoading = false);

      String tip = e.message;

      Fluttertoast.showToast(msg: tip, toastLength: Toast.LENGTH_LONG);

    } catch (e) {
      // 网络或其它未预期错误
      Navigator.of(context).pop();
      setState(() => _isLoading = false);
      Fluttertoast.showToast(
        msg: '服务器正在升级，请稍后再试。\n${e.toString()}',
        toastLength: Toast.LENGTH_LONG,
      );
    }
  }


}
