/*
 * @Descripttion: 上拉刷新下拉加载页面封装
 * @version: 
 * @Author: wy
 * @Date: 2020-08-25 14:41:31
 * @LastEditors: wangyang 1147192855@qq.com
 * @LastEditTime: 2022-07-19 09:58:56
 */

import 'package:flutter/cupertino.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:marking_app/utils/easy_refresh/MyEasyRefreshService.dart';
import 'package:marking_app/utils/easy_refresh/MyEmptyWidget.dart';

/*
 * 普通使用
 */

// MyEasyRefresh(
// true,
// _controller,
// getItem,
// url: CommonUtil.teachers,
// param: {
//   "studentId": _currentchild.userId,
// }

class MyEasyRefresh extends StatefulWidget {
  final EasyRefreshController _controller;
  final bool firstRefresh;
  final bool isBase;
  final String url;
  final Map<String, dynamic>? param;
  final Header? header;
  final Footer? footer;
  final Function? getData;
  final List? data;
  final Function itemWidget;
  final bool operation;
  final String? idkey;
  final BuildContext? myContext;
  final bool widthToken;
  final Function? listReturn;
  final String? emptyImagPath;
  final String? emptityTextVal;
  Function? callFunc;
  MyEasyRefresh(
    this.isBase,
    this._controller,
    this.itemWidget, {
    required Key key,
    required this.url,
    this.data,
    this.firstRefresh = true,
    this.getData,
    this.header,
    this.footer,
    
    this.param,
    this.operation = false,
    this.idkey,
    this.myContext,
    this.widthToken = false,
    this.listReturn,
    this.callFunc,
    this.emptyImagPath,
    this.emptityTextVal,
  }) : super(key: key);

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

class _MyEasyRefreshState extends State<MyEasyRefresh> {
  final Map _resData = {
    "page": {
      "currentPage": 1,
      "pageSize": 10,
      "isLastPage": false,
    },
    "data": []
  };

  Future _getData(context, bool isRefresh) async {
    Map _page = _resData["page"];
    List _list = _resData["data"];
    int newPageNumber;
    if (isRefresh)
      newPageNumber = 1;
    else
      newPageNumber = _page["currentPage"] + 1;

    Map<String, dynamic> _paramMap = Map();
    Map<String, dynamic>? param = widget.param;
    if (param!=null && param.isNotEmpty) {
      _paramMap.addAll(param);
    }

    _paramMap["pageNum"] = newPageNumber;
    _paramMap["pageSize"] = _page["pageSize"];

    MyEasyRefreshService.findList(
      context,
      widget._controller,
      isRefresh,
      widget.url,
      _paramMap,
      widget.widthToken,
      (List res, bool flag) {
        if (flag) {
          if (isRefresh) {
            _page["isLastPage"] = false;
            _list.clear();
          }
          if (res != null && res.length > 0) {
            _list.addAll(res);
            _page["currentPage"] = newPageNumber;
          } else {
            _page["isLastPage"] = true;
          }
          // 数据回传
          if (widget.listReturn != null) widget.listReturn!(_list, isRefresh);
        }
        setState(() {});
      },
    );
  }

  Future<void> _deleteAll() async {
    setState(() {
      _resData['data'] = [];
      _resData['page'] = {
        "currentPage": 1,
        "pageSize": 10,
        "isLastPage": false,
      };
    });
  }

  Future<void> _deleteOne(int id) async {
    List list = _resData['data'];
    String keystr = widget.idkey ?? "id";
    for (var i = 0; i < list.length; i++) {
      Map item = list[i];
      int itemId = item[keystr];
      if (itemId == id) {
        list.removeAt(i);
        break;
      }
    }
    setState(() {
      _resData['data'] = list;
    });
  }

  // Future<void> _deleteList(List ids) {
  //   List list = _resData['data'];
  //   String keystr = widget.idkey ?? "id";
  //   List newList = list
  //       .where(
  //         (e) => !ids.contains(e[keystr]),
  //       )
  //       .toList();
  //   setState(() => _resData['data'] = newList);
  // }

  @override
  Widget build(BuildContext context) {
    String msg;
    bool flag = true;
    if (!widget.isBase) {
      // 非普通上拉下拉
      if (widget.getData == null || widget.data == null) {
        msg = "自定义方法或数据异常";
        flag = false;
      }
    } else {
      // 普通上拉下拉
      if (widget.url == null) {
        msg = "普通类型参数，或地址异常";
        flag = false;
      }
    }

    if (!flag) {
      return Container();
    }
    Widget? emptyWidget=null;
    List items;
    if (widget.isBase) {
      if (_resData['data'].length == 0){

        emptyWidget = MyEmptyWidget(imgAssetPath: widget.emptyImagPath,textVal: widget.emptityTextVal??null);
      }
      items = _resData['data'];
    } else {
      if (widget.data?.length == 0){
        emptyWidget = MyEmptyWidget(imgAssetPath: widget.emptyImagPath,textVal: widget.emptityTextVal??null);
      }
      items = widget.data??[];
    }

    return EasyRefresh(
      firstRefresh: widget.firstRefresh,
      taskIndependence: true,
      enableControlFinishRefresh: true,
      enableControlFinishLoad: true,
      controller: widget._controller,
      header: widget.header ?? MaterialHeader(),
      footer: widget.footer ?? MaterialFooter(),
      emptyWidget: emptyWidget,
      onRefresh: () async {
        if (widget.getData != null)
          await widget.getData!(true);
        else
          await _getData(context, true);
      },
      onLoad: () async {
        if (widget.getData != null)
          await widget.getData!(false);
        else
          await _getData(context, false);
      },
      child: Container(
        child: Column(
          children: widget.operation
              ? items.map<Widget>(
                  (e) {
                    return widget.itemWidget(
                      e,
                      deall: _deleteAll,
                      de: _deleteOne,
                    );
                  },
                ).toList()
              : items.map<Widget>(
                  (e) {
                    return widget.itemWidget(e);
                  },
                ).toList(),
        ),
      ),
    );
  }
}
