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/MessageMgr.dart';
import 'package:chat/utils/ShadowButton.dart';
import 'package:chat/utils/TokenMgr.dart';
import 'package:city_pickers/city_pickers.dart';
import 'package:city_pickers/modal/result.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:oktoast/oktoast.dart';

class BindBankPage extends StatefulWidget {
  @required
  final bool isBind;
  @required
  final Map bankInfo;
  BindBankPage({Key key, this.isBind = true, this.bankInfo}) : super(key: key);

  _BindBankPageState createState() => _BindBankPageState();
}

class _BindBankPageState extends State<BindBankPage>
    with SingleTickerProviderStateMixin {
  String bankId;
  var bankCatId;

  Map bankInfo;

  bool isLoading = false;

  TextEditingController nickNameController = new TextEditingController();
  TextEditingController cardIdController = new TextEditingController();
  TextEditingController idController = new TextEditingController();
  TextEditingController mobileController = new TextEditingController();

  @override
  void initState() {
    super.initState();

     print('BindBankPage initState');

    if (widget.bankInfo == null) {
      bankInfo = {};
    } else {
      bankInfo = widget.bankInfo;
    }

    nickNameController.text = bankInfo['Name'] == null ? '' : bankInfo['Name'];
    cardIdController.text =
        bankInfo['CardNo'] == null ? '' : bankInfo['CardNo'];
    idController.text =
        bankInfo['IdNumber'] == null ? '' : bankInfo['IdNumber'];
    mobileController.text =
        bankInfo['MobileNo'] == null ? '' : bankInfo['MobileNo'];
    bankCatId = bankInfo['Bid'] == null ? '' : bankInfo['Bid'];
  }

  @override
  void dispose() {
    nickNameController.dispose();
    cardIdController.dispose();
    idController.dispose();
    mobileController.dispose();

    super.dispose();

    //_cancelTimer();
  }

  initValue() {
    if (!isLoading) {
      bankId = bankInfo['Bid'] == null || bankInfo['Bid'] == 0
          ? I18n.of(context).choose
          : WebData().bankData[bankInfo['Bid'].toString()];
      isLoading = true;
      setState(() {});
    }
  }

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

  Widget _buildBody() {
    return Column(
      children: <Widget>[
        _buildInputList(),
        _buildBotton(),
      ],
    );
  }

  Widget _buildBotton() {
    return Container(
      margin: EdgeInsets.only(top: 30),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: <Widget>[
          _buildCancelButton(),
          _buildRegisterButton(),
        ],
      ),
    );
  }

  //构建注册按钮
  Widget _buildRegisterButton() {
    Text text = new Text(
        widget.isBind ? I18n.of(context).determine : I18n.of(context).save,
        textScaleFactor: 1.0,
        style: TextStyle(fontSize: 15, color: Colors.white));

    LinearGradient gradientColor = new LinearGradient(colors: <Color>[
      Constants.ConfrimButtonColor,
      Constants.ConfrimButtonColor
    ]);
    callback() {
      if (nickNameController.text == '') {
        showToast(I18n.of(context).enter_name);
        return;
      }
      if (bankCatId == '' || bankCatId == null) {
        showToast(I18n.of(context).choose_bank);
        return;
      }
      if (cardIdController.text == '') {
        showToast(I18n.of(context).bank_number);
        return;
      }
      if (idController.text == '') {
        showToast(I18n.of(context).id_number);
        return;
      }
      if (mobileController.text == '') {
        showToast(I18n.of(context).enter_number);
        return;
      }
      widget.isBind ? addBank() : editBank();
    }

    return new Container(
      height: 44,
      width: MediaQuery.of(context).size.width * 0.4,
      child: ShadowButton().builder(gradientColor, text, callback),
    );
  }

  void addBank() async {
    var data = {
      "userId": UserData().basicInfo.userId,
      "name": nickNameController.text,
      "idNumber": idController.text,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['bId'] = bankCatId;
    data['cardNo'] = cardIdController.text;
    data['mobile'] = mobileController.text;

    Response res = await HttpUtil().post('wallet/banding/bankcard', data: data);

      if (res == null) {
      return;
    }
    Map resData = res.data;
    if (resData['code'] == 0) {
      Navigator.of(context).pop();
      MessageMgr().emit('bind_bank', {
        'Name': data['name'],
        'Bid': bankCatId,
        'CardNo': data['cardNo'],
        'IdNumber': data['idNumber'],
        'MobileNo': data['mobile']
      });

      showToast(resData['msg']);
      return;
    }
  }

  void editBank() async {
    var data = {
      "userId": UserData().basicInfo.userId,
      "cId": bankInfo['CId'],
      "name": nickNameController.text,
      "idNumber": idController.text,
    };
    data['sign'] = TokenMgr().getSign(data);
    data['bId'] = bankCatId;
    data['mobile'] = mobileController.text;
    data['cardNo'] = cardIdController.text;

    Response res = await HttpUtil().post('wallet/edit/accountbank', data: data);

      if (res == null) {
      return ;
    }
    Map resData = res.data;
    if (resData['code'] == 0) {
      Navigator.of(context).pop();
      MessageMgr().emit('bind_bank', {
        'Name': data['name'],
        'Bid': bankCatId,
        'CardNo': data['cardNo'],
        'IdNumber': data['idNumber'],
        'MobileNo': data['mobile']
      });
      showToast(resData['msg']);
      return;
    }
  }

  //构建注册按钮
  Widget _buildCancelButton() {
    Text text = new Text(
        widget.isBind ? I18n.of(context).cancel : I18n.of(context).cancel,
        textScaleFactor: 1.0,
        style: TextStyle(fontSize: 15, color: Constants.BlackTextColor));

    LinearGradient gradientColor = new LinearGradient(colors: <Color>[
      Colors.white,
      Colors.white,
    ]);
    callback() {
      Navigator.of(context).pop();
    }

    return new Container(
      height: 44,
      width: MediaQuery.of(context).size.width * 0.4,
      child: ShadowButton().builder(gradientColor, text, callback),
    );
  }

  Widget _buildInputList() {
    return Container(
      margin: EdgeInsets.only(top: 10),
      color: Colors.white,
      child: Column(
        children: <Widget>[
          _buildItem(I18n.of(context).name, nickNameController,
              [LengthLimitingTextInputFormatter(8)]),
          _buildDivider(),
          _buildSelectRank(I18n.of(context).career10, selectBankCat),
          _buildDivider(),
          _buildItem(I18n.of(context).bank_number2, cardIdController, [
            WhitelistingTextInputFormatter.digitsOnly,
            LengthLimitingTextInputFormatter(30)
          ]),

          _buildDivider(),
          _buildItem(I18n.of(context).license_number, idController, [
            WhitelistingTextInputFormatter.digitsOnly,
            LengthLimitingTextInputFormatter(20)
          ]),
          _buildDivider(),
          _buildItem(I18n.of(context).bind_phone, mobileController, [
            WhitelistingTextInputFormatter.digitsOnly,
            LengthLimitingTextInputFormatter(11)
          ]),
          // _buildDivider(),
          // _buildVerifyCode()
        ],
      ),
    );
  }

  void selectBankCat() async {
    Result temp = await CityPickers.showCityPicker(
      context: context,
      showType: ShowType.p,
      provincesData: WebData().bankData,
      citiesData: WebData().bankListData,
      height: 400,
    );
    setState(() {
      if (temp == null) return;
      bankId = temp.provinceName;
      bankCatId = temp.provinceId;
    });
  }

  Widget _buildSelectRank(str, callback) {
    return Container(
      height: 45,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 100,
            padding: EdgeInsets.only(left: 25),
            child: Text(
              str,
              textScaleFactor: 1.0,
            ),
          ),
          Expanded(
              child: new InkWell(
            highlightColor: Colors.transparent,
            radius: 0.0,
            onTap: callback,
            child: Padding(
              padding: EdgeInsets.only(left: 35),
              child: new Text(
                bankId,
                textScaleFactor: 1.0,
                style: TextStyle(fontSize: 14),
              ),
            ),
          ))
        ],
      ),
    );
  }

  Widget _buildItem(str, controller, inputFormatters) {
    return Container(
      height: 45,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            width: 100,
            padding: EdgeInsets.only(left: 25),
            child: Text(
              str,
              textScaleFactor: 1.0,
            ),
          ),
          Expanded(
            child: Container(
              alignment: Alignment.center,
              padding: EdgeInsets.only(left: 25),
              child: TextField(
                  keyboardAppearance: Brightness.light,
                style: TextStyle(fontSize: 14,textBaseline: TextBaseline.alphabetic),
                controller: controller,
                decoration: new InputDecoration(
                  hintText: I18n.of(context).fill_out,
                  hintStyle: TextStyle(fontSize: 14),
                  border: InputBorder.none,
                ),
                maxLines: 1,
                inputFormatters: inputFormatters,
                //onChanged: callback,
              ),
            ),
          ),
        ],
      ),
    );
  }

  //下划线
  Widget _buildDivider() {
    return new Container(
      margin: EdgeInsets.zero,
      padding: EdgeInsets.zero,
      width: MediaQuery.of(context).size.width * 0.85,
      child: new Divider(
        color: Colors.grey[300],
        height: 0.1,
      ),
    );
  }
}
