import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';

import '../../../components/commonFun.dart';
import '../../../components/dioFun.dart';
import '../../../components/doJSON.dart';
import '../../../components/hyxx_data_handle.dart';
import '../../../services/EventBus.dart';
import 'led_xsxx_content.dart';

//LedXsxx是本项目中“LED显示信息”的统一缩写
class LedXsxxGetList extends StatefulWidget {
  //hyshlx为黑烟审核类型，处理'LedXsxx'LED显示信息。mapHyshlx[hyshlx]获取为各种类型的设置数据
  LedXsxxGetList({this.sbgllx = 'led_xsxx', Key key}) : super(key: key);
  String sbgllx;

  _LedXsxxPageState createState() => _LedXsxxPageState();
}

class _LedXsxxPageState extends State<LedXsxxGetList> {
  //try_setState();   //避免异常报错
  try_setState() {
    try {
      setState(() {});
    } catch (e) {
      print('setState(() {})异常：${e}');
    }
  }

  @override
  void dispose() {
    _controller.dispose(); //销毁控制器
    super.dispose();
  }

  @override
  void initState() {
    hyshlx = widget.sbgllx;
    iPage = 0;
    listLedXsxxGetList2.clear();

    ///从接口 mapHyshlx[hyshlx]['api'] 获取第 iPage 页的列表数据，返回 list
    getPageList().then((value) {
      listLedXsxxGetList2 = value;
      //按照用户选择的_selectedValue、_descending对listLedXsxxGetList2进行排序，并延时更新
      _listSort();
      firstIndex = 0;
      lastIndex = 7;
    });

    ///从接口 mapHyshlx[theHyshlx]['api'] 获取指定类型第 page 页的列表数据，返回 list
    ///获取点位信息数据
    listDwinfoGetList2.clear();
    getThePageList(theHyshlx: 'dwxx').then((value) {
      listDwinfoGetList2 = value;
      print('listDwinfoGetList2 = \n$listDwinfoGetList2');
    });

    //监听违章信息数据更新事件
    eventBus.on<LedXsxxUpdateEvent>().listen((event) async {
      iPage = 0;
      print(event.str);
      //按照用户选择的_selectedValue、_descending对listLedXsxxGetList2进行排序，并延时更新
      _listSort();
    });

    //监听违章信息数据审核事件
    eventBus.on<WzxxDataAuditEvent>().listen((event) async {
      print('LedXsxxGetList: ' + event.str);
      //按照用户选择的_selectedValue、_descending对listLedXsxxGetList2进行排序，并延时更新
      _listSort();
    });

    //监听违章信息Listview滚动事件
    eventBus.on<WzxxDataScrollEvent>().listen((event) async {
      firstIndex = event.firstIndex;
      lastIndex = event.lastIndex;
      try_setState();
    });

    super.initState();
  }

