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

    // FP_SERIES
    int iFieldCount1 = 0;
    String sFieldPairs1[2][100];
    SetArrayItem(sFieldPairs1, iFieldCount1, "FP_STUDY_KEY", 		"");					// 外键
    SetArrayItem(sFieldPairs1, iFieldCount1, "SERIES_KEY", 			"series_key");			// 原主键
    SetArrayItem(sFieldPairs1, iFieldCount1, "SERIES_INSTANCE", 	"series_instance");
    SetArrayItem(sFieldPairs1, iFieldCount1, "SERIES_GUID", 		"series_guid");
    SetArrayItem(sFieldPairs1, iFieldCount1, "SERIES_DTTM", 		"series_dttm");
    SetArrayItem(sFieldPairs1, iFieldCount1, "SERIES_ORDINAL", 		"series_ordinal");
    SetArrayItem(sFieldPairs1, iFieldCount1, "SERIES_BODYPART", 	"series_bodypart");		
    SetArrayItem(sFieldPairs1, iFieldCount1, "SERIES_MODALITYTYPE", "series_modalitytype");	
    SetArrayItem(sFieldPairs1, iFieldCount1, "SERIES_DESCRIPTION", 	"series_description");
    SetArrayItem(sFieldPairs1, iFieldCount1, "SERIES_DIRECTION", 	"series_direction");	
    SetArrayItem(sFieldPairs1, iFieldCount1, "SERIES_THICKNESS", 	"series_thickness");	
    SetArrayItem(sFieldPairs1, iFieldCount1, "SERIES_LAYERS", 		"series_layers");		
    SetArrayItem(sFieldPairs1, iFieldCount1, "SERIES_STATE", 		"series_state");		
    
	// FP_IMAGES
	int iFieldCount2 = 0;
    String sFieldPairs2[2][100];       
    SetArrayItem(sFieldPairs2, iFieldCount2, "FP_STUDY_KEY",		""); 					// 外键
    SetArrayItem(sFieldPairs2, iFieldCount2, "SERIES_KEY",			"series_key"); 			// 原外键
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_KEY",			"image_key"); 			// 原主键
    SetArrayItem(sFieldPairs2, iFieldCount2, "VOLUME_KEY",			""); 					// 存储卷
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_INSTANCE",  	"image_instance");           
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_GUID",    		"image_guid");
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_DTTM",  		"image_dttm");  
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_ORDINAL",   	"image_ordinal");
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_NAME",			"image_name");
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_PATH",			"image_path");
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_FORMAT",		"image_format");
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_KEYMARK",		""); 
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_DELETED",		""); 
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_REPORTINDEX", 	"image_reportindex");
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_FILMINDEX", 	"image_filmindex");
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_ANNOTATION", 	"image_annotation");
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMAGE_STATE", 		"image_staten");
    
    // 打开数据库
    String sFPSeries = "SELECT * FROM FP_SERIES WHERE 0 > 1";
    TADOQuery qryFPSeries = new TADOQuery(nil);
    qryFPSeries.ConnectionString = _hisconnection;
    qryFPSeries.SQL.Text = sFPSeries;
    try
    {
    	qryFPSeries.Open();
    }
    except
    {
    	ShowLog("SyncServer", "打开FP_SERIES表失败！");
    	delete qryFPSeries;
    	return 0;
    }
    ////
    String sFPImage = "SELECT * FROM FP_IMAGES WHERE 0 > 1";
    _qryHisImage.Close();
    _qryHisImage.SQL.Text = sFPImage;
    try
    {
    	_qryHisImage.Open();
    }
    except
    {
    	ShowLog("SyncServer", "打开FP_IMAGES表失败！");
    	return 0;
    }
        
	// 获取传送图像清单
    _qryImage.Close();
    _qryImage.SQL.Text = BuildImagesQuerySQL();
    try
    {
    	_qryImage.Open();
    }
    except
    {
    	ShowLog("SyncServer", "打开IMAGES表失败！");
    	return 0;
    }
    if (_qryImage.IsEmpty())
        return 0;
    
    // 获取传送序列清单
    TADOQuery qrySeries = new TADOQuery(nil);
    qrySeries.ConnectionString = _opacsconnection;
    qrySeries.Close();
    qrySeries.SQL.Text = BuildSeriesQuerySQL();
    try
    {
    	qrySeries.Open();
    }
    except
    {
    	ShowLog("SyncServer", "打开SERIES表失败！");
    	delete qrySeries;
    	return 0;
    }

    // 执行图像传送
    bool bSuccess = true;
    String sSendLog = "";
    ////
    if (!qrySeries.IsEmpty())
    {
    	qrySeries.First();
    	while (!qrySeries.Eof)
    	{
	        String sStudyKey = qrySeries.FieldByName("study_key").AsString;
	        String sFPStudyKey = sHospitalID + _modalitytype + sStudyKey; // !!!
	        ////
	    	qryFPSeries.Append();
	        for (int i = 0; i < iFieldCount1; i++)
	        {
	            if (sFieldPairs1[1][i] == "")
	                continue;              
	            if (!qrySeries.FieldByName(sFieldPairs1[1][i]).IsNull)
	                qryFPSeries.FieldByName(sFieldPairs1[0][i]).Value =
	                	qrySeries.FieldByName(sFieldPairs1[1][i]).Value;
	        }
	        qryFPSeries.FieldByName("FP_STUDY_KEY").Value = sFPStudyKey;
	        ////
	        bSuccess = true;
	        try
	        {
	        	qryFPSeries.Post();
	        }
	        except
	        {
	        	qryFPSeries.Close();
	        	qryFPSeries.Open();
	        	bSuccess = false;
	        }
	        if (bSuccess)
	            sSendLog = "传送序列【" + sStudyKey + "】到目标系统【FP_SERIES】...成功!" ;
	        else
	            sSendLog = "传送序列【" + sStudyKey + "】到目标系统【FP_SERIES】...失败!";
	        ShowLog("SyncServer", sSendLog);
		    if (!bSuccess)
	        {
	            qrySeries.Next();
	            continue;
	        }
	        ////
	        if (bSuccess)
	        {
	            qrySeries.Edit();
	            qrySeries.FieldByName("series_state").Value = 1;
	            qrySeries.Post();
	        }
	        ////
	        qrySeries.Next();
	    }
	}
    ///////////
    _qryImage.First();
    while (!_qryImage.Eof)
    {
        int iVolumeKey = _qryImage.FieldByName("volume_key").AsInteger;
    	String sImagePath = _qryImage.FieldByName("image_path").AsString;
    	String sImageName = _qryImage.FieldByName("image_name").AsString;
    	String sImageFile = sImagePath + "\\" + sImageName; 
        sStudyKey = _qryImage.FieldByName("study_key").AsString;
        ////
        int iDstVolumeKey = GetDstVolumeKey(iVolumeKey); // !!!
        sFPStudyKey = sHospitalID + _modalitytype + sStudyKey; // !!!
        ////
        _qryHisImage.Append();
        for (int j = 0; j < iFieldCount2; j++)
        {
            if (sFieldPairs2[1][j] == "")
                continue;              
            if (!_qryImage.FieldByName(sFieldPairs2[1][j]).IsNull)
                _qryHisImage.FieldByName(sFieldPairs2[0][j]).Value =
                	_qryImage.FieldByName(sFieldPairs2[1][j]).Value;
        }
        _qryHisImage.FieldByName("FP_STUDY_KEY").Value = sFPStudyKey;
        _qryHisImage.FieldByName("VOLUME_KEY").Value = iDstVolumeKey;
        ////
        bSuccess = true;
        try
        {
        	_qryHisImage.Post();
        }
        except
        {
        	_qryHisImage.Close();
        	_qryHisImage.Open();
        	bSuccess = false;
        }
        if (bSuccess)
            sSendLog = "传送图像【" + sImageFile + "】到目标系统【FP_IMAGES】...成功!" ;
        else
            sSendLog = "传送图像【" + sImageFile + "】到目标系统【FP_IMAGES】...失败!";
        ShowLog("SyncServer", sSendLog);
        if (!bSuccess)
        {
            _qryImage.Next();
            continue;
        }
        ////
        if (bSuccess)
        {
            _qryImage.Edit();
            _qryImage.FieldByName("image_state").Value = 1;
            _qryImage.Post();
        }
        ////
        _qryImage.Next();
    }
    ////
    delete qryFPSeries;
    delete qrySeries;
}
//---------------------------------------------------------------------------

