import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hyzp_ybqx/pages/Works/TJXX/zptj_bar_chart.dart';
import 'package:hyzp_ybqx/pages/Works/TJXX/zptj_bar_chart_one.dart';

import '../../../components/commonFun.dart';
import '../../../components/hyxx_data_handle.dart';
import 'tj_data.dart';

//zptj 是本项目中“抓拍统计”的统一缩写
//sh_hyc_tj 是本项目中“审核黑烟车统计”的统一缩写
//clltj 是本项目中“车流量统计”的统一缩写
class ZptjPage extends StatefulWidget {
  //mapStatisType 为统计数据类型数据结构。用于在同一套代码中，处理相似类型的多种统计数据
  //statisType 为统计类型。mapStatisType[statisType] 为各种相似类型的设置数据
  ZptjPage({@required this.statisType, Key key}) : super(key: key);
  String statisType;

  _ZptjPageState createState() => _ZptjPageState();
}

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

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

  @override
  void initState() {
    // ///获取点位信息数据
    // listZptjStatis.clear(); //最后需要显示的数据
    //
    // if (listDwinfoGetList2.isEmpty) {
    //   //若没有读取了点位数据，便需要先读取
    //   getThePageList(theHyshlx: 'dwxx').then((value) {
    //     listDwinfoGetList2 = value;
    //     print('listDwinfoGetList2 = \n$listDwinfoGetList2');
    //     getZptjStatis(widget.statisType).then((value) {
    //       _listSort(sortField: 'dwbh');
    //     });
    //   });
    // } else {
    //   //若已经读取了点位数据，便直接使用
    //   print('listDwinfoGetList2 = \n$listDwinfoGetList2');
    //   getZptjStatis(widget.statisType).then((value) {
    //     _listSort(sortField: 'dwbh');
    //   });
    // }

    super.initState();
  }

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

  //listZptjStatis = [
  //  {today: 832, all: 4479, dwip: 172.16.3.1},
  //  {today: 0, all: 185, dwip: 172.16.3.2},
  //  {today: 0, all: 131, dwip: 172.16.3.3},
  //  {today: 0, all: 72, dwip: 172.16.3.4},
  //  {today: 0, all: 30, dwip: 172.16.3.5},
  //  {today: 0, all: 26, dwip: 172.16.3.6},
  //  {today: 0, all: 0, dwip: 172.16.3.7},
  //  {today: 0, all: 135, dwip: 172.16.3.8},
  //  {today: 0, all: 65, dwip: 172.16.3.9},
  //  {today: 0, all: 36, dwip: 172.16.3.10},
  //  {today: 0, all: 44, dwip: 172.16.3.11},
  //  {today: 0, all: 76, dwip: 172.16.3.12},
  //  {today: 0, all: 83, dwip: 172.16.3.13}
  //]

  Widget _getListTile(BuildContext context, int indexRecord, {double width = 520}) {
    switch (widget.statisType) {
      case 'zptj':
        return _getZptjListTile(context, indexRecord, 520);
        break;
      case 'clltj':
        return _getClltjListTile(context, indexRecord, 520);
        break;
      case 'sh_hyc_tj':
        return _getSh_hyc_tjListTile(context, indexRecord, 510);
        break;
      default:
        return Container();
        break;
    }
  }

  //抓拍统计数据
  //{
  //  "today": 0,
  //  "all": 72
  //  "dwbh": 1,
  //  "dwmc": "江北振兴大道",
  //  "dwip": "172.16.3.1"
  //}
  Widget _getSh_hyc_tjListTile(BuildContext context, int indexRecord, double width) {
    return Column(
      children: <Widget>[
        ListTile(
          //leading: new Icon(Icons.phone),
          title: getDwmcField(indexRecord, 40),
          // subtitle:
          //     Text('今日：${listZptjStatis[indexRecord]['today']}', style: TextStyle(fontSize: 10)),
          trailing: Container(
            width: ScreenUtil().setWidth(width),
            child: Row(
              children: [
                getText(
                    text: listAllStatisData[indexRecord]['hyc_all'].toString(),
                    width: 260,
                    fontSize: 16),
                getText(
                    text: listAllStatisData[indexRecord]['send_all'].toString(),
                    width: 240,
                    fontSize: 16),
              ],
            ),
          ),
          contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 0),
          enabled: true,
          onTap: () async {},
        ),
        Divider(height: 1.0),
      ],
    );
  }

  Widget getText({String text = '', double width = 100, double fontSize = 16}) {
    return SizedBox(
      width: ScreenUtil().setWidth(width),
      child: Text(
        text,
        maxLines: 1,
        overflow: TextOverflow.ellipsis,
        //textAlign: TextAlign.right,
        style: TextStyle(fontSize: fontSize),
      ),
    );
  }

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

  Widget getDwmcField(int indexRecord, double width) {
    return SizedBox(
      width: ScreenUtil().setWidth(width),
      child: Text(
        // '${listAllStatisData[indexRecord]["id"].toString()}. ${listAllStatisData[indexRecord]["dwmc"]}',
        '${(indexRecord + 1).toString()}. ${listAllStatisData[indexRecord]["dwmc"]}',
        style: TextStyle(fontSize: 16),
      ),
    );
  }

  /*
  listAllStatisData =
  [
        {
            "id": 1,
            "dwip": "172.16.3.1",
            "dwmc": "锦绣花园",
            "zp_all": 54,
            "hyc_all": 53,
            "zp_today": 1,
            "sends": 1,
            "send_all": 34,
            "csnum": 1,
            "fsnum": 1,
            "cll_today": 23200,
            "cll_all": 3242513
        },
        ...
  ]
  */
  Widget _getZptjListTile(BuildContext context, int indexRecord, double width) {
    return Column(
      children: <Widget>[
        ListTile(
          //leading: new Icon(Icons.phone),
          title: getDwmcField(indexRecord, 40),
          // subtitle:
          //     Text('今日：${listAllStatisData[indexRecord]['today']}', style: TextStyle(fontSize: 10)),
          trailing: Container(
            width: ScreenUtil().setWidth(width),
            child: Row(
              children: [
                getText(
                    text: listAllStatisData[indexRecord]['zp_today'].toString(),
                    width: 260,
                    fontSize: 16),
                getText(
                    text: listAllStatisData[indexRecord]['zp_all'].toString(),
                    width: 260,
                    fontSize: 16),
              ],
            ),
          ),
          contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 0),
          enabled: true,
          onTap: () async {},
        ),
        Divider(height: 1.0),
      ],
    );
  }

  Widget _getClltjListTile(BuildContext context, int indexRecord, double width) {
    return Column(
      children: <Widget>[
        ListTile(
          //leading: new Icon(Icons.phone),
          title: getDwmcField(indexRecord, 40),
          // subtitle:
          //     Text('今日：${listAllStatisData[indexRecord]['today']}', style: TextStyle(fontSize: 10)),
          trailing: Container(
            width: ScreenUtil().setWidth(width),
            child: Row(
              children: [
                // getText(
                //     text: listAllStatisData[indexRecord]['today'].toString(),
                //     width: 260,
                //     fontSize: 16),
                // getText(
                //     text: (listAllStatisData[indexRecord]['all'] / 10000).toString(),
                //     width: 260,
                //     fontSize: 16),
                getText(text: '', width: 260, fontSize: 16),
                getText(
                    text: listAllStatisData[indexRecord]['cll_today'].toString(),
                    width: 260,
                    fontSize: 16),
              ],
            ),
          ),
          contentPadding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 0),
          enabled: true,
          onTap: () async {},
        ),
        Divider(height: 1.0),
      ],
    );
  }

  bool isLoading = false; //正在处理下载数据、跳转到首项、跳转到尾项等操作

  //Map<String, String> mapTjDataText = {
  //   "dwip": '点位IP',
  //   "today": '今日',
  //   "all": '总共',
  //   "total": '总共2',
  //   "sends": '推送'
  // };

  //抓拍统计数据
  //{
  //    "today": 5,
  //    "all": 77
  //},

  //审核统计数据
  //{
  //     "total": 6,
  //     "sends": 5
  // },

  //车流量统计数据
  //{
  //    "today": 0,
  //    "all": 675338
  //}

  //得到表头行
  Widget getHeadRow() {
    Widget _headRow;
    switch (widget.statisType) {
      case 'zptj':
        _headRow = Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              width: ScreenUtil().setWidth(475),
              child: _getSortBtn(sortField: 'dwmc', left: 78),
            ),
            SizedBox(
              width: ScreenUtil().setWidth(285),
              child: _getSortBtn(sortField: 'today', left: 10),
            ),
            SizedBox(
              width: ScreenUtil().setWidth(280),
              child: _getSortBtn(sortField: 'all', left: 10),
            ),
          ],
        );
        break;
      case 'sh_hyc_tj':
        _headRow = Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              width: ScreenUtil().setWidth(495),
              child: _getSortBtn(sortField: 'dwmc', left: 78),
            ),
            SizedBox(
              width: ScreenUtil().setWidth(265),
              child: _getSortBtn(sortField: 'total', left: 10),
            ),
            SizedBox(
              width: ScreenUtil().setWidth(300),
              child: _getSortBtn(sortField: 'sends', left: 20),
            ),
          ],
        );
        break;
      case 'clltj':
        _headRow = Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              width: ScreenUtil().setWidth(465),
              child: _getSortBtn(sortField: 'dwmc', left: 78),
            ),
            // SizedBox(
            //   width: ScreenUtil().setWidth(265),
            //   child: _getSortBtn(sortField: 'today', left: 20),
            // ),
            // SizedBox(
            //   width: ScreenUtil().setWidth(300),
            //   child: _getSortBtn(sortField: 'all', left: 50),
            // ),
            SizedBox(
              width: ScreenUtil().setWidth(265),
              child: Text(''),
            ),
            SizedBox(
              width: ScreenUtil().setWidth(300),
              child: _getSortBtn(sortField: 'today', left: 20),
            ),
          ],
        );
        break;
      default:
        return Container();
        break;
    }

    return _headRow;
  }

  /*
  listAllStatisData =
  [
        {
            "id": 1,
            "dwip": "172.16.3.1",
            "dwmc": "锦绣花园",
            "zp_all": 54,
            "hyc_all": 53,
            "zp_today": 1,
            "sends": 1,
            "send_all": 34,
            "csnum": 1,
            "fsnum": 1,
            "cll_today": 23200,
            "cll_all": 3242513
        },
        ...
  ]
  */
  //得到统计行
  Widget getStatisRow() {
    Widget _headRow;
    switch (widget.statisType) {
      case 'zptj':
        List _listSum = tj_getAllSum('zp_today');
        List _listAll = tj_getAllSum('zp_all');
        _headRow = Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              width: ScreenUtil().setWidth(455),
              //xx个点位正常\n（共xx个点位）
              child: _getStatisText(
                  //text: '${getOKdw().toString()}个点位正常\n（共${listDwinfoGetList2.length.toString()}个点位）',
                  text: '共 ${listDwinfoGetList2.length.toString()} 个点位',
                  left: ScreenUtil().setWidth(170)),
            ),
            SizedBox(
              width: ScreenUtil().setWidth(270),
              //xx个点位，今日共抓拍xx
              child: _getStatisText(
                  //text: '${_listSum[0].toString()}个点位，今日共抓拍${_listSum[1].toString()}',
                  text: '今日 ${_listSum[1].toString()} 次',
                  width: ScreenUtil().setWidth(245)),
            ),
            SizedBox(
              width: ScreenUtil().setWidth(300),
              //xx个点位，总共抓拍xx
              child: _getStatisText(
                  //text: '${_listAll[0].toString()}个点位，总共抓拍${_listAll[1].toString()}',
                  text: '总共 ${_listAll[1].toString()} 次',
                  width: ScreenUtil().setWidth(260)),
            ),
          ],
        );
        break;
      case 'sh_hyc_tj':
        List _listSum = tj_getAllSum('send_all');
        //List _listAll = tj_getAllSumCll('total'); // 'total' 字段没有记录详情，所以用tj_getAllSumCll()
        List _listAll = tj_getAllSum('hyc_all');
        _headRow = Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              width: ScreenUtil().setWidth(475),
              //xx正常(共13)
              child: _getStatisText(
                  //text: '${getOKdw().toString()}个点位正常\n（共${listDwinfoGetList2.length.toString()}个点位）',
                  text: '共 ${listDwinfoGetList2.length.toString()} 个点位',
                  left: ScreenUtil().setWidth(170)),
            ),
            SizedBox(
              width: ScreenUtil().setWidth(260),
              //xx个点位，总共审核xx
              child: _getStatisText(
                  //text: '${_listAll[0].toString()}个点位，总共审核${_listAll[1].toString()}',
                  text: '共审核 ${_listAll[1].toString()} 次',
                  width: ScreenUtil().setWidth(225)),
            ),
            SizedBox(
              //xx个点位，总共推送xx
              child: _getStatisText(
                  //text: '${_listSum[0].toString()}个点位，总共推送${_listSum[1].toString()}',
                  text: '共推送 ${_listSum[1].toString()} 次',
                  width: ScreenUtil().setWidth(260)),
            ),
          ],
        );
        break;
      case 'clltj':
        List _listSum = tj_getAllSum('cll_today');
        List _listAll = tj_getAllSum('cll_all');
        _headRow = Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            SizedBox(
              width: ScreenUtil().setWidth(445),
              //xx个点位正常\n（共xx个点位）
              child: _getStatisText(
                  //text: '${getOKdw().toString()}个点位正常\n（共${listDwinfoGetList2.length.toString()}个点位）',
                  text: '共 ${listDwinfoGetList2.length.toString()} 个点位',
                  left: ScreenUtil().setWidth(150)),
            ),
            // SizedBox(
            //   width: ScreenUtil().setWidth(280),
            //   //xx个点位，今日共抓拍xx
            //   child: _getStatisText(
            //       //text: '${_listSum[0].toString()}个点位，今日车流量${_listSum[1].toString()}',
            //       text: '今日 ${_listSum[1].toString()}',
            //       width: ScreenUtil().setWidth(265)),
            // ),
            // SizedBox(
            //   width: ScreenUtil().setWidth(280),
            //   //xx个点位，总共抓拍xx
            //   child: _getStatisText(
            //       //text: '${_listAll[0].toString()}个点位，总共车流量${_listAll[1].toString()}',
            //       text: '总共 ${(_listAll[1] ~/ 10000).toString()} 万',
            //       width: ScreenUtil().setWidth(280)),
            // ),
            SizedBox(
              width: ScreenUtil().setWidth(280),
              //xx个点位，今日共抓拍xx
              child: _getStatisText(
                  //text: '${_listSum[0].toString()}个点位，今日车流量${_listSum[1].toString()}',
                  text: '',
                  width: ScreenUtil().setWidth(265)),
            ),
            SizedBox(
              width: ScreenUtil().setWidth(280),
              //xx个点位，今日共抓拍xx
              child: _getStatisText(
                  //text: '${_listSum[0].toString()}个点位，今日车流量${_listSum[1].toString()}',
                  text: '今日 ${_listSum[1].toString()}',
                  width: ScreenUtil().setWidth(205)),
            ),
          ],
        );
        break;
      default:
        return Container();
        break;
    }

    return _headRow;
  }

  //获取已审核黑烟车统计数据：App.Car_Statis.GetStaHyc
  //{
  //     "ret": 200,
  //     "data": {
  //         "total": 40,
  //         "sends": {
  //             "total": 0,
  //             "data": []
  //         },
  //         "csnum": {
  //             "total": 0,
  //             "data": []
  //         },
  //         "fsnum": {
  //             "total": 0,
  //             "data": []
  //         }
  //     },
  //     "msg": ""
  // }

  //获取抓拍统计数据：App.Car_Statis.GetStaYjxx
  //{
  //     "ret": 200,
  //     "data": {
  //         "today": {
  //             "total": 0,
  //             "data": []
  //         },
  //         "all": 40
  //     },
  //     "msg": ""
  // }

  //得到 listAllStatisData[field] 的统计数据，
  //适用的字段：抓拍统计的'today'、all；审核统计的"total"、"sends"；
  List<int> tj_getAllSum(String field) {
    int items = 0;
    int sum = 0;
    for (var item in listAllStatisData) {
      if (item[field] > 0) {
        items++;
        sum += item[field];
      }
    }
    return [items, sum];
  }

  //获取车流量统计数据：App.Car_Statis.GetStaCll
  //{
  //     "ret": 200,
  //     "data": {
  //         "today": 7010,
  //         "all": 1640350
  //     },
  //     "msg": ""
  //}

  //得到 listZptjStatis[field] 的统计数据，
  //适用的字段：车流量统计的'today'、all
  List<int> tj_getAllSumCll(String field) {
    int items = 0;
    int sum = 0;
    for (var item in listZptjStatis) {
      if (item[field] > 0) {
        items++;
        sum += item[field];
      }
    }
    return [items, sum];
  }

  Widget _getStatisText({@required String text, double left = 0, double width = 100}) {
    return Row(
      children: [
        SizedBox(width: ScreenUtil().setWidth(left)),
        Container(
          width: width,
          child:
              Text(text, style: TextStyle(fontSize: 12), maxLines: 2, textAlign: TextAlign.center),
        ),
        //SizedBox(width: ScreenUtil().setWidth(20)),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: PreferredSize(
        preferredSize: Size.fromHeight(ScreenUtil().setHeight(173)), // 设置appBar高度
        // 设置appBar高度
        child: AppBar(
          automaticallyImplyLeading: false,
          centerTitle: true,
          titleSpacing: 0.0,
          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: () {
                    Navigator.pop(context);
                  },
                ),
                Expanded(
                  child: Text(mapStatisType[widget.statisType]['text'],
                      style: TextStyle(color: Colors.white, fontSize: 20),
                      textAlign: TextAlign.center,
                      overflow: TextOverflow.ellipsis),
                ),
                SizedBox(width: 10),
              ],
            ),
          ),
          actions: [
            InkWell(
              child: Image.asset(
                  widget.statisType == 'zptj'
                      ? 'assets/images/statis_blue.png'
                      : widget.statisType == 'sh_hyc_tj'
                          ? 'assets/images/statis_red.png'
                          : 'assets/images/statis_green.png',
                  width: 32,
                  height: 32,
                  color: Colors.white),
              onTap: () {
                Navigator.of(context).push(
                  MaterialPageRoute(builder: (context) {
                    if (widget.statisType == 'clltj') {
                      return ZptjBarChartOne(
                        data_ok: true, //listAllStatisData 中的数据已经准备好
                        statisType: widget.statisType,
                      );
                    } else {
                      return ZptjBarChart(
                        data_ok: true, //listAllStatisData 中的数据已经准备好
                        statisType: widget.statisType,
                      );
                    }
                  }),
                );
              },
            ),
            SizedBox(width: 15),
          ],
        ),
      ),
      body: (listAllStatisData.isEmpty)
          ? getMoreWidget(color: Colors.black38)
          : Column(
              children: [
                SizedBox(height: ScreenUtil().setHeight(20)),
                getHeadRow(), //得到表头行
                SizedBox(height: ScreenUtil().setHeight(20)),
                Divider(height: 1.0, color: Colors.blue),
                SizedBox(height: ScreenUtil().setHeight(10)),
                getStatisRow(), //得到统计行
                SizedBox(height: ScreenUtil().setHeight(10)),
                Divider(height: 1.0, color: Colors.blue),
                Expanded(
                  child: ListView.builder(
                    itemCount: listAllStatisData.length,
                    itemBuilder: (BuildContext context, index) {
                      return Column(
                        children: <Widget>[
                          _getListTile(context, index),
                          Divider(height: 1.0),
                        ],
                      );
                    },
                  ),
                ),
              ],
            ),
    );
  }

  Widget _getImage(String sortField) {
    sortField = (sortField == 'dwmc' ? 'id' : sortField);
    String _image = _sortField != sortField
        ? 'assets/images/sort.png'
        : _descending
            ? 'assets/images/descending.png'
            : 'assets/images/ascending.png';

    return Container(
        margin: EdgeInsets.only(top: 4),
        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
                : (_sortField == sortField ? Colors.blue : null)));
  }

  String _sortField = 'dwmc';
  bool _descending = false; //默认升序排列

  Widget _getSortBtn({@required String sortField, double left = 0}) {
    return InkWell(
      // color: Colors.white,
      // padding: EdgeInsets.all(0),
      //iconSize: this.iconSize,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          SizedBox(width: ScreenUtil().setWidth(left)),
          Text(mapTjDataText[sortField],
              style: TextStyle(
                  fontSize: 18,
                  color: Colors.blue,
                  fontWeight: _sortField == sortField || (_sortField == 'id' && sortField == 'dwmc')
                      ? FontWeight.bold
                      : null)),
          SizedBox(width: ScreenUtil().setWidth(20)),
          _getImage(sortField),
        ],
      ),
      onTap: () {
        if (isLoading) {
          return;
        }
        print('sortField = $sortField，_descending = $_descending');
        //按照用户选择的 sortField、_descending对listSbbjGetList2进行排序，并延时更新
        _listSort(sortField: sortField == 'dwmc' ? 'id' : sortField);
      },
    );
  }

  // Map<String, String> mapTjDataText = {
  //   "dwip": '点位IP',
  //   "today": '今日',
  //   "all": '总共',
  //   "total": '总共2',
  //   "sends": '推送'
  // };

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

      if (_sortField == sortField) {
        _descending = !_descending; //若是与上一次按同一个自动排序，则切换升序降序
      } else {
        _descending = false; //默认升序排列
      }

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

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