//---------------------------------------------------------------------------
// 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 top 100 * from study";
    sQuerySQL = AddWhereCondition(sQuerySQL, "study_modalitytype='" + _modalitytype + "'");
    sQuerySQL = AddWhereCondition(sQuerySQL, "(patient_state is null or patient_state=0)");  // 未传送
    //sQuerySQL = AddWhereCondition(sQuerySQL, "login_state=2");  // 已分诊
    sQuerySQL = AddWhereCondition(sQuerySQL, "login_ordinal in (2, 8)");
    ////
    if (IsConnetSQLServer(_hisconnection))
        sQuerySQL = AccessToSQL(sQuerySQL);

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

int ExecStudySend()
{
	//  Patient表对应字段
    int iFieldCount1 = 0;
    String sFieldPairs1[2][100];
    SetArrayItem(sFieldPairs1, iFieldCount1, "PatientName",		"login_extinfo1"); // from"AQ检查Fetch.cpp"
    SetArrayItem(sFieldPairs1, iFieldCount1, "ChineseName",		"patient_name");
    SetArrayItem(sFieldPairs1, iFieldCount1, "PatientSex",		"patient_sex");
    SetArrayItem(sFieldPairs1, iFieldCount1, "Birthdate",		"patient_birthday");
    
    // Study表对应字段
    int iFieldCount2 = 0;
    String sFieldPairs2[2][100];
    SetArrayItem(sFieldPairs2, iFieldCount2, "InPatientNo",		"study_number2"); // 住院号
    SetArrayItem(sFieldPairs2, iFieldCount2, "BedNo",			"study_number3"); // 病床号
    SetArrayItem(sFieldPairs2, iFieldCount2, "StayInsu",		"patient_type"); // 病人类型
    //SetArrayItem(sFieldPairs2, iFieldCount2, "ExamineRoom",		"study_examkind");
    //SetArrayItem(sFieldPairs2, iFieldCount2, "ExamineType",		"study_examkind");
   
	SetArrayItem(sFieldPairs2, iFieldCount2, "Register",		"login_registrar");
    SetArrayItem(sFieldPairs2, iFieldCount2, "RegTime",			"login_dttm");
    SetArrayItem(sFieldPairs2, iFieldCount2, "ReqOffice",		"study_department");
    SetArrayItem(sFieldPairs2, iFieldCount2, "StudyDateTime",	"study_dttm");
    SetArrayItem(sFieldPairs2, iFieldCount2, "Height",			"patient_height");
    SetArrayItem(sFieldPairs2, iFieldCount2, "Weight",			"patient_weight");
    
    // 打开数据库
    String sHisPatient = "SELECT * FROM PATIENT WHERE 0 > 1";
    _qryHisPatient.Close();
    _qryHisPatient.SQL.Text = sHisPatient;
    try
    {
        _qryHisPatient.Open();
    }
    except
    {
        return 0;
    }
    ////
    String sHisStudy = "SELECT * FROM STUDY WHERE 0 > 1";
    _qryHisReport.Close();
    _qryHisReport.SQL.Text = sHisStudy;
    try
    {
        _qryHisReport.Open();
    }
    except
    {
        return 0;
    }
    
    // 获取检查清单
    _qryStudy.Close();
    _qryStudy.SQL.Text = BuildQuerySQL();
    _qryStudy.Open(); 
    
    // 数据传送
    bool bSuccess = true;
    String sSendLog = "";
    ////
    _qryStudy.First();
    while (!_qryStudy.Eof)
    {
    	String sPatientGuid = _qryStudy.FieldByName("patient_guid").AsString;
    	String sStudyGuid = _qryStudy.FieldByName("study_guid").AsString;
    	String sStudyAge = _qryStudy.FieldByName("patient_studyage").AsString;
    	TDateTime dtStudy = _qryStudy.FieldByName("study_dttm").AsDateTime;
    	TDateTime dtBirthday = _qryStudy.FieldByName("patient_birthday").AsDateTime;
    	
    	String sAgeUnit = "";
    	int iStudyAge = 0;
    	if ((sStudyAge == "") || IsNumString(sStudyAge))
    	{
    		if (dtStudy != NULL && dtBirthday != NULL)
    		{
    			sStudyAge = CalcStudyAge(dtBirthday, dtStudy);
    		}
    	}	

    	if (sStudyAge != "")
    	{
 			sStudyAge=Trim(sStudyAge);
    		sAgeUnit = Copy(sStudyAge, Length(sStudyAge)-1, 2);
    		iStudyAge = StrToInt(Copy(sStudyAge, 1, Length(sStudyAge)-2));
	    }

    	String sBodyPart = "";
    	String sExamKind = _qryStudy.FieldByName("study_examkind").AsString;
    	// convert " " to "|"
    	if (sExamKind != "")
    		sBodyPart = ReplaceCommaText(sExamKind, "|");
    	
    	// 插入Patient表记录
		bool bAppendPatient = false;
    	if (FindPatient(sPatientGuid) > 0)
    	{
    		_qryHisPatient.Edit();
    	}
    	else
    	{
        	// 说明：如果病历号为空，则计算RIS病历号，否则复制病历号到RIS系统。
    		if (sPatientGuid == "")
    		{
            	int iMedRecID = GetNewMedRecID();
            	sPatientGuid = IntToStr(iMedRecID);
    		}
    		////
    		bAppendPatient = true;
    		_qryHisPatient.Append();
    	}  	
        for (int i = 0; i < iFieldCount1; i++)
        {
            if (sFieldPairs1[1][i] == "")
                continue;        
            if (!_qryStudy.FieldByName(sFieldPairs1[1][i]).IsNull())
                _qryHisPatient.FieldByName(sFieldPairs1[0][i]).Value =
                	_qryStudy.FieldByName(sFieldPairs1[1][i]).Value;
        }     
        if (bAppendPatient) // 注：MedRecID不可重复插入
			_qryHisPatient.FieldByName("MedRecID").Value = sPatientGuid; // 患者编号
        ////
        bSuccess = true;
        try
        {
        	_qryHisPatient.Post();
        }
        except
        {
        	_qryHisPatient.Close();
        	_qryHisPatient.Open();
        	bSuccess = false;
        }
        if (bSuccess)
        	sSendLog = "传送记录【" + sPatientGuid + "】到目标系统【PATIENT】...成功!";
        else
        	sSendLog = "传送记录【" + sPatientGuid + "】到目标系统【PATIENT】...失败!";
        ShowLog("SyncServer", sSendLog);
        ////
        if (!bSuccess)
        {
        	_qryStudy.Next();
        	continue;
        }
		//---------------------------------------------------------------------------     
        // 插入Study表记录
        bool bAppendStudy = false;
        if (FindStudy(sStudyGuid) > 0)
        {
        	_qryHisReport.Edit();
        }
        else
        {
        	// 说明：如果检查号为空，则计算RIS检查号，否则复制检查号到RIS系统。
    		if (sStudyGuid == "")
    		{
	            int iExamineID = GetNewExamineID();
	            sStudyGuid = IntToStr(iExamineID);
    		}
    		////
    		bAppendStudy = true;
        	_qryHisReport.Append();
        }
         
        for (int j = 0; j < iFieldCount2; j++)
        {
            if (sFieldPairs2[1][j] == "")
                continue;              
            if (!_qryStudy.FieldByName(sFieldPairs2[1][j]).IsNull())
                _qryHisReport.FieldByName(sFieldPairs2[0][j]).Value =
                	_qryStudy.FieldByName(sFieldPairs2[1][j]).Value;
            else if (sFieldPairs2[1][j] == "patient_height")
            	_qryHisReport.FieldByName(sFieldPairs2[0][j]).Value = "0";
            else if (sFieldPairs2[1][j] == "patient_weight")
            	_qryHisReport.FieldByName(sFieldPairs2[0][j]).Value = "0";
        }
        _qryHisReport.FieldByName("MedRecID").Value = sPatientGuid; // 患者编号
        _qryHisReport.FieldByName("ImgRecID").Value = sPatientGuid; // 影像号
        _qryHisReport.FieldByName("ExamineID").Value = sStudyGuid; // 检查序号
        _qryHisReport.FieldByName("AccessionNumber").Value = "e" + sStudyGuid;
        _qryHisReport.FieldByName("Age").Value = iStudyAge;	// 病人年龄
        _qryHisReport.FieldByName("AgeUnit").Value = sAgeUnit; // 年龄单位
        _qryHisReport.FieldByName("ExamineItem").Value = "普通摄片"; // 检查项目
        _qryHisReport.FieldByName("BodyPartExamined").Value = sBodyPart; // 检查部位
        _qryHisReport.FieldByName("State").Value = 0; // RIS检查状态 SCHEDULED
        _qryHisReport.FieldByName("ExamineType").Value = "CR";
        _qryHisReport.FieldByName("ExamineRoom").Value = "CR" ;
        ////
        bSuccess = true;
        try
        {
        	_qryHisReport.Post();
        }
        except
        {
        	_qryHisReport.Close();
        	_qryHisReport.Open();
        	bSuccess = false;
        }
        if (bSuccess)
        	sSendLog = "传送记录【" + sStudyGuid + "】到目标系统【STUDY】...成功!";
        else
        	sSendLog = "传送记录【" + sStudyGuid + "】到目标系统【STUDY】...失败!";
        ShowLog("SyncServer", sSendLog);
        ////
        if (!bSuccess)
        {
        	_qryStudy.Next();
        	continue;
        }
        if (bSuccess && bAppendStudy)
        {
    		// 填写ProcessDisposeInfo
    		String sHisQuery = "select * from ProcessDisposeInfo where 0 > 1";
        	_qryHisCommon.Close();
        	_qryHisCommon.SQL.Text = sHisQuery;
        	try
        	{
        		_qryHisCommon.Open();
        	}
        	except
        	{
        		sSendLog = "【ProcessDisposeInfo】表打开失败！";
        		ShowLog("SyncServer", sSendLog);
        		return;
        	}
        	////
        	_qryHisCommon.Append();
        	_qryHisCommon.FieldByName("ExamineID").Value = sStudyGuid;
        	_qryHisCommon.FieldByName("ShootStart").Value = Now();
        	////
        	bSuccess = true;
        	try
        	{
        		_qryHisCommon.Post();
        	}
        	except
        	{
        		_qryHisCommon.Close();
        		_qryHisCommon.Open();
        		bSuccess = false;
        	}
        	if (bSuccess)
        		sSendLog = "传送记录【" + sStudyGuid + "】到目标系统【ProcessDisposeInfo】成功！";
        	else
        		sSendLog = "传送记录【" + sStudyGuid + "】到目标系统【ProcessDisposeInfo】失败！";        		      		
        	ShowLog("SyncServer", sSendLog);
        	////
        	if (bSuccess)
        	{
	            String sStudyKey = _qryStudy.FieldByName("study_key").AsString;
	            _qryCustom.Close();  // 绕过审核权限管理
	            _qryCustom.SQL.Text = "update study set patient_state = 1 where study_key = " + sStudyKey;
	            _qryCustom.ExecSQL();
        	}
        }
        ////
    	_qryStudy.Next();
	}
}
//---------------------------------------------------------------------------

