//---------------------------------------------------------------------------
// String _opacsconnection; 约定的输入变量名
// String _hisconnection; 	约定的输入变量名   
// String _modalitytype; 	约定的输入变量名
// bool _ischarging; 		约定的输入变量名
// TADOQuery _qryStudy 	 	外部已定义的对象
// TADOQuery _qryCustom	 	外部已定义的对象
// TADOQuery _qryPriceList  外部已定义的对象
// TADOQuery _qryPriceCombo 外部已定义的对象
// TADOQuery _qryBillDetail 外部已定义的对象
// TADOQuery _qryHisCustom  外部已定义的对象
// TADOQuery _qryHisCommon  外部已定义的对象
//
// 脚本必须实现的函数 int _CanCharging();
// 脚本必须实现的函数 double _CalcSpareMoney();
// 脚本必须实现的函数 double _InitCharging();
// 脚本必须实现的函数 int _FillPriceList(); 	
// 脚本必须实现的函数 int _FillPriceCombo(); 	
// 脚本必须实现的函数 double _AppendBillCombo();
// 脚本必须实现的函数 double _AppendBillDetail();
// 脚本必须实现的函数 double _DeleteBillDetail();
// 脚本必须实现的函数 double _ClearBillDetail();
// 脚本必须实现的函数 int _CommitCharging();
// 脚本必须实现的函数 int _RefundCharging();
//---------------------------------------------------------------------------

#include "..\\Common\\HisCommon.cpp", "..\\Common\\LZCommon.cpp"

//String    _opacsconnection;
//String    _hisconnection;
//String 	_modalitytype;
bool 		_ischarging;

//---------------------------------------------------------------------------
// 自定义变量
String g_sBillDetail = "";		// 收费明细表表名
int g_iRefundRecordCount = 0; 	// 退费初始记录数

//---------------------------------------------------------------------------
// 是否可以执行计费划价：1 成功，0 失败
//---------------------------------------------------------------------------
int _CanCharging()
{
	if (_ischarging) // 收费
	{
		/*
			1.非住院病人不允许划价收费
			2.预约病人不允许划价收费
			3.patient_guid（BRXH）为空时不允许划价收费
			4.patient_guid（BRXH）值可以转换为NUMBER(10)类型
			5.study_number0（JCDXH）为空时不允许划价收费
			6.study_number0（JCDXH）值可以转换为NUMBER(10)类型
			7.已退费病人不允许划价收费
			8.已撤销申请单的病人不允许划价收费
		*/
		String sStudySource = _qryStudy.FieldByName("study_source").AsString;
		float fPatientGuid = _qryStudy.FieldByName("patient_guid").Value;
		float fStudyNumber0 = _qryStudy.FieldByName("study_number0").Value;
		int iLoginState = _qryStudy.FieldByName("login_state").AsInteger;
	  	if (sStudySource == "住院")
	    {                           
	        if (iLoginState == -2)
	        {
	        	MessageBox("预约病人不允许执行收费退费！", "电子申请单", 1);
	            return 0;
	        } 
	        if (FloatToStr(fPatientGuid) == "")
	        {
	        	MessageBox("不允许执行收费退费！", "电子申请单", 1);
	            return 0;            
	        }   
	        if (!IsNumString(FloatToStr(fPatientGuid)))
	        {
	        	MessageBox("不允许执行收费退费！", "电子申请单", 1);
	            return 0;            
	        }      
	        if (FloatToStr(fStudyNumber0) == "")
	        {
	        	MessageBox("不允许执行收费退费！", "电子申请单", 1);
	            return 0;            
	        }  
	        if (!IsNumString(FloatToStr(fStudyNumber0)))
	        {
	        	MessageBox("不允许执行收费退费！", "电子申请单", 1);
	            return 0;            
	        } 
	        if (PatsIsRefund(fStudyNumber0))
	        {
	        	MessageBox("该病人已退费！不允许执行收费退费！", "电子申请单", 1);
	            return 0;            
	        }
	        if (PatsIsCancel(fStudyNumber0))
	        {
	        	MessageBox("该病人已撤销申请单！不允许执行收费退费！", "电子申请单", 1);
	            return 0;            
	        }        
	            
			return 1;
	    }
		else
	    {
	    	MessageBox("不允许执行收费退费！", "电子申请单", 1);
	        return 0;            
	    }
	}
	else
	{
		MessageBox("不允许退费操作！", "电子申请单", 1);
		return 0;
	}
}

