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:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sport/bean/forum.dart';
import 'package:sport/constant/ui.dart' show ui_padding, ui_margin_list;
import 'package:sport/pages/social/search_page.dart';
import 'package:sport/pages/social/user_friend_page.dart';
import 'package:sport/provider/lib/provider_widget.dart';
import 'package:sport/provider/lib/view_state.dart';
import 'package:sport/provider/lib/view_state_lifecycle.dart';
import 'package:sport/provider/social_index_model.dart';
import 'package:sport/router/navigator_util.dart';
import 'package:sport/router/routes.dart';
import 'package:sport/widgets/appbar.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/page_resume.dart';
import 'package:sport/widgets/space.dart';

class SocialIndexPage extends StatefulWidget {
  @override
  createState() => _PageState();
}

class _PageState extends ViewStateLifecycle<SocialIndexPage, SocialIndexModel> with AutomaticKeepAliveClientMixin, PageResume {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
  }

  @override
  void onResume() {
    super.onResume();
  }

  Future<int> _getCount() async {
    int count = 0;
    try {
      count += (await model.api.getNoticeCount("comment", "0")).data;
    } catch (e) {
      print(e);
    }
    if (count == 0) {
      try {
        count += (await model.api.getNoticeCount("like", "0")).data;
      } catch (e) {
        print(e);
      }
    }
    return count;
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: Colors.white,
      body: ProviderWidget<SocialIndexModel>(
          model: model,
          onModelReady: (model) => model.initData(),
          builder: (_, model, __) {
            return EasyRefresh.builder(
                controller: model.refreshController,
                enableControlFinishRefresh: true,
                onRefresh: () => model.refresh(),
                header: buildClassicalHeader(),
                builder: (context, physics, header, footer) {
                  return CustomScrollView(
                    physics: physics,
                    slivers: <Widget>[
                      buildSliverAppBar(context, "社区",
                          canBack: false,
                          actions: <Widget>[
                            IconButton(
                              icon: Image.asset("lib/assets/img/topbar_friendslist.png"),
                              onPressed: () {
                                NavigatorUtil.goPage(context, (context) => UserFriendPage());
                              },
                            ),
                            SizedBox(
                              width: 20,
                            ),
                            Selector<SocialIndexModel, ViewState>(
                              selector: (_, SocialIndexModel model) => model.viewState,
                              shouldRebuild: (_, v) => v == ViewState.idle,
                              builder: (BuildContext context, ViewState value, Widget child) => IconButton(
                                icon: Stack(
                                  alignment: Alignment.center,
                                  children: <Widget>[
                                    Image.asset("lib/assets/img/bbs_icon_news.png"),
                                    FutureBuilder(
                                        future: SharedPreferences.getInstance(),
                                        builder: (BuildContext context, AsyncSnapshot<SharedPreferences> snapshot) {
                                          if (snapshot.connectionState == ConnectionState.done) {
                                            if (snapshot.data.getBool("message_setting") ?? true == true) {
                                              return FutureBuilder(
                                                  future: _getCount(),
                                                  builder: (BuildContext context, AsyncSnapshot<int> snapshot) {
                                                    if (snapshot.data != null && snapshot.data > 0) {
                                                      return Align(
                                                        alignment: Alignment.topRight,
                                                        child: Container(
                                                          margin: const EdgeInsets.only(top: 6.0),
                                                          width: 10,
                                                          height: 10,
                                                          decoration: BoxDecoration(shape: BoxShape.circle, color: Colors.red),
                                                          child: Center(
                                                            child: Text(""),
                                                          ),
                                                        ),
                                                      );
                                                    }
                                                    return Container();
                                                  });
                                            }
                                          }
                                          return Container();
                                        }),
                                  ],
                                ),
                                onPressed: () async {
                                  await NavigatorUtil.go(context, Routes.socialMessage);
                                  setState(() {});
                                },
                              ),
                            ),
                          ],
                          paddingLeading: false),
                      header,
                      SliverToBoxAdapter(
                        child: _buildSearchWidget(),
                      ),
                      if (model.isBusy)
                        SliverToBoxAdapter(
                          child: RequestLoadingWidget(),
                        ),
                      if (model.isEmpty)
                        SliverToBoxAdapter(
                          child: _buildSearchWidget(),
                        ),
                      if (model.isIdle)
                        SliverList(
                          delegate: SliverChildBuilderDelegate(
                            (context, index) {
                              return _buildItemWidget(model.list[index]);
                            },
                            childCount: model.list.length,
                          ),
                        ),
                      if (model.isError)
                        SliverToBoxAdapter(
                          child: RequestErrorWidget(() {
                            model.initData();
                          }),
                        ),
                    ],
                  );
                });
          }),
    );
  }

  Widget _buildSearchWidget() {
    return GestureDetector(
      onTap: () {
        Navigator.push(context, new MaterialPageRoute(builder: (context) => SearchPage()));
      },
      child: Container(
        margin: EdgeInsets.fromLTRB(12.0, 0, 12.0, 12.0),
        height: 35,
        padding: EdgeInsets.fromLTRB(12.0, 0, 12.0, 0),
        decoration: BoxDecoration(
          color: Color(0xffF1F1F1),
          shape: BoxShape.rectangle,
          borderRadius: BorderRadius.all(Radius.circular(50)),
        ),
        child: Row(
          children: <Widget>[
            Image.asset("lib/assets/img/searchbar_icon_search.png"),
            Space(
              width: 4,
            ),
            Text(
              "输入关键词",
              style: TextStyle(fontSize: 14, color: Color(0xff999999)),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildItemWidget(Forum item) {
    return Container(
      decoration: card(),
      margin: EdgeInsets.fromLTRB(ui_padding, 6.0, ui_padding, 6.0),
      padding: const EdgeInsets.all(ui_padding),
      child: InkWell(
        onTap: () => NavigatorUtil.goSocialDetail(context, item),
        child: Column(
          children: <Widget>[
            Row(
              children: <Widget>[
                CircleAvatar(backgroundImage: CachedNetworkImageProvider(item.cover), radius: 30.0),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 12.0),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: <Widget>[
                        Text(
                          "${item.name}",
                          style: Theme.of(context).textTheme.subtitle1.copyWith(fontSize: 16.0),
                        ),
                        Space(
                          height: 3,
                        ),
                        Text(
                          "${item.digest}",
                          style: Theme.of(context).textTheme.bodyText1,
                        ),
                        Space(
                          height: 3,
                        ),
                        Text(
                          "${item.userCount}人在玩\t\t|\t\t帖子 ${item.subjectCount}",
                          style: Theme.of(context).textTheme.bodyText1,
                        )
                      ],
                    ),
                  ),
                ),
                arrowRight5()
              ],
            ),
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;

  @override
  SocialIndexModel createModel() => SocialIndexModel();
}
