/*
 * @author dx
 * @date   2019-09-17
 **/
import 'dart:async';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart' as IMAGE;
import 'package:flutter_boost/flutter_boost.dart';
import 'package:gmalpha_flutter/ActivityReportModel/page/AnimationList.dart';
import 'package:gmalpha_flutter/ActivityReportModel/service/remote/entity/ActivityReportEntity.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gmalpha_flutter/ActivityReportModel/page/ActivityReportModel.dart';
import 'package:gmalpha_flutter/commonModel/ui/ALColors.dart';

final _goldenColor = Color(0xFFB59C64);

class ActivityReportPage extends StatefulWidget {
  ActivityReportModel _model;

  ActivityReportPage(String cookie, int id, int type) {
    _model = new ActivityReportModel(cookie, id, type);
  }

  @override
  State<StatefulWidget> createState() => ActivityReportState(_model);
}

class ActivityReportState extends State<ActivityReportPage> {
  ActivityReportModel _model;


  ActivityReportState(this._model);

  @override
  void initState() {
    super.initState();
    _model.init(context);
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 375, height: 667)..init(context);
    return Scaffold(
      appBar: AppBar(
        title: Text(''),
        centerTitle: true,
        leading: IconButton(
          onPressed: () {
            FlutterBoost.singleton.openPage('url', {});
          },
          icon: Icon(
            Icons.keyboard_arrow_left,
          ),
        ),
        actions: <Widget>[
          GestureDetector(
            child: Container(
              margin: EdgeInsets.only(right: 30),
              child: Center(
                child: Text(
                  '再测一次',
                  style: TextStyle(
                    color: ALColors.Color323232,
                    fontSize: 14,
                    fontWeight: FontWeight.bold
                  ),
                )
              )
            ),
            onTap: () {
              FlutterBoost.singleton.openPage('url', {});
            },
          )
        ],        
      ),
      body: StreamBuilder<ActivityReportEntity>(
        stream: _model.activityReportLive.stream,
        initialData: _model.activityReportLive.data,
        builder: (context, data) {
          if (data.data == null) {
            return loadingItem();
          }
          if (data.data.error != 0 || data.data.data == null) {
            return errorItem(data.data.message);
          }
          return Container(
            padding: EdgeInsets.only(left: ScreenUtil().setWidth(16), right: ScreenUtil().setWidth(16)),
            child: SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  TopCard(share: data.data.data.report.share),
                  // SizedBox(height: ScreenUtil().setHeight(41)),
                  // // AnimatedListSample(pictorialList: data.data.data.report.cards),
                  // PictorialCard(pictorialList: data.data.data.report.cards),
                  // SizedBox(height: ScreenUtil().setHeight(38))
                ],
              ),
            ),
          );
        },
      )
    );
  }

  Widget errorItem(String reason) {
    return Center(
      child: Text("$reason"),
    );
  }

  Widget loadingItem() {
    return Center(
      child: CircularProgressIndicator()
    ); 
  }

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

class TopCard extends StatelessWidget {
  final share;
  TopCard({Key key, this.share}) : super(key: key);