//---------------------------------------------------------------------------
// 填充CC_PriceList价格表
//---------------------------------------------------------------------------
int _FillPriceList()
{
	_qryPriceList.Close();
	_qryPriceList.SQL.Text = "DELETE FROM CC_PRICELIST";
	_qryPriceList.ExecSQL();
	_qryPriceList.SQL.Text = "SELECT * FROM CC_PRICELIST";
	_qryPriceList.Open();
	////
	String sHisQuery = "";
	int iFieldCount = 0;
    String sFieldPairs[2][100];
    SetArrayItem(sFieldPairs, iFieldCount, "price_examkind",	"SFXM");
    SetArrayItem(sFieldPairs, iFieldCount, "price_examname", 	"YLMC");
    SetArrayItem(sFieldPairs, iFieldCount, "price_examcost", 	"DJ");
    SetArrayItem(sFieldPairs, iFieldCount, "price_itemcode", 	"YLXH");
    SetArrayItem(sFieldPairs, iFieldCount, "price_inputcode", 	"SRM1");
    SetArrayItem(sFieldPairs, iFieldCount, "price_itemunit", 	"DW");
    //SetArrayItem(sFieldPairs, iFieldCount, "price_itemspec", 	"");
    ////
    if (IsConnetAccessDB(_hisconnection))
    {
	     // 测试语句：适用于ACCESS数据库
	     /*sHisQuery = "SELECT a.YLXH, a.YLMC, a.DJ, a.DW, a.SRM1, b.SL "+
	      "FROM GY_YLSF a, YZ_CHARGE b WHERE a.YLXH = b.YLXH "+
	      "UNION ALL SELECT c.YLXH, c.YLMC, c.DJ, c.DW, c.SRM1,d.SL*e.SL AS SL "+
	      "FROM GY_YLSF c, YZ_CHARGE d, GY_YLSFTC e WHERE c.YLXH = e.YLXH AND d.YLXH = e.GLXH";
	     sHisQuery = "SELECT DISTINCT YLXH, YLMC, DJ, DW, SRM1 FROM (" + sHisQuery + ")";*/
	     
	 	sHisQuery = "select distinct SFXM, YLMC, DJ, YLXH, SRM1, DW from zjhis.GY_YLSF " +
	 		"where ZYSY=1 and (TCPB=0 or TCPB is null) and (ZFPB=0 or ZFPB is null)";
	 }
	 else
	 {
	 	/*
	    sHisQuery = "SELECT a.YLXH, a.YLMC, a.DJ, a.DW, a.SRM1, b.SL "+
	      "FROM zjhis.GY_YLSF a, zjhis.YZ_CHARGE b WHERE a.YLXH = b.YLXH "+
	      "union all SELECT c.YLXH, c.YLMC, c.DJ, c.DW, c.SRM1, d.SL*e.SL AS SL "+
	      "FROM zjhis.GY_YLSF c, zjhis.YZ_CHARGE d, zjhis.GY_YLSFTC e "+
	      "WHERE c.YLXH = e.YLXH AND d.YLXH = e.GLXH ";
	  	sHisQuery = "SELECT DISTINCT YLXH, YLMC, DJ, DW, SRM1 FROM (" + sHisQuery + ")";
	  	*/
	  	
	 	sHisQuery = "select distinct SFXM, YLMC, DJ, YLXH, SRM1, DW from zjhis.GY_YLSF " +
	 		"where ZYSY=1 and (TCPB=0 or TCPB is null) and (ZFPB=0 or ZFPB is null)";
	 }	
    _qryHisCustom.Close();
  	_qryHisCustom.SQL.Text = sHisQuery;
  	try
  	{
  		_qryHisCustom.Open();
  	}
  	except
  	{
        ShowMessage("价目表查询失败！");
        return 0;
  	}
    ////
  	if (!_qryHisCustom.IsEmpty())
    {
        _qryHisCustom.First();
        while (!_qryHisCustom.Eof)
        {
            _qryPriceList.Append();
            for (int i = 0; i < iFieldCount; i++)
            {
                if (!_qryHisCustom.FieldByName(sFieldPairs[1][i]).IsNull)
                    _qryPriceList.FieldByName(sFieldPairs[0][i]).Value =
                        _qryHisCustom.FieldByName(sFieldPairs[1][i]).Value;
            }
            _qryPriceList.Post();
            _qryHisCustom.Next();
        }
        ////
	    _qryPriceList.First();
	}
	
	MessageBox("更新价目表成功！", "电子申请单",1);
    return 1;
}

//---------------------------------------------------------------------------
// 填充CC_PriceCombo套餐价格表
//---------------------------------------------------------------------------
int _FillPriceCombo()
{
	// 不支持套餐
	return 1;
	
	_qryPriceCombo.Close();
	_qryPriceCombo.SQL.Text = "DELETE FROM CC_PRICECOMBO";
	_qryPriceCombo.ExecSQL();
	_qryPriceCombo.SQL.Text = "SELECT * FROM CC_PRICECOMBO";
	_qryPriceCombo.Open();
	////
    int iFieldCount = 0;
    String sFieldPairs[2][100];
    SetArrayItem(sFieldPairs, iFieldCount, "COMBO_EXAMKIND", 	"b.SFXM");
    SetArrayItem(sFieldPairs, iFieldCount, "COMBO_EXAMNAME", 	"b.YLMC");
    SetArrayItem(sFieldPairs, iFieldCount, "COMBO_ITEMCODE", 	"a.YLXH");
    SetArrayItem(sFieldPairs, iFieldCount, "COMBO_INPUTCODE", 	"a.SL");
	////
    String sHisQuery = "select * from gy_ylsftc a, zjhis.GY_YLSF b " +
    	" where a.GLXH = b.YLXH and b.ZYSY=1 and b.TCPB=1";
    _qryHisCustom.Close();
  	_qryHisCustom.SQL.Text = sHisQuery;
  	try
  	{
  		_qryHisCustom.Open();
  	}
  	except
    {
        ShowMessage("套餐价目表查询失败！");
        return 0;
    }
    ////
  	if (!_qryHisCustom.IsEmpty())
    {
        _qryPriceCombo.First();
        while (!_qryHisCustom.Eof)
        {
            _qryPriceCombo.Append();
            for (int i = 0; i < iFieldCount; i++)
            {
                if (!_qryHisCustom.FieldByName(sFieldPairs[1][i]).IsNull)
                    _qryPriceCombo.FieldByName(sFieldPairs[0][i]).Value =
                        _qryHisCustom.FieldByName(sFieldPairs[1][i]).Value;
            }
            _qryPriceCombo.Post();
            _qryHisCustom.Next();
        }
        ////
	    _qryPriceCombo.First();
	}
	MessageBox("更新套餐价目表成功！", "电子申请单",1);
	return 1;
}

