//---------------------------------------------------------------------------
// String _hisconnection; 	约定的输入变量名
// String _opacsconnection; 约定的输入变量名
// String _modalitytype; 	约定的输入变量名
// String _configsection; 	约定的输入变量名
// TADOQuery _qryStudy 	    外部已定义的对象
// TADOQuery _qryReport 	外部已定义的对象
// TADOQuery _qryImage      外部已定义的对象
// TADOQuery _qryCustom     外部已定义的对象
// TADOQuery _qryHisPatient 外部已定义的对象
// TADOQuery _qryHisReport  外部已定义的对象
// TADOQuery _qryHisImage   外部已定义的对象
// TADOQuery _qryHisCommon  外部已定义的对象
// TADOQuery _qryHisCustom  外部已定义的对象
//---------------------------------------------------------------------------
#include "..\\Common\\HisCommon.cpp"

String      _hisconnection;
String      _opacsconnection;
String      _modalitytype;
String 		_configsection;
//---------------------------------------------------------------------------

String BuildQuerySQL()
{
    // 构造查询语句
    String sQuerySQL = "SELECT * FROM VIEW_PATIENT_QUEUE WHERE " +
    	"(SYNCED=0 OR SYNCED IS NULL) ORDER BY QUEUE_NAME, QUEUE_NUMBER";
    ////
    if (IsConnetSQLServer(_hisconnection))
        sQuerySQL = AccessToSQL(sQuerySQL);

    return sQuerySQL;
}
//---------------------------------------------------------------------------

int ExecStudyFetch()
{  
    // 执行数据同步
    int iFieldCount = 0;
    String sFieldPairs[2][100];
    SetArrayItem(sFieldPairs, iFieldCount, "PATIENT_ID",			"patient_guid");
    SetArrayItem(sFieldPairs, iFieldCount, "PATIENT_NAME",			"patient_name");
    SetArrayItem(sFieldPairs, iFieldCount, "PATIENT_NAME_PYCODE",	"patient_name2");
    SetArrayItem(sFieldPairs, iFieldCount, "PATIENT_SEX",			"patient_sex");
    SetArrayItem(sFieldPairs, iFieldCount, "PATIENT_BIRTHDATE",		"patient_birthday");
    SetArrayItem(sFieldPairs, iFieldCount, "EXAM_ITEM_NAME",		"study_examname");
    SetArrayItem(sFieldPairs, iFieldCount, "ACCESSION_NUMBER", 		"study_guid");
    SetArrayItem(sFieldPairs, iFieldCount, "ACCESSION_NUMBER", 		"study_ordinal");
    SetArrayItem(sFieldPairs, iFieldCount, "QUEUE_NAME", 			"study_bodypart");// 为了方便根据QUEUE_NAME设置分诊规则
    SetArrayItem(sFieldPairs, iFieldCount, "QUEUE_NUMBER", 			"login_guid");
    SetArrayItem(sFieldPairs, iFieldCount, "EXAM_MODALITY_TYPE", 	"study_examkind");
    SetArrayItem(sFieldPairs, iFieldCount, "APT_DATETIME", 			"login_bookdttm"); // 为了预约叫号顺序
    SetArrayItem(sFieldPairs, iFieldCount, "APT_DATETIME", 			"login_dttm"); // 为了预约叫号顺序
    SetArrayItem(sFieldPairs, iFieldCount, "APT_DATETIME", 			"study_dttm"); // 为了预约叫号顺序   

    // 打开数据库
    _qryStudy.Close();
    _qryStudy.SQL.Text = "select * from study where 0 > 1";
    try
	{
		_qryStudy.Open();
	}
	except
	{
		ShowLog("SyncServer", "study表打开失败！");
		return 0;
	}
      
    // 获取检查清单
    _qryHisCommon.Close();
    _qryHisCommon.SQL.Text = BuildQuerySQL(); 
    try
	{
		_qryHisCommon.Open();
	}
	except
	{
		ShowLog("SyncServer", "VIEW_PATIENT_QUEUE视图打开失败！");
		return 0;
	} 

    // 数据传送
    bool bSuccess = true;
    String sSendLog = "";
    ////
    _qryHisCommon.First();
    while (!_qryHisCommon.Eof)
    {
    	String sObsID = _qryHisCommon.FieldByName("OBSID").AsString;
    	String sPatientName = _qryHisCommon.FieldByName("PATIENT_NAME").AsString; 
    	////
    	_qryStudy.Append();
    	for (int i = 0; i < iFieldCount; i++)
        {
            if (sFieldPairs[0][i] == "")
                continue;              
            if (sFieldPairs[1][i] == "")
                continue;              
            if (!_qryHisCommon.FieldByName(sFieldPairs[0][i]).IsNull)
                _qryStudy.FieldByName(sFieldPairs[1][i]).Value =
                	_qryHisCommon.FieldByName(sFieldPairs[0][i]).Value;
        }
        _qryStudy.FieldByName("study_modalitytype").Value = _modalitytype;
        if (_qryStudy.FieldByName("login_guid").IsNull)
        	_qryStudy.FieldByName("login_guid").Value = GetLoginGuid(); // 登记号        
        _qryStudy.FieldByName("login_state").Value = 0; // 登记状态 
		if (_qryStudy.FieldByName("patient_birthday").AsFloat < 0)
			_qryStudy.FieldByName("patient_birthday").Value = 0;
        ////
        bSuccess = true;
        try
        {
        	_qryStudy.Post();
        }
        except
        {
            _qryStudy.Close();
            _qryStudy.Open();
            bSuccess = false;
        }
        ////
        if (bSuccess)
            sSendLog = "传送记录【" + sPatientName + "】到目标系统【STUDY】...成功!" ;
        else
            sSendLog = "传送记录【" + sPatientName + "】到目标系统【STUDY】...失败!";
        ShowLog("SyncServer", sSendLog);
        ////
        if (!bSuccess)
        {
            _qryHisCommon.Next();
            continue;
        }
        ////
        if (bSuccess)
        {
        	String sExecSQL = "Select UPDATE_APT_SYNCED ('" + sObsID + "') Return_value from dual ";
        	_qryHisCustom.Close();
        	_qryHisCustom.SQL.Text = sExecSQL;
        	_qryHisCustom.Open();
        	int iResult = _qryHisCustom.FieldByName("Return_value").AsInteger;
        	if (iResult > 0)
        		ShowLog("SyncServer", "更新成功！");
        	else
        		ShowLog("SyncServer", "更新失败！");
        }
        ////
        _qryHisCommon.Next();
    }
}
//---------------------------------------------------------------------------

