import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.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_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: Scaffold(
        appBar: _createNav(),
        backgroundColor: Colors.white,
        body: SafeArea(
          child: BlocProvider<WithdrawBloc>(
            bloc: WithdrawBloc(),
            child: _WithdrawContainer(widget.data),
          ),
        ),
      ),
    );
  }

  // 导航栏
  Widget _createNav() {
    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(
        '提现',
        style: TextStyle(
          fontSize: 15,
          color: Color(0xff333333),
        ),
      ),
      trailing: GestureDetector(
        child: Text(
          '明细',
          style: TextStyle(fontSize: 13, color: Color(0xff333333)),
        ),
        onTap: () {},
      ),
    );
  }
}

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']);
    }
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: StreamBuilder<WithdrawModel>(
          stream: _bloc.outData,
          builder: (BuildContext context, AsyncSnapshot snapshot) {
            WithdrawModel model = snapshot.data;
            if (model == null) {
              return WithdrawPageSketelon();
            }

            return 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),
                ],
              ),
            );
          }),
      // child: Column(
      //   children: <Widget>[],
      // ),
    );
  }

  Widget _createHeader(WithdrawModel model) {
    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(
                  '￥0.03',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 30,
                  ),
                ),
                Text(
                  '可提现总余额',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          )
        ],
      ),
    );
  }

  Widget _createVerify(WithdrawModel model) {
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        Logger.debug('绑定支付宝');
      },
      child: Container(
        margin: EdgeInsets.only(top: 8, bottom: 8),
        child: Row(
          children: <Widget>[
            CachedNetworkImage(
              imageUrl: model.unbindAlipayImg,
              height: 23,
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(left: 8, right: 8),
                child: Text(
                  model.unbindAlipayText,
                  style: TextStyle(fontSize: 11, color: Color(0xff999999)),
                ),
              ),
            ),
            Icon(
              Icons.arrow_forward_ios,
              size: 12,
              color: Color(0xff999999),
            )
          ],
        ),
      ),
    );
  }

  Widget _createPrice(WithdrawModel model) {
    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);
              },
            ),
          ),
          Container(
            margin: EdgeInsets.only(top: 5, bottom: 20),
            width: double.infinity,
            height: 0.5,
            color: Color(0xffe4e4e4),
          ),
        ],
      ),
    );
  }

  Widget _createSubmit(WithdrawModel model) {
    return 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) {
    _submitable = value.length > 0;
    setState(() {});
  }
}