//---------------------------------------------------------------------------
// 计算本次检查后余额
//---------------------------------------------------------------------------
double _CalcSpareMoney()
{
    float fPatientGuid = _qryStudy.FieldByName("patient_guid").Value;
	double fStudyCharge = _qryStudy.FieldByName("study_charge").AsFloat;
    double fTotalExamCharge = CalcTotalExamCharge(_qryBillDetail);
    double fSpaceMoney = CalcSpaceMoney(fPatientGuid);
    double fResult = fSpaceMoney - (fStudyCharge + fTotalExamCharge);
    return fResult;
}

//---------------------------------------------------------------------------
// 初始化计费信息
//---------------------------------------------------------------------------
double _InitCharging()
{
	g_sBillDetail = GetTableNameByIP("CC_BILLDETAIL");
	return _CalcSpareMoney(); // 不支持退费操作！
	////
    float fPatientGuid = _qryStudy.FieldByName("patient_guid").Value;
    float fStudyNumber0 = _qryStudy.FieldByName("study_number0").Value;
    String sSystemType = GetSystemType(fStudyNumber0);
    String sRequester = GetKDKSCode(fStudyNumber0);
    String sPerformer = GetZXKSCode(fStudyNumber0);
    String sLoginDoctor = GetConfigStr("SysLogon", "sLastAccounts");
    String sOperator = GetUserID(sLoginDoctor);
    double fSpaceMoney = CalcSpaceMoney(fPatientGuid);
    double fStudyCharge = _qryStudy.FieldByName("study_charge").AsFloat;
    bool bPatsIsCharging = PatsIsCharging(fStudyNumber0, fPatientGuid);
	////
    if (!_ischarging)	// 初始化退费清单
	{	    
    	String sHisQuery = "select a.YLXH, a.AMOUNT, b.SFXM, b.YLMC, b.DW, b.DJ, b.SRM1 " +
    		"from YZ_ORDER_YLSF a, GY_YLSF b, YZ_JCSQXM c " +
    		"where c.XIANGMUXH = a.ORDER_CODE and a.YLXH = b.YLXH";
		sHisQuery = AddWhereCondition(sHisQuery, "c.JCDXH =" + FloatToStr(fStudyNumber0));  	
		_qryHisCustom.Close();
		_qryHisCustom.SQL.Text = sHisQuery;
		_qryHisCustom.Open();
		////
		if (!bPatsIsCharging)
		{
			if (_qryHisCustom.IsEmpty())
			{
				return fSpaceMoney - fStudyCharge;
			}
			
			// 由HIS开出的申请单项目
			_qryHisCustom.First();
		    while (!_qryHisCustom.Eof)
		    {
		    	float fExamCost = _qryHisCustom.FieldByName("DJ").AsFloat;
		    	int iAmount = _qryHisCustom.FieldByName("AMOUNT").AsInteger;
		    	////
		        _qryBillDetail.Append();
		        _qryBillDetail.FieldByName("bill_patientid").Value = fPatientGuid;
                _qryBillDetail.FieldByName("bill_visitid").Value = fStudyNumber0;
		        _qryBillDetail.FieldByName("bill_itemno").Value = GetRecordCount(_qryBillDetail) + 1;
		        _qryBillDetail.FieldByName("bill_examkind").Value =  _qryHisCustom.FieldByName("SFXM").AsString;
		        _qryBillDetail.FieldByName("bill_examname").Value =  _qryHisCustom.FieldByName("YLMC").AsString;
		        _qryBillDetail.FieldByName("bill_amount").Value = iAmount;
		        _qryBillDetail.FieldByName("bill_examcost").Value = fExamCost;
		        _qryBillDetail.FieldByName("bill_examcharge").Value = fExamCost * iAmount;
		        _qryBillDetail.FieldByName("bill_itemcode").Value = _qryHisCustom.FieldByName("YLXH").AsString;
		        _qryBillDetail.FieldByName("bill_itemunit").Value = _qryHisCustom.FieldByName("DW").AsString;
		        _qryBillDetail.FieldByName("bill_datetime").Value = Now();
			    _qryBillDetail.FieldByName("bill_requester").Value = sRequester;
		        _qryBillDetail.FieldByName("bill_performer").Value = sPerformer;
		        _qryBillDetail.FieldByName("bill_operator").Value = sOperator;
		        _qryBillDetail.Post();
		        ////
		        _qryHisCustom.Next();
		    }
		}
		else
		{
			// OPACS修改后的申请单项目
			sHisQuery = "select * from GY_CHARGE_INTERFACE";
	        sHisQuery = AddWhereCondition(sHisQuery, "JCDXH=" + FloatToStr(fStudyNumber0));
	        sHisQuery = AddWhereCondition(sHisQuery, "PATIENTNO=" + FloatToStr(fPatientGuid));
	        sHisQuery = AddWhereCondition(sHisQuery, "SYSTEMTYPE='" + sSystemType + "'");
	        _qryHisCustom.Close();
	        _qryHisCustom.SQL.Text = sHisQuery;
	        _qryHisCustom.Open();
	        ////
	        TADOQuery qryHisExamInfo = new TADOQuery(nil);
	        qryHisExamInfo.ConnectionString = _hisconnection;   
	        ////
	        _qryHisCustom.First();
	        while (!_qryHisCustom.Eof)
	        {
	        	String sHisChargeCode = _qryHisCustom.FieldByName("CHARGECODE").AsString;
	            String sHisChargeName = _qryHisCustom.FieldByName("CHARGENAME").AsString;
	            int iHisAmount = _qryHisCustom.FieldByName("AMOUNT").AsInteger;
	            double fHisPrice = _qryHisCustom.FieldByName("PRICE").AsFloat;
	            double fHisFee = _qryHisCustom.FieldByName("FEE").AsFloat;
	            TDateTime dtHisCharge = _qryHisCustom.FieldByName("CHARGEDATE").AsDateTime;
		        ////
		        if (iHisAmount > 0)
		        {
		        	String sHisExamInfo = "select sum(AMOUNT) as SUMAMOUNT from GY_CHARGE_INTERFACE";
		        	sHisExamInfo = AddWhereCondition(sHisExamInfo, "JCDXH=" + FloatToStr(fStudyNumber0));
		        	sHisExamInfo = AddWhereCondition(sHisExamInfo, "PATIENTNO=" + FloatToStr(fPatientGuid));
		        	sHisExamInfo = AddWhereCondition(sHisExamInfo, "SYSTEMTYPE='" + sSystemType + "'");
		        	sHisExamInfo = AddWhereCondition(sHisExamInfo, "CHARGECODE=" + sHisChargeCode);
		        	sHisExamInfo = AddWhereCondition(sHisExamInfo, "CHARGENAME='" + sHisChargeName + "'");
		        	qryHisExamInfo.Close();
		        	qryHisExamInfo.SQL.Text = sHisExamInfo;
		        	qryHisExamInfo.Open();
		        	////
		        	int iSumAmount = qryHisExamInfo.FieldByName("SUMAMOUNT").AsInteger;
		        	if (iSumAmount > 0)
		        	{
		        		String sBillExamInfo = "select * from " + g_sBillDetail;
	                    sBillExamInfo = AddWhereCondition(sBillExamInfo, "bill_itemcode='" + sHisChargeCode + "'");
	                    sBillExamInfo = AddWhereCondition(sBillExamInfo, "bill_examname='" + sHisChargeName + "'");
		        		_qryBillDetail.Close();
	                    _qryBillDetail.SQL.Text = sBillExamInfo;  
	                    _qryBillDetail.Open();	
	                    ////
	                    if (_qryBillDetail.IsEmpty())
	                    {
	                    	_qryBillDetail.Append();
					        _qryBillDetail.FieldByName("bill_patientid").Value = fPatientGuid;
			                _qryBillDetail.FieldByName("bill_visitid").Value = fStudyNumber0;
					        _qryBillDetail.FieldByName("bill_itemno").Value = GetRecordCount(_qryBillDetail) + 1;
					        _qryBillDetail.FieldByName("bill_examname").Value = sHisChargeName;
					        _qryBillDetail.FieldByName("bill_amount").Value = iSumAmount; 
					        _qryBillDetail.FieldByName("bill_examcost").Value = fHisPrice;
					        _qryBillDetail.FieldByName("bill_examcharge").Value = fHisFee;
					        _qryBillDetail.FieldByName("bill_itemcode").Value = sHisChargeCode; 
					        _qryBillDetail.FieldByName("bill_itemunit").Value = "";
					        _qryBillDetail.FieldByName("bill_datetime").Value = dtHisCharge;
						    _qryBillDetail.FieldByName("bill_requester").Value = sRequester;
					        _qryBillDetail.FieldByName("bill_performer").Value = sPerformer;
					        _qryBillDetail.FieldByName("bill_operator").Value = sOperator;
					        _qryBillDetail.Post();
	                    }
		        	}
		        }	
	        	////
	        	_qryHisCustom.Next();
	    	}
	    	////
	    	delete qryHisExamInfo;
		}
    }
    ////
    _qryBillDetail.Close();
    _qryBillDetail.SQL.Text = "SELECT * FROM " + g_sBillDetail;
    _qryBillDetail.Open();
    ////
	if (!_ischarging)
	{
		g_iRefundRecordCount = GetRecordCount(_qryBillDetail);
	}
    ////
    return _CalcSpareMoney();
}

