import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import '../styles/colors.dart';
import 'dart:ui';
import '../styles/totast.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import 'package:flutter_redux/flutter_redux.dart';
import '../redux/AppState.dart';
import '../model/CompetitionSeason.dart';
import '../widget/Dialog.dart';
import 'dart:math';
import '../model/UserInfo.dart';

class RankList extends StatefulWidget {
  RankList({Key key, this.raceId = 0, this.gameId}) : super(key: key);
  final int raceId; // 用来储存传递过来的值
  final int gameId;
  @override
  RankListState createState() => RankListState();
}

class RankListState extends State<RankList> {
  String raceName = '2019';
  List raceNameList = ['2019', '2018', '2017'];
  List<UserInfo> rankList = [];
  ScrollController _mcontroller;
  bool scrollFlag = true;
  int currentPage = 1;
  int raceId = 0;
  int gameId = 0;
  List<CompetitionSeason> seasonList = [];
  UserInfo myPlayInfo;
  bool isFinish = false;
  bool showMore = false;

  Future<void> getUserRank() async {
    Result res = await HttpManager.get('userInfo/myCoinRank', data: {'id': StoreProvider.of<AppState>(context).state.userInfo.id, 'gameId': gameId});
    print('*******************************************');
    print(res.data);
    if (res.success && res.data != null) {
      setState(() {
        myPlayInfo = UserInfo.fromJson(res.data);
      });
    } else {
      setState(() {
        myPlayInfo = null;
      });
    }

    currentPage = 1;
    getListPage();
  }

  Future<void> getListPage() async {
    scrollFlag = false;
    Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get('userInfo/coinRank', data: {'currentPage': currentPage, 'pageNumber': 20});
    Toast.hide();
    List<UserInfo> list = rankList;
    if (currentPage == 1) {
      list = [];
    }
    if (res.success) {
      print(res.data['pp']);
      for (var item in res.data['pp']) {
        UserInfo tip = UserInfo.fromJson(item);
        list.add(tip);
      }
      if (res.data['page']['currentPage'] < res.data['page']['totalPage']) {
        scrollFlag = true;
      } else {
        setState(() {
          isFinish = true;
        });
      }
    } else {}
    setState(() {
      rankList = list;
    });

    if (rankList.isEmpty) {
      showBackDialog();
    }
  }

  //没有赛季排行数据弹窗
  void showBackDialog() {
    MyDialog.showDialog(context, '该赛季暂未产生排行数据，尽情期待...');
    // showDialog<Null>(
    //   context: context,
    //   barrierDismissible: false,
    //   builder: (BuildContext context) {
    //     return AlertDialog(
    //       content: Container(
    //         height: 50,
    //         child: Text(
    //           '该赛季暂未产生排行数据，尽情期待...',
    //           style: TextStyle(color: Colors.black),
    //         ),
    //       ),
    //       actions: <Widget>[
    //         FlatButton(
    //           child: Text('确定'),
    //           onPressed: () {
    //             Navigator.of(context).pop();
    //           },
    //         ),
    //       ],
    //     );
    //   },
    // ).then((val) {
    //   Navigator.of(context).pop();
    // });
  }

  Future<void> getSeasonInfo() async {
    Result res = await HttpManager.get('competitionSeason/all');
    if (res.success) {
      List<CompetitionSeason> list = [];
      for (var item in res.data) {
        list.add(CompetitionSeason.fromJson(item));
      }
      setState(() {
        seasonList = list;
      });
    } else {}

    if (seasonList.length > 0) {
      raceId = seasonList[0].id;
      gameId = seasonList[0].gameId;
      getUserRank();
    }
  }

