import 'dart:convert';
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_easyrefresh/easy_refresh.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:provider/provider.dart';
import 'package:sport/bean/achievement_info.dart';
import 'package:sport/bean/rank_game_info.dart';
import 'package:sport/bean/user.dart';
import 'package:sport/provider/lib/provider_widget.dart';
import 'package:sport/provider/lib/simple_model.dart';
import 'package:sport/provider/user_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/router/routes.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/box.dart';
import 'package:sport/widgets/error.dart';
import 'package:sport/widgets/image.dart';
import 'package:sport/widgets/loading.dart';
import 'package:sport/widgets/misc.dart';
import 'package:sport/widgets/space.dart';

import 'achievement_page.dart';

class LevelPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _PageState();
}

class _PageState extends State<LevelPage> with InjectLoginApi {
  SimpleModel _model;
  bool _max = false;

  @override
  void initState() {
    super.initState();
    _model = SimpleModel((page) async => [(await loginApi.getAchievementInfo()).data]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: ProviderWidget<SimpleModel>(
      model: _model,
      onModelReady: (model) => model.initData(),
      builder: (_, model, __) {
        AchievementInfoData _data = model.list.isNotEmpty ? model.list.first : null;
        return EasyRefresh.builder(
            controller: model.refreshController,
            enableControlFinishRefresh: true,
            enableControlFinishLoad: true,
            onRefresh: () => model.refresh(),
            header: buildClassicalHeader(),
            builder: (context, physics, header, footer) {
              return CustomScrollView(
                physics: physics,
                slivers: <Widget>[
                  buildSliverAppBar(context, "我的等级", backgroundColor: Theme.of(context).scaffoldBackgroundColor),
                  header,
                  if (model.isBusy)
                    SliverToBoxAdapter(
                      child: RequestLoadingWidget(),
                    ),
                  if (model.isIdle && _data != null)
                    SliverToBoxAdapter(
                        child: BoxWidget(
                            body: Column(
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.only(bottom: 8.0),
                          child: Row(
                            mainAxisAlignment: MainAxisAlignment.spaceBetween,
                            children: <Widget>[
                              Row(
                                children: <Widget>[
                                  Text(
                                    "积分:",
                                    style: Theme.of(context).textTheme.subtitle1,
                                  ),
                                  Space(
                                    width: 5.0,
                                  ),
                                  Text(
                                    '${_data.exp}',
                                    style: TextStyle(fontSize: 14.0, color: Color(0xffFFC400)),
                                  )
                                ],
                              ),
                              InkWell(
                                child: Row(
                                  children: <Widget>[
                                    Padding(
                                      child: Text(
                                        "积分商城",
                                        style: Theme.of(context).textTheme.bodyText1,
                                      ),
                                      padding: EdgeInsets.only(right: 5.0),
                                    ),
                                    arrowRight4()
                                  ],
                                ),
                                onTap: () {
                                  NavigatorUtil.go(context, Routes.scoreShopPage);
                                },
                              )
                            ],
                          ),
                        ),
                        Padding(
                            padding: const EdgeInsets.only(top: 16.0, bottom: 8.0),
                            child: Container(width: 90.0, height: 90.0, child: CachedNetworkImage(imageUrl: _data.level.logo ?? ""))),
                        Text(
                          "Lv.${_data.level.level}",
                          style: Theme.of(context).textTheme.headline3,
                        ),
                        Space(
                          height: 24,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Text(
                                  "${_data.exp}",
                                  style: TextStyle(fontSize: 11, color: Theme.of(context).accentColor),
                                ),
                                Text("/${_data.exp + _data.nextLevelExp}", style: TextStyle(fontSize: 11)),
                              ],
                            ),
                          ],
                        ),
                        Space(
                          height: 2,
                        ),
                        ClipRRect(
                          borderRadius: BorderRadius.circular(10),
                          child: Container(
                            child: CustomPaint(
                              painter: _ProgressBar(
                                _data.exp / (_data.nextLevelExp + _data.exp),
                              ),
                              child: Container(
                                height: 12,
                              ),
                            ),
//                      height: 12,
                          ),
                        ),
                        Space(
                          height: 8,
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Text("经验值：", style: Theme.of(context).textTheme.subtitle1),
                                Space(
                                  width: 2.0,
                                ),
                                Text(
                                  "${_data.exp}",
                                  style: Theme.of(context).textTheme.subtitle1.copyWith(color: Theme.of(context).accentColor),
                                ),
                              ],
                            ),
                            Text(
                              "再获得 ${_data.nextLevelExp} 经验可升到下一段",
                              style: Theme.of(context).textTheme.bodyText1,
                            ),
                          ],
                        ),
                      ],
                    ))),
                  if (model.isIdle && _data != null)
                    SliverToBoxAdapter(
                      child: BoxWidget(
                        body: Column(
                          children: <Widget>[
                            Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: <Widget>[
                                Text(
                                  "我的成就",
                                  style: Theme.of(context).textTheme.headline3,
                                ),
                                if (_data.getAchievementList.length > -1 || _max)
                                  InkWell(
                                    onTap: () {
//                                setState(() {
//                                  _max = true;
//                                });
//                              NavigatorUtil.go(context, "achievement");
                                      NavigatorUtil.go(context, "${Routes.achievement}?data=${Uri.encodeComponent(json.encode(_data))}");
                                    },
                                    child: Row(
                                      children: <Widget>[
                                        Text(
                                          "查看全部  ",
                                          style: Theme.of(context).textTheme.bodyText1,
                                        ),
                                        arrowRight4()
                                      ],
                                    ),
                                  ),
                              ],
                            ),
                            if (_data.getAchievementList.length == 0)
                              Padding(
                                  padding: const EdgeInsets.all(30.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 (_data.getAchievementList.length > 0)
                              Padding(
                                padding: EdgeInsets.symmetric(vertical: 16.0),
                                child: StaggeredGridView.countBuilder(
                                  padding: EdgeInsets.zero,
                                  shrinkWrap: true,
                                  physics: NeverScrollableScrollPhysics(),
                                  crossAxisCount: 4,
                                  itemCount: _max ? _data.getAchievementList.length : min(4, _data.getAchievementList.length),
                                  itemBuilder: (BuildContext context, int index) =>
                                      achievementWidget(context, _data.getAchievementList[index], isRadius: false),
                                  mainAxisSpacing: 12.0,
                                  crossAxisSpacing: 12.0,
                                  staggeredTileBuilder: (int index) => StaggeredTile.fit(1),
                                ),
                              ),
                            Center(
                              child: Padding(
                                padding: const EdgeInsets.all(1.0),
                                child: Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: Divider(
                                        endIndent: 20.0,
                                      ),
                                    ),
                                    Text("未获得成就", style: Theme.of(context).textTheme.bodyText1),
                                    Expanded(
                                      child: Divider(
                                        indent: 20.0,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            getList(_data)
                          ],
                        ),
                      ),
                    ),
                ],
              );
            });
      },
    ));
  }
}

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

  double _paddingBar = 2;

  double percent;

  _ProgressBar(this.percent);

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