import 'dart:math';
import 'dart:ui';

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:flutter_swiper/flutter_swiper.dart';
import 'package:sport/bean/achievement_detail_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/services/api/inject_api.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/box.dart';
import 'package:sport/widgets/loading.dart';
import 'package:sport/widgets/misc.dart';
import 'package:sport/widgets/space.dart';

class AchievementDetailPage extends StatefulWidget {
  final int id;
  final int userId;

  AchievementDetailPage(this.id, this.userId);

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

class _PageState extends State<AchievementDetailPage> with InjectLoginApi {
  SimpleModel _model;

  @override
  void initState() {
    super.initState();
//    _model = SimpleModel((page) async {
//      return List()..add((await loginApi.getAchieveDetailInfo(widget.id, userId: widget.userId == 0 ? null : "${widget.userId}")).data);
//    });
  }

//  @override
//  Widget build(BuildContext context) {
//    return Scaffold(
////        backgroundColor: Color(0xffF1F1F1),
//        body: ProviderWidget<SimpleModel>(
//      model: _model,
//      onModelReady: (model) => model.initData(),
//      builder: (_, model, __) {
//        AchieveDetailInfoData _data = _model.list?.isNotEmpty == true ? _model.list.first : AchieveDetailInfoData();
//        return EasyRefresh.custom(
//          controller: model.refreshController,
//          enableControlFinishRefresh: true,
//          enableControlFinishLoad: true,
//          // onRefresh: () => model.refresh(),
////              header: buildClassicalHeader(),
////              footer: buildClassicalFooter(),
//          slivers: <Widget>[
//            buildSliverAppBar(context, "成就详情", backgroundColor: Theme.of(context).scaffoldBackgroundColor),
//            if (model.isBusy)
//              SliverToBoxAdapter(
//                child: RequestLoadingWidget(),
//              ),
//            if (model.isIdle)
//              SliverToBoxAdapter(
//                child: BoxWidget(
//                  body: Column(
//                    crossAxisAlignment: CrossAxisAlignment.center,
//                    children: <Widget>[
//                      Space(height: 10.0),
//                      CachedNetworkImage(
//                        width: 130.0,
//                        height: 130.0,
//                        imageUrl: _data.logo ?? "",
//                      ),
//                      Space(height: 12.0),
//                      Text("${_data.name}", style: Theme.of(context).textTheme.headline3),
//                      Space(height: 17.0),
//                      Divider(),
//                      Space(height: 12.0),
//                      Row(
//                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                        children: <Widget>[
//                          Text("成就名称：", style: Theme.of(context).textTheme.subtitle1),
//                          Text("${_data.name}", style: Theme.of(context).textTheme.bodyText2.copyWith(color: Theme.of(context).accentColor))
//                        ],
//                      ),
//                      Space(height: 8.0),
//                      Row(
//                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                        children: <Widget>[
//                          Text("成就条件：", style: Theme.of(context).textTheme.subtitle1),
//                          Text("${_data.conditionDetail}", style: Theme.of(context).textTheme.bodyText2)
//                        ],
//                      ),
//                      Space(height: 8.0),
//                      Row(
//                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                        children: <Widget>[
//                          Text("获取时间：", style: Theme.of(context).textTheme.subtitle1),
//                          Text("${_data.createdAt ?? '未获得成就'}", style: Theme.of(context).textTheme.bodyText2)
//                        ],
//                      ),
//                      Space(height: 8.0),
//                    ],
//                  ),
//                ),
//              ),
//            if (model.isIdle)
//              SliverToBoxAdapter(
//                child: BoxWidget(
//                  body: Column(
//                    crossAxisAlignment: CrossAxisAlignment.start,
//                    children: <Widget>[
//                      Row(
//                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                        children: <Widget>[
//                          Text("晋级奖励：", style: Theme.of(context).textTheme.subtitle1),
//                          Text("经验值 +${_data.rewardExp} 积分+${_data.rewardScore}",
//                              style: Theme.of(context).textTheme.bodyText2.copyWith(color: Theme.of(context).accentColor))
//                        ],
//                      ),
//                      Space(height: 4.0),
//                      Divider(),
//                      Space(height: 4.0),
//                      Text("晋级进度: ", style: Theme.of(context).textTheme.subtitle1),
//                      Padding(
//                        padding: EdgeInsets.symmetric(vertical: 10.0),
//                        child: ClipRRect(
//                          borderRadius: BorderRadius.circular(12),
//                          child: Container(
//                            child: CustomPaint(
//                              painter: _ProgressBar(
//                                ((_data?.nextConditionCount ?? 0) > 0) ? _data.conditionProgress / _data.nextConditionCount : 0,
//                              ),
//                              child: Container(
//                                height: 8,
//                              ),
//                            ),
//                          ),
//                        ),
//                      ),
//                      Row(
//                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
//                        children: <Widget>[
//                          Text('${_data.conditionProgress}${_data.conditionMeasure}', style: Theme.of(context).textTheme.bodyText1.copyWith(fontSize: 11.0)),
//                          Text('${_data.nextConditionCount}${_data.conditionMeasure}', style: Theme.of(context).textTheme.bodyText1.copyWith(fontSize: 11.0))
//                        ],
//                      )
//                    ],
//                  ),
//                ),
//              ),
//            if (model.isIdle)
//              SliverToBoxAdapter(
//                  child: Padding(
//                padding: const EdgeInsets.all(12.0),
//                child: Column(
//                  children: <Widget>[
//                    Row(
//                      children: <Widget>[
//                        Expanded(
//                          child: Divider(
//                            endIndent: 10.0,
//                          ),
//                        ),
//                        Text("成就组"),
//                        Expanded(
//                            child: Divider(
//                          indent: 10.0,
//                        )),
//                      ],
//                    ),
//                  ],
//                ),
//              )),
//            if (_data.relateAchievements?.length == 0)
//              Padding(padding: const EdgeInsets.all(24.0), child: Text("没有关联成就", style: Theme.of(context).textTheme.bodyText1)),
//            if (model.isIdle && _data.relateAchievements.isNotEmpty)
//              SliverToBoxAdapter(
//                child: Text("${_data.relateAchievements}"),
//              ),
////              SliverToBoxAdapter(
////                child: StaggeredGridView.countBuilder(
////                  padding: EdgeInsets.symmetric(horizontal: 12.0),
////                  shrinkWrap: true,
////                  physics: NeverScrollableScrollPhysics(),
////                  crossAxisCount: 4,
////                  itemCount: _data.relateAchievements?.length,
////                  itemBuilder: (BuildContext context, int index) =>
////                      achievementWidget(context, _data.relateAchievements[index], replace: true, isRadius: false, jump: false),
////                  mainAxisSpacing: 12.0,
////                  crossAxisSpacing: 12.0,
////                  staggeredTileBuilder: (int index) => StaggeredTile.fit(1),
////                ),
////              )
//          ],
//        );
//      },
//    ));
//  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
//    throw UnimplementedError();
    return Material(color: Colors.black.withOpacity(0.5), child: Column());
  }
}

