import 'dart:async';
import 'package:chat/data/UserData.dart';
import 'package:chat/data/WebData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/HttpUtil.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:chat/utils/screen.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:wifi_info_plugin/wifi_info_plugin.dart';

import 'package:oktoast/oktoast.dart';
import '../utils/OtherLogin.dart';

const RATE_NUM = 0.82;

const BlueColor = Constants.BlueTextColor;

enum PageType {
  register,
  changePWD,
  bindPhone,
}

class RegisterPage extends StatefulWidget {
  @required
  final int type;
  RegisterPage({Key key, this.type});

  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  String _phoneNumber = '';

  String _selectType = UserData().language == LanguageType.Vietnamese
      ? phone.keys.toList()[1]
      : phone.keys.toList()[0];

  String _verifyCode = '';

  String _passWorld = '';
  // String _rePassWorld = '';

  bool isChangePWD = false;

  int _seconds = 0;

  String _verifyStr = '';

  Timer _timer;

  @override
  void initState() {
    super.initState();
    isChangePWD = widget.type == PageType.changePWD.index;
  }

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }

  _startTimer() {
    _seconds = 60 * 5;
    _timer = new Timer.periodic(new Duration(seconds: 1), (timer) {
      _seconds--;
      _verifyStr = '$_seconds(s)';
      setState(() {});
      if (_seconds == 0) {
        _verifyStr = I18n.of(context).send_again;
        _cancelTimer();
      }
    });
  }

  _cancelTimer() {
    _timer?.cancel();
  }

  @override
  Widget build(BuildContext context) {
    String title = I18n.of(context).number_registration;
    if (widget.type == PageType.changePWD.index) {
      title = I18n.of(context).change_password;
    } else if (widget.type == PageType.bindPhone.index) {
      title = I18n.of(context).bind_phone1;
    }

    Widget appBar = new AppBar(
      backgroundColor: AppColors.NewAppbarBgColor,
      title: new Text(
        title,
        style: TextStyle(color: AppColors.NewAppbarTextColor),
        textScaleFactor: 1.0,
      ),
      leading: CustomUI.buildCustomLeading(context),
      centerTitle: true,
    );
    return Scaffold(
      appBar: appBar,
      body: SafeArea(
          child: Center(
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: _buildBody(),
        ),
      )),
      resizeToAvoidBottomPadding: false,
    );
  }

  Widget _buildBody() {
    return new Column(
      children: <Widget>[
        _buildAcountInput(),
        _buildSecurityInput(),
        _buildPasswordInput(),
        _buildLoginButton(),
        widget.type == PageType.register.index
            ? _buildOtherLogin()
            : Container(),
      ],
    );
  }

  //构建底部第三方登陆
  Widget _buildOtherLogin() {
    return new Expanded(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          new Container(
            alignment: Alignment.bottomCenter,
            child: OtherLogin().builder(context),
          )
        ],
      ),
    );
  }

  //账号输入框
  Widget _buildAcountInput() {
    double height = 54.5;
    return new Container(
        alignment: Alignment.center,
        margin: EdgeInsets.only(top: 8.5),
        height: height,
        padding: EdgeInsets.only(left: 17),
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
                top: Constants.GreyBorderSide,
                bottom: Constants.GreyBorderSide)),
        child: Stack(
          children: <Widget>[
            Container(
              width: Screen.width,
              height: height,
              alignment: Alignment.centerLeft,
              child: Icon(
                Icons.phone_android,
                color: BlueColor,
                size: Constants.TextFieldIconSize,
              ),
            ),
            Positioned(
              left: 46,
              child: Container(
                padding: EdgeInsets.only(top: 5),
                margin: EdgeInsets.all(0),
                alignment: Alignment.centerLeft,
                child: new DropdownButtonHideUnderline(
                    child: new DropdownButton(
                  items: phone.keys.map((key) {
                    return DropdownMenuItem(
                      child: new Text(key, textScaleFactor: 1.0),
                      value: key,
                    );
                  }).toList(),
                  onChanged: (value) {
                    setState(() {
                      _selectType = value;
                    });
                  },
                  value: _selectType,
                  elevation: 24, //设置阴影的高度
                  style: new TextStyle(
                    //设置文本框里面文字的样式
                    color: Constants.BlackTextColor,
                    fontSize: 12,
                  ),
                  iconSize: 25.0,
                )),
              ),
            ),
            Positioned(
              left: 90,
              child: Container(
                alignment: Alignment.center,
                width: Screen.width - 90,
                height: height,
                child: TextField(
                  keyboardAppearance: Brightness.light,
                  decoration: new InputDecoration(
                    hintText: I18n.of(context).enter_number,
                    hintStyle: TextStyle(fontSize: 14),
                    border: InputBorder.none,
                  ),
                  maxLines: 1,
                  style: TextStyle(textBaseline: TextBaseline.alphabetic),
                  inputFormatters: [
                    WhitelistingTextInputFormatter.digitsOnly,
                  ],
                  onChanged: (str) {
                    _phoneNumber = str;
                    setState(() {});
                  },
                  keyboardType: TextInputType.phone,
                ),
              ),
            )
          ],
        ));
  }

  //验证码
  Widget _buildSecurityInput() {
    Widget verifyCodeEdit = new TextField(
      keyboardAppearance: Brightness.light,
      decoration: new InputDecoration(
        hintText: I18n.of(context).enter_code,
        hintStyle: TextStyle(fontSize: 14),
        icon: new Icon(
          Icons.security,
          color: BlueColor,
          size: Constants.TextFieldIconSize,
        ),
        border: InputBorder.none,
      ),
      maxLines: 1,
      keyboardType: TextInputType.number,
      style: TextStyle(textBaseline: TextBaseline.alphabetic),
      inputFormatters: [
        WhitelistingTextInputFormatter.digitsOnly,
        LengthLimitingTextInputFormatter(6)
      ],
      onChanged: (str) {
        _verifyCode = str;
        setState(() {});
      },
    );

    void getSms() async {
      var data = {
        "mobile": phone[_selectType] + _phoneNumber,
        "type": 0,
        "language": UserData().language,
      };
      data['sign'] = TokenMgr().getSign(data);

      try {
        Response res = await HttpUtil()
            .post('user/send/sms', data: data, isShowLoading: true);
        var resData = res.data;
        if (resData['code'] == 0) {
          setState(() {
            _startTimer();
          });
        } else {
          showToast(resData['msg']);
        }
      } catch (e) {}
    }

    Widget verifyCodeBtn = new InkWell(
      onTap: (_seconds == 0)
          ? () {
              if (_phoneNumber == null || _phoneNumber == "") {
                showToast(I18n.of(context).enter_number);
                return;
              }
              getSms();
            }
          : null,
      child: new Container(
        margin: EdgeInsets.only(right: 21.5),
        padding: EdgeInsets.symmetric(vertical: 4, horizontal: 6),
        decoration: BoxDecoration(
            border: Border.all(color: BlueColor),
            borderRadius: BorderRadius.all(Radius.circular(15))),
        alignment: Alignment.center,
        child: new Text(
          '${_verifyStr == '' ? I18n.of(context).send_code : _verifyStr}',
          textScaleFactor: 1.0,
          style: new TextStyle(fontSize: 11.34, color: BlueColor),
        ),
      ),
    );
    return new Container(
      alignment: Alignment.center,
      height: 54.5,
      padding: EdgeInsets.only(left: 17),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(bottom: Constants.GreyBorderSide)),
      child: new Stack(
        alignment: Alignment.center,
        children: <Widget>[
          verifyCodeEdit,
          Positioned(
            right: 0,
            child: verifyCodeBtn,
          )
        ],
      ),
    );
  }

  //密码
  Widget _buildPasswordInput() {
    return new Container(
      alignment: Alignment.center,
      height: 54.5,
      padding: EdgeInsets.only(left: 17),
      decoration: BoxDecoration(
          color: Colors.white,
          border: Border(bottom: Constants.GreyBorderSide)),
      child: new TextField(
        keyboardAppearance: Brightness.light,
        decoration: new InputDecoration(
          hintText: I18n.of(context).set_password2,
          hintStyle: TextStyle(fontSize: 14),
          icon: new Icon(
            Icons.lock,
            color: BlueColor,
            size: Constants.TextFieldIconSize,
          ),
          border: InputBorder.none,
        ),
        maxLines: 1,
        inputFormatters: [LengthLimitingTextInputFormatter(20)],
        obscureText: true,
        style: TextStyle(textBaseline: TextBaseline.alphabetic),
        onChanged: (str) {
          _passWorld = str;
          setState(() {});
        },
      ),
    );
  }

  // //密码
  // Widget _buildRePasswordInput() {
  //   return new Container(
  //     child: new TextField(
  //       decoration: new InputDecoration(
  //         hintText: '请重新输入登陆密码',
  //         icon: new Icon(Icons.lock),
  //         border: InputBorder.none,
  //       ),
  //       maxLines: 1,
  //       obscureText: true,
  //       onChanged: (str) {
  //         _rePassWorld = str;
  //         setState(() {});
  //       },
  //     ),
  //     width: MediaQuery.of(context).size.width * RATE_NUM,
  //   );
  // }

  //下一步按钮
  Widget _buildLoginButton() {
    Text text = new Text(I18n.of(context).submit,
        textScaleFactor: 1.0,
        style: TextStyle(
            fontSize: Constants.ShaderButtonFontSize, color: Colors.white));

    void postRegister(phoneNum) async {
      var type = 0;
      if (widget.type == PageType.register.index) {
        type = 0;
      } else if (widget.type == PageType.bindPhone.index) {
        type = 1;
      } else {
        return;
      }

      var data = {
        "mobile": phoneNum,
        "code": _verifyCode,
        "pwd": _passWorld,
        "cPwd": _passWorld,
        "type": type,
        "language": UserData().language,
      };
      data['sign'] = TokenMgr().getSign(data);
      data['userid'] = UserData().basicInfo.userId;
      data['lng'] = UserData().longitude;
      data['lat'] = UserData().latitude;

      try {
        WifiInfoWrapper wifiObject = await WifiInfoPlugin.wifiDetails;
        if (wifiObject != null) {
          data['routerName'] = wifiObject.ssid;
          data['mac'] = wifiObject.bssId;
        }
      } catch (e) {
        print(e);
      }
      try {
        Response res = await HttpUtil()
            .post('user/binding/mobile', data: data, isShowLoading: true);
        var resData = res.data;
        showToast(resData['msg']);
        if (resData['code'] == 0) {
          UserData().mobile = int.parse(phoneNum);
          if (widget.type == PageType.register.index) {
            HttpUtil().login(phoneNum, _passWorld, context);
          }
          if (widget.type == PageType.bindPhone.index) {
            Navigator.of(context).pop();
          }
        }
      } catch (e) {}
    }

    void postChangePwd(phoneNum) async {
      var data = {
        "mobile": phoneNum,
        "code": _verifyCode,
        "newpassword": _passWorld,
        "confirmPassword": _passWorld,
      };
      data['sign'] = TokenMgr().getSign(data);
      try {
        Response res = await HttpUtil()
            .post('password/setting/password', data: data, isShowLoading: true);
        var resData = res.data;
        showToast(resData['msg']);
        if (resData['code'] == 0) {
          Navigator.of(context).pop();
        }
      } catch (e) {}
    }

    callback() {
      if (_phoneNumber == null || _phoneNumber == "") {
        showToast(I18n.of(context).enter_number);
        return;
      }
      if (_verifyCode == null || _verifyCode == "" || _verifyCode.length != 6) {
        showToast(I18n.of(context).enter_code);
        return;
      }
      if (_passWorld == null || _passWorld == "") {
        showToast(I18n.of(context).enter_password);
        return;
      }
      if (_passWorld.length < 6) {
        showToast(I18n.of(context).password_limit);
        return;
      }
      var phoneNum = phone[_selectType] + _phoneNumber;
      !isChangePWD ? postRegister(phoneNum) : postChangePwd(phoneNum);
    }

    return InkWell(
      onTap: callback,
      child: Container(
        margin: EdgeInsets.only(top: 60),
        alignment: Alignment.center,
        height: Constants.ShaderButtonHeight,
        width: Screen.width * RATE_NUM,
        decoration: BoxDecoration(
            color: Constants.ConfrimButtonColor,
            border:
                Border.all(color: AppColors.NewAppbarTextColor.withAlpha(140)),
            borderRadius:
                BorderRadius.all(Radius.circular(Constants.BigButtonRadius))),
        child: text,
      ),
    );
  }
}
