import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:hyzp_ybqx/config/service_url.dart';
import 'package:hyzp_ybqx/services/EventBus.dart';

import 'commonFun.dart';

///用户权限管理
//   static const String getUserAccessUrl = ServiceUrl + '?s=App.User_User.GetAccess'; //1、根据用户ID获取用户所属角色
//   static const String getUserGroupUrl = ServiceUrl + '?s=App.User_User.GetGroup'; //2、获取后台用户角色分组数据
//   static const String getUserGroupListUrl = ServiceUrl + '?s=App.User_User.GetGroupList'; //3、获取后台用户角色分组分页列表数据
//   static const String getUserAuthUrl = ServiceUrl + '?s=App.User_User.GetAuth'; //4、获取后台功能分类数据
//   static const String getUserAuthListUrl = ServiceUrl + '?s=App.User_User.GetAuthList'; //5、获取后台功能分类分页列表数据

//2.2、获取后台用户全部角色分组数据
Future getUserGroupAll({int user_id = -1}) async {
  if (user_id < 0) {
    user_id = g_userInfo.mapUserInfo['user_id'];
  }
  //1、根据用户ID获取用户所属角色（用户组）
  getUserAccess(user_id: user_id).then((value) {
    // I/flutter (15540): g_userInfo.userGroupIDlist = [31, 27]
    int len = g_userInfo.userGroupIDlist.length;
    for (int i = 0; i < len; i++) {
      getUserGroup(group_id: g_userInfo.userGroupIDlist[i]);
    }
    print('g_userInfo.userRulesMap = ${g_userInfo.userRulesMap}');
  });
}

//2.1、获取后台用户指定 group_id 角色分组数据
Future getUserGroup({@required int group_id}) async {
  var api = ServicePath.getUserGroupUrl;
  print(api);
  //I/flutter (15540): http://125.64.218.67:9904/?s=App.User_User.GetGroup

  String random = RandomBit(6);
  Map map = {
    'random': random,
    'sign': GenerateMd5(APPkey + random),
    'id': group_id,
  };

  print('开始处理登录请求...');
  Response response;
  Dio dio = Dio();

  //返回结果
  // 返回字段	类型	说明
  // id	整型	角色分组ID
  // type	整型	角色分组类型：1普通角色
  // level	整型	角色分组级次(1-顶级,2-次级)
  // pid	整型	上级角色分组ID(为0则表示为顶级)
  // rules	字符串	授权功能ID（如:5,7,112,331），表示此角色拥有相应ID的功能权限
  //{
  //     "ret": 200,
  //     "data": {
  //         "id": 31,
  //         "jgid": 2,
  //         "type": 0,
  //         "title": "监控室",
  //         "level": 0,
  //         "pid": 0,
  //         "sort": 2,
  //         "status": 1,
  //         "rules": ""
  //     },
  //     "msg": ""
  // }

  try {
    print('response = ${response}');
    // I/flutter (15540): response = null
    response = await dio.post(api, data: map);
    print('response = ${response}');
    //I/flutter (15540): response = {"ret":200,"data":{"id":31,"jgid":2,"type":0,"title":"监控室","level":0,"pid":0,"sort":2,"status":1,"rules":""},"msg":""}
    if (response.statusCode == 200) {
      Map _mapRet = await getMapFromJson(response.data);
      print('_mapRet = ${_mapRet}');
      // I/flutter (15540): _mapRet = {ret: 200, data: {id: 31, jgid: 2, type: 0, title: 监控室, level: 0, pid: 0, sort: 2, status: 1, rules: }, msg: }
      //print('_mapRet[\'data\']["rules"] is a = ${_mapRet['data']["rules"] is String}');
      //_mapRet['data']["rules"] is a = true

      //I/flutter (15540): _mapRet = {ret: 200, data: false, msg: }
      //I/flutter (15540): 网络请求过程异常e = NoSuchMethodError: Class 'bool' has no instance method '[]'.
      if (_mapRet['data'] is Map) {
        String _rules = _mapRet['data']["rules"].trim();
        //print('_rules = ${_rules}');
        print('_rules.length = ${_rules.length}');
        //_rules.length = 0
        List<int> _list = [];
        if (_rules.isNotEmpty) {
          List _list2 = _rules.split(',');
          print('_list2 = $_list2');
          //I/flutter (15540): _list2 = [1968, 1972, 1973, 1969, 1976, 1977, 2008, 2009, 2011, 2014,
          // 2015, 2018, 2029, 2030, 2031, 2054, 2055, 2035, 2036, 2037, 2041, 2042, 2043, 2047, 2048,
          // 2049, 2053, 1970, 1980, 1981, 1971, 1984, 1985, 1992, 1993, 2000, 2001, 2020, 2022]
          int len = _list2.length;
          List<int> _list3 = [];
          for (int i = 0; i < len; i++) {
            _list3.add(int.parse(_list2[i].trim()));
          }
          _list = _list3;
        }
        print('_list = $_list');
        //I/flutter (15540): _list = [{uid: 135, group_id: 31}, {uid: 135, group_id: 27}]
        g_userInfo.userRulesMap[_mapRet['data']['id']] = _list;
        print('g_userInfo.userRulesMap = ${g_userInfo.userRulesMap}');
        // I/flutter (15540): g_userInfo.userGroupIDlist = [31, 27]
      } else {
        print('获取数据失败！');
      }
      print('网络请求过程正常完成');
    } else {
      throw Exception('后端接口出现异常，请检测代码和服务器情况.........');
    }
  } catch (e) {
    print('网络请求过程异常e = ${e}');
    Fluttertoast.showToast(
      msg: 'ERROR:======>${e}',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
    );
  }
}