  //Led数据变量
  // Map mapGetLedXsxxGetData = {
  //   "id": 2,
  //   "xsnr": "绿水青山就是金山银山     宜宾市翠屏生态环境局宣。",
  //   "addtime": "2021-01-20 10:16:07",
  //   "updatetime": "2021-02-13 11:48:51"
  // };
  Widget _getListTile(BuildContext context, indexRecord) {
    return Column(
      children: <Widget>[
        ListTile(
          //leading: new Icon(Icons.phone),
          title: Text(
              "${(indexRecord + 1).toString()}. " +
                  listLedXsxxGetList2[indexRecord]['addtime'] +
                  ' 添加',
              style: TextStyle(fontSize: 10)),
          subtitle: Text(getDate(listLedXsxxGetList2[indexRecord]['updatetime']) + ' 更新',
              style: TextStyle(fontSize: 10)),
          trailing: Container(
            width: 180,
            child: Text(
              'id：' +
                  listLedXsxxGetList2[indexRecord]['id'].toString() +
                  '， 显示信息：' +
                  listLedXsxxGetList2[indexRecord]['xsnr'],
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              //textAlign: TextAlign.right,
              style: TextStyle(fontSize: 12),
            ),
          ),
          contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 0),
          enabled: true,
          onTap: () async {
            int ret = await Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => LedXsxxContent(
                  title: 'LED显示信息详情',
                  sbgllx: widget.sbgllx,
                  id: listLedXsxxGetList2[indexRecord]['id'],
                ),
              ),
            );

            print('ret = $ret');
          },
        ),
        Divider(height: 1.0),
      ],
    );
  }

  ScrollController _controller = ScrollController(); //ListView控制器
  bool isLoading = false; //正在处理下载数据、跳转到首项、跳转到尾项等操作
  int firstIndex = 0; //ListView当前显示页面首项0基序号
  int lastIndex = 0; //ListView当前显示页面末项0基序号
  int itemOnPage = 8; //估计一屏显示的项目数量

  Widget getIconButton({IconData iconData, var onPressed, double iconSize = 22}) {
    return SizedBox(
      height: iconSize,
      width: iconSize + 10,
      child: IconButton(
        padding: EdgeInsets.all(0.0),
        icon: Icon(iconData, size: iconSize),
        onPressed: onPressed,
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
        centerTitle: true,
        //leading: Text(''),
        titleSpacing: 0.0,
        //设置title的左边距
        title: Padding(
          padding: EdgeInsets.only(left: 0, right: 0),
          child: Row(
            //mainAxisAlignment: MainAxisAlignment.start,
            children: [
              getIconAndTextButton(
                iconData: Icons.arrow_back,
                onPress: () {
                  Navigator.pop(context);
                },
              ),
              Expanded(
                child: Text("${mapHyshlx[hyshlx]['text']}",
                    textAlign: TextAlign.left,
                    overflow: TextOverflow.ellipsis,
                    style: widget.sbgllx == 'fhycx' ? TextStyle(fontSize: 16) : null),
              ),
              SizedBox(width: 5),
            ],
          ),
        ),
        actions: <Widget>[
          getDropdownButton(),
          SizedBox(width: 10),
          getIconButton(
            iconData: Icons.cloud_download,
            onPressed: !isLoading
                ? () async {
                    if (isLoading) {
                      return;
                    }
                    isLoading = true;
                    try_setState();
                    //print("I Pressed the Iconbutton");
                    int oldItems = listLedXsxxGetList2.length;
                    for (int i = 0; i < 10; i++) {
                      List list = await getPageList();
                      if (list.length > 0) {
                        listLedXsxxGetList2.addAll(list); //加载累加
                      } else {
                        break;
                      }
                    }
                    Future.delayed(const Duration(milliseconds: 1000), () async {
                      if (listLedXsxxGetList2.length > oldItems) {
                        eventBus.fire(WzxxDataAuditEvent('${mapHyshlx[hyshlx]['text']}数据已更新'));
                        Fluttertoast.showToast(
                          msg: '新增 ${listLedXsxxGetList2.length - oldItems} 条数据下载完成！',
                          toastLength: Toast.LENGTH_SHORT,
                          gravity: ToastGravity.CENTER,
                        );

                        //按照用户选择的_selectedValue、_descending对listLedXsxxGetList2进行排序，并延时更新
                        _listSort();
                      }
                      isLoading = false;
                      try_setState();
                    });
                  }
                : null,
          ),
          getIconButton(
            iconData: Icons.vertical_align_top_outlined,
            onPressed: (!isLoading && (firstIndex > 0)) //未到顶部
                ? () async {
                    if (isLoading) {
                      return;
                    }
                    isLoading = true;
                    try_setState();

                    //必须延时执行，否则不能及时完成按钮状态更新
                    Timer(
                      Duration(milliseconds: 500),
                      () {
                        _controller.jumpTo(_controller.position.minScrollExtent);
                      },
                    );

                    Timer(
                      Duration(milliseconds: 1000),
                      () {
                        // Fluttertoast.showToast(
                        //   msg: '已经跳转到开头记录！',
                        //   toastLength: Toast.LENGTH_SHORT,
                        //   gravity: ToastGravity.CENTER,
                        // );
                        firstIndex = 0;
                        lastIndex = itemOnPage - 1; //0基序号，所以需要减1
                        isLoading = false;
                        try_setState();
                      },
                    );
                  }
                : null,
          ),
          getIconButton(
            iconData: Icons.vertical_align_bottom_outlined,
            onPressed: (!isLoading && (lastIndex < listLedXsxxGetList2.length)) //未到尾部
                ? () async {
                    if (isLoading) {
                      return;
                    }
                    isLoading = true;
                    try_setState();

                    //必须延时执行，否则不能及时完成按钮状态更新
                    Timer(
                      Duration(milliseconds: 500),
                      () {
                        _controller.jumpTo(_controller.position.maxScrollExtent);
                      },
                    );

                    Timer(
                      Duration(milliseconds: 1000),
                      () {
                        // Fluttertoast.showToast(
                        //   msg: '已经跳转到末尾记录！',
                        //   toastLength: Toast.LENGTH_SHORT,
                        //   gravity: ToastGravity.CENTER,
                        // );
                        //0基序号需要减1，再加上底部有一组显示信息，所以需要减2
                        firstIndex = listLedXsxxGetList2.length - itemOnPage - 2;
                        lastIndex = listLedXsxxGetList2.length;
                        isLoading = false;
                        try_setState();
                      },
                    );
                  }
                : null,
          ),
        ],
      ),
      body: (0 == listLedXsxxGetList2.length)
          ? getMoreWidget(color: Colors.black38)
          : EasyRefresh(
              child: ListView.custom(
                controller: _controller,
                cacheExtent: 1.0, // 只有设置了1.0 才能够准确的标记position 位置
                childrenDelegate: MyChildrenDelegate(
                  _getListTile,
                  childCount: listLedXsxxGetList2.length,
                ),
              ),
              onRefresh: () async {
                // await Future.delayed(const Duration(seconds: 1), () async {
                //   iPage = 0;
                //   //await getWzxxGetList();
                //   listLedXsxxGetList2 = await getPageList();
                //   eventBus.fire(WzxxDataAuditEvent('${mapHyshlx[hyshlx]['text']}数据已更新'));
                // });
              },
              onLoad: () async {
                if (isLoading) {
                  return;
                }
                isLoading = true;
                try_setState();

                print('iPage = $iPage');
                await Future.delayed(const Duration(seconds: 1), () async {
                  //await getWzxxGetList();
                  List list = await getPageList();
                  if (list.length > 0) {
                    listLedXsxxGetList2.addAll(list); //加载累加
                    eventBus.fire(WzxxDataAuditEvent('${mapHyshlx[hyshlx]['text']}数据已更新'));
                  }
                  isLoading = false;
                  try_setState();
                });
              },
              header: getHeader(),
              footer: getFooter(),
            ),
    );
  }

  //DropdownButton需要设置初始值的时候，初始值必须是显示列表里面的值，否则会导致弹出框异常。
  // 比如说：你的DropdownButton的items属性使用的是list这个列表里面的值，那么你的初始值应该在list[index]里面取，要不就会报错。
  //
  // There should be exactly one item with [DropdownButton]'s value: 0.0.
  // Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
  // 'package:flutter/src/material/dropdown.dart':
  // Failed assertion: line 834 pos 15: 'items == null || items.isEmpty || value == null ||
  //               items.where((DropdownMenuItem<T> item) {
  //                 return item.value == value;
  //               }).length == 1'
  String _selectedValue = '主键ID';
  bool _descending = false; //默认生效排列

  Widget _getImage(String _image) {
    return Container(
        margin: EdgeInsets.only(),
        height: ScreenUtil().setWidth(38),
        width: ScreenUtil().setWidth(38),
        //child: Image.asset('assets/images/ybsthbj.png', fit: BoxFit.fitHeight),
        child: Image.asset(_image,
            fit: BoxFit.cover, color: isLoading ? Theme.of(context).disabledColor : null));
  }

  //按照用户选择的_selectedValue、_descending对listLedXsxxGetList2进行排序，并延时更新
  Future _listSort({bool bShowToast = false}) {
    if (!isLoading && listLedXsxxGetList2.length > 0) {
      isLoading = true;
      try_setState();

      switch (_selectedValue) {
        default:
          if (_descending) {
            //按_selectedValue排序，降序
            listLedXsxxGetList2.sort((a, b) =>
                (b[mapWzxxDataText[_selectedValue]]).compareTo(a[mapWzxxDataText[_selectedValue]]));
          } else {
            //按_selectedValue排序，升序
            listLedXsxxGetList2.sort((a, b) =>
                (a[mapWzxxDataText[_selectedValue]]).compareTo(b[mapWzxxDataText[_selectedValue]]));
          }
          break;
      }

      Future.delayed(const Duration(milliseconds: 1000), () {
        if (bShowToast) {
          Fluttertoast.showToast(
            msg: '按“${_selectedValue}”${_descending ? '降序' : '升序'}排列完成！',
            toastLength: Toast.LENGTH_SHORT,
            gravity: ToastGravity.CENTER,
          );
        }
        isLoading = false;
        try_setState(); //避免如下异常报错
      });
    }
  }

  Widget getDropdownButtonItemText(String item) {
    return Row(
      //crossAxisAlignment: CrossAxisAlignment.center,
      children: [
        Container(
          alignment: Alignment(0, 0.28),
          child: item == _selectedValue
              ? _descending
                  ? _getImage('assets/images/descending.png')
                  : _getImage('assets/images/ascending.png')
              // ? Icon(Icons.arrow_downward_outlined, size: 20)
              // : Icon(Icons.arrow_upward_outlined, size: 20)
              : SizedBox(),
        ),
        SizedBox(
          width: 3,
        ),
        Container(
          //alignment: Alignment(0, -1),
          child: Text(item,
              style: isLoading
                  ? TextStyle(color: Theme.of(context).disabledColor)
                  : (item == _selectedValue ? TextStyle(color: Colors.blue) : null)),
        ),
      ],
    );
  }

  Widget getDropdownButton() {
    //DropdownMenuItem项目文本list
    List<String> itemList = [
      '主键ID',
      '添加时间',
      '更新时间',
      '显示信息',
    ];

    //添加按'推送状态'排序
    if (hyshlx != 'led_xsxx') {
      itemList.removeLast();
      itemList.addAll(['推送状态', '主键ID']);
    }

    //获取DropdownMenuItem项目组件list
    List<DropdownMenuItem<String>> _dropDownMenuItems =
        itemList.map<DropdownMenuItem<String>>((String item) {
      return DropdownMenuItem<String>(
        value: item,
        child: getDropdownButtonItemText(item),
      );
    }).toList();

    return Padding(
      padding: EdgeInsets.only(top: 10, bottom: 10),
      child: Container(
        alignment: Alignment(0.7, 0),
        width: 125,
        margin: EdgeInsets.only(bottom: 0),
        padding: EdgeInsets.only(left: 0, bottom: 0),
        decoration: BoxDecoration(
          border: Border.all(width: 0),
          //边框圆角设置
          borderRadius:
              BorderRadius.vertical(top: Radius.elliptical(2, 2), bottom: Radius.elliptical(2, 2)),
        ),
        //DropdownButton默认有一条下划线，DropdownButtonHideUnderline去除下划线
        child: DropdownButtonHideUnderline(
          child: DropdownButton<String>(
            isDense: true,
            value: _selectedValue,
            items: _dropDownMenuItems,
            onChanged: (String selectedValue) {
              if (isLoading) {
                return;
              }

              if (_selectedValue == selectedValue) {
                _descending = !_descending;
              } else {
                _descending = true;
              }
              _selectedValue = selectedValue;
              print('_selectedValue = $_selectedValue');

              //按照用户选择的_selectedValue、_descending对listLedXsxxGetList2进行排序，并延时更新
              _listSort(bShowToast: true);
            },
          ),
        ),
      ),
    );
  }
}

