<?php
/*********************************************************      
 程序说明:(和paramEditPreview.php保持一致)          
    功能说明:本程序实现参数编辑模板代码的产生，保存，预览

    调用关系:调用: header.inc     
    被调用:      
 
    变量说明:

    返回值:

 作者:      
      
修改注释:      
NO.1      
姓名:	            
时间:      
修改说明:
*********************************************************/    
require("../../inc/header.inc");
$DEBUG	= 0;
$TEST	= ($TEST > 0)?$TEST:0;
//*****
//$url_temp=$_SERVER["REQUEST_URI"];
//echo "This page URL:$url_temp<br>";
//value Type
$nInteger = 2;
$nOctStr = 4;

function omcGetObjDb($sysTypeNo){
	$dbName = 'OBJ_'.$sysTypeNo;
	return($dbName);
}

function omcGetObjTbl($sysTypeNo,$tableType){
	$dbName = 'OBJ_'.$sysTypeNo;
	$tableName = $dbName.'.paramConf';
	return($tableName);
}

function omcStrFill($string,$defLen,$fillWay='high',$fillChar='0'){
	if(strlen($string) <= $defLen){
		$fillLen=$defLen - strlen($string);
		for($i=0;$i<$fillLen;$i++){
			if($fillWay == 'low'){
				$string = $string.$fillChar;
			}else{
				$string = $fillChar.$string;
			}
		}
		return($string);
	}else{
		echo "<br>Error in omcStrFill:the defLen < lengh of string!!";
		echo "<br>defLen=$defLen and string=$string!!";
		exit();
	}
}

$sysConfTable = 'OMC_PUB.sysConf';
$sysTypeNo	= (isset($sysTypeNo)?$sysTypeNo:0);

$pubDb			='OMC_PUB';
$objDb 			= omcGetObjDb($sysTypeNo);
$paramConfTable	= omcGetObjTbl($sysTypeNo,paramConf);
$maxLevelNum	= 10;

if($DEBUG) echo "<br>$paramConfTable<br>";
if($DEBUG) echo "<br>aliasName=$aliasName<br>";
//----------------------
//选择语言版本
if($language == 'eng'){
	$objNameField=name_2;
	$objSetField=setTemplate_2 ; //语种2
}else{	
	$objNameField=name_1;
	$objSetField=setTemplate_1 ; //语种1(默认语种)
}
//-----------------------

