import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:provider/provider.dart';
import 'package:sport/pages/login/license.dart';
import 'package:sport/provider/login_info_model.dart';
import 'package:sport/provider/user_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/sharesdk/tencent.dart';
import 'package:sport/sharesdk/wechat.dart';
import 'package:sport/utils/toast.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/loading.dart';

import 'login_widget.dart';

class Login extends StatefulWidget {
  final int type;

  Login(this.type); // type = 1 登录界面 选择哪种 type = 2 验证码 type = 3 密码登录
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _LoginState();
  }
}

class _LoginState extends State<Login> with TencentMixin, InjectLoginApi, WechatMixin {
  String _phone = ""; // 输入的电话号码
  String _password = ""; // 输入的密码号码
  LoginInfoModel _loginInfoModel;
  int _type;
  bool _isLoading;
  TextEditingController _controller;
  bool _isDisabled;
  bool _license = false;

  @override
  void initState() {
    super.initState();
    _loginInfoModel = LoginInfoModel();
    _type = widget.type; // 初始化？
    _isLoading = false;
    _isDisabled = true;
    _controller = new TextEditingController();
  }

  @override
  void dispose() {
    super.dispose();
    _controller?.dispose();
  }

  void loginSuccess(Map<String, dynamic> data) {
    if (data['code'] == 0) {
      _loginInfoModel.saveUserInfo({}..addAll(data['data']['user'])..addAll(data['data']['user']['bind_info'] ?? {}), token: data['data']['token']);
      Provider.of<UserModel>(context, listen: false).initUser();
      NavigatorUtil.goHomePage(context);
    }
  }

  void loginByPassWord() async {
    FocusScope.of(context).requestFocus(FocusNode());
    if (!_license) {
      ToastUtil.show("请先勾选已阅读用户协议和隐私条款");
      return;
    }
    setState(() {
      _isLoading = true;
    });
    bool flag = await _loginInfoModel.getlogin(context, _phone, pwd: _password);
    setState(() {
      _isLoading = false;
    });
    if (flag) {
      NavigatorUtil.goHomePage(context);
    }
  }

