import 'dart:async';
import 'dart:ffi';
import 'package:farmer_client/models/app.dart';
import 'package:farmer_client/pages/home/index.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../models/entities/person.dart';
import '../../services/user.dart';
import '../../widgets/Cell.dart';

class MyRouteLogin extends StatefulWidget {
  @override
  State<MyRouteLogin> createState() => _RouteLogin();
}

class _RouteLogin extends State<MyRouteLogin> {
  var userInfo = AppController.t.user;

  bool isButtonEnable = true; //按钮状态  是否可点击
  String buttonText = '发送验证码'; //初始文本
  int count = 60; //初始倒计时时间
  var timer; //倒计时的计时器
  TextEditingController mController = TextEditingController();

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

  @override
  void initState() {
    super.initState();
    //注册协议的手势

    var location = AppController.t.testInt.value;
    print('--------------');
    print(location);
  }

  @override
  void dispose() {
    timer?.cancel(); //销毁计时器
    timer = null;
    mController.dispose();
    super.dispose();

    ///销毁
  }

  // -------------逻辑分割-------------------------------------------
  var handlePhones = '';
  var handleCodes = '';
  var userContent = {'phones': '', 'code': ''};
  bool _newValue = false;

  void _handlePhone(e) => {
        setState(() => {handlePhones = e})
      };

  void _handleCode(e) => {
        setState(() => {handleCodes = e})
      };

  // 获取验证码
  void _buttonClickListen() {
    setState(() {
      if (isButtonEnable) {
        if (handlePhones != '') {
          isButtonEnable = false; //按钮状态标记
          _initTimer();
          getSMSCaptch(handlePhones);
        } else {
          Fluttertoast.showToast(msg: '请正确输入手机号！');
        }
      }
    });
  }

  //登陆按钮
  void _handelSubmit() {
    if (handleCodes == '' || handlePhones == '') {
      Fluttertoast.showToast(msg: '请输入验证码或手机号！');
    } else {
      if (_newValue) {
        userLogin(handlePhones, handleCodes).then((value) {
          userInfo(Person.fromJson(value['person']));


          Get.off(Home());
        });
      } else {
        Fluttertoast.showToast(msg: '请阅读并同意相关隐私政策！');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.transparent,
      resizeToAvoidBottomInset: false,
      body: Container(
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("images/icon_login.png"),
            fit: BoxFit.cover,
          ),
        ),
        child: Container(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Padding(
                padding: EdgeInsets.fromLTRB(15, 0, 0, 5),
                child: const Text(
                  '您好!',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 33,
                  ),
                ),
              ),
              Padding(
                padding: EdgeInsets.fromLTRB(15, 0, 0, 0),
                child: const Text(
                  '欢迎进入农户端应用!',
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 27,
                  ),
                ),
              ),
              Cell(
                  // margin: EdgeInsets.symmetric(horizontal: 13.w),
                  margin: const EdgeInsets.fromLTRB(13, 43, 10, 0),
                  header: Text(
                    "+86",
                    style: TextStyle(
                      fontSize: 19.sp,
                    ),
                  ),
                  child: TextField(
                    maxLength: 11,
                    keyboardType: TextInputType.number,
                    style: TextStyle(
                      fontSize: 17.sp,
                    ),
                    decoration: const InputDecoration(
                      isCollapsed: true,
                      contentPadding:
                          EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                      labelText: "请输入手机号码",
                      counterText: '', //去掉计数
                      border: InputBorder.none,
                      floatingLabelBehavior: FloatingLabelBehavior.never,
                    ),
                    onChanged: (e) {
                      _handlePhone(e);
                    },
                  ),
                  footer: SizedBox(
                    child: ElevatedButton(
                      onPressed: () => {
                        setState(() {
                          _buttonClickListen();
                        })
                      },
                      child: Text(
                        '$buttonText',
                        style: TextStyle(
                          fontSize: 15.sp,
                        ),
                      ),
                      style: ButtonStyle(
                        backgroundColor: isButtonEnable
                            ? MaterialStateProperty.all(const Color(0xFFFF703B))
                            : MaterialStateProperty.all(
                                const Color(0xFFCBCBCB)),
                        shape: MaterialStateProperty.all(
                            const RoundedRectangleBorder(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(10)))),
                      ),
                    ),
                  )),
              Cell(
                // margin: EdgeInsets.symmetric(horizontal: 13.w),
                margin: const EdgeInsets.fromLTRB(13, 16, 10, 0),

                header: Align(
                  alignment: FractionalOffset(0.1, 0.5),
                  child: Image.asset(
                    'images/phoneCode.png',
                    width: 20,
                    height: 20,
                  ),
                ),

                child: TextField(
                  keyboardType: TextInputType.number,
                  style: TextStyle(
                    fontSize: 17.sp,
                  ),
                  decoration: const InputDecoration(
                    isCollapsed: true,
                    contentPadding:
                        EdgeInsets.symmetric(vertical: 8, horizontal: 16),
                    labelText: "请输入验证码",
                    border: InputBorder.none,
                    floatingLabelBehavior: FloatingLabelBehavior.never,
                  ),
                  onChanged: (e) {
                    _handleCode(e);
                  },
                ),
              ),
              Container(
                height: 350.h,
                alignment: Alignment.bottomCenter,
                child: SizedBox(
                  width: 315.w,
                  height: 49.h,
                  child: ElevatedButton(
                    onPressed: () {
                      _handelSubmit();
                    },
                    child: const Text(
                      "登陆",
                      style: TextStyle(
                          fontSize: 18,
                          color: Colors.white,
                          fontWeight: FontWeight.bold),
                    ),
                    style: ButtonStyle(
                      elevation: MaterialStateProperty.all(0),
                      backgroundColor:
                          MaterialStateProperty.all(const Color(0xFFFF703B)),
                      shape: MaterialStateProperty.all(
                          const RoundedRectangleBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(24.4)))),
                    ),
                  ),
                ),
              ),
              Container(
                  padding: EdgeInsets.fromLTRB(10.0, 10, 10.0, 10),
                  child: Row(
                    children: <Widget>[
                      Radio<bool>(
                          value: true,
                          activeColor: Color(0xFFFF703B),
                          groupValue: _newValue,
                          onChanged: (value) {
                            setState(() {
                              _newValue = value!;
                            });
                          }),
                      RichText(
                        text: TextSpan(children: <InlineSpan>[
                          const TextSpan(
                              text: '请认真查看',
                              style: TextStyle(color: Color(0xff2a2a2a))),
                          TextSpan(
                            text: '文本协议/隐私政策，',
                            style: TextStyle(color: Color(0xffce3800)),
                            recognizer:
                                TapGestureRecognizer() //踩坑。。。recognizer 是手势交互 除了我现在些的是 点击交互，其他一般都是抽象类。
                                  ..onTap = () {
                                    Get.toNamed('/agreement');
                                  },
                          ),
                          const TextSpan(
                              text: '确认之后选择此项',
                              style: TextStyle(color: Color(0xff2a2a2a))),
                        ]),
                      ),
                    ],
                  )),
            ],
          ),
        ),
      ),
    );
  }
}
