import 'package:hyzp_ybqx/components/commonFun.dart';
import 'package:hyzp_ybqx/components/dioFun.dart';
import 'package:hyzp_ybqx/components/hyxx_data_handle.dart';
import 'package:hyzp_ybqx/services/EventBus.dart';

///获取车流量日统计数据
bool cllRStatisDataGeting = false; //正在获取车流量日统计数据，禁止重入
bool cllRStatisDataOk = false; //listCllrtjStatis 中的数据是否准备好
//List listCllrtjStatis = [];
// [
//     {
//         "dwbh": 4,
//         "dwmc": "一曼路",
//         "dwip": "172.16.3.4"
//         "all": "770742",
//         "cllmx": [
//             {
//                 "day": "2021-04-12",
//                 "am_order": "0730:0930",
//                 "pm_order": "1730:1930",
//                 "all": "17760",
//                 "am": "1272",
//                 "pm": "3153"
//             },
//             {
//                 "day": "2021-04-11",
//                 "am_order": "0730:0930",
//                 "pm_order": "1730:1930",
//                 "all": "18005",
//                 "am": "1677",
//                 "pm": "2275"
//             },
//             // ...
//         ]
//     },
//     {
//         "dwbh": 5,
//         "dwmc": "柏溪收费站",
//         "dwip": "172.16.3.5"
//         "all": "770742",
//         "cllmx": [
//             {
//                 "day": "2021-04-12",
//                 "am_order": "0730:0930",
//                 "pm_order": "1730:1930",
//                 "all": "17760",
//                 "am": "1272",
//                 "pm": "3153"
//             },
//             {
//                 "day": "2021-04-11",
//                 "am_order": "0730:0930",
//                 "pm_order": "1730:1930",
//                 "all": "18005",
//                 "am": "1677",
//                 "pm": "2275"
//             },
//             // ...
//         ]
//     },
// ]

///获取抓拍统计数据
List listZptjStatis = [];

///获取审核黑烟车统计数据
List listSh_hyc_tjStatis = [];

///获取审核黑烟车统计数据
List listClltjStatis = [];

///获取车流量日统计数据
List listCllrtjStatis = [];
bool statisDataOk = false; //listCllrtjStatis 中的数据是否准备好
Map mapCllrtjStatis = {};
/*
{
    "total": 6635167,
    "am": 713074,
    "pm": 981656,
    "view": [
        {
            "dwip": "172.16.3.1",
            "dw_all": 701120,
            "dw_am": 76210,
            "dw_pm": 105153,
            "cllmx": [
                {
                    "day": "2021-05-25",
                    "am_order": "0730:0930",
                    "pm_order": "1730:1930",
                    "all": "24190",
                    "am": "2148",
                    "pm": "5173"
                },
                {
                    "day": "2021-05-24",
                    "am_order": "0730:0930",
                    "pm_order": "1730:1930",
                    "all": "20254",
                    "am": "1825",
                    "pm": "3975"
                },
                ...
        },
        {
            "dwip": "172.16.3.2",
            "dw_all": 533990,
            "dw_am": 65276,
            "dw_pm": 78055,
            "cllmx": [
                {
                    "day": "2021-05-25",
                    "am_order": "0730:0930",
                    "pm_order": "1730:1930",
                    "all": "16355",
                    "am": "1375",
                    "pm": "3029"
                },
                {
                    "day": "2021-05-24",
                    "am_order": "0730:0930",
                    "pm_order": "1730:1930",
                    "all": "15997",
                    "am": "1797",
                    "pm": "2216"
                },
                ...
*/

// [
//     {
//         "dwbh": 4,
//         "dwmc": "一曼路",
//         "dwip": "172.16.3.4"
//         "all": "770742",
//         "cllmx": [
//             {
//                 "day": "2021-04-12",
//                 "am_order": "0730:0930",
//                 "pm_order": "1730:1930",
//                 "all": "17760",
//                 "am": "1272",
//                 "pm": "3153"
//             },
//             {
//                 "day": "2021-04-11",
//                 "am_order": "0730:0930",
//                 "pm_order": "1730:1930",
//                 "all": "18005",
//                 "am": "1677",
//                 "pm": "2275"
//             },
//             // ...
//         ]
//     },
//     {
//         "dwbh": 5,
//         "dwmc": "柏溪收费站",
//         "dwip": "172.16.3.5"
//         "all": "770742",
//         "cllmx": [
//             {
//                 "day": "2021-04-12",
//                 "am_order": "0730:0930",
//                 "pm_order": "1730:1930",
//                 "all": "17760",
//                 "am": "1272",
//                 "pm": "3153"
//             },
//             {
//                 "day": "2021-04-11",
//                 "am_order": "0730:0930",
//                 "pm_order": "1730:1930",
//                 "all": "18005",
//                 "am": "1677",
//                 "pm": "2275"
//             },
//             // ...
//         ]
//     },
// ]

