import 'dart:async';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:gmalpha_flutter/FindModel/page/FindModel.dart';
import 'package:gmalpha_flutter/FindModel/service/remote/entity/FindEntity.dart';
import 'package:gmalpha_flutter/commonModel/base/BaseComponent.dart';
import 'package:gmalpha_flutter/commonModel/base/BasePage.dart';
import 'package:gmalpha_flutter/res/value/ALColors.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class FindPage extends StatefulWidget {
  FindModel _findModel;
  final String fromPage;

  FindPage(this.fromPage) {
    _findModel = new FindModel(1, 8);
  }

  @override
  _FindPageState createState() => _FindPageState(_findModel);
}

class _FindPageState extends BasePage<FindPage> {
  FindModel _findModel;
  static int count = 8;
  static int page = 1;

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  _FindPageState(this._findModel);

  @override
  Widget build(BuildContext context) {
    ScreenUtil.instance = ScreenUtil(width: 375.0, height: 667.0)
      ..init(context);
    return Scaffold(
        appBar: AppBar(
          leading: GestureDetector(
            child: Center(
              child: Container(
                padding: EdgeInsets.fromLTRB(12, 0, 0, 0),
                child: Text("发现"),
              ),
            )),
          centerTitle: false,
          backgroundColor: ALColors.ColorFFFFFF,
          actions: <Widget>[
            Container(
              padding: EdgeInsets.only(right: 16),
              child: new Icon(Icons.search , size: 24.0,),
            ),
          ],
        ),
        body: SmartRefresher(
            enablePullDown: true,
            enablePullUp: true,
            header: WaterDropHeader(),
            footer: CustomFooter(
              builder: (BuildContext context, LoadStatus mode) {
                Widget body;
                if (mode == LoadStatus.idle) {
                  body = Text("上拉加载");
                } else if (mode == LoadStatus.loading) {
                  body = CupertinoActivityIndicator();
                } else if (mode == LoadStatus.failed) {
                  body = Text("加载失败！点击重试！");
                } else if (mode == LoadStatus.canLoading) {
                  body = Text("松手,加载更多!");
                } else {
                  body = Text("没有更多数据了!");
                }
                return Container(
                  height: 55.0,
                  child: Center(child: body),
                );
              },
            ),
            controller: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: CustomScrollView(
              slivers: <Widget>[
//                SliverToBoxAdapter(
//                  child: Container(height: 1,
//                  color: Colors.amberAccent,),
//                ),
                getListView(),
              ],
            )));
  }

  void _onRefresh() {
    _findModel.init(context, (value) {
      Timer(Duration(seconds: 1), () {
        _refreshController.refreshToIdle();
      });
    });
  }

  void _onLoading() async {
    page++;
    await _findModel.getFindPage(page, count, (data) {
      if (data.data?.cards?.length == 0) {
        _refreshController.loadNoData();
      } else {
        _refreshController.loadComplete();
      }
    });
  }

