using System;

using HISClinic.DataModel;
using HISClinic.DataServices;

namespace HISClinic.BLL
{
	/// <summary>
	/// Prescription 的摘要说明。
	/// </summary>
	public class Prescription
	{
		public Prescription()
		{
			//
			// TODO: 在此处添加构造函数逻辑
			//
		}

		
		/// <summary>
		/// 计算单种药品的价格的小计
		/// </summary>
		/// <param name="prescriptionDetailRow"></param>
		/// <returns></returns>
		public static void CalculateSubTotal(PrescriptionsEx.t_PrescriptionDetailDataTable prescriptionDetail)
		{
			foreach(PrescriptionsEx.t_PrescriptionDetailRow row in prescriptionDetail)
			{
				row.BeginEdit();
				row[PrescriptionsEx.t_PrescriptionDetailDataTableEx.FIELD_SubTotal]=CalculateSubTotal(row);
				row.EndEdit();
			}
		}

		/// <summary>
		/// 计算单种药品的价格的小计
		/// </summary>
		/// <param name="prescriptionDetailRow"></param>
		/// <returns></returns>
		public static decimal CalculateSubTotal(PrescriptionsEx.t_PrescriptionDetailRow prescriptionDetailRow)
		{
			return  (decimal)prescriptionDetailRow.Quantity  *  prescriptionDetailRow.UnitPrice;
		}

		
		/// <summary>
		/// 计算各张处方中药品的价格总计
		/// </summary>
		/// <param name="prescriptionDetail"></param>
		/// <returns></returns>
		public static void CalculateSumTotal(PrescriptionsEx prescriptionsEx)
		{
			decimal SumTotal=0M;
			PrescriptionsEx.t_PrescriptionDetailRow[] detailRow;
			
			CalculateSubTotal(prescriptionsEx.t_PrescriptionDetail);

			foreach(PrescriptionsEx.t_PrescriptionMasterRow masterRow in prescriptionsEx.t_PrescriptionMaster)
			{
				detailRow=(PrescriptionsEx.t_PrescriptionDetailRow[])prescriptionsEx.t_PrescriptionDetail.Select( PrescriptionsEx.t_PrescriptionDetailDataTableEx.FIELD_RxID +"="+masterRow.RxID.ToString());
				
				if(detailRow != null)
				{
					for(int i=0;i<detailRow.Length;i++)
					{
						SumTotal+=detailRow[i].SubTotal;
					}
				}
				masterRow.SumTotal=SumTotal;
				SumTotal=0;
			}
		}

		/// <summary>
		/// 计算处方细表中药品的价格总计
		/// </summary>
		/// <param name="prescriptionDetail"></param>
		/// <returns></returns>
		public static decimal CalculateSumTotal(PrescriptionsEx.t_PrescriptionDetailDataTable prescriptionDetail)
		{
			decimal SumTotal=0M;
			foreach(PrescriptionsEx.t_PrescriptionDetailRow row in prescriptionDetail)
			{
				SumTotal+=row.SubTotal;
			}
			return SumTotal;
		}

		public bool SavePrescriptions(PrescriptionsEx prescriptionsEx,long RegistrationID)
		{
			PrescriptionsEx prescriptions=(PrescriptionsEx)prescriptionsEx.GetChanges();
			if(prescriptions!=null)
			{
				return (new PrescriptionMapper()).SavePrescription(prescriptionsEx,RegistrationID);
			}
			return false;
		}

		/// <summary>
		/// 根据PatientID查找未付款的处方
		/// </summary>
		/// <param name="PatientID"></param>
		public PrescriptionsEx FindUnpaidPrescriptions(int PatientID)
		{
			PrescriptionsEx prescriptionsEx;
			prescriptionsEx=(new PrescriptionMapper()).FindUnpaidPrescriptions(PatientID);
			return prescriptionsEx.t_PrescriptionMaster.Count>0?prescriptionsEx:null;
		}
	}
}