//---------------------------------------------------------------------------
// 增加CC_BillDetail表记录，增加单项
//---------------------------------------------------------------------------
double _AppendBillDetail()
{
    float fPatientGuid = _qryStudy.FieldByName("patient_guid").Value;
	float fStudyNumber0 = _qryStudy.FieldByName("study_number0").Value;
	    
    // 开单科室代码
    String sRequester = GetKDKSCode(fStudyNumber0);	
    
	// 执行科室代码
    String sPerformer = GetZXKSCode(fStudyNumber0);	
    
    // 操作者
    String sLoginDoctor = GetConfigStr("SysLogon", "sLastAccounts");
    String sOperator = GetUserID(sLoginDoctor);
    
    float fExamCost = _qryPriceList.FieldByName("price_examcost").AsFloat;
    float fExamCharge = _qryPriceList.FieldByName("price_examcost").AsFloat;
    
    int iRecordCount = GetRecordCount(_qryBillDetail);
    
    String sPriceExamName = _qryPriceList.FieldByName("price_examname").AsString;
    String sPriceItemCode = _qryPriceList.FieldByName("price_itemcode").AsString;

    // 添加收费记录
    String sQuery = "SELECT * FROM " + g_sBillDetail;
    sQuery = AddWhereCondition(sQuery, "BILL_EXAMNAME = '" + sPriceExamName + "'");
    sQuery = AddWhereCondition(sQuery, "BILL_ITEMCODE = '" + sPriceItemCode + "'");
    _qryBillDetail.Close();
    _qryBillDetail.SQL.Text = sQuery;
    _qryBillDetail.Open();
	if (_qryBillDetail.IsEmpty())
	{
        // 添加新收费记录
        int iNewItemNo = iRecordCount + 1;
        
	    _qryBillDetail.Append();
	    _qryBillDetail.FieldByName("bill_patientid").Value = fPatientGuid;
	    _qryBillDetail.FieldByName("bill_visitid").Value = fStudyNumber0;
	    _qryBillDetail.FieldByName("bill_itemno").Value = iNewItemNo;
	    _qryBillDetail.FieldByName("bill_examkind").Value = _qryPriceList.FieldByName("price_examkind").AsString;
	    _qryBillDetail.FieldByName("bill_examname").Value = _qryPriceList.FieldByName("price_examname").AsString;
	    _qryBillDetail.FieldByName("bill_examcost").Value = _qryPriceList.FieldByName("price_examcost").AsFloat;
	    _qryBillDetail.FieldByName("bill_examcharge").Value = _qryPriceList.FieldByName("price_examcost").AsFloat; 
	    _qryBillDetail.FieldByName("bill_itemcode").Value = _qryPriceList.FieldByName("price_itemcode").AsString;
	    _qryBillDetail.FieldByName("bill_itemspec").Value = _qryPriceList.FieldByName("price_itemspec").AsString;
	    _qryBillDetail.FieldByName("bill_itemunit").Value = _qryPriceList.FieldByName("price_itemunit").AsString;
	    _qryBillDetail.FieldByName("bill_amount").Value = 1;
	    _qryBillDetail.FieldByName("bill_datetime").Value = Now();
	    _qryBillDetail.FieldByName("bill_requester").Value = sRequester;
	    _qryBillDetail.FieldByName("bill_performer").Value = sPerformer;
	    _qryBillDetail.FieldByName("bill_operator").Value = sOperator;
	    _qryBillDetail.Post();
	}
    else
    {
    	int iAmount = _qryBillDetail.FieldByName("bill_amount").AsInteger;
    	
    	// 添加已有收费项目    	
    	_qryBillDetail.Edit();
    	_qryBillDetail.FieldByName("bill_amount").Value = iAmount + 1;
    	_qryBillDetail.FieldByName("bill_examcharge").Value = fExamCharge * (iAmount + 1);
    	_qryBillDetail.FieldByName("bill_examcost").Value = fExamCost * (iAmount + 1);
    	_qryBillDetail.FieldByName("bill_datetime").Value = Now();
	    _qryBillDetail.FieldByName("bill_requester").Value = sRequester;
	    _qryBillDetail.FieldByName("bill_performer").Value = sPerformer;
	    _qryBillDetail.FieldByName("bill_operator").Value = sOperator;
    	_qryBillDetail.Post();
	}
	////
	_qryBillDetail.Close();
	_qryBillDetail.SQL.Text = "SELECT * FROM " + g_sBillDetail;
	_qryBillDetail.Open();
	
    return _CalcSpareMoney();
}

