
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:bot_toast/bot_toast.dart';

import 'package:twong/api/index.dart';
import 'package:twong/config/protocols.dart';
import 'package:twong/config/style.dart';
import 'package:twong/router/base.dart';
import 'package:twong/utils/index.dart';
import 'package:twong/widgets/counter_botton.dart';

class LoginPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _LoginPageState();
  }
}

class _LoginPageState extends State<LoginPage> {
  var _enable = true;
  final _max = 60;
  var _counter;
  Timer _timer;
  var _codeTxt = "获取验证码";
  FocusNode _codeNode = FocusNode();
  FocusNode _accountNode = FocusNode();
  FocusNode _passwordNode = FocusNode();
  FocusNode _rePasswordNode = FocusNode();
  PageController _pageController = PageController();
  TextEditingController _codeCtl = TextEditingController();
  TextEditingController _accountCtl = TextEditingController();
  TextEditingController _passwordCtl = TextEditingController();
  TextEditingController _rePasswordCtl = TextEditingController();

  _onLogin(String value) {
    var account = _accountCtl.text;
    var password = _passwordCtl.text;
    if(account.trim() == "" || password.trim() == "") {
      return;
    }

    Network.inst.login(account: account, password: password).then((value) {
      Cache.updateAccount(account, password);
      Navigator.pop(context);
      BotToast.showText(text: "登陆成功!");
    }).catchError((err) {
      Log.e(err);
      BotToast.showText(text: err.toString());
    });
  }

  bool _onGetCode() {
    if(_accountCtl.text.trim() == "") {
      BotToast.showText(text: "手机号不能为空");
      return false;
    }

    return true;
  }

  _onSmsLogin(String value) {

  }

  _onRegister(String value) {

  }

  _onNextInput(String value) {
    FocusScope.of(context).requestFocus(_passwordNode);
  }

  wechatLogin () {
    Utils.notOpen();
  }