  void buttonIsDisabled() {
    if (_phone != "" && _password != "") {
      setState(() {
        _isDisabled = false;
      });
    } else {
      setState(() {
        _isDisabled = true;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    double _w = MediaQuery.of(context).size.width / (_type == 1 ? 3.8 : 4.5);
    return WillPopScope(
      onWillPop: () async {
        if (_type == -1) {
          return true;
        } else {
          setState(() {
            _type = 1;
          });
        }
        return false;
      },
      child: Scaffold(
          backgroundColor: Colors.white,
          body: Column(
            children: <Widget>[
              Expanded(
                child: LoadingWidget(
                    loading: _isLoading,
                    child: CustomScrollView(
                      slivers: <Widget>[
                        SliverAppBar(
                          pinned: true,
                          elevation: 0,
                          expandedHeight: MediaQuery.of(context).size.height / 3,
                          title: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              _type == 1
                                  ? Container()
                                  : SafeArea(
                                      child: IconButton(
                                      icon: arrowBack(),
                                      onPressed: () {
                                        setState(() {
                                          _type = 1;
                                          _phone = ""; // 重置
                                          _password = ""; // 重置
                                        });
                                        _controller.clear();
                                      },
                                    )),
                              _type == 2
                                  ? Container()
                                  : InkWell(
                                      child: Text(
                                        "注册帐号",
                                        textAlign: TextAlign.right,
                                        style: TextStyle(fontSize: 16.0),
                                      ),
                                      onTap: () {
                                        NavigatorUtil.goRegister(context);
                                      },
                                    ),
                            ],
                          ),
                          flexibleSpace: FlexibleSpaceBar(
                            title: SafeArea(
                              child: AnimatedContainer(
                                width: _w,
                                height: _w,
                                duration: Duration(milliseconds: 300),
                                decoration: BoxDecoration(
                                    image: DecorationImage(
                                        image: CachedNetworkImageProvider(
                                            "https://dss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=2301392820,3762246937&fm=26&gp=0.jpg"),
                                        fit: BoxFit.cover),
                                    borderRadius: BorderRadius.all(Radius.circular(_type == 1 ? _w / 2 : 43.0))),
                              ),
                            ),
                          ),
                        ),
                        SliverFillRemaining(
                            hasScrollBody: false,
                            fillOverscroll: false,
                            child: Container(
                              padding: EdgeInsets.only(top: 20.0),
                              child: Column(
                                children: <Widget>[
                                  body(),
                                  Expanded(
                                      child: Align(
                                          alignment: Alignment.bottomCenter,
                                          child: Container(
                                            height: 50.0,
                                            color: Colors.white,
                                            alignment: Alignment.center,
                                            child: Row(
                                              mainAxisAlignment: MainAxisAlignment.center,
                                              children: <Widget>[
                                                if (_type != 1)
                                                  InkWell(
                                                    onTap: () {
                                                      setState(() {
                                                        _license = !_license;
                                                      });
                                                    },
                                                    child: Padding(
                                                      padding: const EdgeInsets.all(8.0),
                                                      child: Image.asset("lib/assets/img/${_license ? "pop_icon_conneted" : "pop_icon_choose_normal"}.png"),
                                                    ),
                                                  ),
                                                Text(
                                                  _type == 1 ? "登录代表已同意" : "已阅读",
                                                  style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: 12.0),
                                                ),
                                                InkWell(
                                                  child: Text(
                                                    "用户协议",
                                                    style: TextStyle(color: Theme.of(context).accentColor, fontSize: 12.0),
                                                  ),
                                                  onTap: () {
                                                    showDialog(
                                                        context: context, //BuildContext对象
                                                        builder: (BuildContext context) {
                                                          return SportLicensePage();
                                                        });
                                                  },
                                                ),
                                                Text(
                                                  "及",
                                                  style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: 12.0),
                                                ),
                                                InkWell(
                                                  child: Text(
                                                    "隐私条款",
                                                    style: TextStyle(color: Theme.of(context).accentColor, fontSize: 12.0),
                                                  ),
                                                  onTap: () {
                                                    showDialog(
                                                        context: context, //BuildContext对象
                                                        builder: (BuildContext context) {
                                                          return SportLicensePage();
                                                        });
                                                  },
                                                ),
                                              ],
                                            ),
                                          ))),
                                ],
                              ),
                            )),
                      ],
                    )),
              ),
            ],
          )),
    );
  }

  Widget body() {
    if (_type == 1) {
      return Padding(
        padding: EdgeInsets.all(40.0),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            InkWell(
              child: Image.asset(
                "lib/assets/img/login_weixin.png",
                width: 70.0,
                height: 70.0,
                fit: BoxFit.cover,
              ),
              onTap: () {
                wechatLogin((code) {
                  print(code);
                  if (code == null) {
                    ToastUtil.show("请先安装最新版的微信客户端");
                    setState(() {
                      _isLoading = false;
                    });
                    return;
                  }
                  setState(() {
                    _isLoading = true;
                  });
                  loginApi.loginByWx(code).then((value) async {
                    loginSuccess(value);
                  }).whenComplete(() => setState(() {
                        _isLoading = false;
                      }));
                });
              },
            ),
            InkWell(
              child: Image.asset("lib/assets/img/login_qq.png", width: 70.0, height: 70.0, fit: BoxFit.cover),
              onTap: () {
                qqlogin((login, userInfo) {
                  if (userInfo == null) {
                    setState(() {
                      _isLoading = false;
                    });
                    return;
                  }
                  setState(() {
                    _isLoading = true;
                  });
                  loginApi.loginQQ(login.openid, userInfo.nickname, gender: userInfo.genderType, avatar: userInfo.figureurl1).then((value) async {
                    loginSuccess(value);
                  }).whenComplete(() => setState(() {
                        _isLoading = false;
                      }));
                });
              },
            ),
            InkWell(
              child: Image.asset("lib/assets/img/login_phone.png", width: 70.0, height: 70.0, fit: BoxFit.cover),
              onTap: () {
                setState(() {
                  _type = 2;
                });
              },
            )
          ],
        ),
      );
    } else if (_type == 2) {
      return Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Input(
            labelText: "请输入手机号",
            textInputType: TextInputType.phone,
            maxLength: 11,
            controller: _controller,
            callBack: (value) {
              setState(() {
                _phone = value; // onchanged
              });
            },
          ),
          Container(
            padding: EdgeInsets.only(bottom: 48.0, top: 6.0),
            child: Text(
              "未注册的手机号验证后自动创建帐号",
              style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: 12.0),
            ),
          ),
          button(
              "获取验证码",
              _phone.length < 11
                  ? null
                  : () {
                      FocusScope.of(context).requestFocus(FocusNode());
                      if (!_license) {
                        ToastUtil.show("请先勾选用户协议和隐私条款");
                        return;
                      }
                      setState(() {
                        _isLoading = true;
                      });
                      loginApi.getCaptcha(_phone).then((value) {
                        if (value["code"] != 0) {
                          // Fluttertoast.showToast(
                          //   msg: "${value['msg']}",
                          //   toastLength: Toast.LENGTH_SHORT,
                          //   gravity: ToastGravity.CENTER,
                          //   textColor: Colors.white,
                          //   backgroundColor: Colors.black,
                          // );
                        } else {
                          NavigatorUtil.goAuthCode(context, phone: _phone);
                        }
                      }).whenComplete(() => setState(() {
                            _isLoading = false;
                          }));
                    }),