  Widget _listViewUI2(BuildContext context, Cards item) {
    return Container(
        width: ScreenUtil.instance.setWidth(375.0),
        margin: EdgeInsets.only(bottom: ScreenUtil.instance.setHeight(3)),
        child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                  margin:
                      EdgeInsets.only(right: ScreenUtil.instance.setWidth(3.0)),
                  child: CachedNetworkImage(
                    imageUrl: '${item.topics[0].imageUrl}',
                    width: ScreenUtil.instance.setWidth(123),
                    height: ScreenUtil.instance.setHeight(123),
                    fit: BoxFit.cover,
                  )),
              Container(
                  margin:
                      EdgeInsets.only(right: ScreenUtil.instance.setWidth(3.0)),
                  child: CachedNetworkImage(
                    imageUrl: '${item.topics[1].imageUrl}',
                    width: ScreenUtil.instance.setWidth(123),
                    height: ScreenUtil.instance.setHeight(123),
                    fit: BoxFit.cover,
                  )),
              Container(
                  child: CachedNetworkImage(
                imageUrl: '${item.topics[2].imageUrl}',
                width: ScreenUtil.instance.setWidth(123),
                height: ScreenUtil.instance.setHeight(123),
                fit: BoxFit.cover,
              )),
            ]));
  }

  Widget _listViewUI1(BuildContext context, Cards item) {
    return Container(
        width: ScreenUtil.instance.setWidth(375.0),
        margin: EdgeInsets.only(bottom: ScreenUtil.instance.setHeight(3)),
        child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Container(
                  margin:
                      EdgeInsets.only(right: ScreenUtil.instance.setWidth(3.0)),
                  child: CachedNetworkImage(
                    imageUrl: '${item.topics[0].imageUrl}',
                    width: ScreenUtil.instance.setWidth(249),
                    height: ScreenUtil.instance.setHeight(249),
                    fit: BoxFit.fitHeight,
                  )),
              Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                        margin: EdgeInsets.only(
                            bottom: ScreenUtil.instance.setHeight(3.0)),
                        child: CachedNetworkImage(
                          imageUrl: '${item.topics[1].imageUrl}',
                          width: ScreenUtil.instance.setWidth(123),
                          height: ScreenUtil.instance.setHeight(123),
                          fit: BoxFit.cover,
                        )),
                    Container(
                        child: CachedNetworkImage(
                      imageUrl: '${item.topics[2].imageUrl}',
                      width: ScreenUtil.instance.setWidth(123),
                      height: ScreenUtil.instance.setHeight(123),
                      fit: BoxFit.cover,
                    )),
                  ]),
            ]));
  }

  Widget _listViewUI3(BuildContext context, Cards item) {
    return Container(
        width: ScreenUtil.instance.setWidth(375.0),
        margin: EdgeInsets.only(bottom: ScreenUtil.instance.setHeight(3)),
        child: Row(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Container(
                        margin: EdgeInsets.only(
                            bottom: ScreenUtil.instance.setHeight(3)),
                        child: CachedNetworkImage(
                          imageUrl: '${item.topics[0].imageUrl}',
                          width: ScreenUtil.instance.setWidth(123),
                          height: ScreenUtil.instance.setHeight(123),
                          fit: BoxFit.cover,
                        )),
                    Container(
                        child: CachedNetworkImage(
                      imageUrl: '${item.topics[1].imageUrl}',
                      width: ScreenUtil.instance.setWidth(123),
                      height: ScreenUtil.instance.setHeight(123),
                      fit: BoxFit.cover,
                    )),
                  ]),
              Container(
                  margin:
                      EdgeInsets.only(left: ScreenUtil.instance.setWidth(3.0)),
                  child: CachedNetworkImage(
                    imageUrl: '${item.topics[2].imageUrl}',
                    width: ScreenUtil.instance.setWidth(249),
                    height: ScreenUtil.instance.setHeight(249),
                    fit: BoxFit.cover,
                  )),
            ]));
  }

  Widget loadingItem() {
    Widget loadCircle = Column(
      mainAxisAlignment: MainAxisAlignment.start,
      children: <Widget>[
        Container(
          padding: EdgeInsets.only(top: 60.0),
          child: CircularProgressIndicator(),
        ),
        Padding(
          padding: EdgeInsets.only(
              left: ScreenUtil.instance.setSp(10),
              right: ScreenUtil.instance.setSp(10),
              top: ScreenUtil.instance.setSp(10),
              bottom: ScreenUtil.instance.setSp(10)),
          child: Text('加载中...'),
        )
      ],
    );
    return SliverFillViewport(delegate: SliverChildListDelegate([loadCircle]));
  }

  Widget getListView() {
    return StreamBuilder<FindEntity>(
        stream: _findModel.findLive.stream,
        initialData: _findModel.findLive.data,
        builder: (BuildContext context, data) {
          var dataList = data?.data?.data;
          if (dataList == null) {
            return loadingItem();
          }
          return SliverList(
              delegate: SliverChildBuilderDelegate(
            (BuildContext context, int index) {
              var item = dataList.cards[index];
              if (item.layout == 1) {
                return _listViewUI1(context, item);
              } else if (item.layout == 2) {
                return _listViewUI2(context, item);
              } else {
                return _listViewUI3(context, item);
              }
            },
            childCount: dataList.cards.length,
          ));
        });
  }

  Widget noData() {
    return Container(
      height: double.maxFinite,
      width: double.maxFinite,
      color: Colors.amberAccent,
    );
  }

  @override
  void dispose() {
    super.dispose();
    _refreshController.dispose();
  }

  @override
  String pageName() {
    return 'find_home';
  }

  @override
  String referrer() {
    return widget.fromPage;
  }

  @override
  void initState() {
    super.initState();
    _findModel.init(context);
  }
}