  Widget _buildInput(String hit, FocusNode node, TextEditingController controller,
      TextInputAction action, Function(String) onSubmit, IconData icon,
      {bool password = false, TextInputType type}) {
    return TextField(
      focusNode: node,
      obscureText: password,
      onSubmitted: onSubmit,
      controller: controller,
      keyboardType: type,
      style: TextStyle(color: Colors.white),
      textInputAction: action,
      cursorColor: Colors.white,
      decoration: InputDecoration(
        filled: true,
        hintText: hit,
        border: InputBorder.none,
        hintStyle: TextStyle(color: Colors.white70),
        enabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Color(0x00FF00a0)),
          borderRadius: BorderRadius.all(
            Radius.circular(100),
          ),
        ),
        focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Color(0x000000a0)),
          borderRadius: BorderRadius.all(
            Radius.circular(100),
          ),
        ),
        contentPadding: EdgeInsets.all(10.px),
        prefixIcon: Icon(icon, color: Colors.white),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    if(_timer != null) {
      _timer.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
            image: DecorationImage(
              fit: BoxFit.cover,
              image: AssetImage('assets/images/launcher.png'),
            )
        ),
        child: SafeArea(
          child: Column(
            children: <Widget>[
              Container(
                alignment: Alignment.topRight,
                child: FlatButton(
                    highlightColor: Colors.transparent,
                    child: Text('跳过，看好货 >',
                        style: TextStyle(color: Colors.white)
                    ),
                    onPressed: () {
                      Navigator.pop(context);
                    }
                ),
              ),
              Container(
                height: 100.px,
                margin: EdgeInsets.only(bottom: 50.px, top: 10.px),
                child: Center(
                  child: Image.asset("assets/images/logo.png"),
                ),
              ),
              Container(
                height: 368.px,
                margin: EdgeInsets.only(left: 12.px, right: 12.px),
                child: PageView(
                  controller: _pageController,
                  physics: NeverScrollableScrollPhysics(),
                  children: [
                    _buildLogin(),
                    _buildRegister(),
                    _buildSMSLogin()
                  ],
                ),
              ),
              Expanded(child: _buildOtherLogin()),
              _buildBottom()
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildLogin() {
    return Column(
      children: [
        Container(
          margin: EdgeInsets.only(bottom: 12.px),
          child: _buildInput("请输入您的手机号", _accountNode, _accountCtl,
              TextInputAction.next,_onNextInput, Icons.account_circle,
              type: TextInputType.phone),
        ),
        _buildInput("请输入您的密码", _passwordNode, _passwordCtl,
            TextInputAction.done, _onLogin, Icons.lock, password: true,
            type: TextInputType.text),
        Container(
          height: 50.px,
          width: double.infinity,
          margin: EdgeInsets.only(left: 56.px, right: 56.px),
          padding: EdgeInsets.only(top: 12.px),
          child: FlatButton(
            color: Colors.white,
            shape: StadiumBorder(),
            onPressed: () { _onLogin(_accountCtl.text); },
            child: Text('登 陆', style: TextStyle(fontSize: 16.px)),
          ),
        ),
        Container(
          margin: EdgeInsets.only(bottom: 22.px),
          child: Row(
            children: [
              Container(
                child: FlatButton(
                    highlightColor: Colors.transparent,
                    child: Text('验证码登陆', style: TextStyle(color:
                    Colors.white, decoration: TextDecoration.underline)),
                    onPressed: () { _jumpTo(2); }),
              ),
              Spacer(),
              Container(
                child: FlatButton(
                    highlightColor: Colors.transparent,
                    child: Text('没有账号？去注册', style: TextStyle(color:
                    Colors.white, decoration: TextDecoration.underline)),
                    onPressed: () { _jumpTo(1); }),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildRegister() {
    return Column(
      children: [
        Container(
          margin: EdgeInsets.only(bottom: 12.px),
          child: _buildInput("请输入您的手机号", _accountNode, _accountCtl,
              TextInputAction.next,_onNextInput, Icons.account_circle,
              type: TextInputType.phone),
        ),
        Row(
          children: [
            Expanded(child: Container(
              margin: EdgeInsets.only(right: 12.px, bottom: 12.px),
              child: _buildInput("请输入短信验证码", _codeNode, _codeCtl,
                  TextInputAction.done, _onNextInput, Icons.sms,
                  type: TextInputType.number),
            )),
            CounterButton(onClick: _onGetCode)
          ],
        ),
        Container(
          margin: EdgeInsets.only(bottom: 12.px),
          child: _buildInput("请输入您的密码", _passwordNode, _passwordCtl,
              TextInputAction.done, _onLogin, Icons.lock, password: true,
              type: TextInputType.text),
        ),
        _buildInput("请再次输入您的密码", _rePasswordNode, _rePasswordCtl,
            TextInputAction.done, _onLogin, Icons.lock_outline, password: true,
            type: TextInputType.text),
        Container(
          height: 50.px,
          width: double.infinity,
          margin: EdgeInsets.only(left: 56.px, right: 56.px),
          padding: EdgeInsets.only(top: 12.px),
          child: FlatButton(
            color: Colors.white,
            shape: StadiumBorder(),
            onPressed: () { _onRegister(_accountCtl.text); },
            child: Text('注 册', style: TextStyle(fontSize: 16.px)),
          ),
        ),
        Container(
          margin: EdgeInsets.only(bottom: 22.px),
          child: Row(
            children: [
              Container(
                child: FlatButton(
                    highlightColor: Colors.transparent,
                    child: Text('验证码登陆', style: TextStyle(color:
                    Colors.white, decoration: TextDecoration.underline)),
                    onPressed: () { _jumpTo(2); }),
              ),
              Spacer(),
              Container(
                child: FlatButton(
                    highlightColor: Colors.transparent,
                    child: Text('已有账号？去登陆', style: TextStyle(color:
                    Colors.white, decoration: TextDecoration.underline)),
                    onPressed: () { _jumpTo(0); }),
              ),
            ],
          ),
        ),
      ],
    );
  }

  Widget _buildSMSLogin() {
    return Column(
      children: [
        Container(
          margin: EdgeInsets.only(bottom: 12.px),
          child: _buildInput("请输入您的手机号", _accountNode, _accountCtl,
              TextInputAction.next,_onNextInput, Icons.account_circle,
              type: TextInputType.phone),
        ),
        Row(
          children: [
            Expanded(child: Container(
              margin: EdgeInsets.only(right: 12.px, bottom: 12.px),
              child: _buildInput("请输入短信验证码", _codeNode, _codeCtl,
                  TextInputAction.done, _onLogin, Icons.sms,
                  type: TextInputType.number),
            )),
            CounterButton(onClick: _onGetCode)
          ],
        ),
        Container(
          height: 50.px,
          width: double.infinity,
          margin: EdgeInsets.only(left: 56.px, right: 56.px),
          padding: EdgeInsets.only(top: 12.px),
          child: FlatButton(
            color: Colors.white,
            shape: StadiumBorder(),
            onPressed: () { _onSmsLogin(_accountCtl.text); },
            child: Text('登 陆', style: TextStyle(fontSize: 16.px)),
          ),
        ),
        Container(
          margin: EdgeInsets.only(bottom: 22.px),
          child: Row(
            children: [
              Container(
                child: FlatButton(
                    highlightColor: Colors.transparent,
                    child: Text('账号密码登陆', style: TextStyle(color:
                    Colors.white, decoration: TextDecoration.underline)),
                    onPressed: () { _jumpTo(0); }),
              ),
              Spacer(),
              Container(
                child: FlatButton(
                    highlightColor: Colors.transparent,
                    child: Text('没有账号？去注册', style: TextStyle(color:
                    Colors.white, decoration: TextDecoration.underline)),
                    onPressed: () { _jumpTo(1); }),
              ),
            ],
          ),
        ),
      ],
    );
  }

  void _jumpTo(int index) {
    _pageController.animateToPage(index, curve: Curves.easeIn,
        duration: Duration(milliseconds: 260));
  }

  Widget _buildOtherLogin() {
    return Column(
      children: [
        Container(
          child: Text('其他登录方式', style: TextStyle(color: Colors.white)),
        ),
        Container(
          width: double.infinity,
          padding: EdgeInsets.only(top: 30),
          child: Row(
            children: <Widget>[
              Expanded(child: Container(
                  width: 46,
                  height: 46,
                  child: InkWell(
                    onTap: () => wechatLogin(),
                    child: Image.asset("assets/images/wechat.png"),
                  )
              )),
            ],
          ),
        )
      ],
    );
  }

  Widget _buildBottom() {
    return
      Container(
        margin: EdgeInsets.only(bottom: 12.px),
        alignment: Alignment.center,
        child: Wrap(
          children: [
            Text("登陆即视为您以阅读并同意",
                style: TextStyle(fontSize: 11.px, color: Colors.black54)),
            InkWell(
              onTap: () {
                Navigator.pushNamed(context, RouteNames.protocol,
                    arguments: ProtocolType.USER);
              },
              child: Text("《用户注册协议》",
                  style: TextStyle(fontSize: 11.px, color: Colors.white)),
            ),
            Text("和",
                style: TextStyle(fontSize: 11.px, color: Colors.black54)),
            InkWell(
              onTap: () {
                Navigator.pushNamed(context, RouteNames.protocol,
                    arguments: ProtocolType.PRIVATE);
              },
              child: Text("《美天旺会员隐私协议》",
                  style: TextStyle(fontSize: 11.px, color: Colors.white)),
            ),
          ],
        ),
      );
  }
}