//---------------------------------------------------------------------------
// 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\\JSDCommon.cpp"

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

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

//---------------------------------------------------------------------------
// 是否可以执行计费划价：1 成功，0 失败
//---------------------------------------------------------------------------
int _CanCharging()
{
    String sStudySource = _qryStudy.FieldByName("study_source").AsString;
	int iLoginState = _qryStudy.FieldByName("login_state").AsInteger;
    if (sStudySource == "门诊")
    {
        if (iLoginState == -2)
        {
        	MessageBox("预约病人不允许执行收费退费！", "电子申请单", 1);
            return 0;
        } 
		return 1;
	}
	else
	{
    	MessageBox("请切换到" + sStudySource + "页面再执行收费退费！", "电子申请单", 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",	"zxks_id");
    SetArrayItem(sFieldPairs, iFieldCount, "price_examname", 	"name");
    SetArrayItem(sFieldPairs, iFieldCount, "price_examcost", 	"xmdj");
    SetArrayItem(sFieldPairs, iFieldCount, "price_itemcode", 	"id");
    SetArrayItem(sFieldPairs, iFieldCount, "price_inputcode", 	"py");
    SetArrayItem(sFieldPairs, iFieldCount, "price_itemspec", 	"xmgg");
    SetArrayItem(sFieldPairs, iFieldCount, "price_itemunit", 	"xmdw");
    ////
    String	zxks = "(4423,4426)";    // (请根据现场情况修改，不能为空)
    if (IsConnetAccessDB(_hisconnection))
    {
    	sHisQuery = "select * from YY_SFXXMK where zxks_id in " + zxks + " and sybz=1";
	}
	else
	{
		sHisQuery = "select * from YY_SFXXMK where zxks_id in " + zxks + " and sybz=1";
	}
    _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()
{
	_qryPriceCombo.Close();
	_qryPriceCombo.SQL.Text = "DELETE FROM CC_PRICECOMBO";
	_qryPriceCombo.ExecSQL();
	_qryPriceCombo.SQL.Text = "SELECT * FROM CC_PRICECOMBO";
	_qryPriceCombo.Open();
	////
	String sHisQuery = "";
    int iFieldCount = 0;
    String sFieldPairs[2][100];
    SetArrayItem(sFieldPairs, iFieldCount, "COMBO_EXAMKIND", 	"zxks_id");
    SetArrayItem(sFieldPairs, iFieldCount, "COMBO_EXAMNAME", 	"name");
    SetArrayItem(sFieldPairs, iFieldCount, "COMBO_EXAMCOST", 	"xmdj");
    SetArrayItem(sFieldPairs, iFieldCount, "COMBO_ITEMCODE", 	"id");
    //SetArrayItem(sFieldPairs, iFieldCount, "COMBO_INPUTCODE", 	"");
    ////                                    
    String	zxks = "(4423,4426)";    // (请根据现场情况修改，不能为空)
    if (IsConnetAccessDB(_hisconnection))
    {
    	sHisQuery = "select * from YY_LCSFXMK where zxks_id in " + zxks + " and xmlb=7 and jlzt=0";
	}
	else
	{
		sHisQuery = "select * from YY_LCSFXMK where zxks_id in " + zxks + " and xmlb=7 and jlzt=0"; 
	}
    _qryHisCustom.Close();
  	_qryHisCustom.SQL.Text = sHisQuery;
  	try
  	{
  		_qryHisCustom.Open();
  	}
  	except
    {
        ShowMessage("价目表查询失败！");
        return 0;
    }
    ////
  	if (!_qryHisCustom.IsEmpty())
    {
        _qryHisCustom.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()
{
    return 0; // 忽略欠费
}

//---------------------------------------------------------------------------
// 初始化计费信息
//---------------------------------------------------------------------------
double _InitCharging()
{
	g_sBillDetail = GetTableNameByIP("CC_BILLDETAIL");
	////
	String sSurveyInfo = _qryStudy.FieldByName("study_surveyinfo").AsString; 
   	String zxks = GetValueByName(sSurveyInfo, "zxks"); // 获取执行科室
    String zxys = GetConfigStr("SysLogon", "sLastAccounts");  // 获取执行医生
    String zxysmc = GetConfigStr("SysLogon", "sLastDoctorName");  // 获取执行医生
	////
	String blh = GetValueByName(sSurveyInfo, "hospno");
	String xmlb = GetValueByName(sSurveyInfo, "itemtype");
	String patid = _qryStudy.FieldByName("patient_guid").AsString;
	String syxh = GetValueByName(sSurveyInfo, "syxh");
	String qqxh = GetValueByName(sSurveyInfo, "qqxh");
	String qqmxxh = GetValueByName(sSurveyInfo, "qqmxxh");
	String ysmc = GetValueByName(sSurveyInfo, "ysmc"); 
	String itemcode = _qryStudy.FieldByName("study_examcode").AsString;
	String itemname = _qryStudy.FieldByName("study_examname").AsString;
	String qqrq = GetValueByName(sSurveyInfo, "qqrq");
	String price = GetValueByName(sSurveyInfo, "price");
	String itemqty = GetValueByName(sSurveyInfo, "itemqty");
	String itemunit = GetValueByName(sSurveyInfo, "itemunit");
	String itemtype = GetValueByName(sSurveyInfo, "itemtype");
	String state = GetValueByName(sSurveyInfo, "state");
	////
	TStringList pText = new  TStringList;
	pText.CommaText = itemcode;
	////
	if (!_ischarging) // 初始化退费清单
	{	    		
		for (int i = 0; i < pText.Count(); i++)
	    { 
            String sPrice = GetValueByIndex(price, i);
            String sItemQty = GetValueByIndex(itemqty, i);
            if ((Length(sPrice) < 1) || (Length(sItemQty) < 1))
                continue;
			int iAmount = StrToInt(sItemQty);
			double fExamCharge = StrToFloat(sPrice);
			String sVisitid = blh + " " + syxh + " " + GetValueByIndex(qqxh, i);
			////
		    _qryBillDetail.Append();
		    _qryBillDetail.FieldByName("bill_patientid").Value = patid;
            _qryBillDetail.FieldByName("bill_visitid").Value = sVisitid;
		    _qryBillDetail.FieldByName("bill_itemno").Value = GetValueByIndex(qqmxxh, i);
		    _qryBillDetail.FieldByName("bill_examkind").Value = GetValueByIndex(itemtype, i);
		    _qryBillDetail.FieldByName("bill_examname").Value = GetValueByIndex(itemname, i);
		    _qryBillDetail.FieldByName("bill_amount").Value = iAmount;
		    _qryBillDetail.FieldByName("bill_examcost").Value = iAmount * fExamCharge;
		    _qryBillDetail.FieldByName("bill_examcharge").Value = iAmount * fExamCharge;
		    _qryBillDetail.FieldByName("bill_itemcode").Value = GetValueByIndex(itemcode, i);
		    _qryBillDetail.FieldByName("bill_itemunit").Value = GetValueByIndex(itemunit, i);
		    _qryBillDetail.FieldByName("bill_itemspec").Value = "";
		    _qryBillDetail.FieldByName("bill_datetime").Value = DecodeDT(GetValueByIndex(qqrq, i));
		    _qryBillDetail.FieldByName("bill_requester").Value = GetValueByIndex(ysmc, i);
		    _qryBillDetail.FieldByName("bill_performer").Value = zxks;
		    _qryBillDetail.FieldByName("bill_operator").Value = zxysmc;
		    _qryBillDetail.FieldByName("bill_sfstate").Value = GetValueByIndex(state, i);;
		    _qryBillDetail.Post();
		}
    }
    ////
	if (pText != NULL)
	{
		delete pText;
		pText = NULL;
	}    
    ////
    _qryBillDetail.Close();
    _qryBillDetail.SQL.Text = "SELECT * FROM " + g_sBillDetail;
    _qryBillDetail.Open();
    ////
	if (!_ischarging)
	{
		g_iRefundRecordCount = GetRecordCount(_qryBillDetail);
	}
    ////
	return _CalcSpareMoney();
}

//---------------------------------------------------------------------------
// 增加CC_BillDetail表记录，增加套餐
//---------------------------------------------------------------------------
double _AppendBillCombo()
{
	String sItemCode = _qryPriceCombo.FieldByName("COMBO_ITEMCODE").AsString;
	String sHisQuery = "SELECT * FROM YY_LCSFXMDYK WHERE lcxmdm = '" + sItemCode + "'";  // YY_LCSFXMDYK 套餐项目明细表
    _qryHisCustom.Close();
    _qryHisCustom.SQL.Text = sHisQuery;
    _qryHisCustom.Open();
    ////
    _qryHisCustom.First();
    while (!_qryHisCustom.Eof)
    {
    	String sChargeItemCode = _qryHisCustom.FieldByName("xmdm").AsString;
    	if (_qryPriceList.Locate("price_itemcode", sChargeItemCode, 0))
    	{
			_AppendBillDetail();
			////
			int iHisAmount = _qryHisCustom.FieldByName("xmsl").AsInteger; 
			if (iHisAmount > 1)
			{
				// 重新定位数据
				_qryBillDetail.Locate("bill_itemcode", sChargeItemCode, 0);	
				
    			int iAmount = _qryBillDetail.FieldByName("bill_amount").AsInteger;
			    double fExamCost = _qryBillDetail.FieldByName("bill_examcost").AsFloat;
			    double fExamCharge = _qryBillDetail.FieldByName("bill_examcharge").AsFloat;
			    ////
				_qryBillDetail.Edit();
		    	_qryBillDetail.FieldByName("bill_amount").Value = iAmount + iHisAmount - 1;
		    	_qryBillDetail.FieldByName("bill_examcharge").Value = fExamCharge / iAmount * (iAmount + iHisAmount - 1);
		    	_qryBillDetail.FieldByName("bill_examcost").Value = fExamCost / iAmount * (iAmount + iHisAmount - 1);
				_qryBillDetail.Post();
			}
		}
		////
    	_qryHisCustom.Next();
    }
	////
	_qryBillDetail.Close();
	_qryBillDetail.SQL.Text = "SELECT * FROM " + g_sBillDetail;
	_qryBillDetail.Open();
	////
	return _CalcSpareMoney();
}

//---------------------------------------------------------------------------
// 增加CC_BillDetail表记录，增加单项
//---------------------------------------------------------------------------
double _AppendBillDetail()
{
	String sSurveyInfo = _qryStudy.FieldByName("study_surveyinfo").AsString; 	
   	String zxks = GetConfigStr("SysLogon", "sLastDepartment"); // 获取执行科室
    String zxys = GetConfigStr("SysLogon", "sLastAccounts");  // 获取执行医生  
    String zxysmc = GetConfigStr("SysLogon", "sLastDoctorName");  // 获取执行医生
    ////
    String patid = _qryStudy.FieldByName("patient_guid").AsString;    	
    String blh = GetValueByName(sSurveyInfo, "hospno");
    String syxh = GetValueByName(sSurveyInfo, "syxh");
    double fExamCost = _qryPriceList.FieldByName("price_examcost").AsFloat;
    double fExamCharge = _qryPriceList.FieldByName("price_examcost").AsFloat; 
    String sPriceExamName = _qryPriceList.FieldByName("price_examname").AsString;
    String sPriceItemCode = _qryPriceList.FieldByName("price_itemcode").AsString;
    int iRecordCount = GetRecordCount(_qryBillDetail);
    int iItemNo = iRecordCount + 1;
    
    // 添加收费记录
    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())
	{
		String sVisitID = blh + " " + syxh + " " + syxh;
		
        // 添加新收费记录
	    _qryBillDetail.Append();
	    _qryBillDetail.FieldByName("bill_patientid").Value = patid;
	    _qryBillDetail.FieldByName("bill_visitid").Value = sVisitID;
	    _qryBillDetail.FieldByName("bill_itemno").Value = iItemNo; // 占位!
	    _qryBillDetail.FieldByName("bill_examkind").Value = "1"; // 项目类别（0临床项目1收费项目）
	    _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 = zxks;
	    _qryBillDetail.FieldByName("bill_performer").Value = zxks;
	    _qryBillDetail.FieldByName("bill_operator").Value = zxysmc;
	    _qryBillDetail.FieldByName("bill_sfstate").Value = 0; // 待确认
	    _qryBillDetail.Post();
	    ////
	    int iBillDetailKey = _qryBillDetail.FieldByName("billdetail_key").AsInteger ;
	    _qryBillDetail.Edit();
	    _qryBillDetail.FieldByName("bill_itemno").Value = iBillDetailKey;
	    _qryBillDetail.Post();
	    ////
	    iItemNo++;
	}
    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 = zxys;
	    _qryBillDetail.FieldByName("bill_performer").Value = zxks;
	    _qryBillDetail.FieldByName("bill_operator").Value = zxysmc;
    	_qryBillDetail.Post();
	}
	////
	_qryBillDetail.Close();
	_qryBillDetail.SQL.Text = "SELECT * FROM " + g_sBillDetail;
	_qryBillDetail.Open();
	
    return _CalcSpareMoney();
}

//---------------------------------------------------------------------------
// 删除CC_BillDetail表记录
//---------------------------------------------------------------------------
double _DeleteBillDetail()
{ 
    String sBillDetailKey = _qryBillDetail.FieldByName("billdetail_key").AsString; 
    String sPatientId = _qryBillDetail.FieldByName("bill_patientid").AsString; 
    String sVisitID = _qryBillDetail.FieldByName("bill_visitid").AsString;
	String sItemNo = _qryBillDetail.FieldByName("bill_itemno").AsString;
	String sExamKind = _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 sItemCode = _qryBillDetail.FieldByName("bill_itemcode").AsString;
	String sItemSpec = _qryBillDetail.FieldByName("bill_itemspec").AsString;
	String sItemUnit = _qryBillDetail.FieldByName("bill_itemunit").AsString;
    int iAmount = _qryBillDetail.FieldByName("bill_amount").AsInteger;
	String sRequester = _qryBillDetail.FieldByName("bill_requester").AsString;
	String sPerformer = _qryBillDetail.FieldByName("bill_performer").AsString;
	String sOperator = _qryBillDetail.FieldByName("bill_operator").AsString;
					
	if (_ischarging) // 收费时删除项目
	{
		_qryBillDetail.Delete();
	}
	else // 退费时删除项目
	{		
		TADOQuery qryTempBill = new TADOQuery(nil);
		qryTempBill.ConnectionString = _opacsconnection;
		String sBillQuery = "SELECT SUM(bill_amount) AS SUMCOUNT FROM " + g_sBillDetail;
        sBillQuery = AddWhereCondition(sBillQuery, "bill_itemcode = '" + sItemCode + "'");
        sBillQuery = AddWhereCondition(sBillQuery, "bill_examname = '" + sExamName + "'");
        sBillQuery = AddWhereCondition(sBillQuery, "bill_patientid = '" + sPatientId + "'");
		qryTempBill.Close();
		qryTempBill.SQL.Text = sBillQuery;
		qryTempBill.Open();
		////
		int iSumAmount = qryTempBill.FieldByName("SUMCOUNT").AsInteger;
		if ((iSumAmount <= 0) || (iAmount <= 0))
		{
			MessageBox("该项目不能进行撤销和退费！", "电子申请单", 1);
		}
		else
		{
			// 插入一条负记录
			_qryBillDetail.Append();
			_qryBillDetail.FieldByName("bill_patientid").Value = sPatientId;
		    _qryBillDetail.FieldByName("bill_visitid").Value = sVisitID;
		    _qryBillDetail.FieldByName("bill_itemno").Value = sItemNo;
		    _qryBillDetail.FieldByName("bill_examkind").Value = sExamKind;
		    _qryBillDetail.FieldByName("bill_examname").Value = sExamName;
		    _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 = sBillDetailKey;// !!!
		    _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.FieldByName("bill_sfstate").Value = 0; // 待确认
			_qryBillDetail.Post();
		}
		////
		delete qryTempBill;			
	}
    return _CalcSpareMoney();
}

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

    return _CalcSpareMoney();
}

//---------------------------------------------------------------------------
// 提交结果到HIS数据库，1=成功，0=失败
//---------------------------------------------------------------------------
int _CommitCharging()
{
	int iReportState = _qryStudy.FieldByName("report_state").AsInteger;
    if (iReportState >= 2)
    {
    	MessageBox("已审核病人不允许执行收费退费！", "电子申请单", 1);
        return 0;
    }
    ////
    if (_qryBillDetail.IsEmpty())
    {
        MessageDlg("必须添加项目才能收费！", mtinformation, mbok, 0);
        return 0;
    }		
    
	// 提交结果
    double fTotalExamCost = 0.0;
    double fTotalExamCharge = 0.0;
    String sTotalExamItem = "";
    String sTotalExamCode = "";
    ////
    String qqxh2 = "", qqmxxh2 = "", qqksmc2 = "", ysmc2 = "", qqrq2 = "";
    String price2 = "", itemqty2 = "", itemunit2 = "", itemtype2 = "", state2 = "";   
    ////
    String zxys = GetConfigStr("SysLogon", "sLastAccounts");  // 获取执行医生  

	// 收费确认 
	int iResult = -100;
	TClientDataSet cds = new TClientDataSet(nil);
	try
	{
		_qryBillDetail.First();
		while (!_qryBillDetail.Eof)
		{
			String sVisitID = _qryBillDetail.FieldByName("bill_visitid").AsString;
			String sRequester = _qryBillDetail.FieldByName("bill_requester").AsString;
			String sPerformer = _qryBillDetail.FieldByName("bill_performer").AsString;
			String sOperator = _qryBillDetail.FieldByName("bill_operator").AsString;
			TDateTime dtBillDetail = _qryBillDetail.FieldByName("bill_datetime").AsDateTime;
			String sItemUnit = _qryBillDetail.FieldByName("bill_itemunit").AsString;
			String sExamKind = _qryBillDetail.FieldByName("bill_examkind").AsString;
			String sItemNo = _qryBillDetail.FieldByName("bill_itemno").AsString;
    		int iAmount = _qryBillDetail.FieldByName("bill_amount").AsInteger;			
		    double fExamCharge = _qryBillDetail.FieldByName("bill_examcharge").AsFloat;
		    			
            // 准备命令(QF01)
            String sSendFile = "C:\\OpacsLog\\QF01.xml";						
            cds.LoadFromFile("..\\Common\\QF01.xml"); 
            cds.First();
			cds.Edit();
			cds.FieldByName("blh").Value = GetValueByIndex(sVisitID, 0);
			cds.FieldByName("brlb").Value = "0"; // 0：门诊1：住院 3：体检 
			cds.FieldByName("xmlb").Value = sExamKind; // 项目类别
			cds.FieldByName("patid").Value = _qryBillDetail.FieldByName("bill_patientid").AsString;
			cds.FieldByName("syxh").Value = GetValueByIndex(sVisitID, 1); // 首页序号
			cds.FieldByName("zxksdm").Value = Trim(GetDeptCode(sPerformer));  // 确认科室代码 
			cds.FieldByName("zxysdm").Value = zxys; // 确认人员代码
			cds.FieldByName("qqxh").Value = GetValueByIndex(sVisitID, 2); // 申请序号
			cds.FieldByName("qqmxxh").Value = sItemNo;  // 项目序号
			cds.FieldByName("itemcode").Value = _qryBillDetail.FieldByName("bill_itemcode").AsString; // 项目代码 
			cds.FieldByName("itemname").Value = _qryBillDetail.FieldByName("bill_examname").AsString; // 项目名称 
			cds.FieldByName("price").Value = fExamCharge / iAmount; // 项目单价
			cds.FieldByName("itemqty").Value = iAmount; // 项目数量
			cds.FieldByName("xmstatus").Value = "1"; // 项目状态 (0不处理1确认2拒绝3撤销)
			cds.FieldByName("sfflag").Value = "1"; // 收费状态 (收费)
			cds.FieldByName("djlb").Value = "0"; // 单价类别
			cds.FieldByName("bgdh").Value = "0"; // 报告单号 (确费时可为空)
			cds.FieldByName("bglx").Value = "0"; // 报告类型 (确费时可为空)
			cds.FieldByName("tssm").Value = "";
			cds.FieldByName("tjrybh").Value = "";
			cds.Post();	
            cds.SaveToFile(sSendFile);
			
            // 发送命令
            String sResultFile = "C:\\OpacsLog\\QF01.result.xml";
            String sAppDir = ExtractFilePath(Application.ExeName);
            String sIniDir = sAppDir + "Interface";	
            String sCommand = sIniDir + "\\SendEmr.exe QF01 " + sSendFile + " " + sResultFile;
            iResult = RunConsoleProgram(sCommand);
            ////
            if (iResult != 0) // 0-成功，-1-失败，7-获取参数失败，8-参数无效，9-连接失败 
            {   
                MessageBox("执行QF01命令出错(" + IntToStr(iResult) + ")！请确认门诊收费权限！", "电子申请单", 1);		    	
            }
            else
            {
				fTotalExamCost = fTotalExamCost + _qryBillDetail.FieldByName("bill_examcost").AsFloat;
				fTotalExamCharge = fTotalExamCharge + _qryBillDetail.FieldByName("bill_examcharge").AsFloat;
				sTotalExamItem = sTotalExamItem + " " + TrimX(_qryBillDetail.FieldByName("bill_examname").AsString);
				sTotalExamCode = sTotalExamCode + " " + TrimX(_qryBillDetail.FieldByName("bill_itemcode").AsString);
                ////    
                qqxh2 += Trim(cds.FieldByName("qqxh").AsString) + "|";  
                qqmxxh2 += Trim(cds.FieldByName("qqmxxh").AsString) + "|"; 
                qqksmc2 += Trim(sRequester) + "|";  
                ysmc2 += Trim(sOperator) + "|"; 
                qqrq2 += EncodeDT(dtBillDetail) + "|"; 
                price2 += Trim(cds.FieldByName("price").AsString) + "|"; 
                itemqty2 += Trim(cds.FieldByName("itemqty").AsString) + "|"; 
                itemunit2 += Trim(sItemUnit) + "|"; 
                itemtype2 += Trim(sExamKind) + "|";
                state2 += "1" + "|"; // 已确认                    
            }
		
			_qryBillDetail.Next();
		}	
	}
	finally
	{
		if (cds != NULL)
		{
			delete cds;
			cds = NULL;
		}	
    }
	
    // 保存修改
    // 注意：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;
    String sStudyExamCode = _qryStudy.FieldByName("study_examcode").AsString;
    String sSurveyInfo = _qryStudy.FieldByName("study_surveyinfo").AsString; 	
    ////
    _qryStudy.Edit();
    _qryStudy.FieldByName("study_examname").Value = Trim(sStudyExamItem + " " + Trim(sTotalExamItem));
    _qryStudy.FieldByName("study_examcode").Value = Trim(sStudyExamCode + " " + Trim(sTotalExamCode));
    _qryStudy.FieldByName("study_cost").Value = fStudyCost + fTotalExamCost;
    _qryStudy.FieldByName("study_charge").Value = fStudyCharge + fTotalExamCharge;
    //_qryStudy.FieldByName("study_payment").Value = "";
    {
        String qqxh = "", qqmxxh = "", qqksmc = "", ysmc = "", qqrq = "";
        String price = "", itemqty = "", itemunit = "", itemtype = "", state = "";     	  		
        
        qqxh = GetValueByName(sSurveyInfo, "qqxh");
        if (Length(qqxh) == 0)
            qqxh = TrimX(qqxh2);
        else
            qqxh += TrimX(qqxh2); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "qqxh", qqxh);
        
        qqmxxh = GetValueByName(sSurveyInfo, "qqmxxh");
        if (Length(qqmxxh) == 0)
            qqmxxh = TrimX(qqmxxh2);
        else
            qqmxxh += TrimX(qqmxxh2); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "qqmxxh", qqmxxh);

        qqksmc = GetValueByName(sSurveyInfo, "qqksmc");
        if (Length(qqksmc) == 0)
            qqksmc = TrimX(qqksmc2);
        else
            qqksmc += TrimX(qqksmc2); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "qqksmc", qqksmc);

        ysmc = GetValueByName(sSurveyInfo, "ysmc");
        if (Length(ysmc) == 0)
            ysmc = TrimX(ysmc2);
        else
            ysmc += TrimX(ysmc2); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "ysmc", ysmc);

        qqrq = GetValueByName(sSurveyInfo, "qqrq");
        if (Length(qqrq) == 0)
            qqrq = TrimX(qqrq2);
        else
            qqrq += TrimX(qqrq2); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "qqrq", qqrq);

        price = GetValueByName(sSurveyInfo, "price");
        if (Length(price) == 0)
            price = TrimX(price2);
        else
            price += TrimX(price2); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "price", price);

        itemqty = GetValueByName(sSurveyInfo, "itemqty");
        if (Length(itemqty) == 0)
            itemqty = TrimX(itemqty2);
        else
            itemqty += TrimX(itemqty2); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "itemqty", itemqty);

        itemunit = GetValueByName(sSurveyInfo, "itemunit");
        if (Length(itemunit) == 0)
            itemunit = TrimX(itemunit2);
        else
            itemunit += TrimX(itemunit2); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "itemunit", itemunit);

        itemtype = GetValueByName(sSurveyInfo, "itemtype");
        if (Length(itemtype) == 0)
            itemtype = TrimX(itemtype2);
        else
            itemtype += TrimX(itemtype2); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "itemtype", itemtype);
            
        state = GetValueByName(sSurveyInfo, "state");
        if (Length(state) == 0)
            state = TrimX(state2);
        else
            state += TrimX(state2); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "state", state);
    }
    _qryStudy.FieldByName("study_surveyinfo").Value = sSurveyInfo;
    _qryStudy.Post();
    ////
    if (iResult != 0) // 0-成功，-1-失败，7-获取参数失败，8-参数无效，9-连接失败 
    {   
		return 0;
	}
    else
    {
    	return 1;
    }
}

