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

//---------------------------------------------------------------------------
String _opacsconnection;	
String _modalitytype;
int _number;
String _guid = "";

//---------------------------------------------------------------------------
int GetNewMedRecID()
{
	// 根据安装情况，下面的连接和查询字符串可能需要修改。
	String sRisConnection = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=eRadMiniPacs"; 
	String sRisQuery = "select MedRecID from study where ExamineID= (select max(ExamineID) from study where ISNUMERIC(MedRecID)=1)";
	int iMedRecID = 0;
	////
  	TADOQuery qryRisCustom = new TADOQuery(nil);
  	qryRisCustom.ConnectionString = sRisConnection; 
  	qryRisCustom.SQL.Text = sRisQuery;
  	qryRisCustom.Open();
  	if (!qryRisCustom.Bof || !qryRisCustom.Eof)
	    iMedRecID = qryRisCustom.FieldByName("MedRecID").AsInteger + 1;
  	delete qryRisCustom;
  	////
    return iMedRecID;
}

//---------------------------------------------------------------------------
int GetNewPatientGuid()
{
	// 根据安装情况，下面的连接和查询字符串可能需要修改。
	String sConnection = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=opacs"; 
	String sQuery = "select patient_guid from study where study_guid= (select max(study_guid) from study where ISNUMERIC(patient_guid)=1 and study_modalitytype='US')";
	int iPatientGuid = 0;
	////
  	TADOQuery qryCustom = new TADOQuery(nil);
  	qryCustom.ConnectionString = sConnection; 
  	qryCustom.SQL.Text = sQuery;
  	qryCustom.Open();
  	if (!qryCustom.Bof || !qryCustom.Eof)
    	iPatientGuid = qryCustom.FieldByName("patient__guid").AsInteger + 1;
  	delete qryCustom;
  	////
    return iPatientGuid;
}

//---------------------------------------------------------------------------
// 主程序：生成RIS病历号
//---------------------------------------------------------------------------
{
	int iMedRecID = GetNewMedRecID();
	int iPatientGuid = GetNewPatientGuid();
  	Variant a[1];
  	if (iPatientGuid > iMedRecID)
  		a[0] = iPatientGuid;
  	else
  		a[0] = iMedRecID; 
  	_guid = Format("%.6d", a);
}
