function Log(str) {
  if (typeof window.external.HLog === "undefined") {
    console.log(str);
  } else {
    window.external.HLog(str);
  }
}

var utils = {
  parseSatelliteData: function (data) {
    function convertDdmmmmToDd(decimalDdmmmm) {
      // 获取度和分的部分
      var degrees = Math.floor(decimalDdmmmm / 100);
      var minutes = decimalDdmmmm - degrees * 100;

      // 将分的部分转换为以度为单位的小数部分
      var decimalMinutes = minutes / 60;

      // 最终的纬度
      var finalLatitude = degrees + decimalMinutes;

      return finalLatitude;
    }
    function combineDateTime(utcTime, dateStr) {
      if (!utcTime || !dateStr) {
        return null;
      }
      // 解析 UTC 时间
      var hours = parseInt(utcTime.substr(0, 2), 10);
      var minutes = parseInt(utcTime.substr(2, 2), 10);
      var seconds = parseInt(utcTime.substr(4, 2), 10);
      var milliseconds = parseInt(utcTime.substr(7), 10);

      // 解析日期
      var day = parseInt(dateStr.substr(0, 2), 10);
      var month = parseInt(dateStr.substr(2, 2), 10) - 1; // 月份是从0开始的
      var year = 2000 + parseInt(dateStr.substr(4, 2), 10); // 假设年份在2000年之后

      // 创建日期对象
      var combinedDate = new Date(
        year,
        month,
        day,
        hours,
        minutes,
        seconds,
        milliseconds
      );

      if (isNaN(combinedDate.getTime())) {
        return null;
      }

      return combinedDate;
    }

    var satelliteDataList = [];
    var RMCData = {
      status: "",
      utc: "",
      lat: "",
      lng: "",
      xiangDuiHangXingShuDu: "",
      xiangDuiHangXingFangXiang: "",
      chiJiBianLiang: "",
      chiFangWeiJiaoDu: ""
    };

    var GPSData = {
      totalSatellite: 0,
      totalNetOKSatelite: 0,
      totalLocatedSatellite: 0
    };
    var BDSData = {
      totalSatellite: 0,
      totalNetOKSatelite: 0,
      totalLocatedSatellite: 0
    };

    var lines = data.split("\n");

    for (var lineIndex = 0; lineIndex < lines.length; lineIndex++) {
      var line = lines[lineIndex];

      // 判断是否为空行
      if (line.replace(/^\s+|\s+$/g, "") === "") {
        continue;
      }

      // 判断是否以"$GPGSV"或"$BDGSV"开头
      if (line.indexOf("$GPGSV") === 0 || line.indexOf("$BDGSV") === 0) {
        var satelliteData = {
          SentenceId: null,
          TotalMessages: null,
          MessageNumber: null,
          SatellitesInView: null,
          Satellites: []
        };

        var fields = line.split(",");

        if (fields.length >= 7) {
          satelliteData.SentenceId = fields[0];
          satelliteData.TotalMessages = parseInt(fields[1], 10);
          satelliteData.MessageNumber = parseInt(fields[2], 10);
          satelliteData.SatellitesInView = parseInt(fields[3], 10);

          for (var i = 4; i < fields.length; i += 4) {
            if (i + 3 < fields.length) {
              var satellite = {
                PRN: parseInt(fields[i], 10) || 0,
                Elevation: parseInt(fields[i + 1], 10) || 0,
                Azimuth: parseInt(fields[i + 2], 10) || 0,
                SNR: parseInt(fields[i + 3], 10) || 0
              };
              satelliteData.Satellites.push(satellite);
            }
          }

          satelliteDataList.push(satelliteData);

          if (line.indexOf("$GPGSV") === 0) {
            GPSData.totalNetOKSatelite = satelliteData.TotalMessages;
            GPSData.totalLocatedSatellite = satelliteData.MessageNumber;
            GPSData.totalSatellite = satelliteData.SatellitesInView;
          } else if (line.indexOf("$BDGSV") === 0) {
            BDSData.totalNetOKSatelite = satelliteData.TotalMessages;
            BDSData.totalLocatedSatellite = satelliteData.MessageNumber;
            BDSData.totalSatellite = satelliteData.SatellitesInView;
          }
        }
      } else if (line.indexOf("$GNRMC") === 0) {
        var fields = line.split(",");
        var date = combineDateTime(fields[1], fields[9]);

        var lat = convertDdmmmmToDd(fields[3]);
        var lng = convertDdmmmmToDd(fields[5]);
        RMCData = {
          status: fields[2],
          utc: date,
          lat: fields[4] + lat ? lat.toFixed(6) : "",
          lng: fields[6] + lng ? lng.toFixed(6) : "",
          xiangDuiHangXingShuDu: fields[7],
          xiangDuiHangXingFangXiang: fields[8],
          chiJiBianLiang: fields[10],
          chiFangWeiJiaoDu: fields[11]
        };
      }
    }
    return {
      satelliteDataList: satelliteDataList,
      RMCData: RMCData,
      GPSData: GPSData,
      BDSData: BDSData
    };
  },
  findTopSatellites: function (data, sentenceId) {
    var filteredData = [];
    for (var i = 0; i < data.length; i++) {
      if (data[i].SentenceId === sentenceId) {
        filteredData.push(data[i]);
      }
    }

    var topSatellites = [];

    for (var j = 0; j < filteredData.length; j++) {
      var satellites = filteredData[j].Satellites.slice(0); // 克隆数组，以避免修改原始数组

      satellites.sort(function (a, b) {
        return b.SNR - a.SNR;
      });

      for (var k = 0; k < satellites.length && k < 6; k++) {
        topSatellites.push(satellites[k]);
      }
    }

    topSatellites.sort(function (a, b) {
      return b.SNR - a.SNR;
    });

    return topSatellites;
  },
  formatDateTime: function (date) {
    if (!date) {
      return "";
    }

    var year = date.getFullYear();
    var month = utils.padZero(date.getMonth() + 1);
    var day = utils.padZero(date.getDate());
    var hours = utils.padZero(date.getHours());
    var minutes = utils.padZero(date.getMinutes());
    var seconds = utils.padZero(date.getSeconds());

    return (
      year +
      "-" +
      month +
      "-" +
      day +
      " " +
      hours +
      ":" +
      minutes +
      ":" +
      seconds
    );
  },
  padZero: function (num) {
    return num < 10 ? "0" + num : num;
  }
};