  _moneyContainer(val) {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            decoration: BoxDecoration(
              border: Border(
                bottom: BorderSide(color: Color(0xffeeeeee), width: 1.0))
            ),
            margin: EdgeInsets.only(left: 18, right: 18),
            height: 62,
            child: Row(
              children: <Widget>[
                Text(
                  '¥',
                  style: TextStyle(
                    fontSize: 28,
                    color: _goldenColor,
                    fontWeight: FontWeight.bold
                  )
                ),
                SizedBox(width: 8),
                Text(
                  '$val',
                  style: TextStyle(
                    color: _goldenColor,
                    fontSize: 45,
                    fontWeight: FontWeight.bold
                  )
                ),
              ]
            ),
          )
        ],
      )
    );
  }

  _percentageContainer(val) {
    return Container(
      child: Row(
        children: <Widget>[
          Text(
            '$val%',
            style: TextStyle(
              fontSize: 24,
              color: _goldenColor,
              fontWeight: FontWeight.bold,
              height: 34/24
            ),
          ),
          SizedBox(width: 4),
          Text(
            '的全国同龄人',
            style: TextStyle(
              fontSize: 11,
              color: _goldenColor,
              fontWeight: FontWeight.bold,
              height: 2
            ),
          )
        ],
      ) 
    );
  }

  _rankingContainer(val) {
    return Container(
      child: Row(
        children: <Widget>[
          Text(
            '第',
            style: TextStyle(
              fontSize: 11,
              color: _goldenColor,
              fontWeight: FontWeight.bold,
              height: 2
            ),
          ),
          SizedBox(width: 4),
          Text(
            '$val',
            style: TextStyle(
              fontSize: 24,
              color: _goldenColor,
              fontWeight: FontWeight.bold,
              height: 34/24
            ),
          ),
          SizedBox(width: 4),
          Text(
            '名',
            style: TextStyle(
              fontSize: 11,
              color: _goldenColor,
              fontWeight: FontWeight.bold,
              height: 2
            ),
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.white,
      width: ScreenUtil().setWidth(343),
      height: ScreenUtil().setHeight(277),
      child: Container(
        width: ScreenUtil().setWidth(343),
        height: ScreenUtil().setHeight(277),
        decoration: BoxDecoration(
          border: Border.all(color: ALColors.Color323232, width: ScreenUtil().setWidth(2))
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            SizedBox(
              height: ScreenUtil().setHeight(8.5),
              child: Container(
                margin: EdgeInsets.only(top: ScreenUtil().setHeight(.5)),
                color: ALColors.Color323232,
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: ScreenUtil().setWidth(18), top: ScreenUtil().setHeight(20)),
              child: Text(
                '你一年的颜值氪金约为：', 
                textAlign: TextAlign.left,
                style: TextStyle(
                  color: ALColors.Color323232,
                  fontSize: ScreenUtil().setSp(12),
                  fontWeight: FontWeight.bold,
                  letterSpacing: 1.5,
                ),
              )
            ),
            AnimationNumber(targetNmber: share.totalCost, delay: 400, container: _moneyContainer),
            Container(
              padding: EdgeInsets.only(
                left: ScreenUtil().setWidth(18),
                right: ScreenUtil().setWidth(18),
                top: ScreenUtil().setHeight(14)
              ),
              child: AnimationCharacter(targetNmber: 1, delay: 1000)
            ),
            Container(
              padding: EdgeInsets.only(
                left: ScreenUtil().setWidth(18),
                right: ScreenUtil().setHeight(18),
                top: ScreenUtil().setHeight(16)
              ),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Container(
                    color: Color(0xFFF6F6F6),
                    width: ScreenUtil().setWidth(139),
                    height: ScreenUtil().setHeight(55),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(left: ScreenUtil().setWidth(8), top: ScreenUtil().setHeight(4)),
                          child: Text(
                            '你的氪金量超过了',
                            style: TextStyle(
                              fontSize: ScreenUtil().setSp(11),
                              color: ALColors.Color8E8E8E,
                              fontWeight: FontWeight.bold
                            )
                          ),
                        ),
                        Stack(
                          children: <Widget>[
                            Container(
                              width: double.maxFinite,
                              height: ScreenUtil().setHeight(32),
                            ),
                            Positioned(
                              right: ScreenUtil().setWidth(8),
                              bottom: 0,
                              child: AnimationNumber(targetNmber: share.beat, delay: 1000, container: _percentageContainer)
                            )
                          ],
                        )
                      ],
                    ),
                  ),
                  Container(
                    color: Color(0xFFF6F6F6),
                    width: ScreenUtil().setWidth(139),
                    height: ScreenUtil().setHeight(55),
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.spaceBetween,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Container(
                          margin: EdgeInsets.only(top: ScreenUtil().setHeight(4), left: ScreenUtil().setWidth(14)),
                          child: Text(
                            '你的氪金排名为全国',
                            style: TextStyle(
                              fontSize: ScreenUtil().setSp(11),
                              color: Color(0xFF8E8E8E),
                              fontWeight: FontWeight.bold
                            )
                          )
                        ),
                        Stack(
                          children: <Widget>[
                            Container(
                              width: double.maxFinite,
                              height: ScreenUtil().setHeight(32),
                            ),
                            Positioned(
                              right: ScreenUtil().setWidth(11),
                              bottom: 0,
                              child: AnimationNumber(targetNmber: share., delay: 1000, container: _rankingContainer),
                            )
                          ],
                        )
                      ],
                    ),
                  )
                ],
              )
            )
          ],
        ),
      )
    );
  }
}

class PictorialCard extends StatelessWidget {
  final List<Cards> pictorialList;
  
  PictorialCard({Key key, this.pictorialList}) : super(key: key);

  Widget _gridViewItemUI(BuildContext context, item) {
    return Container(
      padding: EdgeInsets.all(3),
      child: CachedNetworkImage(
        imageUrl: item.image + '-w',
        width: ScreenUtil().setWidth(110),
        height: ScreenUtil().setHeight(110)
      )
    );
  }

  Widget _listViewUI(BuildContext context, item) {
    List<Widget> list = [];
    item.drafts.forEach((item){
      list.add(_gridViewItemUI(context,item));
    });
    return Container(
      child: GestureDetector(
        onTap: () {
          FlutterBoost.singleton.openPage(item.protocol, {});
        },
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Padding(
              padding: EdgeInsets.only(bottom: 14.0),
              child: Wrap(
                children: list
              ),
            ),
            Container(
              width: ScreenUtil().setWidth(343),
              height: ScreenUtil().setHeight(53),
              color: Colors.white,
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Stack(
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.only(right: 12),
                        child: Text(
                          '${item.guide}',
                          style: TextStyle(
                            color: Color(0xFF323232),
                            fontWeight: FontWeight.bold,
                            fontSize: ScreenUtil().setSp(14)
                          ),
                        ),
                      ),
                      Positioned(
                        width: ScreenUtil().setWidth(10),
                        height: ScreenUtil().setHeight(20),
                        top: ScreenUtil().setHeight(2),
                        right: 0,
                        child: IMAGE.Image.asset('images/right_icon.png', width: ScreenUtil().setWidth(5), height: ScreenUtil().setHeight(10)),
                      )
                    ],
                  )
                ],
              )
            )
          ],
        )
      )
    );
  }
  
  @override
  Widget build(BuildContext context) {
    return Column(
      children: pictorialList.map((item) {
        return _listViewUI(context, item);
      }).toList(),
    );
  }
}

