import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:sport/bean/achievement_info.dart';
import 'package:sport/bean/user.dart';
import 'package:sport/provider/achievement_info_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/box.dart';
import 'package:sport/widgets/error.dart';
import 'package:sport/widgets/misc.dart';
import 'package:sport/widgets/space.dart';

class AchievementPage extends StatefulWidget {
  final AchievementInfoData data;

  AchievementPage(this.data);

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

class _PageState extends State<AchievementPage> {
  AchievementInfoModel _achievementInfoModel = new AchievementInfoModel(1);

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initData();
  }

  initData() async {
    await _achievementInfoModel.getAchievementInfo();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // provider 只能有一个？
      body: CustomScrollView(slivers: <Widget>[
        buildSliverAppBar(context, "我的成就", backgroundColor: Theme.of(context).scaffoldBackgroundColor),
        SliverToBoxAdapter(
            child: Padding(
          padding: EdgeInsets.symmetric(vertical: 16.0, horizontal: 13.0),
          child: Column(
            children: <Widget>[
              Row(children: <Widget>[
                Text("我的勋章: ", style: Theme.of(context).textTheme.bodyText2.copyWith(color: Color(0xff666666))),
                Text("${widget.data.getAchievementCount}枚勋章已获得", style: Theme.of(context).textTheme.bodyText2.copyWith(color: Theme.of(context).accentColor))
              ]),
              Padding(
                padding: EdgeInsets.symmetric(vertical: 10.0),
                child: ClipRRect(
                  borderRadius: BorderRadius.circular(10),
                  child: Container(
                    child: CustomPaint(
                      painter: _ProgressBar(
//                                1.0
                        widget.data.exp / (widget.data.nextLevelExp + widget.data.exp), Color(0xffdcdcdc)
                      ),
                      child: Container(
                        height: 12,
                      ),
                    ),
                  ),
                ),
              ),
              Container(
                alignment: Alignment.centerLeft,
                child: Text("收集进度 ${widget.data.getAchievementPercent}%", style: Theme.of(context).textTheme.bodyText1.copyWith(fontSize: 11.0)),
              ),
            ],
          ),
        )),
        SliverToBoxAdapter(
          child: BoxWidget(
            body: Column(
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 8.0),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Divider(
                          endIndent: 10.0,
                        ),
                      ),
                      Text("已获得成就"
                         , style: Theme.of(context).textTheme.bodyText1,),
                      Expanded(
                          child: Divider(
                        indent: 10.0,
                      )),
                    ],
                  ),
                ),
                if (widget.data.getAchievementList.length == 0)
                  Padding(
                      padding: const EdgeInsets.all(24.0),
                      child: Column(
                        children: <Widget>[
                          Image.asset("lib/assets/img/${RequestErrorWidget.ASSETS_NO_RANK}"),
                          Padding(
                            padding: const EdgeInsets.fromLTRB(0, 12, 0, 12),
                            child: Text("还未获得任何成就",style: Theme.of(context).textTheme.bodyText2,),
                          ),
                        ],
                      )),
                if (widget.data.getAchievementList.length > 0)
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 16.0),
                    child: StaggeredGridView.countBuilder(
                      padding: EdgeInsets.zero,
                      shrinkWrap: true,
                      physics: NeverScrollableScrollPhysics(),
                      crossAxisCount: 3,
                      itemCount: widget.data.getAchievementList.length,
                      itemBuilder: (BuildContext context, int index) => achievementWidget(context, widget.data.getAchievementList[index], isRadius: false,w: 84),
                      mainAxisSpacing: 18.0,
                      crossAxisSpacing: 12.0,
                      staggeredTileBuilder: (int index) => StaggeredTile.fit(1),
                    ),
                  ),
                if (widget.data.getAchievementList.length > 0)
                  Center(
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: <Widget>[
                        Image.asset("lib/assets/img/icon_problem.png"),
                        SizedBox(width: 2,),
                        Text(
                          "默认排序按最近获得顺序",
                          style: Theme.of(context).textTheme.bodyText1.copyWith(color: Color(0xffcecece)),
                        ),
                      ],
                    ),
                  ),
                Padding(
                  padding: EdgeInsets.only(top: 31.0),
                  child: Row(
                    children: <Widget>[
                      Expanded(
                        child: Divider(
                          endIndent: 10.0,
                        ),
                      ),
                      Text("未获得成就", style: Theme.of(context).textTheme.bodyText1),
                      Expanded(
                          child: Divider(
                        indent: 10.0,
                      )),
                    ],
                  ),
                ),
                getList(widget.data)
              ],
            ),
          ),
        ),
      ]),
    );
  }
}