  @override
  void initState() {
    raceId = widget.raceId;
    super.initState();
    _mcontroller = ScrollController();
    _mcontroller.addListener(() {
      if (_mcontroller.position.pixels == _mcontroller.position.maxScrollExtent) {
        setState(() {
          showMore = true;
        });
        if (scrollFlag) {
          currentPage++;
          getListPage();
        } else {
          Future.delayed(Duration(seconds: 2), () {
            setState(() {
              showMore = false;
            });
          });
        }
      }
    });

    Future.delayed(Duration.zero, () {
      getSeasonInfo();
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          appBar: AppBar(
              title: Text('排行榜'),
              centerTitle: true,
              bottom: PreferredSize(
                preferredSize: const Size.fromHeight(66),
                child: myPlayInfo == null ? Container() : RankItem(myPlayInfo, myPlayInfo.rank, height: 66, color: 0xFF23253C, border: false),
              )),
          body: Container(
            color: BG_SUB_COLOR,
            child: RefreshIndicator(
                color: PRIMARY_COLOR,
                backgroundColor: Colors.white,
                onRefresh: () async {
                  await Future.delayed(const Duration(seconds: 1));
                  getUserRank();
                },
                child: CustomScrollView(
                  controller: _mcontroller,
                  physics: AlwaysScrollableScrollPhysics(),
                  slivers: <Widget>[_sliverList()],
                )),
          ),
        ),
        onWillPop: () {
          Toast.hide();
          Navigator.pop(context);
          return Future.value(false);
        });
  }

  Widget _sliverAppBar() {
    CompetitionSeason competitionSeason;
    for (var item in seasonList) {
      if (item.id == raceId) {
        competitionSeason = item;
      }
    }
    return SliverAppBar(
        title: Text('排行榜'),
        centerTitle: true,
        // actions: <Widget>[
        //   PopupMenuButton(
        //       initialValue: raceId,
        //       child: Row(
        //         crossAxisAlignment: CrossAxisAlignment.center,
        //         mainAxisAlignment: MainAxisAlignment.center,
        //         children: <Widget>[
        //           Text(
        //             competitionSeason != null ? competitionSeason.season : '',
        //             style: TextStyle(color: Colors.white, fontSize: 13, fontWeight: FontWeight.w400),
        //           ),
        //           Image.asset(
        //             'images/icon_zhankai_baise.png',
        //             width: 20,
        //           ),
        //           Container(
        //             width: 15,
        //           )
        //         ],
        //       ),
        //       onSelected: (value) {
        //         setState(() {
        //           raceId = value;
        //         });
        //         getUserRank();
        //       },
        //       itemBuilder: (BuildContext context) {
        //         return seasonList.map((choice) {
        //           return PopupMenuItem(child: Text(choice.season), value: choice.id);
        //         }).toList();
        //       }),
        // ],
        pinned: true);
  }

