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

//---------------------------------------------------------------------------
String _opacsconnection;	
String _modalitytype;
int _number;
String _guid = "";
  	
//---------------------------------------------------------------------------
String GetSimpleGuid(int number)
{
 	Variant a[2];
  	a[0] = FormatDateTime("yyyymmdd", Now());
  	a[1] = number + 1;
  	String sStudyGuid = Format("%s%.3d", a);
  	return sStudyGuid;
}

//---------------------------------------------------------------------------
String GetStudydttmGuid()
{
	String sDate = FormatDateTime( "yyyymmdd", _qryStudy.FieldByName("study_dttm").AsDateTime );
	String sQuery = "select max(convert(int,right(study_guid,3))) as MaxNum from study " +
		"where study_guid like '"+ sDate + "%'" +
		"and study_modalitytype='" + _modalitytype + "'";
	////
	int iMaxNum = 0;
  	_qryCustom.Close();
  	_qryCustom.SQL.Text = sQuery;
	try
	{
		_qryCustom.Open();
	  	iMaxNum = _qryCustom.FieldByName("MaxNum").AsInteger;
	}
	except
	{
		ShowMessage("自动编号出错");
	}
	////
 	Variant a[2];
  	a[0] = sDate;
  	a[1] = iMaxNum + 1;
  	String sStudyGuid = Format("%s%.3d", a);
  	return sStudyGuid;
}

//---------------------------------------------------------------------------
String GetYearGuid()
{
	// 根据安装情况，下面的连接和查询字符串可能需要修改。
	String sQuery = "select max(study_guid) as max_study_guid from study " + 
		"where ISNUMERIC(study_guid)=1 and LEN(study_guid)=8 " + 
		"and LEFT(study_guid, 2)=RIGHT(YEAR(GETDATE()),2) " + 
		"and study_modalitytype='" + _modalitytype + "'";
	////
	String sMaxGuid = "";
	String sStudyGuid = "09000001";
  	_qryCustom.Close();
  	_qryCustom.SQL.Text = sQuery;
	try
	{
	  	_qryCustom.Open();
	  	sMaxGuid = _qryCustom.FieldByName("max_study_guid").AsString;
	  	if (sMaxGuid == "")
	  	{
	  		String sYear = FormatDateTime("yy", Now());
	    	sStudyGuid = sYear + "000001";
		}
		else
		{
			int iStudyGuid = StrToInt(Trim(sMaxGuid)) + 1;
		  	Variant a[1];
			a[0] = iStudyGuid;
			sStudyGuid = Format("%.8d", a);	
		}
	}
	except
	{
		ShowMessage(sMaxGuid + "是错误的检查号！请立即手工纠正！");   
	}
  	////
    return sStudyGuid;
}

//---------------------------------------------------------------------------
// 主程序 
//---------------------------------------------------------------------------
{
  	String sToday = FormatDateTime("yyyymmdd", Now());
  	String sStudyDay = FormatDateTime("yyyymmdd", _qryStudy.FieldByName("study_dttm").AsDateTime );
	
	_guid = GetStudydttmGuid();  	
}