String BuildSeriesQuerySQL()
{
    // 构造查询语句
    String sQuerySQL = "";
    sQuerySQL = "select * from series left join study on series.study_key = study.study_key "
    	+ "where study.study_modalitytype='" + _modalitytype + "' and study.patient_state2=1 "
    	+ "and study.report_state=2 and (series.series_state is null or series.series_state=0)";
    ////
    if (IsConnetSQLServer(_opacsconnection))
        sQuerySQL = AccessToSQL(sQuerySQL);
    
    return sQuerySQL;
}
//---------------------------------------------------------------------------

String BuildImagesQuerySQL()
{
    // 构造查询语句
    String sQuerySQL = "";
    sQuerySQL = "select * from images left join study on images.study_key = study.study_key "
		+ "where study.study_modalitytype='" + _modalitytype + "' and study.patient_state2=1 "
		+ "and study.report_state=2 and images.image_reportindex > 0 and "
		+ "(images.image_state is null or images.image_state=0) and "
		+ "images.volume_key in (select volume_key from volume where volume_name = 'SERVER')";
    ////
    if (IsConnetSQLServer(_opacsconnection))
        sQuerySQL = AccessToSQL(sQuerySQL);
    
    return sQuerySQL;
}
//---------------------------------------------------------------------------

int GetVolumeKey(String sVolumeGuid)
{
	String sQuery = "SELECT * FROM VOLUME";
	sQuery = AddWhereCondition(sQuery, "VOLUME_GUID = '" + sVolumeGuid +"'");
	_qryHisCommon.Close();
	_qryHisCommon.SQL.Text = sQuery;
	_qryHisCommon.Open();
    if (_qryHisCommon.IsEmpty())
    	return 0;
	////
	return _qryHisCommon.FieldByName("volume_key").AsInteger;
}
//---------------------------------------------------------------------------