//=======================Get value From submit===================
if($set == 'Set'){
	
	//sort by offset
	for($i=1;$i<=$unitNum;$i++){
		$tmpDef = ${'unitDef_'.$i};
		$tmpValue = ${'unit_'.$i};
		if($DEBUG) echo "<br>tmpDef = $tmpDef";
		$defArr[$i] = $tmpDef;
		$tmpDefArr=explode('-',$tmpDef);
		$sortArr[$i] = $tmpDefArr[0];
		$valueArr[$i] = $tmpValue;
	}
	$lastValue = '';
	$k = 0;
	asort($sortArr);
	for(reset($sortArr); $key = key($sortArr); next($sortArr)){
		if($DEBUG) echo "<br>sortArr[$key] = {$sortArr[$key]}";
		if($DEBUG) echo "<br>unitValue = {$valueArr[$key]}";
		$unitValue = $valueArr[$key];
		if($DEBUG) echo "<br>defArr[$key] = {$defArr[$key]}";
		$unitDefArr = explode('-',$defArr[$key]); //例:0.0-0.7-input -toDec-high-0
		if(sizeof($unitDefArr) <= 1){
			if($DEBUG) echo "<br>nothing,just a name";
			continue;
		}
		$bgnOffset	= $unitDefArr[0];
		$endOffset	= $unitDefArr[1];
		$operType	= $unitDefArr[2];
		$valueType  = $unitDefArr[3];
		$fillWay	= $unitDefArr[4];
		$fillChar	= $unitDefArr[5];
		
		$bgnOffsetArr = explode('.',$bgnOffset);
		$bgnByte = $bgnOffsetArr[0];
		$bgnBit  = $bgnOffsetArr[1];
		$endOffsetArr = explode('.',$endOffset);
		$endByte = $endOffsetArr[0];
		$endBit  = $endOffsetArr[1];
		$byteLen = $endByte - $bgnByte + 1;
		$byteValue = '';
		if($DEBUG) echo "<br>valueType = $valueType";
		switch($valueType){
			case 'toDec':
				if($bgnBit > 0 ||$endBit < 7){
					$bitLen = $byteLen*8 - $bgnBit - (7 - $endBit) ; //1 BYTE = 8 bit
					$bitValue = DecBin($unitValue);
					if($DEBUG) echo "<br>bitValue = $bitValue ";
					$bitValue  = omcStrFill($bitValue,$bitLen,$fillWay,$fillChar);
					if($DEBUG) echo "<br>omcStrFill($bitValue,$bitLen,$fillWay,$fillChar)";
					
					if($bgnByte!=$endByte){	
						if($DEBUG) echo "<br>substr($bitValue,0,1+$endBit)";
						$tmpBitValue=substr($bitValue,0,1+$endBit);
						$newBitValue=$tmpBitValue;
						if($DEBUG) echo "<br>newBitValue=$newBitValue";					
						
						for($byteNum=$endByte-1;$byteNum >= $bgnByte;$byteNum--){
							if($DEBUG) echo "<br>substr($bitValue,($byteNum-($endByte-1))*8+1+$endBit,8)";
							$tmpBitValue=substr($bitValue,($byteNum-($endByte-1))*8+1+$endBit,8);
							if($DEBUG) echo "<br>$newBitValue.$tmpBitValue";
							$newBitValue=$newBitValue.$tmpBitValue;
							if($DEBUG) echo "<br>newBitValue=$newBitValue";
						}
						$bitValue=$newBitValue;	
					}
					
					$bitValueArr[$k] = $bitValue;
					if($DEBUG) echo "<br>bitValueArr[$k] = {$bitValueArr[$k]}";
					if($endBit == 7){//发现这个单元结束，并没有跨byte，这时需要组成一个byte值
						$bitValue = '';
						for($bitNo=0; $bitNo<=$k; $bitNo++){
							if($DEBUG) echo "<br>bitValueArr[$bitNo] = {$bitValueArr[$bitNo]}";
							$bitValue = $bitValueArr[$bitNo].$bitValue;
						}
						$k=0;
						if($DEBUG) echo "<br>bitValue = $bitValue";
						$byteLen = strlen($bitValue) / 8;
						if($DEBUG) echo "<br>byteLen = $byteLen";
						$byteValue = BinDec($bitValue);
						$byteValue = DecHex($byteValue);
						$strLen = $byteLen*2;
						if($DEBUG) echo "<br>omcStrFill($byteValue,$strLen,$fillWay,$fillChar)";
						$byteValue = omcStrFill($byteValue,$strLen,$fillWay,$fillChar);
						$newByteValue="";
						for($tmp=0;$tmp<strlen($byteValue);$tmp=$tmp+2){
							$tmpByteValue=substr($byteValue,$tmp,2);
							$newByteValue=$tmpByteValue.$newByteValue;
						}
						$byteValue=$newByteValue;
					}else{//否则，继续组合下一个bit组
						$byteValue = '';
						$k++;
					}
				}else{
					$byteValue = DecHex($unitValue);
					$strLen = $byteLen*2;
					$byteValue = omcStrFill($byteValue,$strLen,$fillWay,$fillChar);
					if($DEBUG) echo "<br>omcStrFill($byteValue,$strLen,$fillWay,$fillChar)";
				}
				if($DEBUG) echo "<br>byteValue = $byteValue";
				break;
			case 'keepDec':
				//echo "<br>Error:keepDec";
				$byteValue = $unitValue - 0;
				break;
			case 'toHex':
				echo "<br>Error:toHex";
				break;
			case 'keepHex':
				if($bgnBit > 0 || $endBit < 7){//这里的处理不够全面,没有对=7的进行收尾
					$byteValue = $unitValue;
					$strLen = $byteLen;
					$byteValue = omcStrFill($byteValue,$strLen,$fillWay,$fillChar);
					$bitValue = DecBin(HexDec($byteValue));
					$byteValue='';
					$bitLen = $byteLen*8 - $bgnBit - (7 - $endBit) ; //1 BYTE = 8 bit
					$bitValue  = omcStrFill($bitValue,$bitLen,'high','0');
					if($DEBUG) echo "<br>bitValue = $bitValue";
					$bitValueArr[$k] = $bitValue;
					$k++;
				}else{
					$k=0;
					$byteValue = $unitValue;
					$strLen = $byteLen*2;
					$byteValue = omcStrFill($byteValue,$strLen,$fillWay,$fillChar);
					if($DEBUG) echo "<br>omcStrFill($byteValue,$strLen,$fillWay,$fillChar)";
				}
				break;
			case 'toAscii':
				if($bgnBit > 0 ||$endBit < 7){
					echo "<br>Error:toAscii";
					exit(1);
				}else{
					$tmpLen=strlen($unitValue);
					for($i=0;$i<$tmpLen;$i++){
						$unitChar = substr($unitValue,$i,1);
						$decValue = ord($unitChar); //ascii -> dec
						$byteValue .= DecHex($decValue);
						if(strlen($byteValue) < 2){
							$byteValue = '0'.$byteValue;
						}
					}
					$strLen = $byteLen*2;
					$byteValue = omcStrFill($byteValue,$strLen,$fillWay,$fillChar);
				}
				break;
			default: 
				echo "Error:Unknown valueType";
				break;
		}
		if($DEBUG) echo "<br>byteValue  = $byteValue ";
		//--><-//$lastValue = $byteValue.$lastValue;
		$lastValue = $lastValue.$byteValue;
	}
	if($DEBUG) echo "<br>lastValue  = $lastValue ";
	$setValue = $lastValue;
	if($TEST != 1){
		//set back to input field
		echo "setValue=$setValue<br>";
		echo "<script LANGUAGE=\"JavaScript\">";
		echo "\n var setValue='$setValue'; ";
		echo "\n var aliasValue='$strAlias'; ";
		echo "\n window.opener.document.update.$inputName.value=setValue.toUpperCase();";
//		echo "\n window.opener.document.update.$aliasName.value=aliasValue;";
		echo "\n window.opener.document.update.$inputName.style.color=\"BLUE\";";
		if($DEBUG) exit();
		echo "\n window.opener.document.update.$inputName.focus();";
		echo "\n window.close();";
		echo "\n </script>";
	}else{
		$setValue = strtoupper($setValue);
	}
}//end of if($set == 1)

