//---------------------------------------------------------------------------
// 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;
//---------------------------------------------------------------------------

int ExecReportSend()
{
    // 注意：不同分院上传数据后可能会重号，配合分院标识（前缀）就不会重号！
    String sHospitalID = ""; // 例如：01,02,03..., 请根据现场情况进行配置。

    /* 	FP_STUDY 需特殊处理的字段
    	FP_STUDY_KEY	主键
    	FP_DATA_SOURCE	区域医疗使用
    	HIS_PATIENT_ID	区域医疗使用
    	HIS_REQUEST_ID	区域医疗使用
    	
    	FP_REPORT 需特殊处理的字段
    	FP_STUDY_KEY	外键   
    	REPORT_KEY		原主键           
    	REPORT_TYPE		报告类型（TXT/RTF/JPG/PDF）
    	REPORT_FILE		报告文件（相对存储卷的路径）    
    	VOLUME_KEY		存储卷    
    */
    
    // 打开数据库
    String sFPStudy = "SELECT * FROM FP_STUDY WHERE 0 > 1";
    _qryHisPatient.Close();
    _qryHisPatient.SQL.Text = sFPStudy;
    try
    {
        _qryHisPatient.Open();
    }
    except
    {
    	ShowLog("SyncServer", "打开FP_STUDY表失败！");
        return 0;
    }
    ////
    String sFPReport = "SELECT * FROM FP_REPORT WHERE 0 > 1";
    _qryHisReport.Close();
    _qryHisReport.SQL.Text = sFPReport;
    try
    {
        _qryHisReport.Open();
    }
    except
    {
    	ShowLog("SyncServer", "打开FP_REPORT表失败！");
        return 0;
    }
    
    // 获取检查清单
    _qryStudy.Close();
    _qryStudy.SQL.Text = BuildQuerySQL();
    _qryStudy.Open();               
    
    // 数据传送
    bool bSuccess = true;
    String sSendLog = "";
    ////
    _qryStudy.First();
    while (!_qryStudy.Eof)
    {
    	String sStudyKey = _qryStudy.FieldByName("study_key").AsString;
        String sPatientName = _qryStudy.FieldByName("patient_name").AsString;
        String sFPStudyKey = sHospitalID + _modalitytype + sStudyKey; // !!!
        ////
        try
        {
        	DeleteFPImages(sFPStudyKey);
        	DeleteFPSeries(sFPStudyKey);
            DeleteFPReport(sFPStudyKey);
            DeleteFPStudy(sFPStudyKey);
        }
        except
        {
            ShowLog("SyncServer", "删除数据失败！");
        }
        ////
        _qryHisPatient.Append();
       
        for (int i = 0; i < _qryStudy.FieldCount; i ++)
        {
        	String sFieldName = _qryStudy.Fields.Fields[i].FieldName;
        	if (FindField(_qryHisPatient, sFieldName))
        	{
        		_qryHisPatient.FieldByName(sFieldName).Value =
                	_qryStudy.FieldByName(sFieldName).Value;	
        	} 
    	}
        _qryHisPatient.FieldByName("FP_STUDY_KEY").Value = sFPStudyKey;
        //_qryHisPatient.FieldByName("FP_DATA_SOURCE").Value = sHospitalID;
        ////
        bSuccess = true;
        try
        {                      
            _qryHisPatient.Post();
        }
        except
        {
            _qryHisPatient.Close();
            _qryHisPatient.Open();
            bSuccess = false;
        }
        if (bSuccess)
            sSendLog = "传送报告【" + sPatientName + " " + sFPStudyKey + "】到目标系统【FP_STUDY】...成功!" ;
        else
            sSendLog = "传送报告【" + sPatientName + " " + sFPStudyKey + "】到目标系统【FP_STUDY】...失败!";
        ShowLog("SyncServer", sSendLog);
        if (!bSuccess)
        {
            _qryStudy.Next();
            continue;
        }
        ////////////////////////////////////////////////////////////////////////
        _qryHisReport.Append();
        for (int j = 0; j < _qryStudy.FieldCount; j ++)
        {
        	sFieldName = _qryStudy.Fields.Fields[j].FieldName;
        	if (FindField(_qryHisReport, sFieldName))
        	{
        		_qryHisReport.FieldByName(sFieldName).Value =
                	_qryStudy.FieldByName(sFieldName).Value;	
        	} 
    	}
        _qryHisReport.FieldByName("FP_STUDY_KEY").Value = sFPStudyKey;
        ////
        
        // 传子报告
        _qryReport.Close();   
        _qryReport.SQL.Text = "select * from report where study_key = " + sStudyKey; 
        _qryReport.Open();  
        while (!_qryReport.Eof)
        {
			_qryHisReport.Append();
	        for (j = 0; j < _qryReport.FieldCount; j ++)
	        {
	        	sFieldName = _qryReport.Fields.Fields[j].FieldName;
	        	if (FindField(_qryHisReport, sFieldName))
	        	{
	        		_qryHisReport.FieldByName(sFieldName).Value =
	                	_qryReport.FieldByName(sFieldName).Value;	
	        	} 
	    	}
	        _qryHisReport.FieldByName("FP_STUDY_KEY").Value = sFPStudyKey;        	
        	_qryReport.Next();
        }
          
        bSuccess = true;
        try
        {
            _qryHisReport.Post();
        }
        except
        {
            _qryHisReport.Close();
            _qryHisReport.Open();
            bSuccess = false;
        }
        if (bSuccess)
            sSendLog = "传送报告【" + sPatientName + " " + sFPStudyKey + "】到目标系统【FP_REPORT】...成功!" ;
        else
            sSendLog = "传送报告【" + sPatientName + " " + sFPStudyKey + "】到目标系统【FP_REPORT】...失败!";
        ShowLog("SyncServer", sSendLog);
        if (!bSuccess)
        {
            _qryStudy.Next();
            continue;
        }
        ////
        if (bSuccess)
        {
            _qryCustom.Close();  // 绕过审核权限管理
            _qryCustom.SQL.Text = "update study set patient_state2 = 1 where study_key = " + sStudyKey;
            _qryCustom.ExecSQL();
        }
        _qryStudy.Next();
    }
}
//---------------------------------------------------------------------------