String GetLoginGuid()
{
	String sQueryNum2 = "select * from system";
	sQueryNum2 = AddWhereCondition(sQueryNum2, "system_modalitytype = '" + _modalitytype + "'");
	sQueryNum2 = AddWhereCondition(sQueryNum2, "Convert(varchar(12), system_today, 112) = "	
		+ "Convert(varchar(12), GetDate(), 112)");
	//// 
	_qryCustom.Close();
	_qryCustom.SQL.Text = sQueryNum2;
	try
	{
		_qryCustom.Open();
	}
	except
	{
		ShowLog("SyncServer", "SYSTEM表打开失败！");
		return "";
	}
	
	int iSystemNum2 = 0;
	if (!_qryCustom.IsEmpty())
	{
		iSystemNum2 = _qryCustom.FieldByName("system_number2").AsInteger;	
	}
	else
	{
		// 解决system表中无当天记录导致序号异常问题
		_qryCustom.Append();
		_qryCustom.FieldByName("system_modalitytype").Value = _modalitytype;
        _qryCustom.FieldByName("system_today").Value = Date();
        _qryCustom.FieldByName("system_number").Value = 0; // study_guid
        _qryCustom.FieldByName("system_number2").Value = 0; // login_guid
        _qryCustom.FieldByName("system_number3").Value = 0; // patient_guid
        _qryCustom.FieldByName("system_number4").Value = 0; // study_ordinal        
        _qryCustom.Post();
	}
	////
	int a[1];
	a[0] = iSystemNum2 + 1;
	String sLoginGuid = Format("%.3d", a);
	////
	_qryCustom.Edit();
	_qrycustom.FieldByName("system_number2").Value = iSystemNum2 + 1;
	_qryCustom.Post();
	
	return sLoginGuid;
}
//---------------------------------------------------------------------------

void ClearUpRecords()
{
	// 查询Study表
	String sQueryStudy = "select * from study where login_state <= 0"; // 预约、等待、排队
	sQueryStudy = AddWhereCondition(sQueryStudy, "study_modalitytype = '" + _modalitytype + "'");
	////
	_qryCustom.Close();
	_qryCustom.SQL.Text = sQueryStudy;
	try
	{
		_qryCustom.Open();
	}
	except
	{
		ShowLog("SyncServer", "STUDY表打开失败！");
		return;
	}
	
	// 查询RIS视图
    String sQueryView = "SELECT * FROM VIEW_PATIENT_QUEUE";
	////
	_qryHisCustom.Close();
	_qryHisCustom.SQL.Text = sQueryView;
	try
	{
		_qryHisCustom.Open();
	}
	except
	{
		ShowLog("SyncServer", "VIEW_PATIENT_QUEUE视图打开失败！");
		return;
	}
	
	// 清除垃圾记录
    _qryCustom.First();
    while (!_qryCustom.Eof) // study
    {
    	String sPatientGuid = _qryCustom.FieldByName("patient_guid").AsString;
    	if (!_qryHisCustom.Locate("PATIENT_ID", sPatientGuid, 0)) // view
		{
			_qryCustom.Edit();
			_qryCustom.FieldByName("login_state").Value = 2; // 已分诊
			_qryCustom.Post();				
		}    		
    	_qryCustom.Next();
	}	
}
//---------------------------------------------------------------------------

// 主程序
{
	try
	{
    	ExecStudyFetch();    	
    	ClearUpRecords();
    }
    except
    {
	}
}
//---------------------------------------------------------------------------