  Widget _slievrToBoxAdapter() {
    return SliverToBoxAdapter(
      child: Container(
        margin: EdgeInsets.only(bottom: 10),
        height: 196,
        // color: PRIMARY_COLOR,
        decoration:
            BoxDecoration(gradient: LinearGradient(begin: Alignment.topCenter, end: Alignment.bottomCenter, colors: [PRIMARY_COLOR, Color(0xFFF4B011)])),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: widgetList(),
        ),
      ),
    );
  }

  Widget _sliverList() {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          if (index != rankList.length) {
            return RankItem(rankList[index], index);
          } else {
            return showMore
                ? Container(
                    height: 60,
                    child: Center(
                      child: Text(
                        isFinish ? '没有更多了' : '加载中...',
                        textAlign: TextAlign.center,
                        style: TextStyle(color: Colors.white30),
                      ),
                    ),
                  )
                : Container(
                    height: 60,
                  );
          }
        },
        childCount: rankList.length + 1,
      ),
    );
  }

  List<Widget> widgetList() {
    List<Widget> list = [];
    if (rankList.isNotEmpty) {
      list.add(Container(
        margin: EdgeInsets.only(top: 0, left: 30, right: 30),
        child: Stack(
          children: <Widget>[
            Column(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 25),
                  width: 80,
                  height: 80,
                  child: Container(
                      padding: EdgeInsets.all(5),
                      width: 80,
                      height: 80,
                      decoration: BoxDecoration(
                          borderRadius: BorderRadius.all(Radius.circular(80)),
                          gradient: LinearGradient(
                            begin: Alignment.topLeft,
                            colors: [Color(0xFFFECF01), Color(0xFFD48E00)],
                          ),
                          boxShadow: [BoxShadow(color: Colors.black12, offset: Offset(2.0, 4.0), blurRadius: 4.0)]),
                      child: CircleAvatar(backgroundImage: NetworkImage(rankList[0].icon))),
                ),
                Container(
                  padding: EdgeInsets.only(top: 7, bottom: 3),
                  width: 60,
                  child: Text(rankList[0].nickname,
                      style: TextStyle(color: Color(0xFF2E3049), fontSize: 14), overflow: TextOverflow.ellipsis, textAlign: TextAlign.center),
                ),
                Row(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.only(right: 2),
                      child: Image.asset('images/icon_jinbi_da_bai.png', width: 20),
                    ),
                    Text(rankList[0].moneyCoin.toString(), style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500))
                  ],
                )
              ],
            ),
            Positioned(top: 0, left: 24, child: Image.asset('images/icon_paihangbang_01.png', width: 32))
          ],
        ),
      ));
    }

    if (rankList.length > 1) {
      list.insert(
          0,
          Container(
              margin: EdgeInsets.only(top: 25),
              child: Stack(
                children: <Widget>[
                  Column(
                    children: <Widget>[
                      Container(
                        margin: EdgeInsets.only(top: 25),
                        width: 70,
                        height: 70,
                        child: Stack(
                          children: <Widget>[
                            Container(
                                padding: EdgeInsets.all(5),
                                width: 70,
                                height: 70,
                                decoration: BoxDecoration(
                                    borderRadius: BorderRadius.all(Radius.circular(70)),
                                    gradient: LinearGradient(
                                      begin: Alignment.topLeft,
                                      colors: [Color(0xFFE3E3E3), Color(0xFFC5C5C5)],
                                    ),
                                    boxShadow: [BoxShadow(color: Colors.black12, offset: Offset(2.0, 4.0), blurRadius: 4.0)]),
                                child: CircleAvatar(backgroundImage: NetworkImage(rankList[1].icon))),
                          ],
                        ),
                      ),
                      Container(
                        padding: EdgeInsets.only(top: 7, bottom: 3),
                        width: 60,
                        child: Text(
                          rankList[1].nickname,
                          style: TextStyle(color: Color(0xFF2E3049), fontSize: 14),
                          overflow: TextOverflow.ellipsis,
                          textAlign: TextAlign.center,
                        ),
                      ),
                      Row(
                        children: <Widget>[
                          Padding(
                            padding: EdgeInsets.only(right: 2),
                            child: Image.asset('images/icon_jinbi_da_bai.png', width: 20),
                          ),
                          Text(rankList[1].moneyCoin.toString(), style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500))
                        ],
                      )
                    ],
                  ),
                  Positioned(top: 0, left: 19, child: Image.asset('images/icon_paihangbang_02.png', width: 32))
                ],
              )));
    }

    if (rankList.length > 2) {
      list.add(Container(
          margin: EdgeInsets.only(top: 25),
          child: Stack(
            children: <Widget>[
              Column(
                children: <Widget>[
                  Container(
                    width: 70,
                    height: 70,
                    margin: EdgeInsets.only(top: 25),
                    child: Stack(
                      children: <Widget>[
                        Container(
                            padding: EdgeInsets.all(5),
                            width: 70,
                            height: 70,
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.all(Radius.circular(70)),
                                gradient: LinearGradient(
                                  begin: Alignment.topLeft,
                                  colors: [Color(0xFFF89E58), Color(0xFFE77023)],
                                ),
                                boxShadow: [BoxShadow(color: Colors.black12, offset: Offset(2.0, 4.0), blurRadius: 4.0)]),
                            child: CircleAvatar(backgroundImage: NetworkImage(rankList[2].icon))),
                      ],
                    ),
                  ),
                  Container(
                    width: 60,
                    padding: EdgeInsets.only(top: 7, bottom: 3),
                    child: Text(rankList[2].nickname,
                        style: TextStyle(color: Color(0xFF2E3049), fontSize: 14), overflow: TextOverflow.ellipsis, textAlign: TextAlign.center),
                  ),
                  Row(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.only(right: 2),
                        child: Image.asset('images/icon_jinbi_da_bai.png', width: 20),
                      ),
                      Text(rankList[2].moneyCoin.toString(), style: TextStyle(color: Colors.white, fontSize: 14, fontWeight: FontWeight.w500))
                    ],
                  )
                ],
              ),
              Positioned(top: 0, left: 19, child: Image.asset('images/icon_paihangbang_03.png', width: 32))
            ],
          )));
    }

    if (rankList.length <= 1) {
      list.insert(
          0,
          Container(
            // margin: EdgeInsets.only(top: 50),
            child: Container(
              width: 70,
              height: 70,
            ),
          ));
    }

    if (rankList.length <= 2) {
      list.add(Container(
        // margin: EdgeInsets.only(top: 50),
        child: Container(
          width: 70,
          height: 70,
        ),
      ));
    }

    return list;
  }
}

