//---------------------------------------------------------------------------
//注意：检查校验脚本在OnBeforePost()事件中执行!
//---------------------------------------------------------------------------
// String _opacsconnection; 	约定的输入变量名
// String _modalitytype; 		约定的输入变量名
// int _number; 				约定的输入变量名：值1为测试模式，0为非测试。
// String _guid; 				约定的输出变量名
// TADOQuery _qryStudy; 		外部已定义的对象
// TADOQuery _qryCustom; 		外部已定义的对象

//---------------------------------------------------------------------------
String _opacsconnection;	
String _modalitytype;
int _number;
String _guid = "";
  	
//---------------------------------------------------------------------------
void ValidStudyInstance()
{
	String sStudyInst = _qryStudy.FieldByName("study_instance").AsString;
	if ( Length( sStudyInst ) > 0 )
	{
		if (_number != 0) // 测试模式
			_guid += "\n study_ordinal=" + sStudyInst; 
		return;
	}
	
	TDateTime dtNow = Now();
	Randomize();
	String sDate = FormatDateTime("yyyymmdd", dtNow);
	int iTime = StrToInt(FormatDateTime("hhnnss", dtNow));
	int dwTick = GetTickCount();
	int dwTickLo = LOWORD(dwTick);
	int dwTickHi = HIWORD(dwTick);
	float rand = Random()*65535;
	int iRand = Round(rand);
	rand = Random()*65535;
	int iKeyLo = Round(rand);

	Variant vtArray[6];
	vtArray[0]=sDate;
	vtArray[1]=iTime;
	vtArray[2]=iRand;
	vtArray[3]=dwTickHi;
	vtArray[4]=dwTickLo;
	vtArray[5]=iKeyLo;
	sStudyInst = Format("1.2.156.27.87582403.%s.%u.%u.%u.%u.%u",vtArray);

	if (_number == 0) // 非测试模式
		_qryStudy.FieldByName("study_instance").Value = sStudyInst;
	else // 测试模式
		_guid = "\n study_instance=" + sStudyInst;	
}
	
//---------------------------------------------------------------------------
void ValidStudyOrdinal()
{
	String sStudyOrdinal = _qryStudy.FieldByName("study_ordinal").AsString;
	if ( Length(sStudyOrdinal) > 0 )
		return;
	
	String sQuery = "";
	sQuery = "select max(study_ordinal) as max_study_ordinal from study " + 
		"where study_modalitytype='" + _modalitytype + "'";
		
	int iStudyOrdinal = 0;		
  	_qryCustom.Close();
  	_qryCustom.SQL.Text = sQuery;
  	try
  	{
  		_qryCustom.Open();
  		iStudyOrdinal = _qryCustom.FieldByName("max_study_ordinal").AsInteger;
  	}
	except
	{
		iStudyOrdinal = 0;    		
	}  	

	if (_number == 0) // 非测试模式
		_qryStudy.FieldByName("study_ordinal").Value = iStudyOrdinal + 1;
	else // 测试模式
		_guid += "\n study_ordinal=" + IntToStr(iStudyOrdinal + 1); 
}

//---------------------------------------------------------------------------
// 主程序
//---------------------------------------------------------------------------
{
	//当表中study_instance为空时，自动填充
  	ValidStudyInstance();
  	
	//当表中study_ordinal为空时，自动填充
  	ValidStudyOrdinal();
}