//          Row(
//            children: <Widget>[
//              Expanded(
//                child: GestureDetector(
//                  child: Container(
//                    alignment: Alignment.centerRight,
//                    child: Text(
//                      "第三方登录",
//                      style: TextStyle(
//                          color: Color.fromRGBO(153, 153, 153, 1),
//                          fontSize: 16.0),
//                    ),
//                  ),
//                  onTap: () {
//                    setState(() {
//                      _type = 1;
//                      _phone = ""; // 重置
//                      _password = ""; // 重置
//                    });
//                    _controller.clear();
//                  },
//                ),
//              ),
//              Container(
//                alignment: Alignment.center,
//                width: 2.0,
//                height: 16.0,
//                color: Color(0xFFF3F3F3),
//                margin: EdgeInsets.symmetric(horizontal: 32.0),
//              ),
//              Expanded(
//                child:
//              ),
//            ],
//          )
          GestureDetector(
            child: Container(
              alignment: Alignment.center,
              child: Text(
                "密码登录",
                style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 16)
              ),
            ),
            onTap: () {
              setState(() {
                _type = 3;
                // _phone = ""; // 重置
                _password = ""; // 重置
              });
              // _controller.clear();
            },
          ),
        ],
      );
    } else {
      return Column(
        children: <Widget>[
          Input(
            labelText: "请输入手机号",
            textInputType: TextInputType.phone,
            maxLength: 11,
            controller: _controller,
            callBack: (value) {
              setState(() {
                _phone = value; // onchanged
                buttonIsDisabled();
              });
            },
          ),
          Input(
            labelText: "请输入密码",
            obscureText: true,
            callBack: (value) {
              setState(() {
                _password = value; // onchanged
                buttonIsDisabled();
              });
            },
          ),
          SizedBox(
            height: 12,
          ),
          button("登录", _isDisabled ? null : loginByPassWord),
          Row(
            children: <Widget>[
              Expanded(
                child: GestureDetector(
                  child: Container(
                    alignment: Alignment.centerRight,
                    child: Text(
                      "验证码登录",
                      style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: 14.0),
                    ),
                  ),
                  onTap: () {
                    setState(() {
                      _type = 2;
                      // _phone = ""; // 重置
                      _password = ""; // 重置
                    });
                    // _controller.clear();
                  },
                ),
              ),
              Container(
                alignment: Alignment.center,
//              padding: EdgeInsets.only(bottom:100),
                width: 1.0,
                height: 16.0,
                color: Color.fromRGBO(153, 153, 153, 1),
                margin: EdgeInsets.symmetric(horizontal: 31.0),
              ),
              Expanded(
                child: GestureDetector(
                  child: Container(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      "忘记密码",
                      style: TextStyle(color: Color.fromRGBO(153, 153, 153, 1), fontSize: 14.0),
                    ),
                  ),
                  onTap: () {
                    setState(() {
//                    _type = 2;
                      NavigatorUtil.goFindPassword(context);
//                    _phone = ""; // 重置
//                    _password = ""; // 重置
                    });
                  },
                ),
              ),
            ],
          ),
        ],
      );
    }
  }
}