// 一次性获取所有点位的统计数据存入 listCllrtjStatis
Future getCllrtjStatisNew(String statisType) async {
  //抓拍统计数据
  //{
  //  "today": 0,
  //  "all": 72
  //  "dwbh": 1,
  //  "dwmc": "江北振兴大道",
  //  "dwip": "172.16.3.1"
  //}

  ///从接口 mapStatisType[statisType]['api'] 获取指定 ip 的 statisType 类型的统计数据，返回 Map
  //Future getStatisData({@required String statisType, @required String ip}) async {
  listCllrtjStatis.clear();
  mapCllrtjStatis = await getStatisData(statisType: statisType);
  listCllrtjStatis = mapCllrtjStatis["view"];

  // int len = listDwinfoGetList2.length;
  // for (int i = 0; i < len; i++) {
  //   Map map = await getStatisData(statisType: statisType, ip: listDwinfoGetList2[i]['dwip']);
  //   map['dwbh'] = listDwinfoGetList2[i]['dwbh'];
  //   map['dwmc'] = listDwinfoGetList2[i]['dwmc'];
  //   map['dwip'] = listDwinfoGetList2[i]['dwip'];
  //   listCllrtjStatis.add(map);
  // }
  //print('listZptjStatis = ${listZptjStatis}');
  //StorageDataToFile.writeCounter(json_print(listZptjStatis, 1));
}

//遍历 listDwinfoGetList2 中所有点位，得到对应点位 ip 的统计数据存入 listCllrtjStatis
Future getCllrtjStatis(String statisType) async {
  //抓拍统计数据
  //{
  //  "today": 0,
  //  "all": 72
  //  "dwbh": 1,
  //  "dwmc": "江北振兴大道",
  //  "dwip": "172.16.3.1"
  //}

  ///从接口 mapStatisType[statisType]['api'] 获取指定 ip 的 statisType 类型的统计数据，返回 Map
  //Future getStatisData({@required String statisType, @required String ip}) async {
  listCllrtjStatis.clear();
  int len = listDwinfoGetList2.length;
  for (int i = 0; i < len; i++) {
    Map map = await getStatisData(statisType: statisType, ip: listDwinfoGetList2[i]['dwip']);
    map['dwbh'] = listDwinfoGetList2[i]['dwbh'];
    map['dwmc'] = listDwinfoGetList2[i]['dwmc'];
    map['dwip'] = listDwinfoGetList2[i]['dwip'];
    listCllrtjStatis.add(map);
  }
  //print('listZptjStatis = ${listZptjStatis}');
  //StorageDataToFile.writeCounter(json_print(listZptjStatis, 1));
}

//遍历 listDwinfoGetList2 中所有点位，得到对应点位 ip 的统计数据存入 listZptjStatis
Future getZptjStatis(String statisType) async {
  //抓拍统计数据
  //{
  //  "today": 0,
  //  "all": 72
  //  "dwbh": 1,
  //  "dwmc": "江北振兴大道",
  //  "dwip": "172.16.3.1"
  //}

  ///从接口 mapStatisType[statisType]['api'] 获取指定 ip 的 statisType 类型的统计数据，返回 Map
  //Future getStatisData({@required String statisType, @required String ip}) async {
  listZptjStatis.clear();
  int len = listDwinfoGetList2.length;
  for (int i = 0; i < len; i++) {
    Map map = await getStatisData(statisType: statisType, ip: listDwinfoGetList2[i]['dwip']);
    map['dwbh'] = listDwinfoGetList2[i]['dwbh'];
    map['dwmc'] = listDwinfoGetList2[i]['dwmc'];
    map['dwip'] = listDwinfoGetList2[i]['dwip'];
    listZptjStatis.add(map);
  }
  //print('listZptjStatis = ${listZptjStatis}');
  //StorageDataToFile.writeCounter(json_print(listZptjStatis, 1));
}

//在Dart语言中，如何通过值获取MAP键？mapTjDataText
String getKey(String value) {
  String key = mapTjDataText.keys.firstWhere((k) => mapTjDataText[k] == value, orElse: () => null);
}

