import 'dart:async';

import 'package:flutter/gestures.dart';
import 'package:worker_client/models/app.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:worker_client/widgets/Cell.dart';
import 'package:worker_client/widgets/GradientButton.dart';
import 'package:worker_client/widgets/MyButton/index.dart';
import '../../models/entities/person.dart';
import '../../services/user.dart';

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

  @override
  State<Login> createState() => _Login();
}

const String checkedImg = 'images/login/checkedImg.png';
const String unCheckedImg = 'images/login/unChecked.png';

class _Login extends State<Login> {
  var userInfo = AppController.t.user;
  @override
  void initState() {
    super.initState();
  }

  String phone = '';
  RegExp exp = RegExp(r'^1[3456789]\d{9}$');
  var timer;

  String qCode = '';
  String qCodeText = '获取验证码';
  bool disableQcode = false;

  bool isCheck = false;

  bool disableLogin = false;

  void setPhone(e) {
    setState(() {
      phone = e;
    });
  }

  void initTimer() {
    int count = 60;
    timer = Timer.periodic(const Duration(seconds: 1), (Timer timer) {
      count--;
      setState(() {
        if (count == 0) {
          timer.cancel(); //倒计时结束取消定时器
          disableQcode = false; //按钮可点击
          count = 60; //重置时间
          qCodeText = '获取验证码'; //重置按钮文本
        } else {
          qCodeText = '$count s后重发'; //更新文本内容
        }
      });
    });
  }

  void handleQCode() {
    if (exp.hasMatch(phone)) {
      disableQcode = true;
      initTimer();
      getSMSCaptch(phone);
    } else {
      Fluttertoast.showToast(msg: '请输入正确的手机号！');
    }
  }