//=======================Show GUI ========================
?> 
<body>
<script LANGUAGE="JavaScript"> 
function checkInt(term){
    
    var checkOK = "0123456789";
    var checkStr = term.value;
    var allValid = true;
	var termName = term.name;
	var minValue = eval("document.confForm."+termName+"_min.value");
	var maxValue = eval("document.confForm."+termName+"_max.value");
	var oldValue = eval("document.confForm."+termName+"_old.value");
	//alert(minValue+'<'+term.value+'<'+maxValue);
    for (i = 0;  i < checkStr.length;  i++){
		ch = checkStr.charAt(i);
		for (j = 0;  j < checkOK.length;  j++){
			if (ch == checkOK.charAt(j))
				break;
		}
		if (j == checkOK.length){
			allValid = false;
			break;
		}
	}

	if (!allValid){  
		var errAlert="parameter Must be a dec number!";
		alert(errAlert);
		term.value=oldValue;
		term.focus();
		return (false);
	}

	if((minValue - term.value) > 0){
		var errAlert="Too little!";
		alert(errAlert);
		term.value=oldValue;
		term.focus();
		return (false);
	}
	if((term.value - maxValue) > 0){
		var errAlert="Too Big!";
		alert(errAlert);
		term.value=oldValue;
		term.focus();
		return (false);
	}

}
</script>

<form method="POST" name="confForm" action="<?php echo"$PHP_SELF";?>" >
<?php
if($DEBUG) echo "<br>setValue = $setValue ,inputName = $inputName";