Map<String, String> mapTjDataText = {
  "dwmc": '点位名称',
  "dwbh": '点位编号',
  "dwip": '点位IP',
  "today": '今日',
  "all": '总共',
  "total": '已审核',
  "sends": '已推送'
};

//////////////////////////////////////////////////////////////////
///独立获取抓拍统计数据
List listZptjStatisAlone = [];
List listTodayZpjl = []; //今日抓拍记录列表

//遍历 listDwinfoGetList2 中所有点位，独立得到对应点位 ip 的统计数据存入 listZptjStatisNew
Future getZptjStatisAlone() async {
  //抓拍统计数据
  //{
  //  "today": 0,
  //  "all": 72
  //  "dwbh": 1,
  //  "dwmc": "江北振兴大道",
  //  "dwip": "172.16.3.1"
  //}

  ///从接口 mapStatisType[statisType]['api'] 获取指定 ip 的 statisType 类型的统计数据，返回 Map
  //Future getStatisData({@required String statisType, @required String ip}) async {
  listZptjStatisAlone.clear();
  int len = listDwinfoGetList2.length;
  for (int i = 0; i < len; i++) {
    getStatisData(statisType: 'zptj', ip: listDwinfoGetList2[i]['dwip']).then((map) {
      map['dwbh'] = listDwinfoGetList2[i]['dwbh'];
      map['dwmc'] = listDwinfoGetList2[i]['dwmc'];
      map['dwip'] = listDwinfoGetList2[i]['dwip'];
      listZptjStatisAlone.add(map);
      // if (listZptjStatisAlone.length >= dwSum) {
      //   //发送统计数据已更新广播
      //   eventBus.fire(StatisDataUpdate('统计数据已更新'));
      // }
      getAllSum('today', listZptjStatisAlone).then((value) {
        //mapStatisInfo['今日抓拍'] = value[1];
        listTodayZpjl = value[2];
        //try_setState();
      });
    });

    // Map map = await getStatisData(statisType: 'zptj', ip: listDwinfoGetList2[i]['dwip']);
    // map['dwbh'] = listDwinfoGetList2[i]['dwbh'];
    // map['dwmc'] = listDwinfoGetList2[i]['dwmc'];
    // map['dwip'] = listDwinfoGetList2[i]['dwip'];
    // listZptjStatisAlone.add(map);
    // // if (listZptjStatisAlone.length >= dwSum) {
    // //   //发送统计数据已更新广播
    // //   eventBus.fire(StatisDataUpdate('统计数据已更新'));
    // // }
    // getAllSum('today', listZptjStatisAlone).then((value) {
    //   //mapStatisInfo['今日抓拍'] = value[1];
    //   listTodayZpjl = value[2];
    //   //try_setState();
    // });
  }
  //print('listZptjStatis = ${listZptjStatis}');
  //StorageDataToFile.writeCounter(json_print(listZptjStatis, 1));
}

///独立获取今日审核统计数据
List listTodayShtj = [];
List listTodayChjl = []; //今日初审记录列表
List listTodayFhjl = []; //今日复审记录列表
List listTodayTsjl = []; //今日推送记录列表

//遍历 listDwinfoGetList2 中所有点位，独立得到对应点位 ip 的统计数据存入 listShtjStatisNew
Future getTodayShtj() async {
  //今日审核统计数据
  //{
  //    "total": 0,"today": 0,
  //    "sends": 0,"all": 72
  //    "csnum": 0,"dwbh": 1,
  //    "fsnum": 0"dwmc": "江北振兴大道",
  //}

  ///从接口 mapStatisType[statisType]['api'] 获取指定 ip 的 statisType 类型的统计数据，返回 Map
  //Future getStatisData({@required String statisType, @required String ip}) async {
  listTodayShtj.clear();
  DateTime dateTime = DateTime.now();
  String _mouth = dateTime.month.toString().trim();
  if (_mouth.length == 1) {
    _mouth = '0' + _mouth;
  }

  String _day = dateTime.day.toString().trim();
  if (_day.length == 1) {
    _day = '0' + _day;
  }

  String date = '${dateTime.year}-${_mouth}-${_day}';
  print('date = $date');
  int len = listDwinfoGetList2.length;
  for (int i = 0; i < len; i++) {
    getStatisData(statisType: 'sh_hyc_tj', ip: listDwinfoGetList2[i]['dwip'], date: date)
        .then((map) {
      map['dwbh'] = listDwinfoGetList2[i]['dwbh'];
      map['dwmc'] = listDwinfoGetList2[i]['dwmc'];
      map['dwip'] = listDwinfoGetList2[i]['dwip'];
      listTodayShtj.add(map);
      // if (listTodayShtj.length >= dwSum) {
      //   print('listTodayShtj = $listTodayShtj');
      //   //发送统计数据已更新广播
      //   eventBus.fire(StatisDataUpdate('统计数据已更新'));
      // }
      getAllSum('csnum', listTodayShtj).then((value) {
        //mapStatisInfo['今日初审'] = value[1];
        listTodayChjl = value[2];
        //try_setState();
      });
      getAllSum('fsnum', listTodayShtj).then((value) {
        //mapStatisInfo['今日复审'] = value[1];
        listTodayFhjl = value[2];
        //try_setState();
      });
      getAllSum('sends', listTodayShtj).then((value) {
        //mapStatisInfo['今日推送'] = value[1];
        listTodayTsjl = value[2];
        //try_setState();
      });
    });
  }
  //print('listZptjStatis = ${listZptjStatis}');
  //StorageDataToFile.writeCounter(json_print(listZptjStatis, 1));
}

