import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../styles/colors.dart';
import 'package:redux/redux.dart';
import 'package:flutter_redux/flutter_redux.dart';
import '../redux/AppState.dart';
import '../model/UserInfo.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import 'dart:ui';
import '../styles/totast.dart';
import 'ShoppingMall.dart';

class MyWallet extends StatefulWidget {
  @override
  MyWalletState createState() => MyWalletState();
}

class MyWalletState extends State<MyWallet> {
  ScrollController _controller;
  List walletList;
  bool isShow = false;
  num _topHeight;
  int currentPage = 1;
  bool canNext = true;

  Future<void> getWalletPage() async {
    Toast.show(context, '加载中', -1, 'loading');
    canNext = false;
    Result res = await HttpManager.get('memberTicket/page',
        data: {'userId': StoreProvider.of<AppState>(context).state.userInfo.id, 'currentPage': currentPage, 'pageNumber': 20});
    Toast.hide();
    if (res.success) {
      if (currentPage == 1) {
        walletList = [];
      }
      setState(() {
        walletList.addAll(res.data['pp']);
      });

      if (res.data['page']['totalNumber'] > currentPage) {
        canNext = true;
      }
    } else {}
  }

  @override
  void initState() {
    super.initState();
    walletList = List<Map>();
    Future.delayed(Duration.zero, () {
      getWalletPage();
    });
    _controller = ScrollController();
    isShow = false;

    _controller.addListener(() {
      if (_controller.position.pixels == _controller.position.maxScrollExtent && canNext) {
        currentPage++;
        getWalletPage();
      }

      if (_controller.position.pixels >= _topHeight + 82) {
        setState(() {
          isShow = true;
        });
      } else {
        setState(() {
          isShow = false;
        });
      }
    });
  }

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

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 375, height: 667)..init(context);
    return StoreConnector<AppState, UserInfo>(
        converter: (Store store) => store.state.userInfo,
        builder: (context, userInfo) {
          return Scaffold(
              body: RefreshIndicator(
            color: PRIMARY_COLOR,
            backgroundColor: Colors.white,
            onRefresh: () async {
              await Future.delayed(const Duration(seconds: 1));
              setState(() {
                walletList = [];
                isShow = false;
                currentPage = 1;
              });
              getWalletPage();
            },
            child: Container(
              color: Color(0xFF2E3049),
              child: Stack(
                children: <Widget>[
                  CustomScrollView(
                    controller: _controller,
                    slivers: <Widget>[
                      SliverAppBar(
                        backgroundColor: PRIMARY_COLOR,
                        title: Text(isShow ? '门票明细' : ''),
                        centerTitle: true,
                        pinned: true,
                      ),
                      _sliverToBoxAdapter(context, userInfo),
                      _sliverList(context),
                    ],
                  ),
                  // _floatTab(context)
                ],
              ),
            ),
          ));
        });
  }

