// ================= 工具函数区域 start ================ //

// 字符串截取长度，从start开始，长度为len
export function subString (str, start, len) 
{
	start = parseInt(start);
	len = parseInt(len);
    let str_ret = str.substr(start, len);
	return str_ret;
}

// 16进制字符串转数字 
export function hexToNumber (hexString) {
 	return parseInt(hexString, 16);
}

 // 2个字节数字转成负数类型，高位默认是1负数
export function numberTurnNegative (num) {
 	// 计算补码，按位取反加一
	let complement = (~num + 1) & 0xFFFF; // 取反加一，并限制在8位范围内

	// 使用位运算符将补码转换为负数
	let negativeNum = -complement;

	return negativeNum;
}

// 16进制字符串高位在后转成高位在前
export function flipHexString(hexStr) {
	// 将16进制字符串两个字符一组逆序
	let reversed = hexStr.match(/.{2}/g).reverse().join('');
	// 若字符串长度为奇数（一个字节中的一个字符），则需要补0
	if (reversed.length % 2 === 1) {
		reversed = '0' + reversed;
	}
	// 将每组字节内的字符位置交换
	let flipped = '';
	for (let i = 0; i < reversed.length; i += 2) {
		flipped += reversed[i] + reversed[i + 1];
	}
	return flipped;
}

// 16进制字符串转成带符号的10进制
export function hex2int(hexStr) {
	let num = parseInt(hexStr,16);
	let twoStr = num.toString(2); // 将十六转十进制，再转2进制
	let bitNum = hexStr.length * 4; // 1个字节 = 8bit ，0xff 一个 "f"就是4位
	if(twoStr.length < bitNum){
		while(twoStr.length < bitNum){
			twoStr = "0" + twoStr;
		}
	}
	if(twoStr.substring(0,1) == "0"){
    // 正数
		twoStr = parseInt(twoStr,2); // 二进制转十进制
		return twoStr;
	}else{
		return numberTurnNegative(num)
	}
}

// 16进制字符串转成2进制字符串
export function BitParse (str16) {
    let map = {
      '0': '0000',
      '1': '0001',
      '2': '0010',
      '3': '0011',
      '4': '0100',
      '5': '0101',
      '6': '0110',
      '7': '0111',
      '8': '1000',
      '9': '1001',
      'a': '1010',
      'b': '1011',
      'c': '1100',
      'd': '1101',
      'e': '1110',
      'f': '1111',
	  'A': '1010',
      'B': '1011',
      'C': '1100',
      'D': '1101',
      'E': '1110',
      'F': '1111'
    };
    let bit = [];
	
	for(let index = 0; index < str16.length; index++)
	{
		for (let key in map) {
			if (str16[index] === key) {
				bit[index] = map[key];
			}
		}
	} 
	
    return bit.join('');
 }
 
 // 字符串转成大写
export function toUpper(str) {
  return str.toUpperCase();
}

 // 字符串转成小写
export function toLower(str) {
  return str.toLowerCase();
}
 
 // 16进制字符串转成ACSII
export function hexStringToAscii(hexString) {
  let asciiStr = '';
  for (let i = 0; i < hexString.length; i += 2) {
    const hexChar = hexString.substr(i, 2);
    const charCode = parseInt(hexChar, 16);
    asciiStr += String.fromCharCode(charCode);
  }
  return asciiStr;
}

export function utf8Encode(str) {
    let utf8Bytes = [];
    for (let i = 0; i < str.length; i++) {
        let codePoint = str.charCodeAt(i);
        
        // 处理单字节字符（ASCII字符）
        if (codePoint <= 0x7F) {
            utf8Bytes.push(codePoint);
        }
        // 处理双字节字符（范围：0x80 ~ 0x7FF）
        else if (codePoint <= 0x7FF) {
            utf8Bytes.push(0xC0 | (codePoint >> 6));
            utf8Bytes.push(0x80 | (codePoint & 0x3F));
        }
        // 处理三字节字符（范围：0x800 ~ 0xFFFF）
        else if (codePoint <= 0xFFFF) {
            utf8Bytes.push(0xE0 | (codePoint >> 12));
            utf8Bytes.push(0x80 | ((codePoint >> 6) & 0x3F));
            utf8Bytes.push(0x80 | (codePoint & 0x3F));
        }
        // 处理四字节字符（范围：0x10000 ~ 0x10FFFF）
        else if (codePoint <= 0x10FFFF) {
            utf8Bytes.push(0xF0 | (codePoint >> 18));
            utf8Bytes.push(0x80 | ((codePoint >> 12) & 0x3F));
            utf8Bytes.push(0x80 | ((codePoint >> 6) & 0x3F));
            utf8Bytes.push(0x80 | (codePoint & 0x3F));
        }
    }
    
    return utf8Bytes;
}

export function utf8ToHexManual(str) {
    let byteArray = utf8Encode(str);
    let hexString = '';
    for (let i = 0; i < byteArray.length; i++) {
        let hex = byteArray[i].toString(16);
        hexString += hex.padStart(2, '0');  // 确保每个字节的 16 进制表示是 2 位
    }
    return hexString;
}


