//蓝牙指令

import 'dart:typed_data';

import 'package:EasyDartModule/EasyDartModule.dart' as edm;
import 'package:easydevice/src/app/thapp.dart';
import 'package:vbvs_app/common/util/DailyLogUtils.dart';
import 'package:vbvs_app/pages/mh_page/device/model/BlueToothDataModel.dart';

// wifi列表指令
getWifiList(THapp tHapp) async {
  try {
    print("wscan scan");
    edm.EasyDartModule.logger.info("发送请求网络列表指令");
    DailyLogUtils.writeLog("发送请求网络列表指令");
    List data = [];
    var wifilist = await tHapp.send("wscan scan", true, (log) {
      print("[aaaaaa]${log.log}");
      if (log.log.contains("SCAN RESULT OVER!")) {
        final wifiList = <Map<String, dynamic>>[];
        final items = log.log.split('[wifi]: SCAN RESULT ITEM:');
        final reg =
            RegExp(r'SSID=([^\t\r\n]+)\s+RSSI=(-?\d+)\s*,\s*auth\s*=\s*(\d+)');

        for (var item in items) {
          final match = reg.firstMatch(item);
          if (match != null) {
            wifiList.add({
              'ssid': match.group(1),
              'rssi': int.parse(match.group(2)!),
              'auth': int.parse(match.group(3)!),
            });
          }
        }

        print('解析得到 Wi-Fi 列表: $wifiList');
        if (wifiList.length != 0) {
          log.result = wifiList;
          data = wifiList;
          log.over = true;
          return true;
        }
      }

      return false;
    }, 1);

    return wifilist;
  } catch (e) {
    print(e);
  }
  return [];
}

getWifiStatus(THapp tHapp) async {
  edm.EasyDartModule.logger.info("发送请求设备网络状态指令");
  DailyLogUtils.writeLog("发送请求设备网络状态指令");
  var result = await tHapp.send(
    "wl show",
    true,
    (ss) {
      var log = ss.log;
      final match = RegExp(r'status=([^\s]+)').firstMatch(log);
      final status = match?.group(1);
      if (status != null) {
        print('提取到的 status: $status');
        if (status == 'connect') {
          ss.result = true;
          ss.over = true;
          return true;
        } else {
          ss.result = false;
          ss.over = true;
          return false;
        }
      } else {
        return false;
      }
    },
  );
  return result;
}

Future<bool> sendWifiSetting(wifiItem, String password, THapp tHapp) async {
  try {
    edm.EasyDartModule.logger.info("发送wifi配置指令");
    DailyLogUtils.writeLog("发送wifi配置指令->");
    String cmd = "vtouch save update -a -i .wifi.sta.auth=${wifiItem['auth']} "
        ".wifi.sta.ssid=${wifiItem['ssid']} .wifi.sta.pwd=$password";
    final success = await tHapp.send(cmd, true, (log) {
      if (log.log.contains("update parm is successful")) {
        print("[wifi456]:" + log.log);
        edm.EasyDartModule.logger.info("WiFi配置参数成功-》log:$log");
        DailyLogUtils.writeLog("WiFi配置参数成功->log:$log");
        log.result = true;
        log.over = true;
        return true;
      }
      return false;
    }, 1);

    if (!success) {
      edm.EasyDartModule.logger.error("WiFi配置超时或失败");
      DailyLogUtils.writeLog("WiFi配置超时或失败");
    }
    return success;
  } catch (e) {
    edm.EasyDartModule.logger.error("发送wifi配置指令异常: ${e.toString()}");
    DailyLogUtils.writeLog("发送wifi配置指令异常-> ${e.toString()}");
    return false;
  }
}

// getDeviceWifiStatus(THapp tHapp, int times) async {
//   edm.EasyDartModule.logger.info("发送请求设备已配置网络状态指令");
//   DailyLogUtils.writeLog("发送请求设备已配置网络状态指令");
//   try {
//     var result = await tHapp.send("at+system info", true, (ss) {
//       var log = ss.log;

//       // 匹配设备状态
//       final statusMatch = RegExp(r'Status=([^\s]+)').firstMatch(log);
//       final status = statusMatch?.group(1);
//       if (status != null) {
//         print('提取到的 status: $status');

