import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'dart:ui';
import '../styles/totast.dart';
import '../model/SystemNotice.dart';
import '../net/HttpManager.dart';
import '../net/Result.dart';
import '../model/HouseInfo.dart';
import '../model/GameInfo.dart';
import '../widget/SuccessfulReception.dart';
import '../widget/LinearButton.dart';
import '../model/PlayerInfo.dart';
import '../widget/HouseItem.dart';
import '../redux/AppState.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'Appeal.dart';
import 'dart:io';

class TipInfo extends StatefulWidget {
  TipInfo({Key key, this.tipId}) : super(key: key);
  final int tipId;
  @override
  TipInfoState createState() => TipInfoState();
}

class TipInfoState extends State<TipInfo> {
  SystemNotice tipInfo = SystemNotice.fromJson({'content': '', 'createTime': DateTime.now().microsecondsSinceEpoch});
  HouseInfo houseInfo;
  PlayerInfo playerInfo;
  bool canAppeal = false;
  int appealState = 0;
  Future<void> getInfo() async {
    Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get('systemNotice/getOne', data: {'id': widget.tipId});
    Toast.hide();
    if (res.success) {
      setState(() {
        tipInfo = SystemNotice.fromJson(res.data);
      });
    }

    if (tipInfo.statusFlag == 0 && tipInfo.typeFlag != 2 && tipInfo.typeFlag != 3) {
      HttpManager.post('systemNotice/update', data: {'id': tipInfo.id, 'statusFlag': 1});
    }

    if (tipInfo.typeFlag == 3) {
      return;
    }

    Result res2 = await HttpManager.get('houseInfo/getOne', data: {'id': tipInfo.houseId});
    if (res2.success) {
      setState(() {
        houseInfo = HouseInfo.fromJson(res2.data);
      });
    }

    Result res3 =
        await HttpManager.get('playerInfo/getOne', data: {'userId': StoreProvider.of<AppState>(context).state.userInfo.id, 'houseId': tipInfo.houseId});
    if (res3.success) {
      playerInfo = PlayerInfo.fromJson(res3.data);
      print(res3.data);
    }

    HttpManager.get('appealInfo/getOne', data: {
      'userId': StoreProvider.of<AppState>(context).state.userInfo.id,
      'playerInfoId': playerInfo.id,
    }).then((res) {
      if (res.success && res.data != null) {
        setState(() {
          canAppeal = true;
          appealState = 1;
        });
      } else {
        setState(() {
          canAppeal = true;
          appealState = 0;
        });
      }
    });

    // if (tipInfo.typeFlag == 2 || tipInfo.typeFlag == 3) {
    //   if (tipInfo.statusFlag == 0) {
    //     showSuccess(tipInfo.playerInfo.bonus, playerInfo.id);
    //   }
    // }
  }