if($keyId > 0){
	$objSql = "SELECT $objNameField,$objSetField,valueType,length,minValue,maxValue FROM $paramConfTable WHERE keyId = '$keyId'";
	$objResult	= mysqli_query($pubConn ,$objSql);
	$objRows	= @mysqli_fetch_array($objResult);
	$totalLen	= $objRows[length]*2;
	$objName	= $objRows[$objNameField];
	$setTemplate = $objRows[$objSetField];
	$valueType	= $objRows[valueType];
	$minValue	= $objRows[minValue];
	$maxValue	= $objRows[maxValue];
}else{
	echo "<font><b>ERROR!!:keyId == NULL</b></font>";
	exit();
}
/**************************************
*objName
*[unit]name[u]xx.xx-yy.yy[u]input[v]toDec-fillHigh-fillChar
*[unit]name[u]xx.xx-yy.yy[u]select[v]value1[opt]desc1[v]value2[opt]desc2
*[remark]
***************************************/

//explode by '[remark]'
$remarkArr = explode('[remark]',$setTemplate);
$remark  = $remarkArr[1];

//explode by '[unit]'
$unitArr = explode('[unit]',$remarkArr[0]);

//show instance's name
echo "<b>{$unitArr[0]}</b><br><br>";
if($DEBUG) echo "<br>$unitArr[1]";
//show every one unit
//--><-//$setValue = strrev($setValue);
if($DEBUG){
	echo "<table border=\"1\" cellpadding=\"0\" cellspacing=\"2\" width=\"100%\">";
}else{
	echo "<table border=\"0\" cellpadding=\"0\" cellspacing=\"2\" width=\"100%\">";
}
for($i=1;$i<sizeof($unitArr);$i++){

	echo "\n <tr><td width=\"10%\"  valign=middle><nobr>";
	//unit input name
	$unitName = "unit_".$i;
	//explode by '[u]'
	$tlvArr = explode('[u]',$unitArr[$i]);
	if(sizeof($tlvArr) <= 1 ){
		echo "<u><b>{$unitArr[$i]}</b></u>";
		continue;
	}

	//show Unit Name
	echo "$tlvArr[0]";
	echo "&nbsp;</nobr></td><td>";
	if($DEBUG) echo "$tlvArr[1]";
	//explode by '-'
	$offsetArr = explode('-',$tlvArr[1]);
	$bgnOffsetArr = explode('.',$offsetArr[0]);
	$bgnByte = $bgnOffsetArr[0];
	$bgnBit  = $bgnOffsetArr[1];

	$endOffsetArr = explode('.',$offsetArr[1]);
	$endByte = $endOffsetArr[0];
	$endBit  = $endOffsetArr[1];
	$byteLen = $endByte - $bgnByte + 1;
	$byteValue = substr($setValue,$bgnByte*2,$byteLen*2);
	//--><-//$byteValue = strrev($byteValue);
	if($DEBUG)
	 echo "<br>byteValue = $byteValue";

	$bitValue = '';
	if($bgnBit > 0 ||$endBit < 7){
		if($DEBUG) echo "<br>$bgnBit > 0 ||$endBit < 7";
		$bitValue = HexDec($byteValue);
		$bitValue = DecBin($bitValue);
		if($DEBUG) echo "<br>bitValue = $bitValue";
		
		$bitLen   = $byteLen*8;//1 byte = 8 bit
		$bitValue = omcStrFill($bitValue,$bitLen,'high','0');
		if($DEBUG) echo "<br>omcStrFill($bitValue,$bitLen,'high','0')";
	
		$newBitValue='';
		for($byteNum=$bgnByte;$byteNum<=$endByte;$byteNum++){
			$tmpBitValue=substr($bitValue,($byteNum-$bgnByte)*8,8);
			if($DEBUG) echo "<br>$tmpBitValue=substr($bitValue,($byteNum-$bgnByte)*8,8)";
			$tmpBitValue = strrev($tmpBitValue);
			if($DEBUG) echo "<br>$tmpBitValue = strrev($tmpBitValue)";
			if($DEBUG) echo "<br>bitValue = $bitValue";
			$newBitValue=$newBitValue.$tmpBitValue;
		}

		$catBitLen = $endByte*8+$endBit - ($bgnByte*8 + $bgnBit) + 1; //1 byte = 8 bit
		if($DEBUG) echo "<br>bitValue = substr($newBitValue,$bgnBit,$catBitLen)";
		$bitValue = substr($newBitValue,$bgnBit,$catBitLen);

		
		$bitValue = strrev($bitValue);
		if($DEBUG) echo "<br>bitValue = $bitValue";

	}
		

	//explode by '[v]'
	$valueArr = explode('[v]',$tlvArr[2]);
	$typeAddTitleArr = explode('[t]',$valueArr[0]);
	$operType = chop($typeAddTitleArr[0]);
	$titleStr = chop($typeAddTitleArr[1]);
	$valueArr[1] = chop($valueArr[1]);

	if($DEBUG) echo "<br>operType = $operType";
	switch($operType){
		case 'input'://
			//explode by '-'
			$defArr = explode('-',$valueArr[1]);
			if($DEBUG) echo "<br>defArr = $defArr[0],$defArr[1],$defArr[2]";
			switch($defArr[0]){
				case 'toDec':
					if(strlen($bitValue) > 0){
						$inputValue = BinDec($bitValue);
					}else{
						$inputValue = HexDec($byteValue);
					} 
					break;
				case 'keepDec':
					$inputValue = $byteValue;
					break;
				case 'toHex':
					echo "<br>Error:toHex";
					break;
				case 'keepHex':
					$inputValue = $byteValue;
					break;
				case 'toAscii':
					$charValue = "";
					if($bgnBit > 0 ||$endBit < 7){
						echo "<br>Error:toAscii";
						exit(1);
					}else{
						$tmpLen=strlen($byteValue);
						for($charCount=0;$charCount<$tmpLen;$charCount++){
							$unitByte = substr($byteValue,$charCount,2);
							$unitChar = chr(HexDec($unitByte)); // hex -> ascii
							if($DEBUG) echo "<br>unitChar=$unitChar";
							$charValue .= $unitChar;
							$charCount++;
						}
						$inputValue = $charValue;
						$inputValue = trim($inputValue);//add by oven 2006-8-2 remvove dirty in Mozilla.
					}
					break;
				default: 
					echo "<br>Error:valueType=$defArr[0]";
					break;
			}
			if($DEBUG)echo "<br>inputValue = $inputValue";
			switch($defArr[1]){
				case 'high':
					switch($defArr[2]){
						case '0':
							if($defArr[0] == 'toHex' || $defArr[0] == 'keepHex'){
								//$inputValue = str_replace('0','',$inputValue);
							}else if($defArr[0] == 'toAscii'){
								for($ii=0;$ii<strlen($inputValue);$ii++){
									if($inputValue[$ii]=='0')
										$inputValue[$ii]='';
									else
										break;
								}
							}else{
								$inputValue = $inputValue - 0;
							}
							break;
						case 'E':
							echo "Error:high fill E";
							break;
						default: break;
					}
					break;
				case 'low':
					if ("toAscii" != $defArr[0]) {
						switch($defArr[2]){
							case '0':
								$inputValue = str_replace('00','',$inputValue);
								break;
							case 'E':
								$inputValue = str_replace('E','',$inputValue);
								break;
							default: break;
						}
					}
					break;
				default: break;
			}
			if($DEBUG) echo "<br>$valueType == $nOctStr";
			if($valueType == $nOctStr){
				if($defArr[0] == 'toAscii'){
					$inputLen = $byteLen;
				}elseif($defArr[0] == 'toHex' || $defArr[0] == 'keepHex'){
					$inputLen = $byteLen *2;
				}else{
					$inputLen = $byteLen *3;
				}
				echo "<input type=\"text\" size=\"$inputLen\" maxLength =\"$inputLen\" name=\"$unitName\" value=\"$inputValue\" class=\"text\">";
			}else{
				echo "<input type=\"text\" size=\"8\" name=\"$unitName\" value=\"$inputValue\" onchange=\"checkInt(this)\" class=\"text\">";
				echo "<input type=\"hidden\" name=\"$unitName"."_min\" value=\"$minValue\">";
				echo "<input type=\"hidden\" name=\"$unitName"."_max\" value=\"$maxValue\">";
				echo "<input type=\"hidden\" name=\"$unitName"."_old\" value=\"$inputValue\">";
			}
			break;
		case 'select':
		
			if($valueType == $nOctStr){
				if($bitValue != ''){
					$selectValue = BinDec($bitValue);
	 
				}else{
					$selectValue = HexDec($byteValue);

				}
			}else{
						
				$selectValue=$byteValue;
			}

			if($DEBUG) echo "<br>bitValue = $bitValue";
			if($DEBUG) echo "<br>selectValue = $selectValue";
			if($DEBUG) echo "<br>$valueType =?= $nOctStr(nOctStr)";
			echo "<select size=\"1\" name=\"$unitName\">";
			$isSelected = 0;

			for($j=1;$j<sizeof($valueArr);$j++){
				//explode by '[opt]'
				$defArr = explode('[opt]',$valueArr[$j]);

				
				if(sizeof($defArr) < 2){
					echo "<option value=\"$selectValue\" selected>Reserved Value</option>";
					break;
				}else if($defArr[0] ==  $selectValue){
					echo "<option value=\"$defArr[0]\" selected>$defArr[1]</option>";

					$isSelected = 1;
				}else{
					echo "<option value=\"$defArr[0]\">$defArr[1]</option>";

				}
			}
			
			if($isSelected ==0 && $j == sizeof($valueArr)){
				echo "<option value=\"$selectValue\" selected>Undefined Value</option>";
			}
			echo "</select>";
			break;
		default: echo "<br>Error:operType =|$operType|";
			break;
	}//end of switch(..)
	//like:unitDef_1 = 1.0-2.0-select-keepHex-high-0 -->$tlvArr[1]-$operType-
	
	if($operType == 'select'){ //select
		if($valueType == $nOctStr){
			$tempDef = $tlvArr[1].'-'.$operType.'-'.'toDec-high-0';
		}else{
			$tempDef = $tlvArr[1].'-'.$operType.'-'.'keepDec-high-0';
		}
	}else{
		$tempDef = $tlvArr[1].'-'.$operType.'-'.$valueArr[1];
	}
	$tempDef = str_replace(" ", "", $tempDef);
	$tempDef = chop($tempDef);
	echo "\n <input type=\"hidden\" name=\"unitDef_$i\" value=\"$tempDef\">";
	echo "</td></tr>";
}//end of for(..)

