import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get/get_core/src/get_main.dart';
import 'package:project_telephony/extensions/num_ext.dart';
import 'package:project_telephony/ui/login/login_page.dart';

import '../../base/base_style.dart';
import '../../constants/api.dart';
import '../../gen/assets.gen.dart';
import '../../model/network/api_client.dart';
import '../../utils/toast/cloud_toast.dart';
import '../../utils/user_tool.dart';
import '../tab_navigator.dart';
import '../user/content_authority_page.dart';
import '../widget/image_scaffold.dart';
import '../widget/plone_back_button.dart';
import '../widget/plone_bottom.dart';

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

  @override
  _LoginPsdPageState createState() => _LoginPsdPageState();
}

class _LoginPsdPageState extends State<LoginPsdPage> {
  bool _chooseAgreement = false;
  late TextEditingController _phoneController;
  late TextEditingController _pwdController;
  DateTime? _lastTap;
  late bool _showPwd = true;

  @override
  void initState() {
    super.initState();
    _phoneController = TextEditingController();
    _pwdController = TextEditingController();
  }

  @override
  void dispose() {
    _phoneController.dispose();
    _pwdController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    return CloudScaffold(
      systemStyle: const SystemUiOverlayStyle(
        statusBarIconBrightness: Brightness.dark,
      ),
      path: Assets.images.bg.path,
      appbar: Row(
        children: [
          Padding(
            padding: EdgeInsets.only(top: 88.w, left: 8.w),
            child: const CloudBackButton(isSpecial: true),
          ),
          Padding(
              padding: EdgeInsets.only(left: 186.w, top: 88.w),
              child: Text(
                "",
                style: TextStyle(
                    fontSize: BaseStyle.fontSize34,
                    color: BaseStyle.color333333,
                    fontWeight: FontWeight.bold),
              ))
        ],
      ),
      extendBody: true,
      body: Container(
        padding: EdgeInsets.only(left: 64.w, right: 64.w, top: 124.w),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              "短信帮手",
              style: TextStyle(
                  fontSize: 64.sp,
                  fontWeight: FontWeight.bold,
                  color: Colors.black),
            ),
            32.hb,
            Text(
              "希望能成为您的短信小助手",
              style: TextStyle(fontSize: 32.sp, color: const Color(0xFF999999)),
            ),
            80.hb,
            LoginBoxWidget(text: "+86", fontSize: 36, plone: _phoneTFWidget()),
            LoginBoxWidget(text: "密码", fontSize: 32, plone: _pwdWidget()),
            Row(
              children: [
                const Spacer(),
                TextButton(
                  onPressed: () {
                    Get.to(() => const LoginPage());
                  },
                  child: const Text(
                    '验证码登录',
                    style: TextStyle(
                      fontSize: 15,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ),
              ],
            ),
            60.hb,
            PloneBottom(
              blM: false,
              border: _phoneController.text.length != 11,
              opacity: _phoneController.text.length == 11 ? 1 : 0.4,
              onTap: () async {
                // DateTime? _lastTap;
                if (_phoneController.text.length < 11) {
                  BotToast.showText(text: "请输入手机号");
                } else if (!_chooseAgreement) {
                  BotToast.showText(text: "请同意并勾选隐私政策");
                } else {
                  if (_lastTap != null &&
                      DateTime.now().difference(_lastTap!).inSeconds < 2) {
                    // BotToast.showText(text: "过快");
                    return;
                  }
                  _lastTap = DateTime.now();
                  var base = await apiClient.request(API.app.psdLogin, data: {
                    'phone': _phoneController.text,
                    'password': _pwdController.text
                  });
                  if (base.code == 0) {
                    await UserTool.userProvider.setToken(base.data['token']);
                    Get.offAll(const TabNavigator());
                  } else {
                    CloudToast.show(base.msg);

                  }
                }
              },
              text: "立即登录",
            ),
            32.hb,
            _getText()
          ],
        ),
      ),
    );
  }

  _getText() {
    return GestureDetector(
      onTap: () {
        _chooseAgreement = !_chooseAgreement;
        setState(() {});
      },
      child: Row(
        mainAxisSize: MainAxisSize.min,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Container(
            width: 50.w,
            height: 50.w,
            padding: EdgeInsets.only(top: 6.w, right: 5.w),
            child: !_chooseAgreement
                ? const Icon(CupertinoIcons.circle,
                    size: 18, color: Color(0xFFdddddd))
                : const Icon(CupertinoIcons.checkmark_circle,
                    size: 18, color: Colors.blue),
          ),
          RichText(
            text: TextSpan(
              text: "我已阅读并同意",
              style:
                  TextStyle(color: BaseStyle.colorcccccc, fontSize: 12 * 2.sp),
              children: [
                TextSpan(
                    text: '《短信帮手隐私协议》',
                    style: TextStyle(color: kPrimaryColor, fontSize: 12 * 2.sp),
                    recognizer: _recognizer(context, 2)),
              ],
            ),
          ),
        ],
      ),
    );
  }

  _recognizer(context, int type) {
    final TapGestureRecognizer recognizer = TapGestureRecognizer();
    recognizer.onTap = () {
      if (kDebugMode) {
        Get.to(() => const ContentAuthorityPage());
        // print("点击协议了");
      }

      ///跳转到用户协议页面
    };
    return recognizer;
  }

  _phoneTFWidget() {
    return SizedBox(
      // alignment: Alignment.centerLeft,
      // padding: EdgeInsets.symmetric(horizontal: 72.w),
      width: 430.w,
      height: 50.w,
      child: TextField(
        maxLength: 11,
        inputFormatters: [FilteringTextInputFormatter.allow(RegExp(r'[0-9]'))],
        textCapitalization: TextCapitalization.none,
        onChanged: (text) {
          _phoneController.text = text;
          setState(() {});
        },
        decoration: InputDecoration(
          contentPadding: EdgeInsets.only(bottom: 20.w),
          border: InputBorder.none,
          counterText: "",
          //textfield占位语,类似于iOS中的placeholder
          hintText: "请输入手机号",
          //占位语颜色
          hintStyle: const TextStyle(color: Colors.black12),
        ),
      ),
    );
  }

  _pwdWidget() {
    return SizedBox(
      width: 430.w,
      height: 50.w,
      child: TextField(
        obscureText: _showPwd,
        maxLength: 16,
        textCapitalization: TextCapitalization.none,
        onChanged: (text) {
          _pwdController.text = text;
          setState(() {});
        },
        decoration: InputDecoration(
          contentPadding: EdgeInsets.only(bottom: 20.w),
          border: InputBorder.none,
          counterText: "",
          hintText: "请输入密码",
          //占位语颜色
          hintStyle: const TextStyle(color: Colors.black12),
          suffixIcon: IconButton(
            padding: EdgeInsets.zero,
            onPressed: () {
              _showPwd = !_showPwd;
              setState((){});
            },
            icon: Icon(Icons.remove_red_eye,color: _showPwd?Colors.black38:Colors.blue,),
          ),
        ),
      ),
    );
  }
}