  void showSuccess(money, playerId) {
    Navigator.of(context).push(
      PageRouteBuilder(
        opaque: false,
        transitionDuration: Duration(milliseconds: 300),
        transitionsBuilder: (BuildContext context, Animation<double> animation, Animation<double> secondaryAnimation, Widget child) {
          return FadeTransition(
            opacity: CurvedAnimation(parent: animation, curve: Curves.linear),
            child: child,
          );
        },
        pageBuilder: (BuildContext context, _, __) {
          return SuccessfulReception(money: money, playerId: playerId);
        },
      ),
    );
  }

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () => getInfo());
  }

  @override
  Widget build(BuildContext context) {
    int type = tipInfo.typeFlag != null ? tipInfo.typeFlag : 0;
    int status = tipInfo.statusFlag ?? 0;
    GameInfo gameInfo;
    if (tipInfo.gameInfo != null) {
      gameInfo = tipInfo.gameInfo;
    }
    return WillPopScope(
      child: Scaffold(
        appBar: AppBar(
          // backgroundColor: PRIMARY_COLOR,
          title: Text('通知详情'),
          centerTitle: true,
          elevation: 0,
        ),
        body: Container(
          color: Color(0xFF2B2B42),
          width: double.infinity,
          height: double.infinity,
          child: SingleChildScrollView(
            child: Column(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(left: 15, right: 15),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Padding(
                        padding: EdgeInsets.symmetric(vertical: 12),
                        child: Text(readTimestamp(tipInfo.createTime, 'yyyy.MM.dd HH:mm:ss'), style: TextStyle(color: Colors.white24, fontSize: 13)),
                      ),
                      Container(
                        height: 1,
                        color: Colors.black26,
                      ),
                      Padding(
                          padding: EdgeInsets.only(top: 10, bottom: 0),
                          child: Text.rich(TextSpan(style: TextStyle(color: Colors.white, fontSize: 14), children: _tipContent(tipInfo.content, context)))),
                    ],
                  ),
                ),
                Container(
                  height: 30,
                ),
                // tipInfo.typeFlag == 4
                //     ? Padding(
                //         padding: EdgeInsets.symmetric(horizontal: 15, vertical: 20),
                //         child: DefaultTextStyle(
                //           style: TextStyle(
                //             fontSize: 13,
                //             color: Colors.white54,
                //           ),
                //           child: Column(
                //             crossAxisAlignment: CrossAxisAlignment.start,
                //             children: <Widget>[
                //               Text('造成此情况等原因可能是：'),
                //               Text('1、确认开始游戏后没有授权系统进行录屏'),
                //               Text('2、视频没有录制到最后的分数名次结算页面就回到APP点击完成比赛了 '),
                //               Text('3、在游戏过程中，猿人点击APP后台进程被退出 '),
                //               Text('4、没有实际进行游戏比赛 '),
                //               Text('5、使用作弊手段录制视频'),
                //             ],
                //           ),
                //         ),
                //       )
                //     : Container(),
                // tipInfo.typeFlag == 5
                //     ? Padding(
                //         padding: EdgeInsets.symmetric(horizontal: 15, vertical: 20),
                //         child: DefaultTextStyle(
                //           style: TextStyle(
                //             fontSize: 13,
                //             color: Colors.white54,
                //           ),
                //           child: Column(
                //             crossAxisAlignment: CrossAxisAlignment.start,
                //             children: <Widget>[
                //               Text('造成此情况等原因可能是：'),
                //               Text('1、游戏结束后没有在规定时间内返回APP点击完成比赛按钮'),
                //             ],
                //           ),
                //         ),
                //       )
                //     : Container(
                //         height: 30,
                //       ),
                // houseInfo != null && tipInfo.typeFlag != 4 && tipInfo.typeFlag != 5 ? RankContent(roomId: houseInfo.id.toString()) : Container(),
                houseInfo != null && type != 3
                    ? HouseItem(
                        houseInfo,
                        gameInfo,
                        playerInfo: playerInfo,
                      )
                    : Container(),
                houseInfo != null && playerInfo != null && type != 3
                    ? (playerInfo != null &&  (type == 4 || type == 0)
                        ? ( type == 0?Container(
                            margin: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                            padding: EdgeInsets.all(15),
                            // height: 239,
                            width: double.infinity,
                            decoration: BoxDecoration(
                                color: Color(0xFF3A3E61),
                                borderRadius: BorderRadius.only(topRight: Radius.circular(8), bottomLeft: Radius.circular(8), bottomRight: Radius.circular(8))),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  '造成此情况等原因可能是：',
                                  style: TextStyle(color: Colors.white54, fontSize: 13),
                                ),
                                Container(
                                  height: 10,
                                ),
                                Text(
                                  '1、倒计时结束内未点击开始',
                                  style: TextStyle(color: Colors.white, fontSize: 13),
                                ),
                              ],
                            ),
                          ):Container(
                            margin: EdgeInsets.symmetric(vertical: 10, horizontal: 15),
                            padding: EdgeInsets.all(15),
                            // height: 239,
                            width: double.infinity,
                            decoration: BoxDecoration(
                                color: Color(0xFF3A3E61),
                                borderRadius: BorderRadius.only(topRight: Radius.circular(8), bottomLeft: Radius.circular(8), bottomRight: Radius.circular(8))),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: <Widget>[
                                Text(
                                  '造成此情况等原因可能是：',
                                  style: TextStyle(color: Colors.white54, fontSize: 13),
                                ),
                                Container(
                                  height: 10,
                                ),
                                Text(
                                  '1、游戏中杀戮人数未到房间任务要求',
                                  style: TextStyle(color: Colors.white, fontSize: 13),
                                ),
                                Text(
                                  '2、没有实际进行游戏比赛 ',
                                  style: TextStyle(color: Colors.white, fontSize: 13),
                                ),
                                Text(
                                  '3、使用作弊手段进行游戏  ',
                                  style: TextStyle(color: Colors.white, fontSize: 13),
                                ),
                                Text(
                                  '4、手机性能或电量过低，在运行和平精英游戏时自动将我们平台APP从后台进程中退掉  ',
                                  style: TextStyle(color: Colors.white, fontSize: 13),
                                ),
                                Text(
                                  '5、游戏时间过长，没有在最大时间内返回平台APP点击结束游戏 ',
                                  style: TextStyle(color: Colors.white, fontSize: 13),
                                ),
                              ],
                            ),
                          ))
                        : _resultContent(houseInfo, playerInfo, tipInfo.typeFlag))
                    : Container(),
                // (type == 2 || type == 3)
                //     ? Container(
                //         width: double.infinity,
                //         height: 48,
                //         padding: EdgeInsets.symmetric(horizontal: 15),
                //         child: status == 0
                //             ? LinearButton(
                //                 btntext: '立即领取',
                //                 onTapHomeMenu: () async {
                //                   Toast.show(context, '加载中', -1, 'loading');
                //                   Result res = type == 2
                //                       ? await HttpManager.post('playerInfo/receive', data: {'id': tipInfo.playerId})
                //                       : await HttpManager.post('systemNotice/receive', data: {'id': widget.tipId});
                //                   Toast.hide();
                //                   if (res.success) {
                //                     if (tipInfo.playerInfo != null) {
                //                       showSuccess(tipInfo.playerInfo.bonus);
                //                     } else {
                //                       showSuccess(tipInfo.bonus);
                //                     }
                //                     getInfo();
                //                   } else {
                //                     Toast.show(context, res.error, 1000, 'info');
                //                   }
                //                 },
                //               )
                //             : LinearButton(btntext: '已领取', colorList: [Color(0xFFC99C09), Color(0xFFC7873E)], textColor: Color(0xFF252532)),
                //       )

                // RaisedButton(
                //   textColor: Colors.white,
                //   disabledColor: Color(0xFF763939),
                //   disabledTextColor: Color(0xFF252532),
                //   child: Text(status==0?'立即领取':'已领取'),
                //   onPressed: status==0?() async {
                //     Toast.show(context, '加载中', -1, 'loading');
                //     Result res = type == 2
                //         ? await HttpManager.post('playerInfo/receive',
                //             data: {'id': tipInfo.playerId})
                //         : await HttpManager.post('systemNotice/receive',
                //             data: {'id': widget.tipId});
                //     Toast.hide();
                //     if (res.success) {
                //       if (tipInfo.playerInfo != null) {
                //         showSuccess(tipInfo.playerInfo.bonus);
                //       } else {
                //         showSuccess(tipInfo.bonus);
                //       }
                //       getInfo();
                //     } else {
                //       Toast.show(context, res.error, 1000, 'info');
                //     }
                //   }:null,
                // ),

                // : Container(),
                // CustomPaint(
                //   painter: CircleProgressBarPainter(
                //       Color(0xFFDCA659), Color(0xFFAE4945), 0.0, 270.0, 360.0, 18.0),
                //   size: Size(108.0, 108.0),
                // )
              ],
            ),
          ),
        ),
        floatingActionButton: _btnContent(),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
      ),
      onWillPop: () {
        Navigator.of(context).pop(true);
        Toast.hide();
        return Future.value(false);
      },
    );
  }

  Widget _btnContent() {
    if (tipInfo.typeFlag == 2 || tipInfo.typeFlag == 3) {
      if (tipInfo.statusFlag == 0) {
        return Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 20),
            height: 88,
            child: LinearButton(
              btntext: '立即领取',
              onTapHomeMenu: () async {
                Toast.show(context, '加载中', -1, 'loading');
                Result res = tipInfo.typeFlag == 2
                    ? await HttpManager.post('playerInfo/receive', data: {'id': tipInfo.playerId})
                    : await HttpManager.post('systemNotice/receive', data: {'id': widget.tipId});
                Toast.hide();
                if (res.success) {
                  showSuccess(tipInfo.playerInfo.bonus, playerInfo.id);
                  getInfo();
                } else {
                  Toast.show(context, res.error, 1000, 'info');
                }
              },
            ));
      } else {
        return Container(
            width: double.infinity,
            padding: EdgeInsets.symmetric(horizontal: 15, vertical: 20),
            height: 88,
            child: LinearButton(btntext: '已领取', colorList: [Color(0xFFB34A4A), Color(0xFFB34A4A)], textColor: Color(0xFF252532)));
      }
    } else if ((tipInfo.typeFlag == 4 || tipInfo.typeFlag == 5 || (playerInfo != null && playerInfo.dataError)) && canAppeal && appealState == 0) {
      return Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(horizontal: 15, vertical: 20),
          height: 88,
          child: LinearButton(
            btntext: '申诉结果',
            colorList: [Color(0xFFAF4946), Color(0xFFAF4946)],
            textColor: Colors.white,
            onTapHomeMenu: () async {
              final success = await Navigator.push(context, CupertinoPageRoute(builder: (context) => Appeal(playerInfo)));
              if (success != null && success) {
                Toast.show(context, '提交成功', 1500, 'success');
                setState(() {
                  appealState = 1;
                });
              }
            },
          ));
    } else if (tipInfo.typeFlag != 3 && canAppeal && appealState == 1) {
      return Container(
          width: double.infinity,
          padding: EdgeInsets.symmetric(horizontal: 15, vertical: 20),
          height: 88,
          child: LinearButton(btntext: '已提交申诉', colorList: [Color(0xFFAF4946), Color(0xFFAF4946)], textColor: Color(0xFF252532)));
    } else {
      return Container();
    }
  }

  List<TextSpan> _tipContent(content, context) {
    // String content = '很遗憾，你在2019-06-05 09:23开始的游戏竞赛 [15166的吃鸡房间]，[无有效结果]，无法获得奖励，该局参赛人数[2]人。';
    List<String> contentlist1 = content.split('[');
    List<Map> totalContent = [];
    contentlist1.forEach((item) {
      List _list = item.split(']');
      if (_list.length > 1) {
        totalContent.add({
          "content": _list[0],
          "isImport": true,
        });
        totalContent.add({
          "content": _list[1],
          "isImport": false,
        });
      } else {
        totalContent.add({
          "content": _list[0],
          "isImport": false,
        });
      }
    });

    List<TextSpan> _widgetList = [];
    totalContent.forEach((item) {
      if (item['isImport']) {
        _widgetList.add(TextSpan(text: ' ' + item['content'] + ' ', style: TextStyle(color: Color(0xFFFFB726), fontWeight: FontWeight.w600)));
      } else {
        _widgetList.add(TextSpan(text: item['content']));
      }
    });

    return _widgetList;
  }

  Widget _resultContent(HouseInfo houseInfo, PlayerInfo playerInfo, int typeFlag) {
    List jiangpaiImg = ['images/jiangpai_huangjin.png', 'images/jiangpai_baiyin.png', 'images/jiangpai_qingtong.png', 'images/jiangpai_bojin.png'];

    String img = '';
    if (playerInfo != null) {
      if (playerInfo.medal == 'platinum') {
        img = jiangpaiImg[3];
      } else if (playerInfo.medal == 'gold') {
        img = jiangpaiImg[0];
      } else if (playerInfo.medal == 'silver') {
        img = jiangpaiImg[1];
      } else if (playerInfo.medal == 'bronze') {
        img = jiangpaiImg[2];
      }
    }
    return Column(children: <Widget>[
      Container(
        margin: EdgeInsets.symmetric(vertical: 5, horizontal: 15),
        padding: EdgeInsets.all(15),
        height: 140,
        decoration: BoxDecoration(color: Color(0xFF3A3E61), borderRadius: BorderRadius.all(Radius.circular(4))),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: <Widget>[
            Text('比赛结果', style: TextStyle(color: Colors.white54, fontSize: 13)),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text("参数成员 ", style: TextStyle(color: Colors.white, fontSize: 14)),
                Text("${houseInfo.playerNumber}人 ", style: TextStyle(color: Color(0xFFFFB726), fontWeight: FontWeight.w500, fontSize: 14))
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text("我的排名", style: TextStyle(color: Colors.white, fontSize: 14)),
                Text("${playerInfo.houseRank}", style: TextStyle(color: Color(0xFFFFB726), fontWeight: FontWeight.w500, fontSize: 14))
              ],
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text("获得积分 ", style: TextStyle(color: Colors.white, fontSize: 14)),
                Row(
                  children: <Widget>[
                    Image.asset('images/icon_jifen.png'),
                    Text('x${playerInfo.bonus}', style: TextStyle(color: Color(0xFFFFB726), fontWeight: FontWeight.w500, fontSize: 14))
                  ],
                )
              ],
            )
          ],
        ),
      )
    ]);
  }
}

