import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:zhiying_base_widget/pages/bil_detail_page/bil_detail_page.dart';
import 'package:zhiying_base_widget/pages/withdraw_page/bloc/withdraw_bloc.dart';
import 'package:zhiying_base_widget/pages/withdraw_page/models/withdraw_model.dart';
import 'package:zhiying_base_widget/pages/withdraw_page/withdraw_page_sk.dart';
import 'package:zhiying_base_widget/utils/contants.dart';
import 'package:zhiying_comm/util/base_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';

/*提现页面*/
class WithdrawPage extends StatefulWidget {
  final Map<String, dynamic> data;

  const WithdrawPage(this.data, {Key key}) : super(key: key);

  @override
  _WithdrawPageState createState() => _WithdrawPageState();
}

class _WithdrawPageState extends State<WithdrawPage> {
  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        FocusScope.of(context).requestFocus(FocusNode());
      },
      child: Container(
        color: Colors.white,
        child: BlocProvider<WithdrawBloc>(
          bloc: WithdrawBloc(),
          child: _WithdrawContainer(widget.data),
        ),
      ),
    );
  }
}

class _WithdrawContainer extends StatefulWidget {
  final Map<String, dynamic> data;

  const _WithdrawContainer(this.data, {Key key}) : super(key: key);

  @override
  _WithdrawContainerState createState() => _WithdrawContainerState();
}

class _WithdrawContainerState extends State<_WithdrawContainer> {
  WithdrawBloc _bloc;

  int _currentIndex = 0;
  TextEditingController _controller = TextEditingController();
  bool _submitable = false;
  bool _inputable = false;

  @override
  void initState() {
    _bloc = BlocProvider.of<WithdrawBloc>(context);
    if (widget.data.containsKey('skip_identifier')) {
      _bloc.loadData(widget.data['skip_identifier']);
      _bloc.loadWithdrawData();
      _bloc.getAlipayStatus();
    }
    super.initState();
  }