int GetNewMedRecID()
{
	String sHisQuery = "select MedRecID from study where ExamineID=" + 
		"(select max(ExamineID) from study where ISNUMERIC(MedRecID)=1)";
    _qryHisCommon.Close();
    _qryHisCommon.SQL.Text = sHisQuery;
    _qryHisCommon.Open();
    ////
    int iMedRecID = _qryHisCommon.FieldByName("MedRecID").AsInteger + 1;
    
    return iMedRecID;
}
//---------------------------------------------------------------------------

int GetNewExamineID()
{
	String sHisQuery = "select MAX(ExamineID) examid from study";
    _qryHisCommon.Close();
    _qryHisCommon.SQL.Text = sHisQuery;
    _qryHisCommon.Open();
    ////
    int iExamineID = _qryHisCommon.FieldByName("examid").AsInteger + 1;
    
    return iExamineID;
}
//---------------------------------------------------------------------------

int FindPatient(String sMedRecID)
{
	String sHisQuery = "";
	if (sMedRecID == "")
		sHisQuery = "select * from patient where 0 > 1";
	else
		sHisQuery = "select * from patient where MedRecID='" + sMedRecID + "'";
	////
	_qryHisCommon.Close();
	_qryHisCommon.SQL.Text = sHisQuery;
	_qryHisCommon.Open();
	
	return GetRecordCount(_qryHisCommon);
}
//---------------------------------------------------------------------------

int FindStudy(String sExamineID)
{
	String sHisQuery = "";
	if (sHisQuery == "")
		sHisQuery = "select * from study where 0 > 1";
	else
		sHisQuery = "select * from study where ExamineID='" + sExamineID + "'";
	////
	_qryHisCommon.Close();
	_qryHisCommon.SQL.Text = sHisQuery;
	_qryHisCommon.Open();
	
	return GetRecordCount(_qryHisCommon);
}
//---------------------------------------------------------------------------

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