import 'package:chat/data/constants.dart';
import 'package:chat/generated/i18n.dart';
import 'package:chat/models/money_change.dart';
import 'package:chat/r.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 'package:provider/provider.dart';

class CoinBagPage extends StatefulWidget {
  @override
  _CoinBagPageState createState() => _CoinBagPageState();
}

class _CoinBagPageState extends State<CoinBagPage> {
  final TextEditingController _textCtrl = TextEditingController();

  FocusNode editFocus = FocusNode();

  final TextEditingController _amountCtrl = TextEditingController();

  FocusNode amountFocus = FocusNode();

  var curAmount = 0;
  var curDesc = '';

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

  @override
  void dispose() {
    _textCtrl.dispose();
    amountFocus.dispose();
    _amountCtrl.dispose();
    editFocus.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (curDesc == '') {
      curDesc = I18n.of(context).little;
    }

    return Scaffold(
        appBar: AppBar(
          title: Text(I18n.of(context).red_money),
          centerTitle: true,
          leading: CustomUI.buildCustomLeading(context),
        ),
        body: SafeArea(
            child: GestureDetector(
          onTap: () {
            if (editFocus.hasFocus) {
              editFocus.unfocus();
            }

            if (amountFocus.hasFocus) {
              amountFocus.unfocus();
            }
          },
          child: SingleChildScrollView(
              child: Center(
            child: Column(
              children: <Widget>[
                Container(
                    padding: EdgeInsets.all(20),
                    child: Column(
                      children: <Widget>[
                        _buildAmountField(),
                        SizedBox(height: 10),
                        _buildTitleTextField(),
                        Padding(
                            padding: EdgeInsets.symmetric(vertical: 30),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: <Widget>[
                                Text(
                                  '$curAmount',
                                  textScaleFactor: 1.0,
                                  style: TextStyle(
                                      fontWeight: FontWeight.w500,
                                      fontSize: 30),
                                ),
                                //SizedBox(width: 5),
                                Text(
                                  I18n.of(context).mask_coin,
                                  textScaleFactor: 1.0,
                                  style: TextStyle(fontSize: 18),
                                ),
                                //Image.asset(R.assetsImagesCoin, scale: 2),
                              ],
                            )),
                        _buildSendBtn(),
                      ],
                    ))
              ],
            ),
          )),
        )));
  }

  _buildAmountField() {
    return Container(
      padding: const EdgeInsets.fromLTRB(8, 8, 0, 8),
      height: 40.0,
      width: Screen.width - 60,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(10.0)),
      child: TextField(
        keyboardAppearance: Brightness.light,
        controller: _amountCtrl,
        focusNode: amountFocus,
        textAlign: TextAlign.right,
        textAlignVertical: TextAlignVertical.center,
        textInputAction: TextInputAction.done,
        style: TextStyle(textBaseline: TextBaseline.alphabetic, fontSize: 16),
        keyboardType: TextInputType.number,
        inputFormatters: <TextInputFormatter>[
          LengthLimitingTextInputFormatter(10) //限制长度
        ],
        onChanged: (String text) {
          if (text.length == 0) {
            curAmount = 0;
          } else {
            curAmount = int.parse(text);
          }

          setState(() {});
        },
        decoration: InputDecoration(
          contentPadding: EdgeInsets.only(top: 8, bottom: 8),
          hintText: curAmount.toString(),
          hintStyle:
              TextStyle(fontSize: 16, color: Constants.LightGreyTextColor),
          prefixIcon: Container(
            width: 65,
            alignment: Alignment.centerLeft,
            child: Text(I18n.of(context).mount),
          ),
          border: InputBorder.none,
          suffixIcon: Container(
            width: 50,
            child: Image.asset(R.assetsImagesCoin, scale: 3),
            alignment: Alignment.center,
          ),
        ),
      ),
    );
  }

  _buildTitleTextField() {
    return Container(
      padding: const EdgeInsets.fromLTRB(8, 8, 0, 8),
      height: 100.0,
      width: Screen.width - 60,
      alignment: Alignment.center,
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(12.0)),
      child: TextField(
        keyboardAppearance: Brightness.light,
        controller: _textCtrl,
        focusNode: editFocus,
        textAlign: TextAlign.center,
        style: TextStyle(textBaseline: TextBaseline.alphabetic, fontSize: 15),
        maxLines: 4,
        minLines: 1,
        textInputAction: TextInputAction.done,
        inputFormatters: <TextInputFormatter>[
          LengthLimitingTextInputFormatter(30) //限制长度
        ],
        onChanged: (String text) {
          curDesc = text;
        },
        decoration: InputDecoration.collapsed(
            hintText: curDesc,
            hintStyle:
                TextStyle(fontSize: 15, color: Constants.LightGreyTextColor)),
      ),
    );
  }

  _buildSendBtn() {
    return SizedBox(
        width: Screen.width * 2 / 3,
        child: RaisedButton(
          child: Text(I18n.of(context).put_money,
              textAlign: TextAlign.center,
              style: TextStyle(color: Colors.white, fontSize: 20)),
          color: Color(0xFFdd643e),
          padding: EdgeInsets.symmetric(horizontal: 16.0, vertical: 12),
          disabledColor: Color(0xFFdd643e).withAlpha(160),
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(8))),
          onPressed: curAmount > 0 ? _sendCoin : null,
        ));
  }

  _sendCoin() {
    if (curDesc == '') {
      curDesc = I18n.of(context).little;
    }

    if (curAmount <= 0) {
      showToast(I18n.of(context).enter_amount);
      return;
    } else {
      if (curAmount < 10) {
        showToast(
            I18n.of(context).little_min.replaceFirst('/s1', 10.toString()));
        return;
      }
      if (curAmount > 999) {
        showToast(
            I18n.of(context).more_big.replaceFirst('/s1', 999.toString()));
        return;
      }
    }
    int curCoin = Provider.of<MoneyChangeProvider>(context).money;
    if (curCoin >= curAmount) {
      Provider.of<MoneyChangeProvider>(context).subMoney(curAmount);
      MessageMgr()
          .emit('Send CoinBag', {'amount': curAmount, 'title': curDesc});
      curAmount = 0;
      Navigator.pop(context);
    } else {
      showToast(I18n.of(context).not_enough);
    }
  }
}