  reload() {
    _bloc.loadData(widget.data['skip_identifier']);
    _bloc.loadWithdrawData();
    _bloc.getAlipayStatus();
  }

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
        stream: _bloc.outData,
        builder: (context, asny) {
          WithdrawModel model = asny.data;
          if (model == null) {
            return WithdrawPageSketelon();
          }

          return Scaffold(
            backgroundColor: HexColor.fromHex('#FFFFFFFF'),
            appBar: _createNav(model),
            body: SafeArea(
              child: SingleChildScrollView(
                  child: Container(
                margin: EdgeInsets.only(left: 12.5, right: 12.5, top: 8),
                child: Column(
                  children: <Widget>[
                    _createHeader(model),
                    _createVerify(model),
                    _createPrice(model),
                    _createInput(model),
                    _createSubmit(model),
                    _createDesc(model),
                  ],
                ),
              )),
            ),
          );
        });
  }

  // 导航栏
  Widget _createNav(WithdrawModel model) {
    return CupertinoNavigationBar(
      leading: Navigator.canPop(context)
          ? GestureDetector(
              child: Container(
                padding: EdgeInsets.zero,
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 20,
                ),
              ),
              onTap: () {
                if (Navigator.canPop(context)) {
                  Navigator.pop(context);
                }
              },
            )
          : Container(),
      middle: Text(
        model.appBarName,
        style: TextStyle(
          fontSize: 15,
          color: HexColor.fromHex(model.appBarNameColor),
        ),
      ),
      trailing: GestureDetector(
        child: Text(
          model.appBarRightText,
          style: TextStyle(fontSize: 13, color: Color(0xff333333)),
        ),
        onTap: () {
          RouterUtil.route(
              model.detailSkipModel, model.detailSkipModel.toJson(), context);
        },
      ),
    );
  }

  Widget _createHeader(WithdrawModel model) {
    var data = _bloc.withdrawDataModel;
    return Container(
      width: double.infinity,
      height: 97,
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(10)),
      child: Stack(
        children: <Widget>[
          Container(
            width: double.infinity,
            height: double.infinity,
            child: CachedNetworkImage(
              imageUrl: model.availableCashOutBgImg ?? '',
              fit: BoxFit.fill,
            ),
          ),
          Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  data?.finValue ?? "",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 30,
                  ),
                ),
                Text(
                  model?.availableCashOutText ?? "",
                  style: TextStyle(
                    color: HexColor.fromHex(model.availableCashOutTextColor),
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _createVerify(WithdrawModel model) {
    var data = _bloc.withdrawDataModel;
    var param = {
      'status': _bloc.aliPayModel,
      Constants.SkipIdentifierName: model.gotoAliPay.skipIdentifier,
      'data': _bloc.aliPayModel
    };
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        Logger.debug('绑定支付宝');
        RouterUtil.route(
                model.gotoAliPay,
                {
                  'status': _bloc.aliPayModel,
                  Constants.SkipIdentifierName: model.gotoAliPay.skipIdentifier,
                  'data': param
                },
                context)
            .then((value) {
          reload();
        });
      },
      child: Container(
        margin: EdgeInsets.only(top: 8, bottom: 8),
        child: Row(
          children: <Widget>[
            CachedNetworkImage(
              imageUrl: (data?.alipayUserName == null ||
                      data?.alipayUserName.length == 0)
                  ? model.unbindAlipayImg
                  : model.bindAlipayImg,
              height: 23,
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(left: 8, right: 8),
                child: Text(
                  (data?.alipayUserName == null ||
                          data?.alipayUserName.length == 0)
                      ? model.unbindAlipayText
                      : data.alipayUserName,
                  style: TextStyle(fontSize: 11, color: Color(0xff999999)),
                ),
              ),
            ),
            Text(
              (data?.alipayUserName == null || data?.alipayUserName.length == 0)
                  ? model.unbindAlipayGotoText
                  : model.bindAlipayGotoText,
              style: TextStyle(fontSize: 11, color: Color(0xff999999)),
            ),
            Icon(
              Icons.arrow_forward_ios,
              size: 12,
              color: Color(0xff999999),
            )
          ],
        ),
      ),
    );
  }

  Widget _createPrice(WithdrawModel model) {
    if (_controller.text.length == 0 &&
        model.cashOutDashbordItems[_currentIndex].name != "自定义") {
      _controller.text = model.cashOutDashbordItems[0].value;
    }
    return GridView.builder(
      shrinkWrap: true,
      physics: NeverScrollableScrollPhysics(),
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 3,
        crossAxisSpacing: 10,
        mainAxisSpacing: 10,
        childAspectRatio: 2.5,
      ),
      itemCount: model?.cashOutDashbordItems?.length ?? 0,
      itemBuilder: (BuildContext context, int index) {
        WithdrawDashbordItems item = model.cashOutDashbordItems[index];
        return GestureDetector(
          onTap: () {
            _controller.text = item.value;
            _currentIndex = index;
            _inputable = item.value == null || item.value == '';
            _checkSubmit(item.value);
          },
          child: Container(
            decoration: BoxDecoration(
              color: index == _currentIndex
                  ? HexColor.fromHex(
                      model.cashOutDashbordItemsSelectedBgColor ?? '')
                  : HexColor.fromHex(
                      model.cashOutDashbordItemsUnselectedBgColor ?? ''),
              borderRadius: BorderRadius.circular(5),
              border: Border.all(
                color: index == _currentIndex
                    ? HexColor.fromHex(
                        model.cashOutDashbordItemsSelectedColor ?? '')
                    : HexColor.fromHex('#d2d2d2'),
              ),
            ),
            child: Center(
              child: Text(
                item.name,
                style: TextStyle(
                  fontSize: 14,
                  color: index == _currentIndex
                      ? HexColor.fromHex(
                          model.cashOutDashbordItemsSelectedColor ?? '')
                      : HexColor.fromHex(
                          model.cashOutDashbordItemsUnselectedColor ?? ''),
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _createInput(WithdrawModel model) {
    return Padding(
      padding: const EdgeInsets.only(top: 8.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.start,
        children: <Widget>[
          Text(
            '提现金额',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: Color(0xff333333),
            ),
          ),
          Container(
            width: double.infinity,
            height: 50,
            child: CupertinoTextField(
              placeholder: '输入提现金额',
              controller: _controller,
              enabled: _inputable,
              style: TextStyle(
                fontSize: 30,
                color: Color(0xff333333),
                fontFamily: 'Din-Bold',
                package: 'zhiying_base_widget',
              ),
              decoration: BoxDecoration(color: Colors.transparent),
              keyboardType: TextInputType.numberWithOptions(decimal: true),
              textInputAction: TextInputAction.done,
              inputFormatters: [
                WhitelistingTextInputFormatter(RegExp("[0-9.]")), //只允许输入小数
              ],
              prefix: Text(
                '￥',
                style: TextStyle(fontSize: 20),
              ),
              onChanged: (value) {
                _checkSubmit(value);
              },
              placeholderStyle:
                  TextStyle(fontSize: 26, color: Colors.grey[400]),
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 5, bottom: 20),
            width: double.infinity,
            height: 0.5,
            color: Color(0xffe4e4e4),
          ),
        ],
      ),
    );
  }

  Widget _createSubmit(WithdrawModel model) {

    String value = model.cashOutDashbordItems[_currentIndex].value;
    try {
      if (num.tryParse(value) != null && null != _bloc.withdrawDataModel && num.tryParse(value) < num.tryParse(_bloc.withdrawDataModel.finValue)) {
        _submitable = true;
      } else {
        _submitable = false;
      }
    } catch (e, s) {
      print(e);
      print(s);
    }

    return GestureDetector(
      onTap: () {
        ///提现
        if (_submitable) {
          _bloc.submitApply(context, _controller.text);
        }
      },
      child: Container(
        height: 50,
        decoration: BoxDecoration(
          color: _submitable
              ? HexColor.fromHex(model.cashOutBtnTextAvailableBgColor ?? '')
              : HexColor.fromHex(model.cashOutBtnTextUnavailableBgColor ?? ''),
          borderRadius: BorderRadius.circular(7.5),
        ),
        child: Center(
          child: Text(
            model.cashOutBtnText ?? '',
            style: TextStyle(
              fontSize: 15,
              color: _submitable
                  ? HexColor.fromHex(model.cashOutBtnTextAvailableColor ?? '')
                  : HexColor.fromHex(
                      model.cashOutBtnTextUnavailableColor ?? ''),
            ),
          ),
        ),
      ),
    );
  }

  Widget _createDesc(WithdrawModel model) {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Container(
          width: double.infinity,
          margin: EdgeInsets.only(top: 8),
          child: Text(
            '提现说明',
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: Color(0xff333333),
            ),
          ),
        ),
        Text(
          model.cashOutTips ?? '',
          style: TextStyle(
            color: Color(0xff999999),
            fontSize: 14,
          ),
        ),
      ],
    );
  }

  void _checkSubmit(String value) {
    try {
      if (num.tryParse(value) != null &&
          num.tryParse(value) < num.tryParse(_bloc.withdrawDataModel.finValue)) {
        _submitable = true;
      } else {
        _submitable = false;
      }
    } catch (e, s) {
      print(e);
      print(s);
    }
    setState(() {});
  }
}