//1、根据用户ID获取用户所属角色（用户组）
Future getUserAccess({int user_id = -1}) async {
  if (user_id < 0) {
    user_id = g_userInfo.mapUserInfo['user_id'];
  }

  var api = ServicePath.getUserAccessUrl;
  print(api);
  //I/flutter (15540): http://125.64.218.67:9904/?s=App.User_User.GetAccess

  String random = RandomBit(6);
  Map map = {
    'random': random,
    'sign': GenerateMd5(APPkey + random),
    'uid': user_id,
  };

  print('开始处理登录请求...');
  Response response;
  Dio dio = Dio();

  //{
  //     "ret": 200,
  //     "data": [
  //         {
  //             "uid": 136,
  //             "group_id": 32
  //         },
  //         {
  //             "uid": 136,
  //             "group_id": 33
  //         }
  //     ],
  //     "msg": ""
  // }

  try {
    print('response = ${response}');
    // I/flutter (15540): response = null
    response = await dio.post(api, data: map);
    print('response = ${response}');
    // I/flutter (15540): response = {"ret":200,"data":[{"uid":135,"group_id":31},{"uid":135,"group_id":27}],"msg":""}
    if (response.statusCode == 200) {
      Map _mapRet = await getMapFromJson(response.data);
      print('_mapRet = ${_mapRet}');
      // I/flutter (15540): _mapRet = {ret: 200, data: [{uid: 135, group_id: 31}, {uid: 135, group_id: 27}], msg: }
      List _list = _mapRet['data'];
      print('_list = $_list');
      //I/flutter (15540): _list = []

      if (_list.isNotEmpty) {
        g_userInfo.userGroupIDlist.clear();
        int len = _list.length;
        for (int i = 0; i < len; i++) {
          g_userInfo.userGroupIDlist.add(_list[i]["group_id"]);
          eventBus.fire(GroupIdUpdateEvent('g_userInfo.userGroupIDlist 数据已更新')); //这样刷新有效
        }
      }
      print('g_userInfo.userGroupIDlist = ${g_userInfo.userGroupIDlist}');
      //I/flutter (15540): g_userInfo.userRulesMap = {31: []}

      print('网络请求过程正常完成');
    } else {
      throw Exception('后端接口出现异常，请检测代码和服务器情况.........');
    }
  } catch (e) {
    print('网络请求过程异常e = ${e}');
    Fluttertoast.showToast(
      msg: 'ERROR:======>${e}',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
    );
  }
}