class _ProgressBar extends CustomPainter {
  final Paint _paint = Paint()
    ..color = Color(0xfff1f1f1)
    ..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;
  }
}

Future<bool> showSharePopup(
    BuildContext context, List<Achievement> relateAchievements, int id) {
  Iterable<Achievement> item =
      relateAchievements.where((element) => element.id == id);
  int startIndex = relateAchievements.indexOf(item.toList()[0]);
  ValueNotifier<int> _valueNotifierIndex = ValueNotifier(startIndex);
  int currentIndex = startIndex;

  return showGeneralDialog<bool>(
      context: context,
      barrierDismissible: true,
      barrierLabel: '',
//      barrierColor: Color(0xff241D19).withOpacity(0.8),
      transitionDuration: Duration(milliseconds: 200),
//                              useRootNavigator: false,
      pageBuilder: (BuildContext context, Animation<double> animation,
          Animation<double> secondaryAnimation) {
        return BackdropFilter(
          filter: ImageFilter.blur(sigmaX: 5, sigmaY: 5),
          child: Material(
            color: Colors.transparent.withOpacity(0.8),
            child: Column(
//            mainAxisSize: MainAxisSize.max,
              children: <Widget>[
                Space(
                  height: MediaQuery.of(context).padding.top + 31,
                ),
                Column(
                  mainAxisSize: MainAxisSize.max,
                  mainAxisAlignment: MainAxisAlignment.start,
                  children: <Widget>[
                    Container(
                        padding: EdgeInsets.symmetric(horizontal: 17.0),
                        alignment: Alignment.centerRight,
                        child: InkWell(
                          child: Container(
                            width: 22.0,
                            height: 22.0,
                            decoration: BoxDecoration(
                                image: DecorationImage(
                                    image: AssetImage(
                                        "lib/assets/img/btn_close_white.png"))),
                          ),
                          onTap: () {
                            Navigator.pop(context, false);
                          },
                        )),
                    Space(
                      height: 115,
                    ),
                    Stack(
//                    fit: StackFit.expand,
                      alignment: Alignment.topCenter,
                      overflow: Overflow.visible,
                      children: <Widget>[
                        Container(
                          height: 278,
                          child: new Swiper(
//                          itemWidth: MediaQuery.of(context).size.width,
                            loop: false,
                            index: startIndex,
                            itemBuilder: (BuildContext context, int index) {
                              return Column(
                                children: <Widget>[
                                  relateAchievements[index].createdAt != ""
                                      ? index != currentIndex
                                          ? Opacity(
                                              opacity: 0.5,
                                              child: Container(
                                                  child: CachedNetworkImage(
                                                imageUrl:
                                                    relateAchievements[index]
                                                        .logo,
                                                width: 180,
                                                height: 180,
                                              )))
                                          : Container(
                                              child: CachedNetworkImage(
                                              imageUrl:
                                                  relateAchievements[index]
                                                      .logo,
                                              width: 180,
                                              height: 180,
                                            ))
                                      : index == currentIndex
                                          ? ColorFiltered(
                                              colorFilter:
                                                  ColorFilter.matrix(<double>[
                                                0.2126,
                                                0.7152,
                                                0.0722,
                                                0,
                                                0,
                                                0.2126,
                                                0.7152,
                                                0.0722,
                                                0,
                                                0,
                                                0.2126,
                                                0.7152,
                                                0.0722,
                                                0,
                                                0,
                                                0,
                                                0,
                                                0,
                                                1,
                                                0,
                                              ]),
                                              child: CachedNetworkImage(
//                                      width: 70.0,
//                                      height: 70.0,
                                                  imageUrl:
                                                      relateAchievements[index]
                                                          .logo),
                                            )
                                          : Opacity(
                                              opacity: 0.5,
                                              child: ColorFiltered(
                                                colorFilter:
                                                    ColorFilter.matrix(<double>[
                                                  0.2126,
                                                  0.7152,
                                                  0.0722,
                                                  0,
                                                  0,
                                                  0.2126,
                                                  0.7152,
                                                  0.0722,
                                                  0,
                                                  0,
                                                  0.2126,
                                                  0.7152,
                                                  0.0722,
                                                  0,
                                                  0,
                                                  0,
                                                  0,
                                                  0,
                                                  1,
                                                  0,
                                                ]),
                                                child: CachedNetworkImage(
//                                      width: 70.0,
//                                      height: 70.0,
                                                    imageUrl:
                                                        relateAchievements[
                                                                index]
                                                            .logo),
                                              ),
                                            ),
//                                  if (index == currentIndex)
//                                    Column(
//                                      children: <Widget>[
//                                        Space(
//                                          height: 20.0,
//                                        ),
//                                        Space(
//                                          height: 5.0,
//                                        ),
//                                      ],
//                                    )
                                ],
                              );
                            },
                            viewportFraction: 0.5,
                            scale: 0.3,
                            itemCount: relateAchievements.length,
                            pagination: new SwiperPagination(
                                margin: new EdgeInsets.symmetric(vertical: 0.0),
                                builder: DotSwiperPaginationBuilder(
                                    size: 6,
                                    activeSize: 6,
                                    color: Colors.white.withOpacity(0.5),
                                    activeColor:
                                        Theme.of(context).accentColor)),
                            onIndexChanged: (index) {
                              _valueNotifierIndex.value = index;
                              currentIndex = index;
                            },
                          ),
                        ),
                        Positioned(
//                          top: 120.0,
                          top: 175,
                          child: Container(
                            child: ValueListenableBuilder(
                                valueListenable: _valueNotifierIndex,
                                builder: (BuildContext context, int value,
                                    Widget child) {
                                  if (currentIndex == value) {
                                    return relateAchievements[value]
                                                .createdAt !=
                                            ""
                                        ? Column(
                                            mainAxisSize: MainAxisSize.min,
                                            children: <Widget>[
                                              Space(
                                                height: 25.0,
                                              ),
                                              Text(
                                                "${relateAchievements[value].name}",
                                                style: TextStyle(
                                                    fontSize: 18.0,
                                                    color: Colors.white,
                                                    fontWeight:
                                                        FontWeight.w600),
                                              ),
                                              Space(
                                                height: 10.0,
                                              ),
                                              Container(
                                                alignment: Alignment.center,
                                                child: Text(
                                                    "${relateAchievements[value].conditionDetail}",
                                                    style: TextStyle(
                                                        fontSize: 14.0,
                                                        color: Colors.white)),
                                              ),
                                              Space(
                                                height: 60.0,
                                              ),
                                              Text(
                                                  "获取时间  ${relateAchievements[value].createdAt.split(" ")[0]}"),
                                              Space(
                                                height: 16.0,
                                              ),
                                              Container(
                                                alignment: Alignment.center,
                                                height: 37.5,
                                                width: MediaQuery.of(context)
                                                    .size
                                                    .width,
                                                decoration: BoxDecoration(
                                                    image: DecorationImage(
                                                        image: AssetImage(
                                                            "lib/assets/img/bg1_pop_achievement.png"),
                                                        fit: BoxFit.cover)),
                                                child: Text(
                                                  "晋级奖励 : 经验值 +${relateAchievements[value].rewardExp} 积分 +${relateAchievements[value].rewardScore}",
                                                  style: TextStyle(
                                                    fontSize: 14.0,
                                                    color: Theme.of(context)
                                                        .accentColor,
                                                  ),
                                                  strutStyle: fixedLine,
                                                ),
                                              ),
                                            ],
                                          )
                                        : Column(
                                            children: <Widget>[
                                              Space(
                                                height: 25.0,
                                              ),
                                              Text(
                                                "${relateAchievements[value].name}",
                                                style: TextStyle(
                                                    fontSize: 18.0,
                                                    color: Colors.white,
                                                    fontWeight:
                                                    FontWeight.w600
                                                ),
                                              ),
                                              Space(
                                                height: 10.0,
                                              ),
                                              Text(
                                                "成就条件: ${relateAchievements[value].conditionDetail}",
                                                style: TextStyle(
                                                    fontSize: 14.0,
                                                    color: Colors.white),
                                              ),
                                              Space(
                                                height: 60.0,
                                              ),
                                              Text("未获得"),
                                              Space(
                                                height: 12.0,
                                              ),
                                              Text(
                                                "晋级奖励 : 经验值 +${relateAchievements[value].rewardExp} 积分 +${relateAchievements[value].rewardScore}",
                                                style: TextStyle(
                                                    fontSize: 14.0,
                                                    color: Color(0xff999999)),
                                              ),
//                                              Space(
//                                                height: 8.0,
//                                              ),
                                              Padding(
                                                padding: EdgeInsets.symmetric(
                                                    vertical: 10.0),
                                                child: ClipRRect(
                                                  borderRadius:
                                                      BorderRadius.circular(12),
                                                  child: Container(
                                                    width: 183.0,
                                                    child: CustomPaint(
                                                      painter: _ProgressBar(
                                                        ((relateAchievements[
                                                                            value]
                                                                        ?.conditionProgress ??
                                                                    0) >
                                                                0)
                                                            ? relateAchievements[
                                                                        value]
                                                                    .conditionProgress /
                                                                relateAchievements[
                                                                        value]
                                                                    .conditionCount
                                                            : 0,
                                                      ),
                                                      child: Container(
                                                        height: 8,
                                                      ),
                                                    ),
                                                  ),
                                                ),
                                              ),
//                                              Space(
//                                                height: 5.0,
//                                              ),
                                              Text(
                                                  "${relateAchievements[value].conditionProgress} / ${relateAchievements[value].conditionCount}")
                                            ],
                                          );
                                  } else {
                                    return Container();
                                  }
                                }),
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              ],
            ),
          ),
        );
      });
}
