/*
 * @Descripttion:
 * @version:
 * @Author: lfzxs@qq.com
 * @Date: 2024-10-16 13:52:11
 * @LastEditors: lfzxs@qq.com
 * @LastEditTime: 2024-10-18 16:33:31
 */

export function buildHead(d_length,d_remote_id,d_local_id,d_cmd,d_dev_type,d_data_type,dataStart,dataLength,dataValue,activeData) {
  // 初始化data为一个32位2进制数

  let data = "0000" + d_data_type + d_dev_type + d_cmd + toBinaryString(d_local_id,9) + toBinaryString(d_remote_id,9) + d_length;

  console.log("获取头部",data);

  let hex_data = binaryToHex(data);
  let dataBuffer = '';
  let buffer = hexToBuffer(hex_data);
  //根据d_cmd的值拼接命令格式
  switch (d_cmd) {
    case "0000"://特殊指令
      break;
    case "0011"://地址读
      buffer = concatenateBuffers(htonl(buffer),htonl(toFixedSizeBuffer(parseInt(dataStart),4)),htonl(toFixedSizeBuffer(parseInt(dataLength),4)));
      break;
    case "0100"://地址写

      if(activeData.dataType === 'hex'){
        dataValue = rearrangeHexStr(dataValue);
        dataBuffer = hexToBuffer(dataValue);
      }else if(activeData.dataType === 'hexString'){
        dataBuffer = hexToBuffer(dataValue);
      }else{
        dataBuffer = stringToHexBuffer(dataValue,dataLength*4*2);
      }
      console.log("dataBuffer",dataBuffer)
      buffer = concatenateBuffers(htonl(buffer),htonl(toFixedSizeBuffer(parseInt(dataStart),4)),htonl(toFixedSizeBuffer(parseInt(dataLength),4)),dataBuffer)
      break;
  }
  console.log("dataValue-buffer",dataValue,buffer)

  let result = bufferToHex(buffer);

  return result;
}

export function allBuildHead(d_length,d_remote_id,d_local_id,d_cmd,d_dev_type,d_data_type,dataStart,dataLength,dataValue,allList) {
  // 初始化data为一个32位2进制数

  let data = "0000" + d_data_type + d_dev_type + d_cmd + toBinaryString(d_local_id,9) + toBinaryString(d_remote_id,9) + d_length;

  console.log("获取头部",data);

  let hex_data = binaryToHex(data);

  let buffer = hexToBuffer(hex_data);
  let allBufferList = [];
  //根据d_cmd的值拼接命令格式
  switch (d_cmd) {
    case "0000"://特殊指令
      break;
    case "0011"://地址读
      buffer = concatenateBuffers(htonl(buffer),htonl(toFixedSizeBuffer(parseInt(dataStart),4)),htonl(toFixedSizeBuffer(parseInt(dataLength),4)));
      break;
    case "0100"://地址写
      allBufferList = allList.map(item=>{
        return stringToHexBuffer(item.inputValue,item.lengthValue*4*2);
      })
      buffer = concatenateBuffers(htonl(buffer),htonl(toFixedSizeBuffer(parseInt(dataStart),4)),htonl(toFixedSizeBuffer(parseInt(dataLength),4)),...allBufferList)
      break;
  }

  let result = bufferToHex(buffer);

  return result;
}

export function bufferToHex(buffer) {
  let hexString = '';
  const view = new Uint8Array(buffer);
  for (let i = 0; i < view.length; i++) {
    const hex = view[i].toString(16).padStart(2, '0');
    hexString += hex;
  }
  return hexString;
}

export function toBinaryString(number, length) {
  let binaryString = number.toString(2);
  return binaryString.padStart(length, '0');
}

export function binaryToHex(binaryStr) {
  // 确保二进制字符串长度是4的倍数
  if (binaryStr.length % 4 !== 0) {
    binaryStr = binaryStr.padStart(binaryStr.length + 4 - (binaryStr.length % 4), '0');
  }

  let hexStr = '';
  for (let i = 0; i < binaryStr.length; i += 4) {
    // 取出每4位二进制字符串
    const binaryChunk = binaryStr.slice(i, i + 4);
    // 转换成十六进制字符并追加到结果字符串中
    hexStr += parseInt(binaryChunk, 2).toString(16);
  }

  return hexStr;
}


export function hexToBuffer(hexStr) {
  if (hexStr.length % 2 !== 0) {
    throw new Error('Invalid hex string');
  }

  let buffer = new ArrayBuffer(hexStr.length / 2);
  let view = new Uint8Array(buffer);

  for (let i = 0; i < hexStr.length; i += 2) {
    view[i / 2] = parseInt(hexStr.substr(i, 2), 16);
  }

  return buffer;
}

export function swapEndian(buffer) {
  const swappedBuffer = new ArrayBuffer(buffer.byteLength);
  const view = new DataView(buffer);
  const swappedView = new DataView(swappedBuffer);

  for (let i = 0; i < buffer.byteLength; i++) {
    swappedView.setUint8(i, view.getUint8(buffer.byteLength - 1 - i));
  }

  return swappedBuffer;
}