//3、获取后台用户角色分组分页列表数据    ServicePath.getUserGroupListUrl
//5、获取后台功能分类分页列表数据        ServicePath.getUserAuthListUrl
//x、获取后台 x 分类分页列表数据
// int pages 为获取的页数， -1 为 All；int perpage 为每页记录数
// 返回：
//  mapRecordList = {
//     'mapRecordListRet': {},
//     'listRecordList': [],
//   };
Future getRecordList({@required String api, int pages = 3, int perpage = 20}) async {
  print(api);
  int _total = 0; //第一页时保存数据库中记录总数
  int _counter = 0; //已读取的记录数计数器

  int _page = 0;
  String random = RandomBit(6);
  Map map = {
    'random': random,
    'sign': GenerateMd5(APPkey + random),
    'page': _page,
    'perpage': perpage,
  };

  print('开始处理登录请求...');
  Response response;
  Dio dio = Dio();

  Map mapRecordList = {
    'mapRecordListRet': {},
    'listRecordList': [],
  };
  try {
    while (pages < 0 ? true : _page < pages) {
      map['page']++;

      response = await dio.post(api, data: map);
      print('response = ${response.toString()}');
      if (response.statusCode == 200) {
        mapRecordList['mapRecordListRet'] = await getMapFromJson(response.data);
        print('mapRecordList[\'mapRecordListRet\'] = ${mapRecordList['mapRecordListRet']}');
        //第一页时保存数据库中记录总数
        if (1 == map['page']) {
          _total = mapRecordList['mapRecordListRet']['data']['total'];
        }
        mapRecordList['listRecordList'].addAll(mapRecordList['mapRecordListRet']['data']['items']);
        //print('mapRecordList[\'listRecordList\'] = ${mapRecordList['listRecordList']}');

        print('map[\'page\'] = ${map['page']}');
        _counter = mapRecordList['listRecordList'].length; //已读取的记录数计数器
        print('_counter = $_counter');
        //I/flutter (23648): _counter = 8
        print('_total = $_total');
        // I/flutter (23648): _total = 8
        //已读取的记录数计数器，超过或等于数据库中记录总数时，则终止循环
        if (_counter >= _total) {
          return mapRecordList;
        }

        print('第 ${map['page']} 次网络请求过程正常完成');
      } else {
        throw Exception('后端接口出现异常，请检测代码和服务器情况.........');
      }
    }
  } catch (e) {
    print('网络请求过程异常e = ${e}');
    Fluttertoast.showToast(
      msg: 'ERROR:======>${e}',
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
    );
  }
  return mapRecordList;
}

Map mapUserGroupList = {
  'mapRecordListRet': {
    "ret": 200,
    "data": {
      "items": [
        {
          "id": 35,
          "jgid": 2,
          "type": 0,
          "title": "局领导",
          "level": 0,
          "pid": 0,
          "sort": 1,
          "status": 1,
          "rules": ""
        },
        {
          "id": 34,
          "jgid": 2,
          "type": 0,
          "title": "系统管理",
          "level": 0,
          "pid": 0,
          "sort": 1,
          "status": 1,
          "rules": ""
        },
        {
          "id": 33,
          "jgid": 2,
          "type": 1,
          "title": "参观者",
          "level": 0,
          "pid": 0,
          "sort": 4,
          "status": 1,
          "rules":
              "1968,1972,1973,1969,1976,1977,2008,2009,2011,2014,2015,2018,2029,2030,2031,2054,2055,2035,2036,2037,2041,2042,2043,2047,2048,2049,2053,1970,1980,1981,1971,1984,1985,1992,1993,2000,2001,2019,2020,2022"
        },
        {
          "id": 32,
          "jgid": 2,
          "type": 0,
          "title": "演示账户",
          "level": 0,
          "pid": 0,
          "sort": 3,
          "status": 1,
          "rules":
              "1968,1972,1973,1969,1976,1977,2008,2009,2011,2014,2015,2018,2029,2030,2031,2054,2055,2035,2036,2037,2041,2042,2043,2047,2048,2049,2053,1970,1980,1981,1971,1984,1985,1992,1993,2000,2001,2020,2022"
        },
        {
          "id": 31,
          "jgid": 2,
          "type": 0,
          "title": "监控室",
          "level": 0,
          "pid": 0,
          "sort": 2,
          "status": 1,
          "rules": ""
        },
        {
          "id": 30,
          "jgid": 2,
          "type": 0,
          "title": "中心领导",
          "level": 0,
          "pid": 0,
          "sort": 1,
          "status": 1,
          "rules":
              "1968,1972,1973,1974,1975,1969,1976,1977,1978,1979,1970,1980,1981,1982,1983,1971,1984,1985,1986,1987,1988,1989,1990,1991,1992,1993,1994,1995,1996,1997,1998,1999,2000,2001,2002,2003,2004,2005,2006,2007"
        },
        {
          "id": 28,
          "jgid": 2,
          "type": 1,
          "title": "审核操作员",
          "level": 0,
          "pid": 0,
          "sort": 3,
          "status": 1,
          "rules":
              "1968,1972,1973,1974,1975,1969,1976,1977,1978,1979,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2029,2030,2031,2054,2055,2032,2033,2034,2035,2036,2037,2038,2039,2040,2041,2042,2043,2044,2045,2046,2047,2048,2049,2050,2051,2052,2053,1970,1980,1981,1982,1983"
        },
        {
          "id": 26,
          "jgid": 2,
          "type": 1,
          "title": "管理员",
          "level": 0,
          "pid": 0,
          "sort": 2,
          "status": 1,
          "rules":
              "1968,1972,1973,1974,1975,1969,1976,1977,1978,1979,2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2029,2030,2031,2054,2055,2032,2033,2034,2035,2036,2037,2038,2039,2040,2041,2042,2043,2044,2045,2046,2047,2048,2049,2050,2051,2052,2053,1970,1980,1981,1982,1983,1971,1984,1985,1986,1987,1988,1989,1990,1991,2019,2020,2021,2022,2023,2024,2025,2026,2027,2028"
        }
      ],
      "total": 8,
      "page": 1,
      "perpage": 20
    },
    "msg": ""
  },
  'listRecordList': [],
};