ListView getList(data) {
  return ListView.builder(
    padding: EdgeInsets.zero,
    physics: NeverScrollableScrollPhysics(),
    itemCount: data?.remainAchievementList?.length ?? 0,
    shrinkWrap: true,
    itemBuilder: (BuildContext context, int index) {
      Achievement item = data.remainAchievementList[index];
      return Padding(
        padding: EdgeInsets.symmetric(vertical: 15.0),
        child: Column(
          children: <Widget>[
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: <Widget>[
                Column(
                  children: <Widget>[
                    ColorFiltered(
                      colorFilter: ColorFilter.mode(Colors.white, BlendMode.color),
                      child: CachedNetworkImage(width: 70.0, height: 70.0, imageUrl: item.logo),
                    ),
                  ],
                ),
                Space(
                  width: 12,
                ),
                Expanded(
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: <Widget>[
                      Row(
                        children: <Widget>[
                          Text("成就名称：", style: Theme.of(context).textTheme.subtitle1),
                          Text("${item.name}", style: Theme.of(context).textTheme.bodyText2.copyWith(color: Theme.of(context).accentColor))
                        ],
                      ),
                      Space(
                        height: 5,
                      ),
                      Row(
                        children: <Widget>[
                          Text("成就奖励：", style: Theme.of(context).textTheme.subtitle1),
                          Text("经验值+${item.rewardExp},积分+${item.rewardScore}", style: Theme.of(context).textTheme.bodyText2)
                        ],
                      ),
                      Space(
                        height: 5,
                      ),
                      Row(
                        children: <Widget>[
                          Text("成就条件：", style: Theme.of(context).textTheme.subtitle1),
                          Expanded(
                            child: Text("${item.conditionDetail}", style: Theme.of(context).textTheme.bodyText2),
                          ),
                        ],
                        crossAxisAlignment: CrossAxisAlignment.start,
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Space(
              height: 8,
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: <Widget>[
                Text(
                  '${item.conditionProgress}',
                  style: Theme.of(context).textTheme.subtitle1.copyWith(color: Theme.of(context).accentColor,fontSize: 12),
                ),
                Text(
                  '/${item.conditionCount}',
                  style: Theme.of(context).textTheme.bodyText1,
                )
              ],
            ),
            Space(
              height: 2,
            ),
            ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: Container(
                child: CustomPaint(
                  painter: _ProgressBar(item.conditionProgress / (item.conditionCount + item.conditionProgress), Color(0xfff1f1f1)),
                  child: Container(
                    height: 8,
                  ),
                ),
              ),
            ),
          ],
        ),
      );
    },
  );
}

class _ProgressBar extends CustomPainter {
  final Color bg;
   Paint _paint;
  final Paint _indicatorPaint = Paint()
    ..color = Color(0xffFFC400)
    ..isAntiAlias = true;

  double _paddingBar = 2;

  double percent;

  _ProgressBar(this.percent,this.bg){
    _paint = Paint()
      ..color = bg
      ..isAntiAlias = true;
  }

  @override
  void paint(Canvas canvas, Size size) {
    double indicator = size.width * min(1.0, this.percent);
    canvas.save();
    var rect = Rect.fromLTRB(0, size.height - 13, size.width, size.height);
    canvas.clipRRect(RRect.fromRectAndRadius(rect, Radius.circular(size.height / 2)), doAntiAlias: true);

    canvas.drawRect(rect, _paint);

    Paint _valuePaint = Paint()
      ..shader = LinearGradient(
        begin: Alignment.centerLeft,
        end: Alignment.centerRight,
        colors: <Color>[Color(0xffFFE600), Color(0xffFF9100)],
      ).createShader(rect);
    canvas.drawRect(Rect.fromLTRB(0, size.height - 13, size.width * this.percent, size.height), _valuePaint);

    canvas.restore();

    Path path = Path()
      ..moveTo(indicator, size.height - 13 - _paddingBar)
      ..lineTo(indicator - 5, 0)
      ..lineTo(indicator + 5, 0)
      ..close();
    canvas.drawPath(path, _indicatorPaint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}
