import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:yumi/ui_kit/theme/socialchat_theme.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'package:yumi/app_localizations.dart';
import 'package:yumi/app/constants/sc_screen.dart';
import 'package:yumi/ui_kit/components/sc_compontent.dart';

///分页列表
class SCPageList extends StatefulWidget {
  const SCPageList({Key? key}) : super(key: key);

  @override
  SCPageListState createState() => SCPageListState();
}

class SCPageListState<M, T extends SCPageList> extends State<SCPageList> {
  final RefreshController _refreshController = RefreshController(
    initialRefresh: false,
  );

  ///当前第几页
  int currentPage = 0;
  List<M> items = [];
  Color backgroundColor = Colors.white;

  ///是否开启分页
  bool enablePullUp = true;
  bool enablePullDown = true;
  bool isLoading = false;
  bool needLoading = true;
  int pageCount = 20;
  EdgeInsetsGeometry? padding;

  bool isShowDivider = true;
  bool isGridView = false;
  bool isShowBottomMsg = true;
  bool isShowFooter = true;
  bool isCanClickEmpty = true;
  int gridViewCount = 3;

  SliverGridDelegateWithFixedCrossAxisCount? gridDelegate;

  void loadComplete() {
    isLoading = false;
    _refreshController.refreshCompleted();
    _refreshController.loadComplete();
  }

  ///刷新列表
  void loadData(int page) {
    setState(() {
      isLoading = true;
    });
    loadPage(
      page: page,
      onSuccess: (list) {
        if (page == 1) {
          items.clear();
        }
        items.addAll(list);
        if (mounted) setState(() {});
        currentPage = page;
        _refreshController.refreshCompleted();
        _refreshController.loadComplete();
        if (list.length < pageCount) {
          _refreshController.loadNoData();
        }
        isLoading = false;
        if (mounted) setState(() {});
      },
      onErr: () {
        _refreshController.loadNoData();
        _refreshController.refreshCompleted();
        isLoading = false;
        if (mounted) setState(() {});
      },
    );
  }

  Widget buildList(BuildContext context) {
    return Container(
      color: backgroundColor,
      child: SmartRefresher(
        enablePullDown: enablePullDown,
        enablePullUp: enablePullUp,
        controller: _refreshController,
        onRefresh: () {
          loadData(1);
        },
        onLoading: () {
          loadData(currentPage + 1);
        },
        footer:
            isShowFooter
                ? null
                : CustomFooter(
                  height: 1,
                  builder: (context, mode) {
                    return SizedBox(
                      height: 1,
                      width: 1,
                      child: SizedBox(height: 1, width: 1),
                    );
                  },
                ),
        child:
            items.isEmpty
                ? (isCanClickEmpty
                    ? GestureDetector(
                      behavior: HitTestBehavior.opaque,
                      onTap: () {
                        loadData(1);
                      },
                      child:
                          needLoading && isLoading
                              ? Center(child: CupertinoActivityIndicator(color: Colors.white24,))
                              : empty(),
                    )
                    : needLoading && isLoading
                    ? Center(child: CupertinoActivityIndicator(color: Colors.white24))
                    : empty())
                : _buildList(),
      ),
    );
  }

  Widget _buildList() {
    if (isGridView) {
      return GridView.builder(
        gridDelegate:
            gridDelegate ??
            SliverGridDelegateWithFixedCrossAxisCount(
              crossAxisCount: gridViewCount,
            ),
        itemBuilder: (c, i) {
          return buildItemOne(items[i], i);
        },
        padding: padding ?? EdgeInsets.zero,
        itemCount: items.length,
      );
    }
    return ListView.separated(
      itemBuilder: (context, i) => buildItemOne(items[i], i),
      itemCount: items.length,
      padding: padding ?? EdgeInsets.zero,
      separatorBuilder: (context, i) => builderDivider(),
    );
  }

  ///默认空页面
  empty() {
    // List<Widget> list = [];
    // list.add(SizedBox(
    //   height: height(80),
    // ));
    // list.add(Image.asset('sc_images/main/empty.png'));
    // list.add(
    //   SizedBox(
    //     height: height(15),
    //   ),
    // );
    // list.add(
    //   Text("暂无数据",
    //       style: TextStyle(
    //         fontSize: sp(14),
    //         color: Color(0xff999999),
    //         fontWeight: FontWeight.w400,
    //         decoration: TextDecoration.none,
    //         height: 1,
    //       )),
    // );

    //return Column(mainAxisSize: MainAxisSize.min, children: list);
    return mainEmpty(msg: SCAppLocalizations.of(context)!.noData);
  }

  ///默认列表项
  Widget buildItemOne(M item, int index) {
    return buildItem(item);
  }

  ///默认列表项
  Widget buildItem(M item) {
    return Card(child: Center(child: Text(item.toString())));
  }

  ///默认加载数据
  void loadPage({
    required int page,
    required Function(List<M>) onSuccess,
    Function? onErr,
  }) {
    onSuccess([]);
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }

  builderDivider() {
    return isShowDivider
        ? Divider(
          height: height(1),
          color: SocialChatTheme.dividerColor,
          indent: width(15),
          endIndent: width(15),
        )
        : Container();
  }
}
