import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:zhiying_base_widget/pages/feedback_page/bloc/feedback_record_bloc.dart';
import 'package:zhiying_base_widget/pages/feedback_page/bloc/feedback_record_repository.dart';
import 'package:zhiying_base_widget/pages/feedback_page/model/feedback_record_data_model.dart';
import 'package:zhiying_base_widget/pages/feedback_page/model/feedback_record_style_model.dart';
import 'package:zhiying_base_widget/pages/feedback_page/widgets/feedback_record_item.dart';
import 'package:zhiying_base_widget/widgets/empty/empty_widget.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:zhiying_comm/zhiying_comm.dart';
import 'bloc/feedback_record_event.dart';
import 'bloc/feedback_record_state.dart';

class FeedbackRecordPage extends StatelessWidget {
  final Map<String, dynamic> data;

  FeedbackRecordPage(this.data);

  @override
  Widget build(BuildContext context) {
    return BlocProvider<FeedbackRecordBloc>(
      create: (_) => FeedbackRecordBloc(FeedbackRecordRepository(data))..add(FeedbackRecordInitEvent()),
      child: _FeedbackRecordPage(),
    );
  }
}

class _FeedbackRecordPage extends StatefulWidget {
  @override
  __FeedbackRecordPageState createState() => __FeedbackRecordPageState();
}

class __FeedbackRecordPageState extends State<_FeedbackRecordPage> {
  RefreshController _controller;

  /// 点击详情

  /// 刷新
  void _refresh() {
    BlocProvider.of<FeedbackRecordBloc>(context).add(FeedbackRecordRefreshEvent());
  }

  /// 加载更多
  void _load() {
    BlocProvider.of<FeedbackRecordBloc>(context).add(FeedbackRecordLoadEvent());
  }

  @override
  void initState() {
    _controller = RefreshController();
    super.initState();
  }

  @override
  void dispose() {
    _controller?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return BlocConsumer<FeedbackRecordBloc, FeedbackRecordState>(
      listener: (context, state) {},
      buildWhen: (prev, current) {
        if (current is FeedbackRecordRefreshSuccessState) {
          _controller?.refreshCompleted(resetFooterState: true);
          return false;
        }
        if (current is FeedbackRecordRefreshErrorState) {
          _controller?.refreshFailed();
          return false;
        }

        if (current is FeedbackRecordLoadSuccessState) {
          _controller?.loadComplete();
          return false;
        }

        if (current is FeedbackRecordLoadErrorState) {
          _controller?.loadNoData();
          return false;
        }

        return true;
      },
      builder: (context, state) {
        /// 数据视图
        if (state is FeedbackRecordLoadedState) {
          return _createDataWidget(state?.styleModel, state?.dataModel);
        }

        /// 初始化失败，空视图
        if (state is FeedbackRecordInitErrorState) {
          return _createEmptyWidget();
        }

        /// 加载中,骨架图
        return _createSkeletonWidget();
      },
    );
  }

  /// 有数据
  Widget _createDataWidget(FeedbackRecordStyleModel styleModel, FeedbackRecordDataModel dataModel) {
    int length = dataModel?.data?.length ?? 0;
    if(length == 0 ) return _createEmptyWidget();

    return Scaffold(
      appBar: _createNav(styleModel),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: SafeArea(
          child: SmartRefresher(
            controller: _controller,
            enablePullUp: true,
            enablePullDown: true,
            onRefresh: _refresh,
            onLoading: _load,
            child: ListView.builder(
                itemCount: length,
                itemBuilder: (context, index) {

                  return FeedbackRecordItem(styleModel, dataModel.data[index]);
                }),
          ),
        ),
      ),
    );
  }

  /// 空数据
  Widget _createEmptyWidget() {
    return Scaffold(
      appBar: _createNav(null),
      body: GestureDetector(
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
        },
        child: SafeArea(
          child: SmartRefresher(
            controller: _controller,
            enablePullDown: true,
            enablePullUp: false,
            onRefresh: _refresh,
            child: Center(child: EmptyWidget()),
          ),
        ),
      ),
    );
  }

  /// 骨架图
  Widget _createSkeletonWidget() {
    return Scaffold(
      appBar: _createNav(null),
      body: Container(),
    );
  }

  /// 导航栏
  Widget _createNav(FeedbackRecordStyleModel styleModel) {
    return CupertinoNavigationBar(
      border: Border(
        bottom: BorderSide(
          width: 0.0, // One physical pixel.
          style: BorderStyle.none,
        ),
      ),
      backgroundColor: HexColor.fromHex(styleModel?.appBarBgColor ?? '#FFFFFF'),
      leading: Navigator.canPop(context)
          ? GestureDetector(
              child: Container(
                padding: EdgeInsets.zero,
                child: Icon(
                  Icons.arrow_back_ios,
                  size: 20,
                ),
              ),
              onTap: () {
                if (Navigator.canPop(context)) {
                  Navigator.pop(context);
                }
              },
            )
          : Container(),
      middle: Text(
        styleModel?.appBarName ?? '反馈列表',
        style: TextStyle(
          fontSize: 15,
          color: HexColor.fromHex(styleModel?.appBarNameColor ?? '#FF333333'),
        ),
      ),
    );
  }
}
