//---------------------------------------------------------------------------
// 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", "..\\Common\\JWCommon.cpp"

//---------------------------------------------------------------------------
// 自定义变量
int g_iExamNoType = 0;
String g_sLocalIDClass = "";
String g_sExamNoSequence = "";
String g_sPatientIDField = "";

//---------------------------------------------------------------------------
int ExecReportSend()
{
	// 初始化参数
	g_iExamNoType = 1; // 取值范围：0,1, 请根据现场情况修改!!!
	g_sLocalIDClass = ""; // 取值范围: 一个字符，g_iExamNoType = 0时配置。
	g_sExamNoSequence = ""; // 取值范围：序列名称，g_iExamNoType = 1时配置。
	//g_sPatientIDField = "patient_guid"; // 超声等科室使用，请根据情况配置。
	g_sPatientIDField = "study_guid"; // 放射等科室使用，请根据情况配置。

	// 设置默认值	
	if (g_sLocalIDClass == "")
		g_sLocalIDClass = Copy(_modalitytype, 1, 1); // U,E,G,X,N,W...
	if (g_sExamNoSequence == "")
		g_sExamNoSequence = "EXAM_NO_SEQ"; 		
		
    // 执行报告传送
    int iFieldCount1 = 0;
    String sFieldPairs1[2][100];
    SetArrayItem(sFieldPairs1, iFieldCount1, "EXAM_NO",           "");            	// 申请序号
    SetArrayItem(sFieldPairs1, iFieldCount1, "LOCAL_ID_CLASS",    "");            	// 检查号类别
    SetArrayItem(sFieldPairs1, iFieldCount1, "PATIENT_LOCAL_ID",  ""); 				// 检查标识号
    SetArrayItem(sFieldPairs1, iFieldCount1, "PATIENT_ID",        "");			  	// 病人标识号
    SetArrayItem(sFieldPairs1, iFieldCount1, "VISIT_ID",          "");            	// 病人本次住院标识：1第一次
    SetArrayItem(sFieldPairs1, iFieldCount1, "NAME",              "patient_name");	// 姓名
    SetArrayItem(sFieldPairs1, iFieldCount1, "SEX",               "patient_sex"); 	// 性别
    SetArrayItem(sFieldPairs1, iFieldCount1, "DATE_OF_BIRTH",     "patient_birthday"); // 出生日期
    SetArrayItem(sFieldPairs1, iFieldCount1, "EXAM_CLASS",        "study_modalitytype"); // 检查类别
    SetArrayItem(sFieldPairs1, iFieldCount1, "EXAM_SUB_CLASS",    "study_examkind");// 检查子类
    SetArrayItem(sFieldPairs1, iFieldCount1, "SPM_RECVED_DATE",   "login_dttm");  	// 标本收到日期及时间
    SetArrayItem(sFieldPairs1, iFieldCount1, "CLIN_SYMP",         "");            	// 临床症状
    SetArrayItem(sFieldPairs1, iFieldCount1, "PHYS_SIGN",         "");            	// 体征
    SetArrayItem(sFieldPairs1, iFieldCount1, "RELEVANT_LAB_TEST", "");            	// 相关化验结果
    SetArrayItem(sFieldPairs1, iFieldCount1, "RELEVANT_DIAG",     "");            	// 其他诊断
    SetArrayItem(sFieldPairs1, iFieldCount1, "CLIN_DIAG",         "study_clinicinfo"); // 临床诊断
    SetArrayItem(sFieldPairs1, iFieldCount1, "EXAM_MODE",         "");            	// 检查方式
    SetArrayItem(sFieldPairs1, iFieldCount1, "EXAM_GROUP",        "");            	// 检查分组
    SetArrayItem(sFieldPairs1, iFieldCount1, "DEVICE",            "study_modalityname");// 使用仪器
    SetArrayItem(sFieldPairs1, iFieldCount1, "PERFORMED_BY",      "");            	// 执行科室：311203彩超,311204B超
    SetArrayItem(sFieldPairs1, iFieldCount1, "PATIENT_SOURCE",    "");            	// 病人来源：1门诊 2住院 3外来
    SetArrayItem(sFieldPairs1, iFieldCount1, "FACILITY",          "");            	// 外来医疗单位名称
    SetArrayItem(sFieldPairs1, iFieldCount1, "REQ_DATE_TIME",     "study_dttm");  	// 申请日期及时间
    SetArrayItem(sFieldPairs1, iFieldCount1, "REQ_DEPT",          "");            	// 申请科室
    SetArrayItem(sFieldPairs1, iFieldCount1, "REQ_PHYSICIAN",     "study_applicant"); // 申请医生
    SetArrayItem(sFieldPairs1, iFieldCount1, "REQ_MEMO",          "");            	// 申请备注
    SetArrayItem(sFieldPairs1, iFieldCount1, "SCHEDULED_DATE_TIME", "study_dttm");	// 预约日期及时间
    SetArrayItem(sFieldPairs1, iFieldCount1, "NOTICE",            "");            	// 注意事项
    SetArrayItem(sFieldPairs1, iFieldCount1, "EXAM_DATE_TIME",    "study_dttm");  	// 检查日期及时间
    SetArrayItem(sFieldPairs1, iFieldCount1, "REPORT_DATE_TIME",  "report_dttm"); 	// 报告日期及时间
    SetArrayItem(sFieldPairs1, iFieldCount1, "TECHNICIAN",        "study_technician"); // 操作者
    SetArrayItem(sFieldPairs1, iFieldCount1, "REPORTER",          "report_diagnostician");// 报告者
    SetArrayItem(sFieldPairs1, iFieldCount1, "RESULT_STATUS",     "");            	// 检查结果状态：3初步报告,4确认报告
    SetArrayItem(sFieldPairs1, iFieldCount1, "COSTS",             "study_cost");  	// 费用
    SetArrayItem(sFieldPairs1, iFieldCount1, "CHARGES",           "study_charge");	// 应收费用
    SetArrayItem(sFieldPairs1, iFieldCount1, "CHARGE_INDICATOR",  "");            	// 计价标志
    ////
    int iFieldCount2 = 0;
    String sFieldPairs2[2][100];
    SetArrayItem(sFieldPairs2, iFieldCount2, "EXAM_NO",         "");                // 申请序号
    SetArrayItem(sFieldPairs2, iFieldCount2, "EXAM_PARA",       "");                // 检查参数
    SetArrayItem(sFieldPairs2, iFieldCount2, "DESCRIPTION",     "report_finding");  // 检查所见
    SetArrayItem(sFieldPairs2, iFieldCount2, "IMPRESSION",      "report_diagnosis");// 影像
    SetArrayItem(sFieldPairs2, iFieldCount2, "RECOMMENDATION",  "");                // 建议
    SetArrayItem(sFieldPairs2, iFieldCount2, "IS_ABNORMAL",     "report_positive"); // 是否阳性（1阳性，其它阴性）
    SetArrayItem(sFieldPairs2, iFieldCount2, "USE_IMAGE",       "");                // 报告中图像编号
    SetArrayItem(sFieldPairs2, iFieldCount2, "MEMO",            "report_memoinfo"); // 备注
    
    // 打开数据库
    String sHisMaster = "SELECT * FROM EXAM_MASTER WHERE 0 > 1";
    _qryHisPatient.Close();
    _qryHisPatient.SQL.Text = sHisMaster;
    try
    {
        _qryHisPatient.Open();
    }
    except
    {
    	ShowLog("SyncServer", "打开EXAM_MASTER表失败！");
        return 0;
    }
    ////
    String sHisReport = "SELECT * FROM EXAM_REPORT WHERE 0 > 1";
    _qryHisReport.Close();
    _qryHisReport.SQL.Text = sHisReport;
    try
    {
        _qryHisReport.Open();
    }
    except
    {
    	ShowLog("SyncServer", "打开EXAM_REPORT表失败！");
        return 0;
    }

    // 获取检查清单
    _qryStudy.Close();
    _qryStudy.SQL.Text = BuildQuerySQL();
    _qryStudy.Open(); 
        
    // 数据传送
    bool bSuccess = true;
    String sSendLog = "";
    String sLoginDepartment = GetConfigStr("SysLogon", "sLastDepartment");
    String sPerformer = GetDeptCode(sLoginDepartment);    
    ////
    _qryStudy.First();
    while (!_qryStudy.Eof)
    {
        String sExamNo = _qryStudy.FieldByName("study_number0").AsString; // 申请单号
        String sPatientGuid = _qryStudy.FieldByName(g_sPatientIDField).AsString;
        String sPatientName = _qryStudy.FieldByName("patient_name").AsString;
        String sStudyDepartment = _qryStudy.FieldByName("study_department").AsString;
        String sStudySource = _qryStudy.FieldByName("study_source").AsString;
        String sStudyInstance = _qryStudy.FieldByName("study_instance").AsString;
		String sStudyOrdinal = _qryStudy.FieldByName("study_ordinal").AsString;        
        String sStudyKey = _qryStudy.FieldByName("study_key").AsString;
    	if (g_iExamNoType == 0)
    	{
    		// 由RIS来定义申请单号
    		sExamNo = g_sLocalIDClass + sStudyKey;
    	}
    	else if (sExamNo == "")
    	{
    		// 由HIS来定义申请单号
    		_qryHisCommon.Close();
		    _qryHisCommon.SQL.Text = "SELECT " + g_sExamNoSequence + ".NEXTVAL AS NewExamNo FROM DUAL";
		    _qryHisCommon.Open();
    		sExamNo = _qryHisCommon.FieldByName("NewExamNo").AsString;
    	}
    	if (sExamNo != "")
    	{
			_qryCustom.Close();  // 绕过审核权限管理
			_qryCustom.SQL.Text = "update study set study_number0 = '" + sExamNo + 
				"' where study_key = " + sStudyKey;
			_qryCustom.ExecSQL();
		}
		if (sStudyInstance == "")
		{
			sStudyInstance = CreateDicomGuid(StrToInt(sStudyKey));
			_qryCustom.Close();  // 绕过审核权限管理
			_qryCustom.SQL.Text = "update study set study_instance = '" + sStudyInstance +
				"' where study_key = " + sStudyKey;
			_qryCustom.ExecSQL();
		}
		if (sStudyOrdinal == "")
		{
			sStudyOrdinal = sStudyKey;
			_qryCustom.Close();  // 绕过审核权限管理
			_qryCustom.SQL.Text = "update study set study_ordinal = " + sStudyOrdinal +
				" where study_key = " + sStudyKey;
			_qryCustom.ExecSQL();
		}
        ////
        _qryHisPatient.Close();
        _qryHisPatient.SQL.Text = "SELECT * FROM EXAM_MASTER WHERE EXAM_NO = '" + sExamNo + "'";
        _qryHisPatient.Open();
        if (_qryHisPatient.IsEmpty())
        {
        	ShowLog("SyncServer", "准备新增EXAM_MASTER表...");
	        _qryHisPatient.Append();
        }  
        else
        {
        	ShowLog("SyncServer", "准备修改EXAM_MASTER表...");
        	_qryHisPatient.Edit(); 
        }
        ////
        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;
        }   
        ////
        _qryHisPatient.FieldByName("EXAM_NO").Value = sExamNo; // !!!
        _qryHisPatient.FieldByName("LOCAL_ID_CLASS").Value = g_sLocalIDClass;
        _qryHisPatient.FieldByName("PATIENT_LOCAL_ID").Value = sStudyOrdinal;
        _qryHisPatient.FieldByName("STUDY_UID").Value = sStudyInstance; // !!!
        _qryHisPatient.FieldByName("PATIENT_ID").Value = sPatientGuid;    
        _qryHisPatient.FieldByName("VISIT_ID").Value = GetMaxVisitID(sPatientGuid);    
        if (sStudySource == "门诊")
            _qryHisPatient.FieldByName("PATIENT_SOURCE").Value = 1;
        else if (sStudySource == "住院")
            _qryHisPatient.FieldByName("PATIENT_SOURCE").Value = 2;
        else
            _qryHisPatient.FieldByName("PATIENT_SOURCE").Value = 3;
        _qryHisPatient.FieldByName("REQ_DEPT").Value = GetDeptCode(sStudyDepartment);
        _qryHisPatient.FieldByName("PERFORMED_BY").Value = sPerformer;
        _qryHisPatient.FieldByName("RESULT_STATUS").Value = 3; // 3初步报告,4最终报告 
        ////
        bSuccess = true;
        try
        {     
            _qryHisPatient.Post();
        }
        except
        {
            bSuccess = false;
        }
        if (bSuccess)
            sSendLog = "传送报告【" + sPatientName + " " + sExamNo + "】到目标系统【EXAM_MASTER】...成功!";
        else
            sSendLog = "传送报告【" + sPatientName + " " + sExamNo + "】到目标系统【EXAM_MASTER】...失败!";
        ShowLog("SyncServer", sSendLog);
        if (!bSuccess)
        {
            _qryStudy.Next();
            continue;
        }
        ////////////////////////////////////////////////////////////////////////
        _qryHisReport.Close();
        _qryHisReport.SQL.Text = "SELECT * FROM EXAM_REPORT WHERE EXAM_NO = '" + sExamNo + "'";;
        _qryHisReport.Open();
        if (_qryHisReport.IsEmpty())
        {
        	ShowLog("SyncServer", "准备新增EXAM_REPORT表...");        	
	        _qryHisReport.Append();
        }  
        else
        {
        	ShowLog("SyncServer", "准备修改EXAM_REPORT表...");        	
        	_qryHisReport.Edit(); 
        }
        ////
        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;
        }
        _qryHisReport.FieldByName("EXAM_NO").Value = sExamNo; // 必须填写！
        ////
        bSuccess = true;
        try
        {
            _qryHisReport.Post();
        }
        except
        {
            bSuccess = false;
        }
        if (bSuccess)
            sSendLog = "传送报告【" + sPatientName + " " + sExamNo + "】到目标系统【EXAM_REPORT】...成功!";
        else
            sSendLog = "传送报告【" + sPatientName + " " + sExamNo + "】到目标系统【EXAM_REPORT】...失败!";
        ShowLog("SyncServer", sSendLog);
        if (!bSuccess)
        {
            _qryStudy.Next();
            continue;
        }
        ////
        if (bSuccess)
        {
            _qryCustom.Close();  // 绕过审核权限管理
            _qryCustom.SQL.Text = "update study set patient_state = 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_state is null or patient_state=0)");
    sQuerySQL = AddWhereCondition(sQuerySQL, "report_state=2");
    ////
    if (IsConnetSQLServer(_opacsconnection))
        sQuerySQL = AccessToSQL(sQuerySQL);

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

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

