import 'package:chat/data/UserData.dart';
import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:chat/utils/MessageMgr.dart';
import 'package:chat/utils/screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:oktoast/oktoast.dart';
import '../utils/ShadowButton.dart';
import '../utils/HttpUtil.dart';
import '../utils/TokenMgr.dart';
import 'package:dio/dio.dart';

enum socialNo {
  wechat,
  facebook,
}

const BorderColor = const Color(0xFFD5D5D5);

class GetRegisterCodePage extends StatefulWidget {
  GetRegisterCodePage({Key key, bool flag}) : super(key: key);

  _GetRegisterCodePageState createState() => _GetRegisterCodePageState();
}

class _GetRegisterCodePageState extends State<GetRegisterCodePage> {
  String _address = '';
  String _sourceChan = '';
  String _weChatNo = '';
  String _facebookNo = '';
  int _socialType = 0;
  String _socialNo = '';

  @override
  void initState() {
    super.initState();
    print('GetRegisterCodePage initState');
  }

  @override
  Widget build(BuildContext context) {
    Widget appBar = AppBar(
      title: Text(
        I18n.of(context).apply_incode,
        textScaleFactor: 1.0,
      ),
      leading: CustomUI.buildCustomLeading(context),
      centerTitle: true,
    );
    return Scaffold(
      body: SafeArea(
          child: Center(
        child: Container(
          height: MediaQuery.of(context).size.height,
          width: MediaQuery.of(context).size.width,
          child: _buildBody(),
        ),
      )),
      appBar: appBar,
      resizeToAvoidBottomPadding: false,
    );
  }

  Widget _buildBody() {
    return new Column(
      children: <Widget>[
        _buildInputs(),
        _buildSocialContact(),
        _buildLoginButton(),
      ],
    );
  }

  Widget _bottomBorderBox(String textLeft, String textRight, bool flag, radio,
      inputFormatters, callback) {
    Widget left = Container(
        width: 90,
        child: Text(
          textLeft,
          textScaleFactor: 1.0,
          style: TextStyle(fontSize: 15, fontWeight: FontWeight.w600),
        ));

    Widget right = flag
        ? new Expanded(
            child: new TextField(
              keyboardAppearance: Brightness.light,
              style: TextStyle(textBaseline: TextBaseline.alphabetic),
              decoration: new InputDecoration(
                hintText: textRight,
                hintStyle: TextStyle(fontSize: 15),
                border: InputBorder.none,
              ),
              maxLines: 1,
              inputFormatters: inputFormatters,
              onChanged: (str) {
                if (flag && callback != null) callback(str);
              },
            ),
          )
        : new Expanded(
            child: new InkWell(
              highlightColor: Colors.transparent,
              radius: 0.0,
              child: fixedText(
                textRight,
                fontSize: 15,
              ),
              onTap: () {
                if (!flag && callback != null) callback();
              },
            ),
          );
    return new Container(
      height: 53,
      margin: EdgeInsets.only(left: 15, bottom: 0),
      child: new Row(
        children: <Widget>[left, right, radio == null ? Container() : radio],
      ),
    );
  }

  //下划线
  Widget _buildDivider() {
    return new Container(
      margin: EdgeInsets.zero,
      padding: EdgeInsets.zero,
      height: 1,
      width: MediaQuery.of(context).size.width,
      child: new Divider(
        color: BorderColor,
      ),
    );
  }

  //所在地，信息渠道
  Widget _buildInputs() {
    List<Widget> basicList = [
      _buildDivider(),
      _bottomBorderBox(I18n.of(context).location, I18n.of(context).fill_out,
          true, null, null, (str) {
        _address = str;
      }),
      _buildDivider(),
      _bottomBorderBox(I18n.of(context).message_channel,
          I18n.of(context).fill_out, true, null, null, (str) {
        _sourceChan = str;
      }),
      _buildDivider(),
    ];

    Widget socialCard = new Container(
      color: Colors.white,
      child: new Column(
        children: basicList,
      ),
    );
    return new Container(
        margin: EdgeInsets.only(top: 11),
        child: Column(
          children: <Widget>[socialCard],
        ));
  }