//https://blog.csdn.net/u014803467/article/details/103750018
//Flutter 使用SliverChildBuilderDelegate获取ListView的第一个和最后一个可见Item序号
// 秋名山交警X 2019-12-28 23:52:52
class _SaltedValueKey extends ValueKey<Key> {
  const _SaltedValueKey(Key key)
      : assert(key != null),
        super(key);
}

class MyChildrenDelegate extends SliverChildBuilderDelegate {
  MyChildrenDelegate(
    Widget Function(BuildContext, int) builder, {
    int childCount,
    bool addAutomaticKeepAlive = true,
    bool addRepaintBoundaries = true,
  }) : super(builder,
            childCount: childCount,
            addAutomaticKeepAlives: addAutomaticKeepAlive,
            addRepaintBoundaries: addRepaintBoundaries);

  // Return a Widget for the given Exception
  Widget _createErrorWidget(dynamic exception, StackTrace stackTrace) {
    final FlutterErrorDetails details = FlutterErrorDetails(
      exception: exception,
      stack: stackTrace,
      library: 'widgets library',
      context: ErrorDescription('building'),
    );
    FlutterError.reportError(details);
    return ErrorWidget.builder(details);
  }

  @override
  Widget build(BuildContext context, int index) {
    assert(builder != null);
    if (index < 0 || (childCount != null && index >= childCount)) return null;
    Widget child;
    try {
      child = builder(context, index);
    } catch (exception, stackTrace) {
      child = _createErrorWidget(exception, stackTrace);
    }
    if (child == null) return null;
    final Key key = child.key != null ? _SaltedValueKey(child.key) : null;
    if (addRepaintBoundaries) child = RepaintBoundary(child: child);
    if (addSemanticIndexes) {
      final int semanticIndex = semanticIndexCallback(child, index);
      if (semanticIndex != null)
        child = IndexedSemantics(index: semanticIndex + semanticIndexOffset, child: child);
    }
    if (addAutomaticKeepAlives) child = AutomaticKeepAlive(child: child);
    return KeyedSubtree(child: child, key: key);
  }

  @override
  void didFinishLayout(int _firstIndex, int _lastIndex) {
    // TODO: implement didFinishLayout
    super.didFinishLayout(_firstIndex, _lastIndex);
  }

  ///监听 在可见的列表中 显示的第一个位置和最后一个位置
  @override
  double estimateMaxScrollOffset(
      int _firstIndex, int _lastIndex, double _leadingScrollOffset, double _trailingScrollOffset) {
    //违章信息Listview滚动广播
    eventBus.fire(WzxxDataScrollEvent(_firstIndex, _lastIndex));

    return super.estimateMaxScrollOffset(
        _firstIndex, _lastIndex, _leadingScrollOffset, _trailingScrollOffset);
  }
}