//---------------------------------------------------------------------------
// 增加CC_BillDetail表记录，增加套餐
//---------------------------------------------------------------------------
double _AppendBillCombo()
{
	// Nothing need to do.
}

//---------------------------------------------------------------------------
// 删除CC_BillDetail表记录
//---------------------------------------------------------------------------
double _DeleteBillDetail()
{
	if (_ischarging) // 删除收费项目
	{
		_qryBillDetail.Delete();
	}
/*	不支持退费功能！
	else // 删除退费项目
	{
		String sPatientGuid = _qryStudy.FieldByName("patient_guid").AsString;
		String sStudyNumber0 = _qryStudy.FieldByName("study_number0").Astring;
		
		int iAmount = _qryBillDetail.FieldByName("bill_amount").AsInteger;
	    String sVisitID = _qryBillDetail.FieldByName("bill_visitid").AsString;
		String sItemCode = _qryBillDetail.FieldByName("bill_itemcode").AsString;
		String sItemName = _qryBillDetail.FieldByName("bill_examname").AsString;
		String sItemClass = _qryBillDetail.FieldByName("bill_examkind").AsString;
		String sExamName = _qryBillDetail.FieldByName("bill_examname").AsString;
		double fExamCost = _qryBillDetail.FieldByName("bill_examcost").AsFloat;
		double fExamCharge = _qryBillDetail.FieldByName("bill_examcharge").AsFloat;
		String sItemSpec = _qryBillDetail.FieldByName("bill_itemspec").AsString;
		String sItemUnit = _qryBillDetail.FieldByName("bill_itemunit").AsString;
		int iCurrItemNo = _qryBillDetail.FieldByName("bill_itemno").AsInteger;
		
		String sRequester = GetKDKSCode(sStudyNumber0);
		String sPerformer = GetZXKSCode(sStudyNumber0);
	    String sLoginDoctor = GetConfigStr("SysLogon", "sLastAccounts");
	    String sOperator = GetUserID(sLoginDoctor);
		////
		TADOQuery qryTempBill = new TADOQuery(nil);
		qryTempBill.ConnectionString = _opacsconnection;
		String sBillQuery = "SELECT SUM(bill_amount) AS SUMCOUNT, MAX(bill_itemno) AS MAXITEMNO FROM " + g_sBillDetail;
        sBillQuery = AddWhereCondition(sBillQuery, "bill_itemcode = '" + sItemCode + "'");
        sBillQuery = AddWhereCondition(sBillQuery, "bill_examname = '" + sItemName + "'");
        sBillQuery = AddWhereCondition(sBillQuery, "bill_patientid = '" + sPatientGuid + "'");
        sBillQuery = AddWhereCondition(sBillQuery, "bill_visitid = '" + sVisitID + "'");
		qryTempBill.Close();
		qryTempBill.SQL.Text = sBillQuery;
		qryTempBill.Open();
		////
		int iSumAmount = qryTempBill.FieldByName("SUMCOUNT").AsInteger;
		int iCurrMaxItemNo = qryTempBill.FieldByName("MAXITEMNO").AsInteger;
		if ((iSumAmount <= 0) || (iAmount <= 0)))
		{
			MessageBox("该项目不能进行退费！", "电子申请单", 1);
		}
		else
		{
			// 退费项目，插入一条负记录
			_qryBillDetail.Append();
			_qryBillDetail.FieldByName("bill_patientid").Value = sPatientGuid;
		    _qryBillDetail.FieldByName("bill_visitid").Value = sVisitID;
		    _qryBillDetail.FieldByName("bill_itemno").Value = iNewItemNo;
		    _qryBillDetail.FieldByName("bill_examkind").Value = sItemClass;
		    _qryBillDetail.FieldByName("bill_examname").Value = sItemName;
		    _qryBillDetail.FieldByName("bill_examcost").Value = -1 * fExamCost;
		    _qryBillDetail.FieldByName("bill_examcharge").Value = -1 * fExamCharge; 
		    _qryBillDetail.FieldByName("bill_itemcode").Value = sItemCode;
		    _qryBillDetail.FieldByName("bill_itemspec").Value = sItemSpec;
		    _qryBillDetail.FieldByName("bill_itemunit").Value = sItemUnit;
		    _qryBillDetail.FieldByName("bill_amount").Value = -1 * iAmount;
		    _qryBillDetail.FieldByName("bill_datetime").Value = Now();
		    _qryBillDetail.FieldByName("bill_requester").Value = sRequester;
		    _qryBillDetail.FieldByName("bill_performer").Value = sPerformer;
		    _qryBillDetail.FieldByName("bill_operator").Value = sOperator;
			_qryBillDetail.Post();
		}
		////
		delete qryTempBill;
	}
*/	
    return _CalcSpareMoney();
}