///独立获取审核统计数据
List listShtjStatisAlone = [];

//遍历 listDwinfoGetList2 中所有点位，独立得到对应点位 ip 的统计数据存入 listShtjStatisNew
Future getShtjStatisAlone() async {
  //抓拍统计数据
  //{
  //  "today": 0,
  //  "all": 72
  //  "dwbh": 1,
  //  "dwmc": "江北振兴大道",
  //  "dwip": "172.16.3.1"
  //}

  ///从接口 mapStatisType[statisType]['api'] 获取指定 ip 的 statisType 类型的统计数据，返回 Map
  //Future getStatisData({@required String statisType, @required String ip}) async {
  listShtjStatisAlone.clear();
  int len = listDwinfoGetList2.length;
  for (int i = 0; i < len; i++) {
    getStatisData(statisType: 'sh_hyc_tj', ip: listDwinfoGetList2[i]['dwip']).then((map) {
      map['dwbh'] = listDwinfoGetList2[i]['dwbh'];
      map['dwmc'] = listDwinfoGetList2[i]['dwmc'];
      map['dwip'] = listDwinfoGetList2[i]['dwip'];
      listShtjStatisAlone.add(map);
      // if (listShtjStatisAlone.length >= dwSum) {
      //   //发送统计数据已更新广播
      //   eventBus.fire(StatisDataUpdate('统计数据已更新'));
      // }
    });
    //print('listZptjStatis = ${listZptjStatis}');
    //StorageDataToFile.writeCounter(json_print(listZptjStatis, 1));
  }
}

///独立获取车流量统计数据
List listClltjStatisAlone = [];

//遍历 listDwinfoGetList2 中所有点位，独立得到对应点位 ip 的统计数据存入 listShtjStatisNew
Future getClltjStatisAlone() async {
  //抓拍统计数据
  //{
  //  "today": 0,
  //  "all": 72
  //  "dwbh": 1,
  //  "dwmc": "江北振兴大道",
  //  "dwip": "172.16.3.1"
  //}

  ///从接口 mapStatisType[statisType]['api'] 获取指定 ip 的 statisType 类型的统计数据，返回 Map
  //Future getStatisData({@required String statisType, @required String ip}) async {
  listClltjStatisAlone.clear();
  int len = listDwinfoGetList2.length;
  for (int i = 0; i < len; i++) {
    getStatisData(statisType: 'clltj', ip: listDwinfoGetList2[i]['dwip']).then((map) {
      map['dwbh'] = listDwinfoGetList2[i]['dwbh'];
      map['dwmc'] = listDwinfoGetList2[i]['dwmc'];
      map['dwip'] = listDwinfoGetList2[i]['dwip'];
      listClltjStatisAlone.add(map);
      // if (listClltjStatisAlone.length >= dwSum) {
      //   //发送统计数据已更新广播
      //   eventBus.fire(StatisDataUpdate('统计数据已更新'));
      // }
    });
  }
  //print('listZptjStatis = ${listZptjStatis}');
  //StorageDataToFile.writeCounter(json_print(listZptjStatis, 1));
}

//////////////////////////////////////////////////////////////////
///获取所有统计数据
List listAllStatisData = [];

///车流量日统计数据类
var trinityData;