//浮块
  Widget _floatTab(BuildContext context) {
    _topHeight = 56 + MediaQueryData.fromWindow(window).padding.top;
    return Positioned(
      top: isShow ? _topHeight : -46,
      child: Container(
        width: window.physicalSize.width / window.devicePixelRatio,
        height: 46,
        color: PRIMARY_COLOR,
        child: _newRouterTab(context),
      ),
    );
  }

  Widget _sliverToBoxAdapter(BuildContext context, UserInfo userInfo) {
    return SliverToBoxAdapter(
        child: Column(
      children: <Widget>[
        Container(
          alignment: Alignment.center,
          width: double.infinity,
          height: 194,
          decoration: BoxDecoration(
              //背景装饰
              gradient: LinearGradient(
            begin: Alignment.bottomRight,
            colors: [Color(0xFFFEA5A1),Color(0xFFE17874), Theme.of(context).primaryColor],
          )),
          child: Stack(
            overflow: Overflow.visible,
            children: <Widget>[
              Container(
                width: 216,
                height: 192,
                decoration: BoxDecoration(
                    image: DecorationImage(
                  image: AssetImage('images/img_wodeshouyi.png'),
                  fit: BoxFit.contain,
                )),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      child: Text(userInfo.moneyTicket.toString(),
                          style: TextStyle(
                            color: Theme.of(context).primaryColor,
                            fontSize: 51,
                            fontWeight: FontWeight.w900,
                          )),
                      padding: EdgeInsets.only(top: 10),
                    ),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: <Widget>[
                        Image(
                          image: AssetImage('images/icon2.png'),
                          width: 20,
                        ),
                        Container(width: 5,),
                        Text('我的参赛券',
                            style: TextStyle(
                              color: Color(0xFFD4504B),
                              fontSize: 14,
                            ))
                      ],
                    )
                  ],
                ),
              ),
              Positioned(
                bottom: -23,
                left: -(ScreenUtil().setWidth(345) - 216) / 2,
                child: Container(
                  width: ScreenUtil().setWidth(345),
                  height: 46,
                  color: PRIMARY_COLOR,
                  child: _newRouterTab(context),
                ),
              )
            ],
          ),
        ),
        Container(
          width: double.infinity,
          // color: Color(0xFF2E3049),
          child: Text(
            '余额明细',
            style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
          ),
          padding: EdgeInsets.only(
            left: 15,
            top: 55,
            bottom: 15,
          ),
        )
      ],
    ));
  }

  //充值，提现
  Widget _newRouterTab(BuildContext context) {
    return Row(
      children: <Widget>[
        // Expanded(
        //   flex: 1,
        //   child: GestureDetector(
        //     child: Container(
        //       padding: EdgeInsets.all(10),
        //       child: Text(
        //         '提现',
        //         textAlign: TextAlign.center,
        //         style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
        //       ),
        //     ),
        //     onTap: () {},
        //   ),
        // ),
        // Container(
        //   width: 1,
        //   height: 20,
        //   color: Color(0x2E000000),
        // ),
        Expanded(
          flex: 1,
          child: GestureDetector(
            child: Container(
                padding: EdgeInsets.all(10),
                child: Text(
                  '充值',
                  textAlign: TextAlign.center,
                  style: TextStyle(color: Colors.white, fontSize: 16, fontWeight: FontWeight.w500),
                )),
            onTap: () {
                 Navigator.push(context, CupertinoPageRoute(builder: (context) => ShoppingMall()));
            },
          ),
        )
      ],
    );
  }

  Widget _sliverList(BuildContext context) {
    return SliverFixedExtentList(
      itemExtent: 66,
      delegate: SliverChildBuilderDelegate((BuildContext context, int index) {
        if (index < walletList.length) {
          return Container(
            padding: EdgeInsets.all(15),
            decoration: BoxDecoration(
              border: BorderDirectional(top: BorderSide(width: 1, color: Color(0x2E000000), style: BorderStyle.solid)),
              color: Color(0xFF2E3049),
            ),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Container(
                    width: 53,
                    child: Text(
                      walletList[index]['money'].toString(),
                      style: TextStyle(color: Colors.white, fontSize: 20, fontWeight: FontWeight.w500),
                    )),
                Expanded(
                  flex: 1,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Text(
                        walletList[index]['remark'],
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500),
                      ),
                      Text(
                        readTimestamp(walletList[index]['createTime'], 'yyyy-MM-dd HH:mm:ss'),
                        style: TextStyle(color: Color(0xFF727785), fontSize: 12, fontWeight: FontWeight.w400),
                      )
                    ],
                  ),
                )
              ],
            ),
          );
        } else {
          return Center(
            child: Text(
              '没有更多了',
              style: TextStyle(color: Color(0xFF727785), fontSize: 12, fontWeight: FontWeight.w400),
            ),
          );
        }
      }, childCount: walletList.length + 1),
    );
  }
}
