import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/utils/CustomUI.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:oktoast/oktoast.dart';
import 'package:wifi_info_plugin/wifi_info_plugin.dart';
import '../utils/ShadowButton.dart';
import '../utils/HttpUtil.dart';
import 'package:dio/dio.dart';
import "../data/UserData.dart";
import '../utils/TokenMgr.dart';

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

  _BindCodePageState createState() => _BindCodePageState();
}

class _BindCodePageState extends State<BindCodePage> {
  String _code = '';
  @override
  Widget build(BuildContext context) {
    Widget appBar = AppBar(
      backgroundColor: AppColors.NewAppbarBgColor,
      title: Text(
        I18n.of(context).bind_code,
        style: TextStyle(color: AppColors.NewAppbarTextColor),
        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,
    );
  }

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

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

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

  Widget _buildTips() {
    var greyStyle = TextStyle(fontSize: 12, color: Constants.GreyTextColor);
    var redStyle = TextStyle(fontSize: 12, color: Colors.red);
    List list = I18n.of(context).fill_tips.split('/s1');
    return Container(
      alignment: Alignment.centerLeft,
      margin: EdgeInsets.only(top: 12, left: 13.5),
      child: RichText(
          text: TextSpan(children: [
        TextSpan(text: list[0], style: greyStyle),
        TextSpan(text: UserData().inviteCodePrice.toString(), style: redStyle),
        TextSpan(text: list[1], style: greyStyle),
      ])),
    );
  }

  Widget _buildTextInput() {
    return Container(
      margin: EdgeInsets.only(top: 5.5),
      color: Colors.white,
      child: Row(
        children: <Widget>[
          Container(
            margin:
                EdgeInsets.only(left: 14, right: 25, top: 27.5, bottom: 27.5),
            child: Text(I18n.of(context).invide_code,
                style: TextStyle(color: Constants.BlackTextColor)),
          ),
          Expanded(
              child: TextField(
            keyboardAppearance: Brightness.light,
            style:
                TextStyle(fontSize: 14, textBaseline: TextBaseline.alphabetic),
            decoration: new InputDecoration(
              hintText: I18n.of(context).enter_incode,
              hintStyle: TextStyle(fontSize: 14),
              border: InputBorder.none,
            ),
            maxLines: 1,
            keyboardType: TextInputType.phone,
            inputFormatters: [
              WhitelistingTextInputFormatter.digitsOnly,
              LengthLimitingTextInputFormatter(5)
            ],
            onChanged: (str) {
              _code = str;
              setState(() {});
            },
          ))
        ],
      ),
    );
  }

  //构建绑定按钮
  Widget _buildLoginButton() {
    Text text = new Text(I18n.of(context).determine,
        textScaleFactor: 1.0,
        style: TextStyle(
            fontSize: Constants.ShaderButtonFontSize, color: Colors.white));

    LinearGradient gradientColor = new LinearGradient(colors: <Color>[
      Constants.ConfrimButtonColor,
      Constants.ConfrimButtonColor,
    ]);
    callback() async {
      if (_code == null || _code == "") {
        showToast(I18n.of(context).enter_incode);
        return;
      }

      Map data = {
        "userId": UserData().basicInfo.userId,
        "agentId": int.parse(_code),
      };
      data['sign'] = TokenMgr().getSign(data);
      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);
      }

      Response res = await HttpUtil()
          .post('user/bind/agent', data: data, isShowLoading: true);

      var resData = res.data;
      showToast(resData['msg']);
      if (resData['code'] == 0) {
        UserData().agentId = int.parse(_code);
        Navigator.of(context).pop();
      }
    }

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