//比赛结束排名
class RankContent extends StatefulWidget {
  RankContent({Key key, this.roomId}) : super(key: key);
  final String roomId; // 用来储存传递过来的值
  @override
  RankContentState createState() => RankContentState();
}

class RankContentState extends State<RankContent> {
  List<PlayerInfo> topList = [];
  Future<void> getTopList() async {
    Toast.show(context, '加载中', -1, 'loading');
    Result res = await HttpManager.get('playerInfo/rankPage', data: {'houseId': widget.roomId, 'currentPage': 1, 'pageNumber': 3});
    Toast.hide();
    List<PlayerInfo> list = [];
    if (res.success) {
      for (var item in res.data['pp']) {
        PlayerInfo jonPlayer = PlayerInfo.fromJson(item);
        list.add(jonPlayer);
      }
    } else {}
    setState(() {
      topList = list;
    });
  }

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero, () {
      getTopList();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: double.infinity,
      height: 180,
      margin: EdgeInsets.only(top: 15),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.end,
        children: <Widget>[_rankItem(2), _rankItem(1), _rankItem(3)],
      ),
    );
  }

  Widget _rankItem(int _num) {
    if (_num > topList.length) {
      return Container(
        width: 107,
        height: 60,
      );
    }
    List colorList = [
      [Color(0xFFD48E00), Color(0xFFFECF01)],
      [Color(0xFFC5C5C5), Color(0xFFE3E3E3)],
      [Color(0xFFE77023), Color(0xFFF89E58)]
    ];
    List imgList = ['images/jiangpai_huangjin.png', 'images/jiangpai_baiyin.png', 'images/jiangpai_qingtong.png'];
    return Container(
      padding: EdgeInsets.only(left: 15, right: 15, top: _num == 1 ? 0 : 15),
      width: 107,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          Container(
            child: Stack(
              children: <Widget>[
                Container(
                  margin: EdgeInsets.only(top: 17, bottom: 20),
                  width: _num == 1 ? 70 : 60,
                  height: _num == 1 ? 70 : 60,
                  decoration: BoxDecoration(
                    gradient: LinearGradient(colors: colorList[_num - 1], begin: Alignment.topLeft, end: Alignment.bottomRight),
                    borderRadius: BorderRadius.all(Radius.circular(100)),
                  ),
                  child: Center(
                      child: Container(
                    width: _num == 1 ? 60 : 50,
                    height: _num == 1 ? 60 : 50,
                    child: CircleAvatar(backgroundImage: NetworkImage(topList[_num - 1].userInfo.icon)),
                  )),
                ),
                Positioned(
                  bottom: 0,
                  child: Center(
                    child: Image.asset(
                      'images/ph_yinpai_no' + '$_num.png',
                      width: 67,
                    ),
                  ),
                ),
                Positioned(
                  top: 0,
                  left: _num == 1 ? 19 : 14,
                  child: Center(
                    child: Image.asset(
                      imgList[_num - 1],
                    ),
                  ),
                ),
              ],
            ),
          ),
          Text(
            topList[_num - 1].userInfo.nickname,
            style: TextStyle(
              color: Color(0xFFFDC372),
              fontSize: 12,
            ),
            overflow: TextOverflow.ellipsis,
            textAlign: TextAlign.center,
          ),
          // SizedBox(
          //   height: 5,
          // ),
          // Row(
          //   mainAxisAlignment: MainAxisAlignment.center,
          //   children: <Widget>[
          //     Image.asset('images/icon_jinbi_xiao_hong.png', width: 20),
          //     Text('×' + (topList[_num - 1].bonus != null ? topList[_num - 1].bonus.toString() : '0'), style: TextStyle(color: PRIMARY_COLOR, fontSize: 12))
          //   ],
          // )
        ],
      ),
    );
  }
}
