import 'package:flutter/material.dart';
import '../styles/colors.dart';
import 'dart:ui';
import '../styles/totast.dart';
import '../model/PlayerInfo.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import 'package:flutter_redux/flutter_redux.dart';
import '../redux/AppState.dart';
import '../model/CompetitionSeason.dart';

class RankList extends StatefulWidget {
  RankList({Key key, this.raceId, 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<PlayerInfo> rankList = [];
  ScrollController _mcontroller;
  bool scrollFlag = true;
  int currentPage = 1;
  int raceId = 0;
  List<CompetitionSeason> seasonList = [];
  PlayerInfo myPlayInfo;

  void getUserRank() async {
    Result res = await HttpManager.get("playerInfo/seasonUserRank", data: {
      "seasonId": raceId,
      "userId": StoreProvider.of<AppState>(context).state.userInfo.id,
      'gameId': widget.gameId
    });
    if (res.success && res.data != null) {
      setState(() {
        myPlayInfo = PlayerInfo.fromJson(res.data);
      });
    } else {
      setState(() {
        myPlayInfo = null;
      });
    }

    currentPage = 1;
    getListPage();
  }

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

    if (rankList.length == 0) {
      showBackDialog();
    }
  }

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

  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 {}
  }

  @override
  void initState() {
    raceId = widget.raceId;
    super.initState();
    _mcontroller = ScrollController();
    _mcontroller.addListener(() {
      if (_mcontroller.position.pixels ==
          _mcontroller.position.maxScrollExtent) {
        if (scrollFlag) {
          currentPage++;
          getListPage();
        }
      }
    });

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

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

  @override
  Widget build(BuildContext context) {
    return new WillPopScope(
        child: Scaffold(
          body: Container(
            color: BG_SUB_COLOR,
            child: RefreshIndicator(
                color: PRIMARY_COLOR,
                backgroundColor: Colors.white,
                onRefresh: () async {
                  await new Future.delayed(const Duration(seconds: 1));
                  getUserRank();
                },
                child: CustomScrollView(
                  controller: _mcontroller,
                  physics: AlwaysScrollableScrollPhysics(),
                  slivers: <Widget>[
                    _sliverAppBar(),
                    _slievrToBoxAdapter(),
                    _sliverList()
                  ],
                )),
          ),
          floatingActionButton: myPlayInfo == null
              ? Container()
              : Container(
                  padding: EdgeInsets.only(left: 20, right: 15),
                  height: 48,
                  decoration: BoxDecoration(
                      gradient: LinearGradient(
                    begin: Alignment.topRight,
                    colors: [Color(0xFF59607A), Color(0xFF3C3C67)],
                  )),
                  child: Row(
                    children: <Widget>[
                      Container(
                        width: 30,
                        height: 30,
                        child: CircleAvatar(
                            backgroundImage:
                                NetworkImage(myPlayInfo.userInfo.icon ?? '')),
                      ),
                      Padding(
                        padding: EdgeInsets.symmetric(horizontal: 10),
                        child: Text(myPlayInfo.userInfo.nickname ?? '',
                            style:
                                TextStyle(color: Colors.white, fontSize: 14)),
                      ),
                      Image.asset('images/icon_jinbi_da_bai.png', width: 20),
                      Padding(
                        padding: EdgeInsets.only(left: 2),
                        child: Text((myPlayInfo.bonus ?? 0).toString(),
                            style: TextStyle(
                                color: Colors.white,
                                fontSize: 14,
                                fontWeight: FontWeight.w500)),
                      ),
                      myPlayInfo.rank == null
                          ? Container()
                          : Expanded(
                              flex: 1,
                              child: Text(
                                  '第 ' + myPlayInfo.rank.toString() + ' 名',
                                  style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500),
                                  textAlign: TextAlign.right),
                            )
                    ],
                  ),
                ),
          floatingActionButtonLocation:
              FloatingActionButtonLocation.centerDocked,
        ),
        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 new PopupMenuItem(
                      child: new 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,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: widgetList(),
        ),
      ),
    );
  }

  Widget _sliverList() {
    return SliverList(
      delegate: SliverChildBuilderDelegate(
        (BuildContext context, int index) {
          if (index > 2 && index < rankList.length) {
            return Container(
              padding: EdgeInsets.symmetric(horizontal: 15),
              child: Container(
                height: 36,
                decoration: BoxDecoration(
                    border: Border(
                        bottom: BorderSide(
                            width: 1,
                            color: Colors.black26,
                            style: BorderStyle.solid))),
                child: Row(
                  children: <Widget>[
                    Container(
                      width: 36,
                      height: 36,
                      margin: EdgeInsets.only(right: 15),
                      child: CircleAvatar(
                        backgroundImage:
                            NetworkImage(rankList[index].userInfo.icon),
                      ),
                    ),
                    Expanded(
                      flex: 1,
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(rankList[index].userInfo.nickname,
                              style: TextStyle(
                                  color: PRIMARY_COLOR,
                                  fontSize: 14,
                                  height: 1.2),
                              overflow: TextOverflow.ellipsis),
                          Row(
                            children: <Widget>[
                              Image.asset('images/icon_jinbi_da_bai.png',
                                  width: 20),
                              Padding(
                                padding: EdgeInsets.only(left: 2),
                                child: Text(rankList[index].bonus.toString(),
                                    style: TextStyle(
                                      color: Colors.white,
                                      fontSize: 14,
                                      fontWeight: FontWeight.w500,
                                    )),
                              )
                            ],
                          )
                        ],
                      ),
                    ),
                    index < 100
                        ? Container(
                            width: 30,
                            height: 30,
                            margin: EdgeInsets.only(right: 33),
                            decoration: BoxDecoration(
                                image: DecorationImage(
                                    image: AssetImage(
                                        'images/icon_paihangbang_04.png'),
                                    fit: BoxFit.cover)),
                            child: Text(
                              rankList[index].rank.toString(),
                              style: TextStyle(
                                  color: Color(0xFF15151D),
                                  fontSize: 12,
                                  fontWeight: FontWeight.w500,
                                  height: 2),
                              textAlign: TextAlign.center,
                            ),
                          )
                        : Container()
                  ],
                ),
              ),
              height: 66,
            );
          } else if (index == rankList.length) {
            return Padding(
              padding: EdgeInsets.only(top: 10, bottom: 68),
              child: Text(
                '没有更多了',
                textAlign: TextAlign.center,
                style: TextStyle(color: Colors.white30),
              ),
            );
          } else {
            return Container();
          }
        },
        childCount: rankList.length + 1,
      ),
    );
  }

  List<Widget> widgetList() {
    List<Widget> list = [];
    if (rankList.length > 0) {
      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].userInfo.icon))),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 7, bottom: 3),
                  child: Text(rankList[0].userInfo.nickname,
                      style: TextStyle(color: Color(0xFF2E3049), fontSize: 14)),
                ),
                Row(
                  children: <Widget>[
                    Padding(
                      padding: EdgeInsets.only(right: 2),
                      child: Image.asset('images/icon_jinbi_da_bai.png',
                          width: 20),
                    ),
                    Text(rankList[0].bonus.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].userInfo.icon))),
                          ],
                        ),
                      ),
                      Padding(
                        padding: EdgeInsets.only(top: 7, bottom: 3),
                        child: Text(rankList[1].userInfo.nickname,
                            style: TextStyle(
                                color: Color(0xFF2E3049), fontSize: 14)),
                      ),
                      Row(
                        children: <Widget>[
                          Padding(
                            padding: EdgeInsets.only(right: 2),
                            child: Image.asset('images/icon_jinbi_da_bai.png',
                                width: 20),
                          ),
                          Text(rankList[1].bonus.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].userInfo.icon))),
                      ],
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.only(top: 7, bottom: 3),
                    child: Text(rankList[2].userInfo.nickname,
                        style:
                            TextStyle(color: Color(0xFF2E3049), fontSize: 14)),
                  ),
                  Row(
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.only(right: 2),
                        child: Image.asset('images/icon_jinbi_da_bai.png',
                            width: 20),
                      ),
                      Text(rankList[2].bonus.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;
  }
}
