import 'dart:convert';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/painting.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:sport/bean/game.dart';
import 'package:sport/bean/game_record_sum.dart';
import 'package:sport/bean/sport_detail.dart';
import 'package:sport/constant/ui.dart';
import 'package:sport/pages/game/game_detail.dart';
import 'package:sport/pages/game/index.dart';
import 'package:sport/pages/home/sport_history_page.dart';
import 'package:sport/provider/lib/provider_widget.dart';
import 'package:sport/provider/lib/simple_model.dart';
import 'package:sport/provider/lib/view_state_lifecycle.dart';
import 'package:sport/provider/sport_history_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/services/api/inject_api.dart';
import 'package:sport/widgets/appbar.dart';
import 'package:sport/widgets/button_primary.dart';
import 'package:sport/widgets/decoration.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';

class SportHistoryAllPage extends StatefulWidget {
  SportHistoryAllPage();

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

class _PageState extends ViewStateLifecycle<SportHistoryAllPage, SimpleModel> with InjectApi {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ProviderWidget<SimpleModel>(
          model: model,
          onModelReady: (model) => model.initData(),
          builder: (_, model, __) {
            return EasyRefresh.builder(
                controller: model.refreshController,
                enableControlFinishRefresh: true,
                enableControlFinishLoad: true,
                onRefresh: () => model.refresh(),
                onLoad: model.isIdle ? () => model.loadMore() : null,
                header: buildClassicalHeader(bgColor: Theme.of(context).scaffoldBackgroundColor),
                footer: buildClassicalFooter(),
                builder: (context, physics, header, footer) => CustomScrollView(
                      slivers: <Widget>[
                        buildSliverAppBar(context, "运动记录", backgroundColor: Theme.of(context).scaffoldBackgroundColor),
                        if (model.isBusy)
                          SliverToBoxAdapter(
                            child: RequestLoadingWidget(),
                          ),
                        // if (model.isIdle)
                        SliverPadding(
                          padding: const EdgeInsets.symmetric(horizontal: 12.0),
                          sliver: SliverList(
                            delegate: SliverChildBuilderDelegate(
                              (context, index) {
                                GameRecordSum item = model.list[index];
                                return GestureDetector(
                                  onTap: () => NavigatorUtil.goPage(context, (context) => SportHistoryPage(item.game)),
                                  child: Container(
                                      margin: index == 0 ?const EdgeInsets.only(top: 0) :const EdgeInsets.only(top: ui_padding),
                                      decoration: circular(),
                                      child: Column(
                                        children: <Widget>[
                                          Padding(
                                            padding: const EdgeInsets.fromLTRB(ui_padding, 14.0, ui_padding, 14.0),
                                            child: Row(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: <Widget>[
                                                GestureDetector(
                                                  onTap: () => NavigatorUtil.goPage(context, (context) => GameDetailsPage(item.game)),
                                                  child: ClipRRect(
                                                    child: CachedNetworkImage(
                                                      width: 50,
                                                      height: 50,
                                                      imageUrl: item.game?.cover,
                                                      fit: BoxFit.cover,
                                                    ),
                                                    // 也可控件一边圆角大小
                                                    borderRadius: new BorderRadius.all(Radius.circular(6.0)),
                                                  ),
                                                ),
                                                SizedBox(
                                                  width: ui_padding,
                                                ),
                                                Expanded(
                                                    child: Column(
                                                  children: <Widget>[
                                                    Text("${item.game?.name}", style: Theme.of(context).textTheme.headline1.copyWith(fontSize: 16.0)),
                                                    const SizedBox(
                                                      height: 6.0,
                                                    ),
                                                    Text(
                                                      "最近打开：${item.lastPlayAt}",
                                                      style: Theme.of(context).textTheme.bodyText1,
                                                    ),
                                                  ],
                                                  crossAxisAlignment: CrossAxisAlignment.start,
                                                )),
                                                RichText(
                                                  text: TextSpan(style: DefaultTextStyle.of(context).style, children: <InlineSpan>[
                                                    TextSpan(text: '详情\t', style: Theme.of(context).textTheme.subtitle2),
                                                    WidgetSpan(
                                                      alignment: PlaceholderAlignment.middle,
                                                      child: arrowRight(),
                                                    ),
                                                  ]),
                                                ),
                                              ],
                                            ),
                                          ),
                                          Divider(
                                            height: 0.5,
                                          ),
                                          Padding(
                                            padding: const EdgeInsets.fromLTRB(ui_padding, 15.0, ui_padding, 15.0),
                                            child: Row(
                                              children: <Widget>[
                                                Column(
                                                  children: <Widget>[
                                                    Text("${item.durationTotalMinute}", style: Theme.of(context).textTheme.headline1.copyWith(fontSize: 20.0)),
                                                    const SizedBox(
                                                      height: 2.0,
                                                    ),
                                                    Text(
                                                      "总时长(分钟）",
                                                      style: Theme.of(context).textTheme.bodyText1,
                                                    ),
                                                  ],
                                                ),
                                                Column(
                                                  children: <Widget>[
                                                    Text("${item.scoreMax.toStringAsFixed(1)}",
                                                        style: Theme.of(context).textTheme.headline1.copyWith(fontSize: 20.0)),
                                                    const SizedBox(
                                                      height: 2.0,
                                                    ),
                                                    Text(
                                                      "最高评分",
                                                      style: Theme.of(context).textTheme.bodyText1,
                                                    ),
                                                  ],
                                                ),
                                                Column(
                                                  children: <Widget>[
                                                    Text("${item.times}", style: Theme.of(context).textTheme.headline1.copyWith(fontSize: 20.0)),
                                                    const SizedBox(
                                                      height: 2.0,
                                                    ),
                                                    Text(
                                                      "运动次数(次）",
                                                      style: Theme.of(context).textTheme.bodyText1,
                                                    ),
                                                  ],
                                                ),
                                              ],
                                              mainAxisAlignment: MainAxisAlignment.spaceAround,
                                            ),
                                          ),
                                        ],
                                      )),
                                );
                              },
                              childCount: model.list.length,
                            ),
                          ),
                        ),
                        if (model.isEmpty)
                          SliverToBoxAdapter(
                              child: Container(
                                  margin: const EdgeInsets.fromLTRB(ui_padding, 14.0, ui_padding, 14.0),
                                  decoration: circular(),
                                  child: RequestErrorWidget(
                                    null,
                                    assets: RequestErrorWidget.ASSETS_NO_MOTION,
                                    msg: "您还未进行任何运动",
                                  ))),
                      ],
                    ));
          }),
    );
  }

  @override
  SimpleModel createModel() => SimpleModel((page) async {
        return (await api.getGameRecordSum()).results;
      });
}