//parmmeter alias
/*
echo "<td>";
echo "Alais:";
echo "<input type=text size=20 name=\"strAlias\" value=\"$strAlias\" class=text>";
echo "</td>";
*/
echo "</table>";

$remark=nl2br($remark);
echo "<br><b>Remarks:</b><br>$remark<br><br>";
$unitNum = $i-1; 
echo "\n<input type=\"hidden\" name=\"unitNum\" value=\"$unitNum\">";
echo "\n<input type=\"hidden\" name=\"inputName\" value=\"$inputName\">";
echo "\n<input type=\"hidden\" name=\"keyId\" value=\"$keyId\">";
echo "\n<input type=\"hidden\" name=\"sysTypeNo\" value=\"$sysTypeNo\">";
echo "\n<input type=\"hidden\" name=\"setValue\" value=\"$setValue\">";
echo "\n<input type=\"hidden\" name=\"TEST\" value=\"$TEST\">";
//echo "\n<input type=\"hidden\" name=\"strAlias\" value=\"$strAlias\">";
echo "\n<input type=\"submit\" name=\"set\" value = \"Set\">";
echo "\n<input type=\"reset\" name=\"Reset\" value =\"Reset\">";
echo "</Form>";

//=======================Test input field========================
if($TEST){
	echo "<Form  method=\"POST\" name=\"testForm\" action=\"$PHP_SELF\">";
	echo "<hr>";
	//--><--// $setValue = strrev($setValue);
	echo "<u><b>Test Area</b></u><br>";
	echo "Test Value:&nbsp;&nbsp;&nbsp;<input type=\"text\" name=\"setValue\" value=\"$setValue\">";
	echo "<input type=\"submit\" name=\"setTest\" value=\"set..\">";
	echo "\n<input type=\"hidden\" name=\"sysTypeNo\" value=\"$sysTypeNo\">";
	echo "\n<input type=\"hidden\" name=\"keyId\" value=\"$keyId\">";
	echo "\n<input type=\"hidden\" name=\"inputName\" value=\"$inputName\">";
	echo "\n<input type=\"hidden\" name=\"TEST\" value=\"$TEST\">";
	echo "</Form>";
}
?>
</body>
</html>
