import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:gmalpha_flutter/NewMessageModel/page/AttentionModel.dart';
import 'package:gmalpha_flutter/NewMessageModel/page/AttentionListItem.dart';
import 'package:gmalpha_flutter/NewMessageModel/service/remote/entity/AttentionEntity.dart';
import 'package:gmalpha_flutter/commonModel/base/BasePage.dart';
import 'package:gmalpha_flutter/commonModel/ui/ALColors.dart';

enum LoadStatus {
  // 正在加载
  LOADING,
  // 加载完成
  COMPLETE,
  // 初始状态
  INITIAL
}

class AttentionPage extends StatefulWidget {
  final AttentionModel _model;
  AttentionPage(String fromPage) : _model = AttentionModel(1, fromPage);
  @override
  _AttentionPageState createState() => _AttentionPageState(_model);
}

class _AttentionPageState extends BasePage<AttentionPage> {
  LoadStatus loadStatus = LoadStatus.INITIAL;
  List<Data> _noticeLists = [];
  bool noData = false;
  AttentionModel _model;
  _AttentionPageState(this._model);

  ScrollController _scrollController = ScrollController();
  bool isPerformingRequest = false;

  // 热更新代码
  @override
  void reassemble() {
    super.reassemble();
    _noticeLists = [];
    _scrollController.jumpTo(0);
    _model.refresh(context);
    loadStatus = LoadStatus.INITIAL;
  }

  @override
  void initState() {
    super.initState();
    _model.init(context);
    // 监听ListView滚动，滚动到底部的时候加载更多
    _scrollController.addListener(() {
      if (noData == false
                 && _scrollController.position.pixels
                 == _scrollController.position.maxScrollExtent) {
        setState(() {
          loadStatus = LoadStatus.LOADING;
        });
        _model.more(context, loadComplete);
      }
    });
  }

  void loadComplete() {
    setState(() {
      loadStatus = LoadStatus.COMPLETE;
    });
  }

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

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

  Widget buildNoticeitem(BuildContext context, int index) {
    if (index == 0) {
      // 第一项是没有用的数据，用来渲染裂变的title-通知
      return Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Padding(
            padding: const EdgeInsets.only(top: 16.0, left: 16.0, right: 16.0, bottom: 10.0),
            child: Text(
              '通知',
              style: TextStyle(fontSize: 20.0, color: ALColors.Color323232),
            ),
          ),
          Divider(
            color: ALColors.ColorE4E4E4,
          ),
        ],
      );
    }
    // 最后一项是没有用的数据，用来渲染加载更多UI和暂无更多数据
    if (index == _noticeLists.length && noData == true) {
      return Padding(
        padding: const EdgeInsets.all(10.0),
        child: Center(
          child: Text('暂时无更多数据'),
        ),
      );
    }
    if (index == _noticeLists.length) {
      return _buildProgressIndicator();
    }
    return Padding(
      padding: const EdgeInsets.only(bottom: 21.0),
      child: AttentionListItem(_noticeLists[index]),
    );
  }

  Widget _buildProgressIndicator() {
    return Opacity(
      opacity: loadStatus == LoadStatus.LOADING ? 1.0 : 0.0,
      child: Container(
        color: Color(0xFFF4F3F8),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
              width: 15.0,
              height: 15.0,
              child: CircularProgressIndicator(strokeWidth: 2.0),
            ),
            Padding(
              padding: const EdgeInsets.only(left: 6.0, top: 20.0, bottom: 20.0),
              child: Text(
                '加载中...',
                style: TextStyle(
                  color: ALColors.Color999999,
                  fontSize: 14.0,
                  height: 1.07
                ),
              ),
            )
          ],
        )
      ),
    );
  }

  Widget loadingItem() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          CircularProgressIndicator(),
          Padding(
            padding: const EdgeInsets.all(10.0),
            child: Text('加载中...'),
          )
        ],
      ),
    );
  }

  Widget errorItem(String reason) {
    return Center(
      child: Text("$reason"),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        elevation: 0.0,
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Padding(
            padding: const EdgeInsets.only(top: 10.0, right: 10.0, bottom: 10.0),
            child: Center(
              child: SvgPicture.asset("images/left_arrow.svg", color: Color(0xff323232)),
            ),
          )
        ),
      ),
      body: StreamBuilder<AttentionEntity>(
        stream: _model.zzgLive.stream,
        initialData: _model.zzgLive.data,
        builder: (context, data) {
          if (data.data == null) {
            return loadingItem();
          }
          if (data.data.error != 0 || data.data.data == null) {
            return errorItem(data.data.message);
          }
          noData = data.data.noData;
          _noticeLists = data.data.data;
          isPerformingRequest = false;
          return ListView.builder(
            shrinkWrap: true,
            controller: _scrollController,
            itemCount: _noticeLists.length + 1,
            itemBuilder: buildNoticeitem
          );
        },
      )
    );
  }

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