  void handleLogin() {
    if (isCheck) {
      if (qCode != '') {
        if (exp.hasMatch(phone)) {
          setState(() {
            disableLogin = true;
          });
          userLogin(phone, qCode).then((res) {
            userInfo(Person.fromJson(res['person']));
            Fluttertoast.showToast(msg: '登录成功！');
            Get.offNamed('/home');
          }).catchError((err) {
            Fluttertoast.showToast(msg: err);
          });
        } else {
          Fluttertoast.showToast(msg: '请输入正确的手机号');
        }
      } else {
        Fluttertoast.showToast(msg: '请输入手机短信验证码');
      }
    } else {
      Fluttertoast.showToast(msg: '请确认文本协议');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: SafeArea(
        child: Container(
            padding: EdgeInsets.all(15.w),
            decoration: const BoxDecoration(
              image: DecorationImage(
                image: AssetImage("images/login/loginImg.png"),
                fit: BoxFit.cover,
              ),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                SizedBox(
                  height: 44.w,
                  child: Center(
                    child: Text(
                      '登录',
                      style: TextStyle(
                        letterSpacing: 3,
                        fontWeight: FontWeight.bold,
                        color: const Color(0xFF333333),
                        fontSize: 17.sp,
                      ),
                    ),
                  ),
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(0, 49.h, 0, 22.h),
                  child: Text(
                    '您好!',
                    style: TextStyle(
                      letterSpacing: 3,
                      fontWeight: FontWeight.bold,
                      fontSize: 33.sp,
                      color: const Color(0xFF333333),
                    ),
                  ),
                ),
                Text(
                  '欢迎进入农机手端小程序！',
                  style: TextStyle(
                    letterSpacing: 3,
                    fontWeight: FontWeight.bold,
                    fontSize: 27.sp,
                    color: const Color(0xFF333333),
                  ),
                ),
                Cell(
                  margin: EdgeInsets.fromLTRB(0, 43.h, 0, 16.h),
                  header: Text(
                    "+86",
                    style: TextStyle(
                      fontWeight: FontWeight.w500,
                      fontSize: 19.sp,
                      color: const Color(0xFF333333),
                    ),
                  ),
                  child: TextField(
                    maxLength: 11,
                    //数字文本框
                    keyboardType: TextInputType.number,
                    style: TextStyle(
                      fontSize: 17.sp,
                    ),
                    decoration: InputDecoration(
                      isCollapsed: true,
                      contentPadding: EdgeInsets.symmetric(
                          horizontal: 15.5.w, vertical: 19.h),
                      labelText: "请输入手机号码",
                      counterText: '', //去掉右下角的东西
                      border: InputBorder.none,
                      floatingLabelBehavior: FloatingLabelBehavior.never,
                    ),
                    onChanged: (val) {
                      setPhone(val);
                    },
                  ),
                  footer: SizedBox(
                    width: 108.w,
                    height: 34.h,
                    child: GradientButton(
                        colors: const [
                          Color(0xFFA0E067),
                          Color(0xFF00AE39),
                        ],
                        borderRadius: BorderRadius.all(Radius.circular(10.w)),
                        onPressed: disableQcode ? null : handleQCode,
                        child: Text(
                          qCodeText,
                          style: TextStyle(
                            fontSize: 15.sp,
                            fontWeight: FontWeight.bold,
                          ),
                        )),
                  ),
                ),
                Cell(
                    header: Padding(
                      padding: EdgeInsets.fromLTRB(9.5.w, 0, 0, 0),
                      child: Stack(
                        children: [
                          Positioned(
                            child: Image.asset(
                              "images/login/VerificationCode.png",
                              width: 20.w,
                              height: 20.w,
                            ),
                          ),
                        ],
                      ),
                    ),
                    child: TextField(
                      maxLength: 11,
                      //数字文本框
                      keyboardType: TextInputType.number,
                      style: TextStyle(
                        fontSize: 17.sp,
                      ),
                      decoration: InputDecoration(
                        isCollapsed: true,
                        contentPadding: EdgeInsets.symmetric(
                            horizontal: 15.5.w, vertical: 19.h),
                        labelText: "请输入验证码",
                        counterText: '', //去掉右下角的东西
                        border: InputBorder.none,
                        floatingLabelBehavior: FloatingLabelBehavior.never,
                      ),
                      onChanged: (val) {
                        setState(() {
                          qCode = val;
                        });
                      },
                    )),
                //找到了 下面就是置底
                const Spacer(),
                Center(
                  child: MyButton(
                      text: '登录',
                      type: 0,
                      disable: disableLogin,
                      onClick: handleLogin),
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(0, 21.h, 0, 0),
                  child: GestureDetector(
                    onTap: () {
                      setState(() {
                        isCheck = !isCheck;
                      });
                    },
                    child: Row(
                      children: <Widget>[
                        Padding(
                          padding: EdgeInsets.fromLTRB(0, 0, 5.5.w, 0),
                          child: GestureDetector(
                            onTap: () {
                              setState(() {
                                isCheck = !isCheck;
                              });
                            },
                            child: Image.asset(
                              isCheck ? checkedImg : unCheckedImg,
                              width: 14.h,
                              height: 14.h,
                            ),
                          ),
                        ),
                        RichText(
                          text: TextSpan(
                            children: <InlineSpan>[
                              TextSpan(
                                text: '请认真查看',
                                style: TextStyle(
                                  color: const Color(0xFF999999),
                                  fontSize: 13.sp,
                                ),
                              ),
                              TextSpan(
                                  text: '文本协议/隐私政策',
                                  style: TextStyle(
                                    color: const Color(0xFF02902E),
                                    fontSize: 13.sp,
                                  ),
                                  //给span添加点击事件厉害
                                  recognizer: TapGestureRecognizer()
                                    ..onTap = () {
                                      print(999);
                                    }),
                              TextSpan(
                                text: '，确认之后选择此项！',
                                style: TextStyle(
                                  color: const Color(0xFF999999),
                                  fontSize: 13.sp,
                                ),
                              ),
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ],
            )),
      ),
    );
  }
}