//         // 如果设备连接状态是 "connect"，继续检测
//         if (status.contains('connect')) {
//           ss.result = true;
//           ss.over = true;

//           // 匹配 Wi-Fi 连接信息
//           final wifiInfoMatch = RegExp(
//                   r'WIFI CONNECTED INFO:SSID=([^\s]+),RSSI=([-0-9]+),AUTH=([0-9]+),CH=([0-9]+),BSSID=([A-F0-9]+)')
//               .firstMatch(log);
//           if (wifiInfoMatch != null) {
//             final ssid = wifiInfoMatch.group(1);
//             final rssi = wifiInfoMatch.group(2);
//             final auth = wifiInfoMatch.group(3);
//             final ch = wifiInfoMatch.group(4);
//             final bssid = wifiInfoMatch.group(5);

//             // 打印并返回 Wi-Fi 信息
//             print(
//                 'Wi-Fi 信息: SSID=$ssid, RSSI=$rssi, AUTH=$auth, CH=$ch, BSSID=$bssid');

//             // 停止监听并返回信息
//             ss.result = {
//               'ssid': ssid,
//               'rssi': rssi,
//               'auth': auth,
//               'ch': ch,
//               'bssid': bssid,
//             };
//             ss.over = true;
//             return ss.result;
//           }
//         }
//       }

//       // 未找到状态或Wi-Fi信息时，返回 false
//       return false;
//     }, times);

//     return result;
//   } catch (e) {
//     print(e);
//   }
// }

getDeviceWifiStatus(THapp tHapp, int times) async {
  edm.EasyDartModule.logger.info("发送请求设备已配置网络状态指令");
  DailyLogUtils.writeLog("发送请求设备已配置网络状态指令");
  print("at+system info");

  try {
    var result = await tHapp.send("at+system info", true, (ss) {
      var log = ss.log;
      // 匹配设备状态
      final statusMatch = RegExp(r'Status=([^\s]+)').firstMatch(log);
      final status = statusMatch?.group(1);
      if (status != null) {
        print('提取到的 status: $status');

        // 如果设备连接状态是 "connect"，继续检测
        if (status.contains('connect')) {
          // 匹配 Wi-Fi 连接信息
          final wifiInfoMatch = RegExp(
                  r'WIFI CONNECTED INFO:SSID=([^\s]+),RSSI=([-0-9]+),AUTH=([0-9]+),CH=([0-9]+),BSSID=([A-F0-9]+)')
              .firstMatch(log);
          if (wifiInfoMatch != null) {
            final ssid = wifiInfoMatch.group(1);
            final rssi = wifiInfoMatch.group(2);
            final auth = wifiInfoMatch.group(3);
            final ch = wifiInfoMatch.group(4);
            final bssid = wifiInfoMatch.group(5);

            // 打印并返回 Wi-Fi 信息
            print(
                'Wi-Fi 信息: SSID=$ssid, RSSI=$rssi, AUTH=$auth, CH=$ch, BSSID=$bssid');

            // 停止监听并返回信息
            ss.result = {
              'ssid': ssid,
              'rssi': rssi,
              'auth': auth,
              'ch': ch,
              'bssid': bssid,
            };
            ss.over = true;
            return true;
          }
        }
      }

      // 继续监听
      return false;
    }, times);

    return result;
  } catch (e) {
    print(e);
  }
}

Future<String> getDeviceNetVersion(THapp tHapp, int times) async {
  edm.EasyDartModule.logger.info("发送请求设备的网络信息");
  DailyLogUtils.writeLog("发送请求设备的网络信息");
  print("ls /root/mnt");

  String netType = "unknown";

  try {
    var result = await tHapp.send("ls /root/mnt", true, (ss) {
      var log = ss.log;
      print("[获取]$log");

      if (log.contains("wifi.json") || log.contains("a76xx.json")) {
        if (log.contains("wifi.json")) {
          netType = "wifi";
        } else if (log.contains("a76xx.json")) {
          netType = "4g";
        } else {
          netType = "unknown";
        }
        ss.over = true;
        ss.result = netType;
        // 继续监听
        return true;
      }
      ss.over = false;
      return false;
    }, times,15000);

    return netType;
  } catch (e) {
    print(e);
    return netType;
  }
}