Map mapUserAuthList = {
  'mapRecordListRet': {},
  'listRecordList': [],
};

Map mapRecordList = {
  'mapRecordListRet': {},
  'listRecordList': [],
};

//用户功能权限索引map，便于直观理解和处理。map_UserAuth.length = 78；1968 - 2069，中间有许多ID没有
Map map_UserAuth = {
  1968: '黑烟车初审',
  1969: '黑烟车复审',
  1970: '推送交警',
  1971: '设备管理',
  1972: '信息审核',
  1973: '查看',
  1975: '审核',
  1976: '信息审核',
  1977: '查看',
  1979: '审核',
  1980: '推送交警',
  1981: '查看',
  1983: '审核',
  1984: 'LED显示设置',
  1985: '查看',
  1986: '新增',
  1987: '编辑',
  1988: '锁定',
  1989: '删除',
  1990: '导出',
  1991: '导入',
  1992: '设备管理',
  1993: '查看',
  1994: '新增',
  1995: '编辑',
  1996: '锁定',
  1997: '删除',
  1998: '导出',
  1999: '导入',
  2000: '点位管理',
  2001: '查看',
  2002: '新增',
  2003: '编辑',
  2004: '锁定',
  2005: '删除',
  2006: '导出',
  2007: '导入',
  2008: '历史数据',
  2009: '查看',
  2010: '新增',
  2014: '审核',
  2015: '打印',
  2016: '导出',
  2019: '报警信息管理',
  2020: '查看',
  2023: '锁定',
  2025: '审核',
  2027: '导出',
  2028: '分析',
  2029: '查询与统计',
  2030: '历史数据查询',
  2031: '查看',
  2034: '导出',
  2035: '分析',
  2036: '车辆点位频率分析',
  2037: '查看',
  2041: '分析',
  2042: '车辆轨迹查询',
  2043: '查看',
  2047: '分析',
  2048: '年度数据统计',
  2049: '查看',
  2053: '分析',
  2054: '实时统计',
  2055: '实时统计今日抓拍数量',
  2056: '历史数据',
  2057: '查看',
  2059: '审核',
  2060: '导出',
  2061: '监测点位状态',
  2062: '查看',
  2063: '分析',
  2064: '监测点位状态详情',
  2065: '查看',
  2066: '分析',
  2067: '车流量统计',
  2068: '查看',
  2069: '分析',
};

Future getUserAuthMap({@required String value, String key = 'id'}) {
  int len = mapUserAuthList['listRecordList'].length;
  map_UserAuth.clear();
  for (int i = 0; i < len; i++) {
    map_UserAuth[mapUserAuthList['listRecordList'][i][key]] =
        mapUserAuthList['listRecordList'][i][value];
  }

  map_UserAuth = mapSort(map_UserAuth);
  print('map_UserAuth.length = ${map_UserAuth.length}');
  //print('map_UserAuth = $map_UserAuth');  //输出不全
  my_segmentPrint(json_print(map_UserAuth, 1));
}

