import 'package:flutter/material.dart';
import '../model/PlayerInfo.dart';
import 'dart:async';
import '../styles/totast.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import '../styles/colors.dart';
import 'package:flutter/cupertino.dart';
import 'VideoPlayer.dart';
import '../model/HouseInfo.dart';

class SecondPage extends StatefulWidget {
  SecondPage({Key key, this.roomId, this.status, this.houseInfo}) : super(key: key);
  final String roomId; // 用来储存传递过来的值
  final int status;
  final HouseInfo houseInfo;
  @override
  SecondPageState createState() => SecondPageState();
}

class SecondPageState extends State<SecondPage> {
  List<PlayerInfo> joinList = [];
  int currentPage = 1;
  bool ismore = true;
  ScrollController _perController;
  List jiangpaiImg = ['images/jiangpai_huangjin.png', 'images/jiangpai_baiyin.png', 'images/jiangpai_qingtong.png', 'images/jiangpai_bojin.png'];

  //获取房间用户
  Future<void> getPlayerPage() async {
    ismore = false;
    Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get('playerInfo/rankPage', data: {'houseId': widget.roomId, 'currentPage': currentPage, 'pageNumber': 20});
    Toast.hide();
    List<PlayerInfo> list = joinList;
    if (currentPage == 1) {
      list = [];
    }
    if (res.success) {
      print(res.data['pp']);
      for (var item in res.data['pp']) {
        PlayerInfo jonPlayer = PlayerInfo.fromJson(item);
        list.add(jonPlayer);
      }
      if (res.data['page']['currentPage'] < res.data['page']['totalPage']) {
        ismore = true;
      }
    } else {}
    setState(() {
      joinList = list;
    });
  }

  @override
  void initState() {
    super.initState();
    _perController = ScrollController();
    currentPage = 1;
    Future.delayed(Duration.zero, () {
      getPlayerPage();
      _perController.addListener(() {
        if (_perController.position.pixels == _perController.position.maxScrollExtent) {
          if (ismore) {
            currentPage++;
            getPlayerPage();
          }
        }
      });
    });
  }

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

  @override
  Widget build(BuildContext context) {
    return RefreshIndicator(
      color: PRIMARY_COLOR,
      backgroundColor: Colors.white,
      displacement: 10,
      onRefresh: () async {
        await Future.delayed(const Duration(seconds: 1));
        currentPage = 1;
        getPlayerPage();
      },
      child: ListView.builder(
          physics: AlwaysScrollableScrollPhysics(),
          controller: _perController,
          itemCount: joinList.length + 2,
          itemBuilder: (BuildContext context, int index) {
            if (index == 0 && widget.houseInfo.customerService!=null) {
              return Container(
                  width: double.infinity,
                  height: 60,
                  color: Color(0xFF2B2B42),
                  padding: EdgeInsets.only(left: 15, right: 15),
                  child: Row(
                    children: <Widget>[
                      ClipOval(
                        child: CircleAvatar(
                          backgroundImage: NetworkImage(widget.houseInfo.customerService.icon),
                        ),
                      ),
                      Container(
                        width: 12,
                      ),
                      Text(
                        widget.houseInfo.customerService.serviceName + ' QQ:' + widget.houseInfo.customerService.qq,
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 14,
                        ),
                      )
                    ],
                  ));
            } else if (index - 1 < joinList.length) {
              return PersonItem(joinList[index - 1], index - 1);
            } else {
              return Container(
                padding: EdgeInsets.all(15),
                child: Text(
                  '其他人员正在火速赶来中...',
                  style: TextStyle(color: Colors.white30),
                  textAlign: TextAlign.center,
                ),
              );
            }
          }),
    );
  }

  Widget PersonItem(PlayerInfo info, int index) {
    String img = '';
    if (info.statusFlag != 7 && info.statusFlag != 9 && !info.dataError && info.statusFlag != 6 && info.killNumber >= info.needkill) {
      if (info.houseRank == 1) {
        img = jiangpaiImg[0];
      } else if (info.houseRank == 2) {
        img = jiangpaiImg[1];
      } else if (info.houseRank == 3) {
        img = jiangpaiImg[2];
      }
    }

    return Container(
      width: double.infinity,
      height: 60,
      color: Color(0xFF2B2B42),
      margin: EdgeInsets.only(top: 0),
      padding: EdgeInsets.only(left: 15, right: 15),
      child: Container(
        decoration: BoxDecoration(border: Border(bottom: BorderSide(width: 1, color: BG_SUB_COLOR, style: BorderStyle.solid))),
        child: Row(
          children: <Widget>[
            Container(
              margin: EdgeInsets.only(right: 12),
              width: 36,
              height: 36,
              child: info.userInfo != null
                  ? CircleAvatar(
                      backgroundImage: NetworkImage(info.userInfo.icon),
                    )
                  : Container(),
            ),
            Expanded(
              flex: 1,
              child: Text(
                info.userInfo != null ? info.userInfo.nickname : '',
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 14,
                ),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
            (widget.status == 4 && index < 3 && info.video != '' && info.video != null && img != '')
                ? Container(
                    width: 68,
                    height: 24,
                    margin: EdgeInsets.only(right: 30),
                    child: OutlineButton(
                      textColor: PRIMARY_COLOR,
                      borderSide: BorderSide(color: PRIMARY_COLOR),
                      padding: EdgeInsets.all(0),
                      highlightColor: BG_SUB_COLOR.withOpacity(0.8),
                      highlightedBorderColor: PRIMARY_COLOR,
                      child: Text(
                        '查看回放',
                        style: TextStyle(fontSize: 12),
                      ),
                      onPressed: () =>
                          {Navigator.push(context, CupertinoPageRoute(builder: (context) => VideoPlayerPage(videoUrl: info.video, fileType: 'netWork')))},
                    ),
                  )
                : Container(),
            img != ''
                ? Image.asset(
                    img,
                    width: 32,
                  )
                : Text('')
          ],
        ),
      ),
    );
  }
}