//---------------------------------------------------------------------------
// 退费操作：1	成功，0	失败
//---------------------------------------------------------------------------
int _RefundCharging()
{
	int iReportState = _qryStudy.FieldByName("report_state").AsInteger;
    if (iReportState >= 2)
    {
    	MessageBox("已审核病人不允许执行收费退费！", "电子申请单", 1);
        return 0;
    }
    ////
    double fTotalExamCost = 0.0;
    double fTotalExamCharge = 0.0;
    String sTotalExamItem = "";
    String sTotalExamCode = "";
    ////
    int iRecordNo = 0;
    int iRecordCount = 0;
    int DelRecords[100];
    ////
    String zxys = GetConfigStr("SysLogon", "sLastAccounts");  // 获取执行医生 
    String zxysmc = GetConfigStr("SysLogon", "sLastDoctorName");  // 获取执行医生姓名          

    // 退费确认 
	int iResult = -100;
	TClientDataSet cds = new TClientDataSet(nil);
	try
	{
		_qryBillDetail.First();
		while (!_qryBillDetail.Eof)
		{
			String sVisitID = _qryBillDetail.FieldByName("bill_visitid").AsString;
			String sPerformer = _qryBillDetail.FieldByName("bill_performer").AsString;
			String sOperator = _qryBillDetail.FieldByName("bill_operator").AsString;
			String sBillDetailKey = _qryBillDetail.FieldByName("bill_itemspec").AsString; // !!!
    		int iAmount = _qryBillDetail.FieldByName("bill_amount").AsInteger;			
		    double fExamCharge = _qryBillDetail.FieldByName("bill_examcharge").AsFloat;
		    			
			if (iAmount < 0)
			{
				// 准备命令(QF01)
				String sSendFile = "C:\\OpacsLog\\QF01.xml";
				cds.LoadFromFile("..\\Common\\QF01.xml"); 
				cds.First();
				cds.Edit();
				cds.FieldByName("blh").Value = GetValueByIndex(sVisitID, 0); // 门诊号   
				cds.FieldByName("brlb").Value = "0"; // 0：门诊1：住院 3：体检  
				cds.FieldByName("xmlb").Value = _qryBillDetail.FieldByName("bill_examkind").AsString; // 项目类别
				cds.FieldByName("patid").Value = _qryBillDetail.FieldByName("bill_patientid").AsString;
				cds.FieldByName("syxh").Value = GetValueByIndex(sVisitID, 1); // 首页序号
				cds.FieldByName("zxksdm").Value = Trim(GetDeptCode(sPerformer));  // 确认科室代码  
				cds.FieldByName("zxysdm").Value = zxys; // 确认人员代码
				cds.FieldByName("qqxh").Value = GetValueByIndex(sVisitID, 2); // 申请序号
				cds.FieldByName("qqmxxh").Value = _qryBillDetail.FieldByName("bill_itemno").AsString;  // 项目序号
				cds.FieldByName("itemcode").Value = _qryBillDetail.FieldByName("bill_itemcode").AsString; // 项目代码 
				cds.FieldByName("itemname").Value = _qryBillDetail.FieldByName("bill_examname").AsString; // 项目名称 
				cds.FieldByName("price").Value = -1 * (fExamCharge / iAmount); // 项目单价
				cds.FieldByName("itemqty").Value = -1 * iAmount; // 项目数量
				cds.FieldByName("xmstatus").Value = "3"; // 项目状态 (0不处理1确认2拒绝3撤销)
				cds.FieldByName("sfflag").Value = "0"; // 收费状态 (不收费)
				cds.FieldByName("djlb").Value = "0"; // 单价类别
				cds.FieldByName("bgdh").Value = "0"; // 报告单号 (确费时可为空)
				cds.FieldByName("bglx").Value = "0"; // 报告类型 (确费时可为空)
				cds.FieldByName("tssm").Value = "";
				cds.FieldByName("tjrybh").Value = "";
				cds.Post();	
                cds.SaveToFile(sSendFile);		

                // 发送命令
                String sResultFile = "C:\\OpacsLog\\QF01.result.xml";
                String sAppDir = ExtractFilePath(Application.ExeName);
                String sIniDir = sAppDir + "Interface";	
                String sCommand = sIniDir + "\\SendEmr.exe QF01 " + sSendFile + " " + sResultFile;
                iResult = RunConsoleProgram(sCommand);
                ////
                if (iResult != 0) // 0-成功，-1-失败，7-获取参数失败，8-参数无效，9-连接失败 
                {   
                    MessageBox("执行QF01命令出错(" + IntToStr(iResult) + ")！请确认住院退费权限！", "电子申请单", 1);		    	
                }
                else
                {
                    fTotalExamCost = fTotalExamCost + _qryBillDetail.FieldByName("bill_examcost").AsFloat;
                    fTotalExamCharge = fTotalExamCharge + _qryBillDetail.FieldByName("bill_examcharge").AsFloat;
                    sTotalExamItem = sTotalExamItem + " " + TrimX(_qryBillDetail.FieldByName("bill_examname").AsString);
                    sTotalExamCode = sTotalExamCode + " " + TrimX(_qryBillDetail.FieldByName("bill_itemcode").AsString);
                    ////
                    TADOQuery qryTempBill = new TADOQuery(nil);
                    qryTempBill.ConnectionString = _opacsconnection;
                    String sBillQuery = "SELECT * FROM " + g_sBillDetail + " WHERE BILL_AMOUNT > 0";
                    qryTempBill.Close();
                    qryTempBill.SQL.Text = sBillQuery;
                    qryTempBill.Open();
                    iRecordNo = 0;
                    qryTempBill.First();
                    while (!qryTempBill.Eof)
                    {
                        String sCurBillDetailKey = qryTempBill.FieldByName("billdetail_key").AsString;
                        if (sCurBillDetailKey == sBillDetailKey)
                        {
                            break;
                        }
                        qryTempBill.Next();
                        iRecordNo++;
                    }
                    delete qryTempBill;
                    ////
                    DelRecords[iRecordCount] = iRecordNo;
                    iRecordCount++;
                }
			}
			////
			_qryBillDetail.Next();
		}
	}
	finally
	{
		if (cds != NULL)
		{
			delete cds;
			cds = NULL;
		}	
    }
    if (iRecordCount < 1)
    {
        MessageDlg("必须删除项目才能退费！", mtinformation, mbok, 0);
        return 0;
    }   
    
    // 必须排序!!!
	for (int x=0; x<iRecordCount; x++)
	{
	    for (int y=x+1; y<iRecordCount; y++)
	    {
	        if (DelRecords[y] < DelRecords[x])
	        {
	            int iTemp = DelRecords[y];
	            DelRecords[y] = DelRecords[x];
	            DelRecords[x] = iTemp;
	        }
	    }
	}    

    // 保存修改   
    // 注意：study_examname必须写在study_charge赋值之前,
    //      否则在StudyFrm的OnDataChange事件中会重置为0！
    double fStudyCharge = _qryStudy.FieldByName("study_charge").AsFloat;
    double fStudyCost = _qryStudy.FieldByName("study_cost").AsFloat;
    String sStudyExamItem = _qryStudy.FieldByName("study_examname").AsString;
    String sStudyExamCode = _qryStudy.FieldByName("study_examcode").AsString;
    String sSurveyInfo = _qryStudy.FieldByName("study_surveyinfo").AsString;
    ////
    _qryStudy.Edit();
    _qryStudy.FieldByName("study_examname").Value = SubtractString(sStudyExamItem, sTotalExamItem, chr(32));
    _qryStudy.FieldByName("study_examcode").Value = SubtractString(sStudyExamCode, sTotalExamCode, chr(32));
    _qryStudy.FieldByName("study_cost").Value = fStudyCost + fTotalExamCost;
    _qryStudy.FieldByName("study_charge").Value = fStudyCharge + fTotalExamCharge;
    //_qryStudy.FieldByName("study_payment").Value = "";
    _qryStudy.FieldByName("login_extinfo1").Value = zxys;   // 退费人员(代码)
    _qryStudy.FieldByName("login_extinfo2").Value = FormatDateTime("yyyy-mm-dd hh:nn:ss", Now());   // 退费时间
    for (int i = iRecordCount-1; i >= 0; i--)
    {
        int iOrder = DelRecords[i];
    
        String qqxh = "", qqmxxh = "", qqksmc = "", ysmc = "", qqrq = "";
        String price = "", itemqty = "", itemunit = "", itemtype = "", state = "";   
        
        qqxh = GetValueByName(sSurveyInfo, "qqxh");
        qqxh = DelValueByIndex(qqxh, iOrder); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "qqxh", qqxh);
            
        qqmxxh = GetValueByName(sSurveyInfo, "qqmxxh");
        qqmxxh = DelValueByIndex(qqmxxh, iOrder); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "qqmxxh", qqmxxh);
    
        qqksmc = GetValueByName(sSurveyInfo, "qqksmc");
        qqksmc = DelValueByIndex(qqksmc, iOrder); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "qqksmc", qqksmc);
    
        ysmc = GetValueByName(sSurveyInfo, "ysmc");
        ysmc = DelValueByIndex(ysmc, iOrder); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "ysmc", ysmc);
    
        qqrq = GetValueByName(sSurveyInfo, "qqrq");
        qqrq = DelValueByIndex(qqrq, iOrder); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "qqrq", qqrq);
    
        price = GetValueByName(sSurveyInfo, "price");
        price = DelValueByIndex(price, iOrder); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "price", price);
    
        itemqty = GetValueByName(sSurveyInfo, "itemqty");
        itemqty = DelValueByIndex(itemqty, iOrder); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "itemqty", itemqty);
    
        itemunit = GetValueByName(sSurveyInfo, "itemunit");
        itemunit = DelValueByIndex(itemunit, iOrder); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "itemunit", itemunit);
    
        itemtype = GetValueByName(sSurveyInfo, "itemtype");
        itemtype = DelValueByIndex(itemtype, iOrder); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "itemtype", itemtype);        
        
        state = GetValueByName(sSurveyInfo, "state");
        state = DelValueByIndex(state, iOrder); 
        sSurveyInfo = SetValueByName(sSurveyInfo, "state", state);        
    }
    _qryStudy.FieldByName("study_surveyinfo").Value = sSurveyInfo;
    _qryStudy.Post();
    ////
    if (iResult != 0) // 0-成功，-1-失败，7-获取参数失败，8-参数无效，9-连接失败 
    {   
		return 0;
	}
   	else    
	{
		return 1;
	}
}
//---------------------------------------------------------------------------

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