  //社交账号
  Widget _buildSocialContact() {
    Widget radio1 = new Radio(
        value: socialNo.wechat.index,
        groupValue: _socialType, //当value和groupValue一致的时候则选中
        onChanged: (T) {
          _socialType = T;
          setState(() {});
        });
    Widget radio2 = new Radio(
        value: socialNo.facebook.index,
        groupValue: _socialType, //当value和groupValue一致的时候则选中
        onChanged: (T) {
          _socialType = T;
          setState(() {});
        });
    Widget tip = new Container(
      margin: EdgeInsets.only(top: 25, bottom: 10, left: 16.5),
      alignment: Alignment.centerLeft,
      child: fixedText(I18n.of(context).your_social,
          color: const Color(0xFF9A9A9A)),
    );
    List<Widget> basicList = [
      _buildDivider(),
      _bottomBorderBox(
          I18n.of(context).wechat_number,
          I18n.of(context).fill_out,
          true,
          radio1,
          [WhitelistingTextInputFormatter(RegExp("^[A-Za-z0-9]+\$"))], (str) {
        _weChatNo = str;
      }),
      _buildDivider(),
      _bottomBorderBox(
          I18n.of(context).facebook,
          I18n.of(context).fill_out,
          true,
          radio2,
          [WhitelistingTextInputFormatter(RegExp("^[A-Za-z0-9]+\$"))], (str) {
        _facebookNo = str;
      }),
      _buildDivider(),
    ];

    Widget socialCard = new Container(
      color: Colors.white,
      child: new Column(
        children: basicList,
      ),
    );
    return new Container(
        margin: EdgeInsets.only(top: 10),
        child: Column(
          children: <Widget>[tip, socialCard],
        ));
  }

  //构建登陆按钮
  Widget _buildLoginButton() {
    Text text = fixedText(I18n.of(context).apply_now, color: Colors.white);

    LinearGradient gradientColor = new LinearGradient(colors: <Color>[
      Constants.ConfrimButtonColor,
      Constants.ConfrimButtonColor,
    ]);
    callback() async {
      if (_address == null || _address == "") {
        showToast(I18n.of(context).enter_city);
        return;
      }
      if (_sourceChan == null || _sourceChan == "") {
        showToast(I18n.of(context).so_know);
        return;
      }
      if (_socialType == socialNo.wechat.index) {
        _socialNo = _weChatNo;
      }
      if (_socialType == socialNo.facebook.index) {
        _socialNo = _facebookNo;
      }
      if (_socialNo == null || _socialNo == '') {
        showToast(I18n.of(context).your_social);
        return;
      }

      var data = {
        "UserId": UserData().basicInfo.userId,
        "Address": _address,
        "SourceChannel": _sourceChan,
        "SocialNo": _socialNo,
        "SocialType": _socialType
      };
      data['sign'] = TokenMgr().getSign(data);
      try {
        Response res = await HttpUtil().post('user/apply/code', data: data);
        if (res == null) {
          return;
        }
        var resData = res.data;
        if (resData['code'] == 0) {
          MessageMgr().emit('register_code');
          CustomUI.buildOneConfirm(context, I18n.of(context).receive_incode,
              I18n.of(context).determine, () {
            Navigator.of(context).pop();
            Navigator.of(context).pop();
          },
              title: I18n.of(context).successfully_submit,
              failcallbak: () => Navigator.of(context).pop());
        } else {
          showToast(resData['msg']);
        }
      } catch (e) {}
    }

    return new Container(
      margin: EdgeInsets.only(top: 53),
      height: 44,
      width: MediaQuery.of(context).size.width * 0.85,
      child: ShadowButton().builder(gradientColor, text, callback),
    );
  }
}