export function hexToUtf8Str(hexStr) {
    // 1. 将16进制字符串转换为字节数组
    let byteArray = [];
    for (let i = 0; i < hexStr.length; i += 2) {
        byteArray.push(parseInt(hexStr.substr(i, 2), 16));
    }

    // 2. 将字节数组解码为字符串
    let str = '';
    let i = 0;
    while (i < byteArray.length) {
        let byte1 = byteArray[i];

        // ASCII字符 (单字节字符)
        if (byte1 <= 0x7F) {
            str += String.fromCharCode(byte1);
            i += 1;
        }
        // 双字节字符
        else if (byte1 >= 0xC0 && byte1 <= 0xDF) {
            let byte2 = byteArray[i + 1];
            let charCode = ((byte1 & 0x1F) << 6) | (byte2 & 0x3F);
            str += String.fromCharCode(charCode);
            i += 2;
        }
        // 三字节字符 (常见汉字)
        else if (byte1 >= 0xE0 && byte1 <= 0xEF) {
            let byte2 = byteArray[i + 1];
            let byte3 = byteArray[i + 2];
            let charCode = ((byte1 & 0x0F) << 12) | ((byte2 & 0x3F) << 6) | (byte3 & 0x3F);
            str += String.fromCharCode(charCode);
            i += 3;
        }
        // 四字节字符 (Unicode扩展字符)
        else if (byte1 >= 0xF0 && byte1 <= 0xF7) {
            let byte2 = byteArray[i + 1];
            let byte3 = byteArray[i + 2];
            let byte4 = byteArray[i + 3];
            let charCode = ((byte1 & 0x07) << 18) | ((byte2 & 0x3F) << 12) | ((byte3 & 0x3F) << 6) | (byte4 & 0x3F);
            str += String.fromCharCode(charCode);
            i += 4;
        } else {
            // 如果是无效字节，跳过
            i++;
        }
    }

    return str;
}

// ================= 工具函数区域 end================ //


// ================= 功能测试函数区域 ============== //
 // 测试获取16进制字符串转2进制字符串是否成功的函数
 export function getStrBitStr (str16) {
    let bit = BitParse(str16);
	let start = 8;
    let len = 1;
	
    return bit.substring(start, len);
 }

// 获取音频音量值
export function getAudioDb (str16, start, len) {
	if(str16.length > start)
	{	
    	let hexString = subString(str16, start, len);
		hexString = flipHexString(hexString); // 将高位在后转成高位在前
		let db = hex2int(hexString);
		let db_value = db / 100;
		return db_value;
	}
	
	return null;
 }

 export function getReplayStrStatus1 (str16, start, len) {
    if(str16.length > start)
	{	
    	let hexString = subString(str16, start, len);
		if(hexString == 'c1') {
			return 1;
		} else {
			return 0;
		}
	}
	return null;
 }	
	
// 根据16进制字符串，转成2进制字符串，然后读取对应的位的值，来判断当前状态 1 表示开启，0表示关闭 返回值 1就是表示按下状态 0 表示弹起状态 null 表示无效，不会有任何处理
 export function getStrReplayStatus (str16, byte_position, start) {
	let total_len = str16.length;          // 获取16进制字符串长度
	let start_position = byte_position * 2; // 16进制字符串，1个Byte等于2位16进制字符串
	let len = total_len - start_position;
	
	str16 = subString(str16, start_position, len) 
	 
    let bit = BitParse(str16);
	
	if(bit.length > start)
	{
		let c = bit[start];
		let d = (c == "0") ? 0 : 1;
		return d;
	}
	
	return null;
 }
 
 // 根据16进制字符串，转成2进制字符串，然后读取对应的位的值，来判断当前状态 1 表示开启，0表示关闭 返回值 1就是表示按下状态 0 表示弹起状态 null 表示无效，不会有任何处理
 export function getStrReplayStatus33 (str16, byte_position, start) {
	let total_len = str16.length;          // 获取16进制字符串长度
	let start_position = byte_position * 2; // 16进制字符串，1个Byte等于2位16进制字符串
	let len = total_len - start_position;
	
	str16 = subString(str16, start_position, len) 
	 
    let bit = BitParse(str16);
	
	if(bit.length > start)
	{
		let c = bit[start];
		let d = (c == "0") ? 0 : 1;
		return d;
	}
	
	return null;
 }

// 根据16进制字符串，转成2进制字符串，然后读取对应的位的值，来判断当前状态 1 表示开启，0表示关闭 返回值 0就是表示按下状态 1 表示弹起状态
 export function getReplayStatus2 (str16, start) {
	let bit = BitParse(str16);
    if(bit.length > start)
	{
		let c = bit[start];
		let d = (c == "1") ? 0 : 1;
		return d;
	}
	
	return null;
 }

// 获取温度值
 export function getTemperature (str16, start, len) {
    if(str16.length > start)
	{	
    	let hexString = subString(str16, start, len);
		console.log(196, hexString);
		let t = hex2int(hexString);
		return t;
	}
	return null;
 }

// 获取温度值字符串
 export function getTemperatureStr (str16, start, len) {
    if(str16.length > start)
	{	
    	let hexString = subString(str16, start, len);
		let t = hex2int(hexString);
		t = t / 1.0
		let t_str = t.toString() + '度'
		return t;
	}
	return null;
 }

// 获取字符串
 export function getStr22 (str16, start, len) {
    if(str16.length > start)
	{	
    	let hexString = subString(str16, start, len);
		if(hexString == "01") {
			return '手动'
		} else if(hexString == "02") {
			return '自动'
		} else if(hexString == "04") {
			return '悬停'
		} else {
			return '告警'
		}
		
	}
	return null;
 }
 
 export function getAsciiStr (str16, start, len) {
    if(str16.length > start)
	{	
    	let hexString = subString(str16, start, len);
		let t = hexStringToAscii(hexString);
		return t;
	}
	return null;
 }

 export function getUtf8Str (str16, start, len) {
    if(str16.length > start)
	{	
    	let hexString = subString(str16, start, len);
		let t = hexToUtf8Str(hexString);
		return t;
	}
	return null;
 }