export function htonl(buffer) {
  if (buffer.byteLength !== 4) {
    throw new Error('Buffer must be exactly 4 bytes.');
  }

  let view = new DataView(buffer);
  let number = view.getUint32(0);

  let swappedNumber = ((number & 0xFF) << 24) |
    ((number & 0xFF00) << 8) |
    ((number & 0xFF0000) >> 8) |
    ((number >> 24) & 0xFF);

  let swappedBuffer = new ArrayBuffer(4);
  let swappedView = new DataView(swappedBuffer);
  swappedView.setUint32(0, swappedNumber);

  return swappedBuffer;
}



//将数字转换成指定字节大小的buffer
export function toFixedSizeBuffer(number, byteSize) {
  if (byteSize <= 0) {
    throw new Error('Byte size must be greater than zero.');
  }

  let buffer = new ArrayBuffer(byteSize);
  let view = new DataView(buffer);

  // 根据指定字节数设置数值到缓冲区中
  for (let i = 0; i < byteSize; i++) {
    view.setUint8(byteSize - 1 - i, number & 0xFF);
    number = number >> 8;
  }

  return buffer;
}


export function concatenateBuffers(...buffers) {

  // 确保所有元素均为 ArrayBuffer
  buffers.forEach(buffer => {
    if (!(buffer instanceof ArrayBuffer)) {
      throw new TypeError('All arguments must be ArrayBuffers');
    }
  });
  // 计算总长度
  let totalLength = buffers.reduce((sum, buffer) => sum + buffer.byteLength, 0);

  // 创建一个新的 ArrayBuffer 并使用 Uint8Array 进行操作
  let concatenatedBuffer = new Uint8Array(totalLength);
  let offset = 0;

  // 逐个复制每个缓冲区的内容
  buffers.forEach(buffer => {
    concatenatedBuffer.set(new Uint8Array(buffer), offset);
    offset += buffer.byteLength;
  });

  return concatenatedBuffer.buffer;
}

export function stringToHexBuffer(str,length) {
  // return new TextEncoder().encode(str).buffer;
  const bufferView = new TextEncoder().encode(str);

  // 计算需要补充的00的数量
  const targetLength = length / 2; // 目标长度（字节数）
  const paddingLength = targetLength - bufferView.length;

  // 创建一个新的Uint8Array，长度为目标长度
  const paddedBufferView = new Uint8Array(targetLength);

  // 将原始Uint8Array的内容复制到新的Uint8Array中
  paddedBufferView.set(bufferView);

  // 填充00
  if (paddingLength > 0) {
    paddedBufferView.fill(0, bufferView.length, targetLength);
  }

  // 返回格式化后的Uint8Array
  return paddedBufferView.buffer;
}

export function hexToString(hexStr) {
  let str = '';
  for (let i = 0; i < hexStr.length; i += 2) {
    if(hexStr.substr(i, 2)!=='00'){
      str += String.fromCharCode(parseInt(hexStr.substr(i, 2), 16));
    }
  }
  return str;
}

export function rearrangeHexStr(hexStr) {
  // 将输入的十六进制字符串解析为字节数组
  // 将输入的十六进制字符串按每8位分组
  const groups = [];
  for (let i = 0; i < hexStr.length; i += 8) {
    groups.push(hexStr.slice(i, i + 8));
  }

  // 对每个组内的每两位进行倒序拼接
  const rearrangedGroups = groups.map(group => {
    let rearrangedGroup = '';
    for (let i = 0; i < group.length; i += 2) {
      rearrangedGroup = group.substr(i, 2) + rearrangedGroup;
    }
    return rearrangedGroup;
  });

  // 将所有组重新拼接成一个字符串
  const rearrangedHexStr = rearrangedGroups.join('');

  return rearrangedHexStr;
}

//高低位交换
export function rearrangeHexStr4(hexStr) {
  let rearrangedGroup = '';
  for (let i = 0; i < hexStr.length; i += 2) {
    rearrangedGroup = hexStr.substr(i, 2) + rearrangedGroup;
  }
  return rearrangedGroup;
}

export function hexToVersion(hexStr) {
  let str = rearrangeHexStr(hexStr);
  str = hexToDec(str);
  return str;
}

export function versionToHex(hexStr) {
  let str = decToHex(hexStr);
  str = rearrangeHexStr(str);
  return str;
}

// 十六进制转十进制
export function hexToDec(hexStr) {
  // 去除前缀 "0x"（如果存在）
  hexStr = hexStr.replace(/^0x/, '');
  // 将十六进制字符串转换为十进制数字
  return parseInt(hexStr, 16);
}

// 十进制转十六进制
export function decToHex(decNum) {
  // 将十进制数字转换为十六进制字符串
  let hexStr = decNum.toString(16);
  // 可选：添加前缀 "0x"
  return `0x${hexStr}`;
}