int CreateVolume(String sVolumeGuid, String sVolumeName, String sHostName, String sSharePath, String sLocalPath)
{	
	_qryHisCommon.Close();
	_qryHisCommon.SQL.Text = "SELECT * FROM VOLUME WHERE 0 > 1";
	_qryHisCommon.Open();
	////
	_qryHisCommon.Append();
	_qryHisCommon.FieldByName("volume_guid").Value = sVolumeGuid;
	_qryHisCommon.FieldByName("volume_name").Value = sVolumeName;
	_qryHisCommon.FieldByName("volume_hostname").Value = sHostName;
	_qryHisCommon.FieldByName("volume_imagepath").Value = sSharePath;
	_qryHisCommon.FieldByName("volume_localpath").Value = sLocalPath;
	_qryHisCommon.Post();
	////
	return _qryHisCommon.FieldByName("volume_key").AsInteger;
}
//---------------------------------------------------------------------------

int GetDstVolumeKey(int iSrcVolumeKey)
{
	// 在节点数据库上定位存储卷
	String sQuery = "SELECT * FROM VOLUME";
    sQuery = AddWhereCondition(sQuery, "VOLUME_KEY = " + IntToStr(iSrcVolumeKey));
    _qryCustom.Close();
    _qryCustom.SQL.Text = sQuery;
    _qryCustom.Open();
    if (_qryCustom.IsEmpty())
    	return 0;
    ////	
	String sVolumeGuid = _qryCustom.FieldByName("volume_guid").AsString;
	String sHostName = _qryCustom.FieldByName("volume_hostname").AsString;
	String sSharePath = _qryCustom.FieldByName("volume_imagepath").AsString;
	String sLocalPath = _qryCustom.FieldByName("volume_localpath").AsString;
	////
	if (sVolumeGuid == "")
	{
		sVolumeGuid = CreateGuid();
		_qryCustom.Edit();
		_qryCustom.FieldByName("volume_guid").Value = sVolumeGuid;
		_qryCustom.Post();
	}
	
	// 在中心数据库上定位存储卷
	int iDstVolumeKey = GetVolumeKey(sVolumeGuid);
	if (iDstVolumeKey == 0)
	{
		iDstVolumeKey = CreateVolume(sVolumeGuid, "INTERNAL", sHostName, sSharePath, sLocalPath);
	}
	return iDstVolumeKey;
}
//---------------------------------------------------------------------------

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