String BuildQuerySQL()
{
    // 构造查询语句
    String sQuerySQL = "select top 100 * from study";
    sQuerySQL = AddWhereCondition(sQuerySQL, "study_modalitytype='" + _modalitytype + "'");
    sQuerySQL = AddWhereCondition(sQuerySQL, "(patient_state2 is null or patient_state2=0)");
    sQuerySQL = AddWhereCondition(sQuerySQL, "report_state=2");
    ////
    if (IsConnetSQLServer(_opacsconnection))
        sQuerySQL = AccessToSQL(sQuerySQL);

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

void DeleteFPStudy(String sFPStudyKey)
{
	String sQuery = "DELETE FROM FP_STUDY WHERE FP_STUDY_KEY = '" + sFPStudyKey + "'"; 
	_qryHisCommon.Close();
    _qryHisCommon.SQL.Text = sQuery;
    _qryHisCommon.ExecSQL();
}
//---------------------------------------------------------------------------

void DeleteFPSeries(String sFPStudyKey)
{
	String sQuery = "DELETE FROM FP_SERIES WHERE FP_STUDY_KEY = '" + sFPStudyKey + "'"; 
	_qryHisCommon.Close();
    _qryHisCommon.SQL.Text = sQuery;
    _qryHisCommon.ExecSQL();
}
//---------------------------------------------------------------------------

void DeleteFPImages(String sFPStudyKey)
{
	String sQuery = "DELETE FROM FP_IMAGES WHERE FP_STUDY_KEY = '" + sFPStudyKey + "'"; 
	_qryHisCommon.Close();
    _qryHisCommon.SQL.Text = sQuery;
    _qryHisCommon.ExecSQL();
}
//---------------------------------------------------------------------------

void DeleteFPReport(String sFPStudyKey)
{
	String sQuery = "DELETE FROM FP_REPORT WHERE FP_STUDY_KEY = '" + sFPStudyKey + "'"; 
	_qryHisCommon.Close();
    _qryHisCommon.SQL.Text = sQuery;
    _qryHisCommon.ExecSQL();
}
//---------------------------------------------------------------------------

int GetRptVolumeKey()
{
	String sVolumeSQL = "SELECT * FROM VOLUME WHERE VOLUME_NAME = 'REPORT'";
	_qryHisCommon.Close();
	_qryHisCommon.SQL.Text = sVolumeSQL;
	_qryHisCommon.Open();
	int iVolumeKey = 0;
	if (!_qryHisCommon.IsEmpty())
		iVolumeKey = _qryHisCommon.FieldByName("volume_key").AsInteger;
	return iVolumeKey;
}
//---------------------------------------------------------------------------

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