// 实现多个基于 Page1_Works 构建的页面共享统计数据
Future startGetStatisDataNew() async {
  ///获取点位信息数据
  //listDwinfoGetList2.clear();

  if (listDwinfoGetList2.isEmpty) {
    //若没有读取点位数据，便需要先读取
    getThePageList(theHyshlx: 'dwxx').then((value) {
      listDwinfoGetList2 = value;
      print('listDwinfoGetList2 = \n$listDwinfoGetList2');
      dwSum = listDwinfoGetList2.length;
      //获取记录数据
      getZptjStatisAlone();
      getTodayShtj();
      getClltjStatisAlone();

      //获取统计数据
      getAllStatisData().then((value) {
        listAllStatisData = value;
        eventBus.fire(StatisDataUpdate('统计数据已更新'));
      });

      //// 仅宜宾市提供
      // if (!cllRStatisDataOk) {
      //   ///车流量日统计数据类
      //   cllRStatisDataGeting = true; //正在获取车流量日统计数据，禁止重入
      //   trinityData = ZptjBarEchartsTrinityNewGetData(); //提取获取车流量日统计数据
      // }
    });
  } else {
    if (mapStatisInfo['今日抓拍'] < 0) {
      //获取记录数据
      getZptjStatisAlone();
      getTodayShtj();
      getClltjStatisAlone();

      //获取统计数据
      getAllStatisData().then((value) {
        listAllStatisData = value;
        eventBus.fire(StatisDataUpdate('统计数据已更新'));
      });
    } else {
      //发送统计数据已更新广播
      eventBus.fire(StatisDataUpdate('统计数据已更新'));
    }

    //// 仅宜宾市提供
    // if (!cllRStatisDataOk) {
    //   ///车流量日统计数据类
    //   cllRStatisDataGeting = true; //正在获取车流量日统计数据，禁止重入
    //   trinityData = ZptjBarEchartsTrinityNewGetData(); //提取获取车流量日统计数据
    // }
  }
}

Map<String, double> mapStatisInfo = {
  '今日抓拍': -1,
  '今日初审': -1,
  '今日复审': -1,
  '今日推送': -1,
  '今日车流': -1,
};

//得到所有5项统计数据
//适用的字段：抓拍统计的'today'、all；审核统计的"total"、"sends"；
Future getAllSumNew() async {
  int items = 0;
  mapStatisInfo['今日抓拍'] = 0;
  mapStatisInfo['今日初审'] = 0;
  mapStatisInfo['今日复审'] = 0;
  mapStatisInfo['今日推送'] = 0;
  mapStatisInfo['今日车流'] = 0;

  for (var item in listAllStatisData) {
    items++;
    if (item["zp_today"] > 0) {
      //listRecords.addAll(item[field]["data"]); //将记录详情存入listRecords
      mapStatisInfo['今日抓拍'] += item["zp_today"];
    }
    if (item["csnum"] > 0) {
      mapStatisInfo['今日初审'] += item["csnum"];
    }
    if (item["fsnum"] > 0) {
      mapStatisInfo['今日复审'] += item["fsnum"];
    }
    if (item["sends"] > 0) {
      mapStatisInfo['今日推送'] += item["sends"];
    }
    if (item["cll_today"] > 0) {
      mapStatisInfo['今日车流'] += item["cll_today"];
    }
  }
  mapStatisInfo['今日车流'] = mapStatisInfo['今日车流'] / 10000;

  // 统计点位数（未用），总计，记录列表
  //return [items, sum, listRecords];
}

/*
[
        {
            "id": 1,
            "dwip": "172.16.3.1",
            "dwmc": "锦绣花园",
            "zp_all": 54,
            "hyc_all": 52,
            "zp_today": 1,
            "sends": 0,
            "send_all": 33,
            "csnum": 1,
            "fsnum": 0,
            "cll_today": 6420,
            "cll_all": 3225733
        },
        {
            "id": 2,
            "dwip": "172.16.3.2",
            "dwmc": "石马溪桥",
            "zp_all": 377,
            "hyc_all": 370,
            "zp_today": 1,
            "sends": 0,
            "send_all": 204,
            "csnum": 1,
            "fsnum": 0,
            "cll_today": 3430,
            "cll_all": 2127839
        },
        ...
]
*/

//获取已审核黑烟车统计数据：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": ""
// }
//得到 listStatis[field] 的统计数据，
//适用的字段：抓拍统计的'today'、all；审核统计的"total"、"sends"；
Future getAllSum(String field, List listStatis) async {
  int items = 0;
  int sum = 0;
  List listRecords = []; //记录详情存入
  for (var item in listStatis) {
    if (item[field]["total"] > 0) {
      items++;
      listRecords.addAll(item[field]["data"]); //将记录详情存入listRecords
      sum += item[field]["total"];
    }
  }
  return [items, sum, listRecords];
}

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

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

//////////////////////////////////////////////////////////////////