class AnimationNumber extends StatefulWidget {
  final targetNmber;
  final delay;
  final container;
  AnimationNumber({Key key, this.targetNmber, this.delay, this.container}) : super(key: key);

  _AnimationNumberState createState() => _AnimationNumberState();
}

class _AnimationNumberState extends State<AnimationNumber> with TickerProviderStateMixin {
  AnimationController _animationController;
  var _timer;

  @override
  void initState() { 
    super.initState();
    _animationController = AnimationController(
      duration: Duration(milliseconds: widget.delay),
      lowerBound: 0,
      upperBound: widget.targetNmber,
      vsync: this
    );

    _animationController.addListener((){
      setState(() {
      });
    });
  }
  @override
  void dispose() {
    super.dispose();
    _animationController.dispose();
    _timer.dispose();
  }

  @override
  Widget build(BuildContext context) {
    
     _timer = Timer(Duration(seconds: 1), (){
      _animationController.forward();
    });
    return widget.container(_animationController.value.toInt());
  }
}

class AnimationCharacter extends StatefulWidget {
  final targetNmber;
  final delay;
  AnimationCharacter({Key key, this.targetNmber, this.delay}) : super(key: key);

  _AnimationCharacterState createState() => _AnimationCharacterState();
}

class _AnimationCharacterState extends State<AnimationCharacter> with TickerProviderStateMixin {
  AnimationController _animationController;
  var _timer;
  List peopleList;
  double margin = 0;  

  @override
  void initState() { 
    super.initState();
    _animationController = AnimationController(
      duration: Duration(milliseconds: widget.delay),
      lowerBound: 0,
      upperBound: 10,
      vsync: this
    );

    peopleList = [
      {'url': 'images/light_grey_person.png', 'width': 14.0, 'height': 36.0},
      {'url': 'images/light_grey_person.png', 'width': 14.0, 'height': 36.0},
      {'url': 'images/light_grey_person.png', 'width': 14.0, 'height': 36.0},
      {'url': 'images/light_grey_person.png', 'width': 14.0, 'height': 36.0},
      {'url': 'images/light_grey_person.png', 'width': 14.0, 'height': 36.0},
      {'url': 'images/light_grey_person.png', 'width': 14.0, 'height': 36.0},
      {'url': 'images/light_grey_person.png', 'width': 14.0, 'height': 36.0},
      {'url': 'images/light_grey_person.png', 'width': 14.0, 'height': 36.0},
      {'url': 'images/light_grey_person.png', 'width': 14.0, 'height': 36.0},
      {'url': 'images/light_grey_person.png', 'width': 14.0, 'height': 36.0},
      {'url': 'images/light_grey_person.png', 'width': 14.0, 'height': 36.0}
    ];

    final target = widget.targetNmber.ceil() / 10;
    _animationController.addListener(() {
      var value = _animationController.value;
      double percent = value / 10;
      double frist = target / 10;
      int nowValue;
      
      setState(() {
        peopleList.forEach((item) {
          int index = peopleList.indexOf(item);
          if(percent < frist) {
            double tempPercent = percent / frist;
            nowValue = (target * tempPercent).ceil();
            margin= ScreenUtil().setWidth(6 + (29 * nowValue).ceil());
            if(index != nowValue) {
              item['url'] = 'images/dark_grey_person.png';
            }else{
              item['url'] = 'images/golden_person.png';
            }
          } else {
            double tempPercent = (percent - frist) / (1 - frist);
            nowValue = (target + (11 - target) * tempPercent).ceil();
            if(index > target && index <= nowValue) {
              item['url'] = 'images/black_person.png';
            }
          }
        });
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _animationController.dispose();
    _timer.dispose();
  }

  Widget _peopleViewUI(BuildContext context, item) {
    return IMAGE.Image.asset(item['url'], width: ScreenUtil().setWidth(item['width']), height: ScreenUtil().setHeight(item['height']));
  }

  @override
  Widget build(BuildContext context) {
     _timer = Timer(Duration(seconds: 1), () {
      _animationController.forward();
    });
    return Column(
      children: <Widget>[
        _youContainer(),
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: peopleList.map((item) {
            return _peopleViewUI(context, item);
          }).toList()
        )
      ],
    );
  }

   _youContainer() {
    return Container(
      child: Stack(
        children: <Widget>[
          Container(
            width: double.maxFinite,
            height: ScreenUtil().setHeight(19),
            margin: EdgeInsets.only(bottom: ScreenUtil().setHeight(4)),
          ),
          Positioned(
            child: Container(
              margin: EdgeInsets.only(left: margin),
              width: ScreenUtil().setWidth(32),
              height: ScreenUtil().setHeight(19),
              child: IMAGE.Image.asset('images/you_icon.png'),
            )
          )
        ]
      )
    );
  }
}