//---------------------------------------------------------------------------
// 清空CC_BillDetail表记录
//---------------------------------------------------------------------------
double _ClearBillDetail()
{
	_qryBillDetail.First();
    while (!_qryBillDetail.Eof)
    {
        _qryBillDetail.Delete();
    }
    ////
    return _CalcSpareMoney();
}

//---------------------------------------------------------------------------
// 收费操作：1	成功，0	失败
//---------------------------------------------------------------------------
int _CommitCharging()
{
	/*
		1.已办理结算手续的病人不允许划价
		2.已进行HIS确认过的病人不允许划价
		3.费用明细为空时不允许划价
	*/
    float fPatientGuid = _qryStudy.FieldByName("patient_guid").Value;
    float fStudyNumber0 = _qryStudy.FieldByName("study_number0").Value;
    ////
    if (!PatsInHospital(fPatientGuid))
    {
		MessageBox("该病人已经办理结算手续！无法划价收费！" , "电子申请单", 1);
		return 0;
	}
	if (PatsIsConfirm(fStudyNumber0))
	{
		MessageBox("该病人已执行过HIS确认登记！无法划价收费！" , "电子申请单", 1);
		return 0;
	}
    if (GetRecordCount(_qryBillDetail) <= 0)
    {
    	MessageBox("费用明细为空！无法划价收费！" , "电子申请单", 1);
		return 0;
    }
    ////
    int iFieldCount = 0;
    String sFieldPairs[2][100];
    SetArrayItem(sFieldPairs, iFieldCount, "bill_patientid", 	"PATIENTNO");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_visitid", 		"JCDXH");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_examname", 	"CHARGENAME");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_examcost", 	"PRICE");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_examcharge", 	"FEE");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_itemcode", 	"CHARGECODE");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_amount", 		"AMOUNT");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_datetime", 	"CHARGEDATE");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_performer", 	"EXECUTDEPT");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_operator", 	"OPERATID");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_operator", 	"AUDITID");
    ////
    String sSystemType = GetSystemType(fStudyNumber0);
    String sDoctorID = GetDoctorID(fStudyNumber0);
    String sSickRegion = _qryStudy.FieldByName("study_sickregion").AsString;
    String sSickRoom = _qryStudy.FieldByName("study_sickroom").AsString;
    ////
	String sHisQuery = "select * from GY_CHARGE_INTERFACE where 0 > 1";
    _qryHisCustom.Close();
    _qryHisCustom.SQL.Text = sHisQuery;
    _qryHisCustom.Open();
	////
	_qryBillDetail.First();
	while (!_qryBillDetail.Eof)
	{		
		_qryHisCustom.Append();
		for (int i = 0; i < iFieldCount; i++)
		{
			if (!_qryBillDetail.FieldByName(sFieldPairs[0][i]).IsNull())
			{
				_qryHisCustom.FieldByName(sFieldPairs[1][i]).Value =
					_qryBillDetail.FieldByName(sFieldPairs[0][i]).Value;
			}
		}
		_qryHisCustom.FieldByName("SYSTEMTYPE").Value = sSystemType;
		_qryHisCustom.FieldByName("DOCTORID").Value = sDoctorID;
		_qryHisCustom.FieldByName("ADMISSSICKROOM").Value = sSickRegion;
		_qryHisCustom.FieldByName("ADMISSSICKDEPT").Value = sSickRoom;
		_qryHisCustom.FieldByName("BEINHOSFLAG").Value = 1;
        _qryHisCustom.FieldByName("ZFBZ").Value = 0;
        _qryHisCustom.FieldByName("JZBS").Value = 1;
		////
		_qryHisCustom.Post();
		////
		_qryBillDetail.Next();
	}
    
    // 复核结果
    _qryBillDetail.First();
    while (!_qryBillDetail.Eof)
    {
		String sBillItemCode = _qryBillDetail.FieldByName("bill_itemcode").AsString;
		String sBillExamName = _qryBillDetail.FieldByName("bill_examname").AsString; 
		////
		sHisQuery = "select * from GY_CHARGE_INTERFACE";
		sHisQuery = AddWhereCondition(sHisQuery, "JCDXH=" + FloatToStr(fStudyNumber0));
		sHisQuery = AddWhereCondition(sHisQuery, "PATIENTNO=" + FloatToStr(fPatientGuid));
		sHisQuery = AddWhereCondition(sHisQuery, "SYSTEMTYPE='" + sSystemType + "'");
		sHisQuery = AddWhereCondition(sHisQuery, "CHARGECODE=" + sBillItemCode);
		sHisQuery = AddWhereCondition(sHisQuery, "CHARGENAME='" + sBillExamName + "'");
		_qryHisCustom.Close();
		_qryHisCustom.SQL.Text = sHisQuery;
		_qryHisCustom.Open();
	    ////
        if (_qryHisCustom.IsEmpty())
        {
        	MessageBox("HIS收费系统忙！写入失败！请重新操作！" , "电子申请单", 1);
            return 0;
        }
    	////
    	_qryBillDetail.Next();
    }
    
    // 保存修改
    // 注意：study_examname必须写在study_charge赋值之前,
    //      否则在StudyFrm的OnDataChange事件中会重置为0！
    double fStudyCost = _qryStudy.FieldByName("study_cost").AsFloat;
    double fStudyCharge = _qryStudy.FieldByName("study_charge").AsFloat;
    String sStudyExamItem = _qryStudy.FieldByName("study_examname").AsString;
    double fTotalExamCharge = CalcTotalExamCharge(_qryBillDetail);
    double fTotalExamCost = CalcTotalExamCost(_qryBillDetail);
    String sTotalExamItem = CalcTotalExamItem(_qryBillDetail);
    double fSpaceMoney = CalcSpaceMoney(fPatientGuid);
    double fResult = fSpaceMoney - (fStudyCharge + fTotalExamCharge);
    ////
    _qryStudy.Edit();
    // 不能合并检查部位
    //_qryStudy.FieldByName("study_examname").Value = MergeString(sStudyExamItem, sTotalExamItem, chr(32));
    _qryStudy.FieldByName("study_examname").Value = sStudyExamItem + " " + sTotalExamItem;
    _qryStudy.FieldByName("study_cost").Value = fStudyCost + fTotalExamCost;
    _qryStudy.FieldByName("study_charge").Value = fStudyCharge + fTotalExamCharge;
    if (fResult < 0)
    	_qryStudy.FieldByName("study_payment").Value = "欠费";
    else
    	_qryStudy.FieldByName("study_payment").Value = "已付费";
    _qryStudy.Post();
                               
    return 1;
}

