import 'package:flutter/material.dart';
import '../styles/colors.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 '../pages/RoomInfo.dart';
import '../widget/SuccessfulReception.dart';
import '../widget/CircleProgressBarPainter.dart';

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;
  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);
      });
    }

    print(tipInfo.bonus);

    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);
      });
    }
  }

  void showSuccess(money) {
    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);
        },
      ),
    );
  }

  @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 new 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: Column(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.only(left: 15, right: 45),
                  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: 17),
                        child: Text(
                          tipInfo.content,
                          style: TextStyle(color: Colors.white, fontSize: 14),
                        ),
                      )
                    ],
                  ),
                ),
                houseInfo != null && type != 3
                    ? houseItem(roomInfo: houseInfo, gameInfo: gameInfo)
                    : Container(),
                (type == 2 || type == 3)
                    ? Container(
                        width: double.infinity,
                        height: 48,
                        padding: EdgeInsets.symmetric(horizontal: 15),
                        child: 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),
                // )
              ],
            ),
          )),
      onWillPop: () {
        Navigator.of(context).pop(true);
        Toast.hide();
        return Future.value(false);
      },
    );
  }
}

class houseItem extends StatelessWidget {
  houseItem({Key key, this.roomInfo, this.gameInfo}) : super(key: key);
  final HouseInfo roomInfo;
  final GameInfo gameInfo;
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(bottom: 50),
      decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [Color(0xFF3F4261), Color(0xFF323456)],
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
          ),
          border: Border(bottom: BorderSide(color: Colors.black, width: 1))),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          child: Padding(
            padding: EdgeInsets.all(15),
            child: Row(
              children: <Widget>[
                Image.network(
                  gameInfo.icon,
                  width: 48,
                  height: 48,
                ),
                Container(
                  width: 10,
                ),
                Expanded(
                  flex: 1,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          LimitedBox(
                            maxWidth: 170,
                            child: Text(
                              roomInfo.houseName,
                              style: TextStyle(
                                  color: Colors.white,
                                  fontSize: 14,
                                  fontWeight: FontWeight.w500),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ),
                          Container(
                            margin: EdgeInsets.only(left: 6),
                            child: Image.network(roomInfo.houseLevel.icon,
                                width: 14),
                          ),
                          Container(
                              margin: EdgeInsets.only(left: 1),
                              child: Text(
                                roomInfo.houseLevel.levelName,
                                style: TextStyle(
                                    color: Color(0xFFF9D881), fontSize: 9),
                              )),
                        ],
                      ),
                      Text(
                        roomInfo.houseAbstract,
                        style: TextStyle(
                            fontSize: 12,
                            fontWeight: FontWeight.w400,
                            color: Color(0xFF9BA0AE)),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                      )
                    ],
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    Image.asset('images/icon_renshu.png', width: 20),
                    Text(
                      (roomInfo.playerNumber != null
                              ? roomInfo.playerNumber.toString()
                              : '0') +
                          '/' +
                          roomInfo.maxNumber.toString(),
                      style: TextStyle(
                          fontSize: 14,
                          fontWeight: FontWeight.w500,
                          color: Color(0xFFB1B2C0)),
                    )
                  ],
                )
              ],
            ),
          ),
          onTap: () {
            Navigator.push(
                context,
                new CupertinoPageRoute(
                    builder: (context) =>
                        new RoomInfo(roomId: roomInfo.id.toString())));
          },
        ),
      ),
    );
  }
}