Future getUserAuth() {
  int len = mapUserAuthList['listRecordList'].length;
  map_UserAuth.clear();
  for (int i = 0; i < len; i++) {
    map_UserAuth[mapUserAuthList['listRecordList'][i]["id"]] =
        mapUserAuthList['listRecordList'][i]["title"];
  }

  //按抓拍次数排序，升序
  // listHycsGetList2.sort((a, b) =>
  //     (a[mapWzxxDataText[_selectedValue]].split(',').length.toString())
  //         .compareTo(b[mapWzxxDataText[_selectedValue]].split(',').length.toString()));

  //print('map_UserAuth = $map_UserAuth');  //输出不全
  print('map_UserAuth.length = ${map_UserAuth.length}');
  my_segmentPrint('map_UserAuth = ${map_UserAuth}');

  map_UserAuth = mapSort(map_UserAuth);
  my_segmentPrint('map_UserAuth = ${map_UserAuth}');
  //I/flutter ( 5140): map_UserAuth = {1968: 黑烟车初审, 1969: 黑烟车复审, 1970: 推送交警, 1971: 设备管理, 1972: 信息审核, 1973: 查看, 1975: 审核, 1976: 信息审核, 1977: 查看, 197
  // 9: 审核, 1980: 推送交警, 1981: 查看, 1983: 审核, 1984: LED显示设置, 1985: 查看, 1986: 新增, 1987: 编辑, 1988: 锁定, 1989: 删除, 1990: 导出, 1991: 导入, 1992: 设备管理, 1993:
  // 查看, 1994: 新增, 1995: 编辑, 1996: 锁定, 1997: 删除, 1998: 导出, 1999: 导入, 2000: 点位管理, 2001: 查看, 2002: 新增, 2003: 编辑, 2004: 锁定, 2005: 删除, 2006: 导出, 2007: 导
  // 入, 2008: 历史数据, 2009: 查看, 2010: 新增, 2014: 审核, 2015: 打印, 2016: 导出, 2019: 报警信息管理, 2020: 查看, 2023: 锁定, 2025: 审核, 2027: 导出, 2028: 分析, 2029: 查询与统
  // 计, 2030: 历史数据查询, 2031: 查看, 2034: 导出, 2035: 分析, 2036: 车
  // I/flutter ( 5140): 辆点位频率分析, 2037: 查看, 2041: 分析, 2042: 车辆轨迹查询, 2043: 查看, 2047: 分析, 2048: 年度数据统计, 2049: 查看, 2053: 分析, 2054: 实时统计, 2055: 实时
  // 统计今日抓拍数量, 2056: 历史数据, 2057: 查看, 2059: 审核, 2060: 导出, 2061: 监测点位状态, 2062: 查看, 2063: 分析, 2064: 监测点位状态详情, 2065: 查看, 2066: 分析, 2067: 车流量
  // 统计, 2068: 查看, 2069: 分析}
}

mapSort(Map map) {
  // List<String> keys = map.keys.toList();
  // // key排序
  // keys.sort((a, b) {
  //   List<int> al = a.codeUnits;
  //   List<int> bl = b.codeUnits;
  //   for (int i = 0; i < al.length; i++) {
  //     if (bl.length <= i) return 1;
  //     if (al[i] > bl[i]) {
  //       return 1;
  //     } else if (al[i] < bl[i]) return -1;
  //   }
  //   return 0;
  // });

  var sortedKeys = map_UserAuth.keys.toList()..sort();
  //print('sortedKeys = $sortedKeys');  //输出不全
  //segmentPrint('sortedKeys = ${sortedKeys}');
  //I/flutter ( 5140): sortedKeys = [1968, 1969, 1970, 1971, 1972, 1973, 1975, 1976, 1977, 1979, 1980, 1981, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 199
  // 4, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2014, 2015, 2016, 2019, 2020, 2023, 2025, 2027, 2028, 2029, 2030, 2031, 203
  // 4, 2035, 2036, 2037, 2041, 2042, 2043, 2047, 2048, 2049, 2053, 2054, 2055, 2056, 2057, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069]

  //new一个map按照keys的顺序将原先的map数据取出来就可以了。
  Map sortedMap = {};
  sortedKeys.forEach((element) {
    sortedMap[element] = map[element];
  });

  return sortedMap;
}