class RankItem extends StatelessWidget {
  RankItem(this.playerInfo, this.index, {this.color = 0, this.height = 66.0, this.border = true});
  final UserInfo playerInfo;
  final int index;
  final int color;
  final double height;
  final bool border;

  List<String> rankImgList = ['images/icon_paihangbang_01.png', 'images/icon_paihangbang_02.png', 'images/icon_paihangbang_03.png'];

  @override
  Widget build(BuildContext context) {
    return Container(
        height: height,
        padding: EdgeInsets.symmetric(horizontal: 15),
        decoration: BoxDecoration(
            // border: Border(bottom: BorderSide(width: 1, color: Colors.black26, style: BorderStyle.solid)),
            color: color == 0 ? Color(0xFF2E3049) : Color(color)),
        child: Container(
          decoration: BoxDecoration(
            border: Border(bottom: BorderSide(width: border ? 1 : 0, color: Colors.black26, style: BorderStyle.solid)),
          ),
          child: Row(
            children: <Widget>[
              playerInfo.rank < 100
                  ? (playerInfo.rank < 4
                      ? Padding(
                          padding: EdgeInsets.only(right: 15),
                          child: Image.asset(rankImgList[playerInfo.rank - 1]),
                        )
                      : Container(
                          width: 30,
                          height: 30,
                          margin: EdgeInsets.only(right: 15),
                          decoration: BoxDecoration(image: DecorationImage(image: AssetImage('images/icon_paihangbang_04_huangse.png'), fit: BoxFit.cover)),
                          child: Text(
                            playerInfo.rank.toString(),
                            style: TextStyle(color: Color(0xFF15151D), fontSize: 12, fontWeight: FontWeight.w500, height: 2),
                            textAlign: TextAlign.center,
                          ),
                        ))
                  : Container(),
              Container(
                width: 36,
                height: 36,
                margin: EdgeInsets.only(right: 15),
                child: CircleAvatar(
                  backgroundImage: NetworkImage(playerInfo.icon),
                ),
              ),
              Expanded(
                flex: 1,
                child: Text(playerInfo.nickname != null ? playerInfo.nickname : '无名氏',
                    style: TextStyle(color: Theme.of(context).primaryColor, fontSize: 14, height: 1.2), overflow: TextOverflow.ellipsis),
              ),
              // Medal(playerInfo.getPlatinum(), '铂金'),
              // Medal(playerInfo.getGold(), '金牌'),
              // Medal(playerInfo.getSilver(), '银牌'),
              Medal('${playerInfo.moneyCoin}', '积分'),
            ],
          ),
        ));
  }
}

class Medal extends StatelessWidget {
  Medal(this.value, this.name);
  final String value;
  final String name;

//   int platinum; //铂金
  // int gold;//金牌
  // int  silver;//银牌
  // int bronze;//铜牌
  List<String> jiangpaiImgList = [
    'images/jiangpai_bojin_xiao.png',
    'images/jiangpai_jinpai_xiao.png',
    'images/jiangpai_baiyin_xiao.png',
    'images/jiangpai_qingtong_xiao.png'
  ];

  Map<String, dynamic> medalInfo = {
    "铂金": {"img": 'images/jiangpai_bojin_xiao.png'},
    "金牌": {"img": 'images/jiangpai_jinpai_xiao.png'},
    "银牌": {"img": 'images/jiangpai_baiyin_xiao.png'},
    "铜牌": {"img": 'images/jiangpai_qingtong_xiao.png'},
    "积分": {"img": 'images/icon_jifen.png'}
  };

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 100,
      child: Row(
        children: <Widget>[
          Image.asset(medalInfo[name]["img"]),
          Container(
            width: 5,
          ),
          Text(
            value,
            style: TextStyle(color: Colors.white, fontSize: 14),
          )
        ],
      ),
    );
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    @required this.child,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => max(maxHeight, minHeight);

  @override
  Widget build(BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new SizedBox.expand(child: child);
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight || minHeight != oldDelegate.minHeight || child != oldDelegate.child;
  }
}