//---------------------------------------------------------------------------
// 退费操作：1	成功，0	失败
//---------------------------------------------------------------------------
int _RefundCharging()
{
	MessageBox("不允许进行退费操作！", "电子申请单", 1);
	return 0;
	////
	float fPatientGuid = _qryStudy.FieldByName("patient_guid").Value;
    float fStudyNumber0 = _qryStudy.FieldByName("study_number0").Value;
    ////
	if (!PatsInHospital(fPatientGuid))
    {
		MessageBox("该病人已经办理结算手续！无法退费！" , "电子申请单", 1);
		return 0;
	}
	////
	String sBillQuery = "select sum(AMOUNT) as SUMCOUNT from " + g_sBillDetail;
	TADOQuery qryTempBill = new TADOQuery(nil);
	qryTempBill.ConnectionString = _opacsconnection;
	qryTempBill.Close();
	qryTempBill.SQL.Text = sBillQuery;
	qryTempBill.Open();
	int iSumCount = qryTempBill.FieldByName("SUMAMOUNT").AsInteger;
	delete qryTempBill;
	////
	if (iSumCount)
	{
		// 退单时填写退单理由
		String sCancelReason = InputDialog("请填写退单理由！", "退单理由");
	    if (sCancelReason == "MB_CANCEL")
	        return 0;
	}
    ////
	// 提交结果
    int iFieldCount = 0;
    String sFieldPairs[2][100];
    SetArrayItem(sFieldPairs, iFieldCount, "bill_patientid", 	"PATIENTNO");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_visitid", 		"JCDXH");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_examname", 	"CHARGENAME");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_examcost", 	"PRICE");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_examcharge", 	"FEE");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_itemcode", 	"CHARGECODE");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_amount", 		"AMOUNT");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_datetime", 	"CHARGEDATE");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_performer", 	"EXECUTDEPT");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_operator", 	"OPERATID");
    SetArrayItem(sFieldPairs, iFieldCount, "bill_operator", 	"AUDITID");
    ////
    String sLoginDoctor = GetConfigStr("SysLogon", "sLastAccounts");
    String sOperator = GetUserID(sLoginDoctor);
    String sSystemType = GetSystemType(fStudyNumber0);
    String sDoctorID = GetDoctorID(fStudyNumber0);
    String sSickRegion = _qryStudy.FieldByName("study_sickregion").AsString;
    String sSickRoom = _qryStudy.FieldByName("study_sickroom").AsString;
    int iInfantFlag = 0;
    if (IsNumString(_qryStudy.FieldByName("study_ordinal").Value))
        iInfantFlag = _qryStudy.FieldByName("study_ordinal").Value;
    ////
    String sHisQuery = "select * from GY_CHARGE_INTERFACE where 0 > 1";
    _qryHisCustom.Close();
    _qryHisCustom.SQL.Text = sHisQuery;
    _qryHisCustom.Open();
	////
	_qryBillDetail.First();
	while (!_qryBillDetail.Eof)
	{		
		_qryHisCustom.Append();
		for (int i = 0; i < iFieldCount; i++)
		{
			if (!_qryBillDetail.FieldByName(sFieldPairs[0][i]).IsNull())
			{
				_qryHisCustom.FieldByName(sFieldPairs[1][i]).Value =
					_qryBillDetail.FieldByName(sFieldPairs[0][i]).Value;
			}
		}
		_qryHisCustom.FieldByName("SYSTEMTYPE").Value = sSystemType;
		_qryHisCustom.FieldByName("DOCTORID").Value = sDoctorID;
		_qryHisCustom.FieldByName("ADMISSSICKROOM").Value = sSickRegion;
		_qryHisCustom.FieldByName("ADMISSSICKDEPT").Value = sSickRoom;
		_qryHisCustom.FieldByName("INFANTFLAG").Value = iInfantFlag;
        _qryHisCustom.FieldByName("BEINHOSFLAG").Value = 1;
        _qryHisCustom.FieldByName("ZFBZ").Value = 0;
        _qryHisCustom.FieldByName("JZBS").Value = 1;
		////
		_qryHisCustom.Post();
		////
		_qryBillDetail.Next();
	}
    
    // 复核结果
    sHisQuery = "select sum(AMOUNT) as SUMAMOUNT from GY_CHARGE_INTERFACE";
	sHisQuery = AddWhereCondition(sHisQuery, "JCDXH=" + FloatToStr(fStudyNumber0));
	sHisQuery = AddWhereCondition(sHisQuery, "PATIENTNO=" + FloatToStr(fPatientGuid));
	sHisQuery = AddWhereCondition(sHisQuery, "SYSTEMTYPE='" + sSystemType + "'");
    _qryHisCustom.Close();
    _qryHisCustom.SQL.Text = sHisQuery;
    _qryHisCustom.Open();
    int iSumAmount = _qryHisCustom.FieldByName("SUMAMOUNT").AsInteger;
    if (iSumAmount != 0)
    {
    	MessageBox("HIS收费系统忙！退费失败！请重新操作！" , "电子申请单", 1);
    	return 0;
    }   
    ////
    if (iSumCount == 0)
    {
    	// 退单时更新标识信息
	    if (IsConnetAccessDB(_hisconnection))
	    {
	    	sHisQuery = "update YZ_JCSQXM set DJBZ=9, DJGH='" + sOperator + "', DJSJ=Now() where (DJBZ=0 OR DJBZ=1)";
	    }
	    else
	    {
	    	sHisQuery = "update YZ_JCSQXM set DJBZ=9, DJGH='" + sOperator + "', DJSJ=sysdate where (DJBZ=0 OR DJBZ=1)";
	    }
	    sHisQuery = AddWhereCondition(sHisQuery, "JCDXH = " + FloatToStr(fStudyNumber0));
	    _qryHisCustom.Close();
	    _qryHisCustom.SQL.Text = sHisQuery;
	    _qryHisCustom.ExecSQL();
	    ////
	    if (IsConnetAccessDB(_hisconnection))
	    {
	        sHisQuery = "update YZ_JCSQD SET DJBZ=9, DJGH='" + sOperator + "', DJSJ=Now(), TUIDANLY='"
	            + sCancelReason + "' where (DJBZ=0 OR DJBZ=1)";
	    }
	    else
	    {
	    	sHisQuery = "update YZ_JCSQD set DJBZ=9, DJGH='" + sOperator + "', DJSJ=sysdate, TUIDANLY='"
	            + sCancelReason + "' where (DJBZ=0 OR DJBZ=1)";
		}
	    sHisQuery = AddWhereCondition(sHisQuery, "JCDXH = " + FloatToStr(fStudyNumber0));
	    _qryHisCustom.Close();
	    _qryHisCustom.SQL.Text = sHisQuery;
	    _qryHisCustom.ExecSQL();
	}
	    
	return 1;
}
//---------------------------------------------------------------------------

// 主程序
{
    // Nothing need to do.
}
//---------------------------------------------------------------------------
