import 'dart:async';

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

import '../../../components/commonFun.dart';
//import 'package:hyzp_ybqx/widget/player_pro.dart';

import '../../../components/dioFun.dart';
import '../../../components/hyxx_data_handle.dart';
import '../../../services/EventBus.dart';

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

  _DwspPageState createState() => _DwspPageState();
}

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

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

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

    ///从接口 mapHyshlx[hyshlx]['api'] 获取第 iPage 页的列表数据，返回 list
    getPageList(theHyshlx: hyshlx, bShowToast: false).then((value) async {
      //mapHyshlx[hyshlx]['api'];
      listDwspGetList2 = value;
      //按照用户选择的_selectedValue、_descending对listDwspGetList2进行排序，并延时更新

      // 在点位视频列表页面，解决点位编号不连续的问题
      // int _len = listDwspGetList2.length;
      // for (int i = 0; i < _len; i++) {
      //   listDwspGetList2[i]['dwbh'] = i + 1;
      // }

      // print('xxxx_listDwspGetList2 = $listDwspGetList2');
      // for (var item in listDwspGetList2) {
      //   print('item = $item');
      // }

      listDwspGetList2.sort((_left, _right) => _left['id'].compareTo(_right['id'])); // list排序
      //listDwspGetList2.insert(1, listDwspGetList2[4]);
      // for (var item in listDwspGetList2) {
      //   print('item = $item');
      // }

      // flutter dart list 排序
      // list.sort((_left,_right)=>_left.age.compare(_right.age));
      // 说明：age为年龄，按age排完序 需要降序的话，right.age.compare(_left.age)。
      // List.sort(),参数支持subtype（当然除bool）。

      _listSort();
      firstIndex = 0;
      lastIndex = 7;
      //try_setState();

      listDwinfoGetList2 = listDwspGetList2;
      // int len = listDwspGetList2.length;
      // for (int i = 0; i < len; i++) {
      //   getDwspUrl(index: listDwspGetList2[i]['id']).then((value) {
      //     listDwspGetList2[i]['dwsp_ok'] = true;
      //     if (value == '' || value == null) {
      //       listDwspGetList2[i]['dwsp_ok'] = false;
      //     }
      //     setState(() {});
      //   });
      // }
    });

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

    //监听点位视频信息数据更新事件
    eventBus.on<DwspUpdateEvent>().listen((event) async {
      print(event.str);
      try_setState();
    });

    super.initState();
  }

  //点位信息数据
  //{
  //    "id": 1,
  //    "dwip": "172.16.3.1",
  //    "dwmc": "江北振兴大道",
  //    "dwbh": 1,
  //    "dwinfo": "江北振兴大道入城方向",
  //    "dwzb": "104.607091|28.807061",
  //    "dwms": "江北振兴大道入城方向，识别孜岩、红坝路入城排放黑烟车辆",
  //    "dwzt": "正常"
  //},

  // Widget getDropdownButton() {
  //   //DropdownMenuItem项目文本list
  //   List<String> itemList = [
  //     '主键ID',
  //     '点位IP',
  //     '点位名称',
  //     '点位编号',
  //     '点位信息',
  //     '点位坐标',
  //     '点位描述',
  //     '点位状态',
  //   ];

  Widget _getMonitorImage(String _image, int indexRecord,
      {double width = 140, double height = 140}) {
    return Container(
      margin: EdgeInsets.only(),
      width: ScreenUtil().setWidth(width),
      height: ScreenUtil().setHeight(height),
      //child: Image.asset('assets/images/ybsthbj.png', fit: BoxFit.fitHeight),
      child: Image.asset(
        _image,
        fit: BoxFit.cover,
        //color: listDwspGetList2[indexRecord]['dwsp_ok'] ? null : Theme.of(context).disabledColor
      ),
    );
  }

  Widget _getListTile(BuildContext context, int indexRecord) {
    List listCoordinate = listDwspGetList2[indexRecord]["dwzb"].trim().split('|');

    return Column(
      children: <Widget>[
        Container(
          decoration: getingIndex == indexRecord
              ? BoxDecoration(
                  border: Border.all(width: 3, color: Colors.red),
                  borderRadius: BorderRadius.all(Radius.circular(5.0)),
                )
              : null,
          child: ListTile(
            //leading: new Icon(Icons.phone),
            contentPadding: EdgeInsets.symmetric(horizontal: 15.0, vertical: 0),
            title: Text("${(indexRecord + 1).toString()}. ${listDwspGetList2[indexRecord]['dwmc']}",
                style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),

            // title: Text(
            //     "${listDwspGetList2[indexRecord]['id'].toString()}. ${listDwspGetList2[indexRecord]['dwmc']}",
            //     style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
            // title: Text(
            //     "${listDwspGetList2[indexRecord]['dwbh'].toString()}. ${listDwspGetList2[indexRecord]['dwmc']}",
            //     style: TextStyle(fontSize: 14, fontWeight: FontWeight.bold)),
            // subtitle: Text(
            //     'dwIP：${listDwspGetList2[indexRecord]['dwip']}，${listDwspGetList2[indexRecord]['dwzt']}',
            //     style: TextStyle(fontSize: 10)),
            trailing: Container(
              width: 200,
              child: Row(
                children: [
                  _getMonitorImage('assets/images/monitor.png', indexRecord),
                  SizedBox(width: 20),
                  Container(
                    width: 120,
                    child: Text(
                      '${listDwspGetList2[indexRecord]['dwms']}' +
                          '， 经纬度：${listCoordinate[0]}、${listCoordinate[1]}',
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                      //textAlign: TextAlign.right,
                      style: TextStyle(fontSize: 14),
                    ),
                  )
                ],
              ),
            ),
            enabled: true,
            onTap: () async {
              // int ret = await Navigator.of(context).push(
              //   MaterialPageRoute(
              //     builder: (context) => DwspContent(
              //       title: '点位视频信息详情',
              //       index: indexRecord,
              //       hyshlx: widget.hyshlx,
              //     ),
              //   ),
              // );

              //{
              //     "ret": 200,
              //     "data": {
              //         "id": 13,
              //         "dwip": "172.16.3.13",
              //         "dwmc": "外江路",
              //         "dwbh": 13,
              //         "dwinfo": "外江路往高铁站方向",
              //         "dwzb": "104.623547|28.74798",
              //         "dwms": "外江路往高铁站方向，识别中坝大桥往高铁站排放黑烟车辆",
              //         "dwzt": "正常",
              //         "video12": null,
              //         "video13": null,
              //         "video14": null,
              //         "video15": null,
              //         "video16": "/rtp/gb_play_34020000001320013016_34020000001320013016/hls.m3u8",
              //         "play_urlhead": "http://125.64.218.67:9903"
              //     },
              //     "msg": ""
              // }

              //getDwspUrl(index: indexRecord, context: context);
              getDwspUrlNew(indexRecord: indexRecord, context: context);
              //@山不在高水不在深 我用PC播放这个地址也等了45秒才开始，
              // http://125.64.218.67:9903/rtp/gb_play_34020000001320013016_34020000001320013016/hls.m3u8

              // getDwspUrl(index: indexRecord + 1).then((url) {
              //   print('index = ${(indexRecord + 1).toString()}, url = $url');
              //   urlnew = url;
              //
              //   //获取视频地址失败
              //   if (!isVideoUrl(urlnew)) {
              //     return;
              //   }
              //
              //   var ret = Navigator.of(context).push(MaterialPageRoute(
              //       builder: (context) => PlayerPro(
              //             url: urlnew,
              //             title:
              //                 '点位视频\n${(indexRecord + 1)}、${listDwinfoGetList2[indexRecord]['dwmc']}',
              //             //initVideoSize: Size(704.0, 576.0),  //16比13
              //             //initVideoSize: Size(16, 9),
              //           )));
              //   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 WillPopScope(
      child: Scaffold(
        appBar: PreferredSize(
          preferredSize: Size.fromHeight(ScreenUtil().setHeight(173)), // 设置appBar高度
          // 设置appBar高度
          child: AppBar(
            automaticallyImplyLeading: false,
            centerTitle: true,
            titleSpacing: 0.0,
            //设置title的左边距
            flexibleSpace: Container(
              //SizedBox(height: ScreenUtil().statusBarHeight), //显示顶部状态栏
              // SizedBox(height: ScreenUtil().setHeight(10)), //显示顶部状态栏
              padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight), //留出顶部状态栏高度
              child: Container(
                //height: ScreenUtil().setHeight(173),
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                    colors: [
                      Color.fromRGBO(12, 186, 156, 1),
                      Color.fromRGBO(39, 127, 235, 1),
                    ],
                  ),
                ),
                // decoration: BoxDecoration(
                //   gradient: LinearGradient(colors: [
                //     Color(0xFF0018EB),
                //     Color(0xFF01C1D9),
                //   ], begin: Alignment.bottomCenter, end: Alignment.topCenter),
                // ),
              ),
            ),
            title: Padding(
              padding: EdgeInsets.only(left: 0, right: 0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  getIconAndTextButton(
                    iconColor: Colors.white,
                    iconData: Icons.chevron_left_outlined,
                    onPress: () {
                      getingDwVideo = false;
                      Navigator.pop(context);
                    },
                  ),
                  Expanded(
                    child: Text("${mapHyshlx[hyshlx]['text']}",
                        style: TextStyle(color: Colors.white, fontSize: 20),
                        textAlign: TextAlign.center,
                        overflow: TextOverflow.ellipsis),
                  ),
                  SizedBox(width: 50),
                ],
              ),
            ),
          ),
        ),
        body: (0 == listDwspGetList2.length)
            ? getMoreWidget(color: Colors.black38)
            : ListView.custom(
                //itemExtent: 75.0, //列表项高度
                controller: _controller,
                cacheExtent: 1.0, // 只有设置了1.0 才能够准确的标记 position 位置
                childrenDelegate: MyChildrenDelegate(
                  _getListTile,
                  childCount: listDwspGetList2.length,
                ),
              ),
      ),
      onWillPop: () {
        // 屏蔽点击返回键的操作
        getingDwVideo = false;
        Navigator.pop(context);
      },
    );
  }

  //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对listDwspGetList2进行排序，并延时更新
  Future _listSort({bool bShowToast = false}) {
    if (!isLoading && listDwspGetList2.length > 0) {
      isLoading = true;
      try_setState();

      switch (_selectedValue) {
        default:
          if (_descending) {
            //按_selectedValue排序，降序
            listDwspGetList2.sort((a, b) =>
                (b[mapWzxxDataText[_selectedValue]]).compareTo(a[mapWzxxDataText[_selectedValue]]));
          } else {
            //按_selectedValue排序，升序
            listDwspGetList2.sort((a, b) =>
                (a[mapWzxxDataText[_selectedValue]]).compareTo(b[mapWzxxDataText[_selectedValue]]));
            // E/flutter ( 5170): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception:
            // NoSuchMethodError: The method 'compareTo' was called on null.
          }
          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)),
        ),
      ],
    );
  }

  //点位信息数据
  //{
  //    "id": 1,
  //    "dwip": "172.16.3.1",
  //    "dwmc": "江北振兴大道",
  //    "dwbh": 1,
  //    "dwinfo": "江北振兴大道入城方向",
  //    "dwzb": "104.607091|28.807061",
  //    "dwms": "江北振兴大道入城方向，识别孜岩、红坝路入城排放黑烟车辆",
  //    "dwzt": "正常"
  //},

  Widget getDropdownButton() {
    //DropdownMenuItem项目文本list
    List<String> itemList = [
      '主键ID',
      '点位IP',
      '点位名称',
      '点位编号',
      '点位信息',
      '点位坐标',
      '点位描述',
      '点位状态',
    ];

    //添加按'推送状态'排序
    if (hyshlx != 'dwxx') {
      // 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对listDwspGetList2进行排序，并延时更新
              _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);
  }
}
