using Newtonsoft.Json;
using AIMSExtension;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.ToolTip;
namespace DrawGraph
{
    [Serializable, JsonObject(MemberSerialization.OptOut)]
    public class DrugsManage : AreaManageBase
    {
        /// 
        /// 药品区域
        ///   
        public LinePackObj H3pack;
        public LinePackObj H5pack;
        public LinesPackObj lines;
        public int RowsCount;
        /// 
        /// 当前手术对象
        /// 
        private OperationRecord myOpeRecord = null;
        #region 初始化药品区域
        public DrugsManage()
        { init(); }
        public DrugsManage(object _operationRecor, ZedGraphControl _zedControl, TemplateManage _template, string _name) : base(_operationRecor, _zedControl, _template, _name)
        { init(); }
        public void init()
        {
            //自己要用的手术对象
            myOpeRecord = OpeRecord as OperationRecord;
        }
        /// 
        /// 初始画的后置方法
        /// 
        public override void FollowUpMethod()
        {
            lines = template.GetPackObjectOTag("DrugsManage_LinesPackObj_5");
            RowsCount = Convert.ToInt32(lines.XPageSpan / lines.XMajorGridStep);
            H3pack = template.GetPackObjectOTag("DrugsManage_LinePackObj_6");
            H5pack = template.GetPackObjectOTag("DrugsManage_LinePackObj_9");
        }
        #endregion
        #region 重写的事件
        /// 
        /// 鼠标点击画板
        /// 
        /// 
        /// 
        public override void MouseDown(ZedGraphControl sender, MouseEventArgs e)
        {
            //if (e.Button == System.Windows.Forms.MouseButtons.Left)
            //{
            //    MessageBox.Show(this.GetType().Name + "is Click Left Button");
            //}
        }
        public override void MouseMove(ZedGraphControl sender, MouseEventArgs e)
        {
        }
        public override void MouseUp(ZedGraphControl sender, MouseEventArgs e)
        {
        }
        public override void MouseDoubleClick(ZedGraphControl sender, MouseEventArgs e)
        {
        }
        public override void KeyUp(ZedGraphControl sender, KeyEventArgs e)
        {
        }
        #endregion 重写的事件结束
        #region 绑定区域数据
        public override void Bind()
        {
            init();
            DrawDrug();
        }
        /// 
        /// 画加药
        /// 
        private void DrawDrug()
        {
            try
            {
                foreach (FactDrug temp in myOpeRecord.FactDrugList)
                {
                    if (!isSapDrugs(temp))
                    {
                        temp.clearAddObj(ZedControl);
                    }
                }
                reDrawDrug();
            }
            catch (Exception exp)
            {
                PublicMethod.WriteLog(exp);
            }
        }
        /// 
        /// 重新画加药文本 
        ///  
        private void reDrawDrug()
        {
            try
            {
                //画在第几行
                int rowDrugsIndex = 0;
                //y的高度//主要高度
                double drugsy = 0;
                //加药最后位置
                double maxDrugsy = lines.RealY + getYPositionByListIndex(RowsCount - 1, lines.RealY, lines.RealEndY, RowsCount);
                //持续加药当前时间
                DateTime curTimeTemp = OperationRecord.getOpeMaxTime(myOpeRecord);
                DateTime serverTime = DateTime.Now;
                if (curTimeTemp > serverTime) curTimeTemp = serverTime;
                //超出的药画备注 镇痛药备注
                List DrugListstr = new List();
                DrugListstr.Add("【手术用药】");
                myOpeRecord.AfterDrugsListstr = new List();
                myOpeRecord.AfterDrugsListstr.Add("【术后镇痛药】");
                myOpeRecord.BeforeDrugs = "";
                int x = 0;
                foreach (var item in myOpeRecord.FactDrugList)
                {
                    string dose = "";
                    if (dose.Trim() != "") dose += " ";
                    dose += ((double)item.Dosage).ToString();
                    if (item.DosageUnit != null)
                    {
                        dose += item.DosageUnit;
                    }
                    if (item.GiveDrugType == "麻醉前用药")
                    {
                        myOpeRecord.BeforeDrugs += string.Format("{0}{1} ", item.DrugName.Trim(), dose);
                    }
                    if (item.GiveDrugType == "术后镇痛药")
                    {
                        myOpeRecord.AfterDrugsListstr.Add(string.Format("({0}){1} {2} {3}{4}{5}", x + 1, "", item.DrugName.Trim(), dose, "", item.DrugChannel == null ? "" : " " + item.DrugChannel.ToString()));
                        myOpeRecord.AnalgesiaDrug += string.Format("{0}{1} ", item.DrugName.Trim(), dose);
                        x++;
                    }
                }
                //当前时间段加药集合
                myOpeRecord.FactDrugList.ForEach(drug =>
                {
                    if (drug.IsContinue == 1 && drug.DrugBeginTime == drug.DrugEndTime) drug.End = curTimeTemp;
                    else if (drug.DrugEndTime != null) drug.End = drug.DrugEndTime;
                });
                List _FactDrugList = myOpeRecord.FactDrugList.Where(s => IfInTimeExist(s.DrugBeginTime, s.End) == true).ToList();
                //存在氧气从第二行开始画
                if (_FactDrugList.Where(s => s.DrugName == "氧气" && s.GiveDrugType != "麻醉前用药" && s.GiveDrugType != "术后镇痛药").ToList().Count > 0) rowDrugsIndex = 1;
                //加药按加药时间排序
                _FactDrugList.Sort(new FactDrugComparer());
                for (int i = 0; i < _FactDrugList.Count; i++)
                {
                    FactDrug temp = _FactDrugList[i];
                    if (temp.GiveDrugType == "麻醉前用药" || temp.GiveDrugType == "术后镇痛药" || temp.DrugChannel == "备用") continue;//|| temp.GiveDrugType == "麻醉诱导用药"
                                                                                                                           //子药不画
                    if (temp.ParentId > 0) continue;
                    bool isEqual = false;
                    bool isChildEqual = false;
                    if (!isSapDrugs(temp))
                    {
                        //以行号返回具休的位置
                        drugsy = lines.RealY + getYPositionByListIndex(rowDrugsIndex, lines.RealY, lines.RealEndY, RowsCount);
                        if (temp.DrugName == "氧气") drugsy = lines.RealY;
                        SetDrug(temp, curTimeTemp, drugsy);
                        temp.ChildFactDrugList = new List();
                        temp.ChildFactDrugList = _FactDrugList.Where(a => a.ParentId == temp.Id).ToList();
                        //判断是否重复的 主药或组药
                        for (int j = 0; j < i; j++)
                        {
                            FactDrug addDrug1 = _FactDrugList[j];
                            if (addDrug1.GiveDrugType == "麻醉前用药" || addDrug1.GiveDrugType == "术后镇痛药" || addDrug1.DrugChannel == "备用") continue;//|| temp.GiveDrugType == "麻醉诱导用药"
                            if (addDrug1.ChildFactDrugList == null) addDrug1.ChildFactDrugList = new List();
                            //如果加药品ID相同并且加加药ID不同,则认为加了同一种加药
                            if (addDrug1.Equal(temp) && temp.ParentId == 0 && addDrug1.ParentId == 0 && addDrug1.ChildFactDrugList.Count == 0 && temp.ChildFactDrugList.Count == 0)
                            {
                                addDrug1.clearDNAndDT(ZedControl);
                                //因为相同则取得相同对象的Y,为当前的对象的高度
                                drugsy = addDrug1.nowY;
                                isEqual = true;
                                continue;
                            }
                            else if (addDrug1.Equal(temp) && temp.ChildFactDrugList != null && addDrug1.ChildFactDrugList != null && EqualChildDrugs(temp.ChildFactDrugList, addDrug1.ChildFactDrugList))
                            {
                                isChildEqual = true;
                                TimeSpan tsp = temp.DrugBeginTime - addDrug1.DrugBeginTime;
                                //清除画图对象的名称及总药
                                addDrug1.clearDNAndDT(ZedControl);
                                drugsy = addDrug1.nowY;
                                if (drugsy <= maxDrugsy)
                                    temp.drawText(H3pack.RealX + 0.006f, drugsy);
                                else
                                    ListAddDrugs(DrugListstr, i, temp);
                                foreach (FactDrug item in temp.ChildFactDrugList)
                                {
                                    foreach (FactDrug addDrug1item in addDrug1.ChildFactDrugList)
                                    {
                                        //如果加药品ID相同并且加加药ID不同,则认为加了同一种加药
                                        if (addDrug1item.Equal(item))
                                        {
                                            SetDrug(item, curTimeTemp, drugsy);
                                            //清除画图对象的名称及总药
                                            addDrug1item.clearDNAndDT(ZedControl);
                                            ////因为相同则取得相同对象的Y,为当前的对象的高度
                                            drugsy = addDrug1item.nowY;
                                            if (drugsy <= maxDrugsy)
                                                item.drawText(H3pack.RealX + 0.006f, drugsy);
                                            else
                                                ListAddDrugs(DrugListstr, i, item);
                                            continue;
                                        }
                                    }
                                }
                                break;
                            }
                        }
                        if (isChildEqual == true) continue;
                        if (drugsy <= maxDrugsy)
                        {
                            temp.drawText(H3pack.RealX + 0.006f, drugsy);
                            if (temp.DrugName != "氧气" && isEqual == false)
                                rowDrugsIndex++;
                        }
                        else
                            ListAddDrugs(DrugListstr, i, temp);
                        if (temp.ChildFactDrugList.Count > 0)
                        {
                            foreach (FactDrug sItem in temp.ChildFactDrugList)
                            {
                                drugsy = lines.RealY + getYPositionByListIndex(rowDrugsIndex, lines.RealY, lines.RealEndY, RowsCount);
                                SetDrug(sItem, curTimeTemp, drugsy);
                                if (drugsy <= maxDrugsy)
                                {
                                    sItem.drawText(H3pack.RealX + 0.006f, drugsy);
                                    rowDrugsIndex++;
                                }
                                else { ListAddDrugs(DrugListstr, i, sItem); }
                            }
                            if (drugsy <= maxDrugsy)
                                DrawZuDragsLine(H3pack.RealX + 0.003f, drugsy, temp.nowY, temp);
                        }
                    }
                }
                myOpeRecord.DrugsListstr = DrugListstr;
                if (myOpeRecord.BeforeDrugs == null || myOpeRecord.BeforeDrugs == "") myOpeRecord.BeforeDrugs = "无";
                template.SetObjValue(myOpeRecord, "OperationRecord.BeforeDrugs", myOpeRecord.BeforeDrugs, myOpeRecord.BeforeDrugs);
                template.SetObjValue(myOpeRecord, "OperationRecord.AnalgesiaDrug", myOpeRecord.AnalgesiaDrug, myOpeRecord.AnalgesiaDrug);
                DrawDrugSapDose();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public bool EqualChildDrugs(List childDrugs, List secondchildDrugs)
        {
            bool b = false;
            foreach (var item in childDrugs)
            {
                bool istrue = false;
                foreach (var secitem in secondchildDrugs)
                {
                    if (secitem.Equal(item))
                    {
                        istrue = true;
                    }
                }
                if (istrue == true)
                {
                    b = true;
                }
                else
                {
                    b = false;
                    break;
                }
            }
            return b;
        }
        private void DrawZuDragsLine(double x, double y, double zhuy, FactDrug temp)
        {
            double height = getYPositionByListIndex(1, lines.RealY, lines.RealEndY, RowsCount) / 2;
            //double x = H3pack.RealX + 0.003f;
            ZUtil.DrawLine(x, zhuy + height, x, y + height, ZedControl, "zhuyDrugs" + temp.Id, Color.Red);
            ZUtil.DrawLine(x, zhuy + height, x + 0.0055f, zhuy + height, ZedControl, "zhuyDrugstop" + temp.Id, Color.Red);
            ZUtil.DrawLine(x, y + height, x + 0.0055f, y + height, ZedControl, "zhuyDrugsend" + temp.Id, Color.Red);
        }
        private void SetDrug(FactDrug temp, DateTime curTimeTemp, double y)
        {
            if (temp.IsContinue == 1 && temp.DrugBeginTime == temp.DrugEndTime) temp.End = curTimeTemp;
            temp.EqualDose = null;
            temp.setAnasArr(ZedControl, H5pack.RealX, lines.RealEndX, myOpeRecord.pageBegin, myOpeRecord.pageBegin.AddMinutes(EVERY_PAGE_TIME_SPAN));
            temp.nowY = y;
        }
        private static void ListAddDrugs(List DrugListstr, int i, FactDrug temp)
        {
            string dose = "";
            if (dose.Trim() != "") dose += " ";
            dose += ((double)temp.Dosage).ToString();
            if (temp.DosageUnit != null)
            {
                dose += temp.DosageUnit;
            }
            DrugListstr.Add(string.Format("({0}){1} {2} {3}{4}{5}", i + 1, (temp.DrugBeginTime == temp.DrugEndTime) ? temp.DrugBeginTime.ToShortTimeString() : temp.DrugBeginTime.ToShortTimeString() + "->" + temp.DrugEndTime.ToShortTimeString(), temp.DrugName.Trim(), dose, "", temp.DrugChannel == null ? "" : " " + temp.DrugChannel.ToString()));
            //DrugListstr.Append(" ");
        }
        private bool isSapDrugs(FactDrug record)
        {
            bool isSap = false;
            if (record.DrugChannel != null && record.DrugChannel == "ivgtt")
            {
                if (record.DosageUnit != null && record.DosageUnit.ToLower() == "ml")
                {
                    if (record.Dosage >= 50)
                    {
                        isSap = true;
                    }
                }
                if (record.BloodType != null && record.BloodType != "")
                {
                    isSap = true;
                }
            }
            return isSap;
        }
        private void DrawDrugSapDose()
        {
            LinePackObj linePack = template.GetPackObjectOTag("RemarkManage_LinePackObj_21");
            if (linePack == null) return;
            double x = linePack.RealX;
            RectangleFramePackObj remarkPpack = template.GetPackObjectOTag("RemarkManage_RectangleFramePackObj_2");
            int DrawIndex = 0;
            double y;
            double StartRemarkRatio = remarkPpack.RealY;
            double EndRemarkRatio = remarkPpack.RealEndY;
            try
            {
                myOpeRecord.ClearDrugsDose(ZedControl);
                double allDrugDose = 0; double allOutDose = 0;
                myOpeRecord.FactDrugList.ForEach(drug =>
                {
                    if (drug.DrugChannel == "ivgtt" || drug.DrugChannel == "iv")
                    {
                        double drugDose = 0;
                        if (drug.DosageUnit.Trim().ToLower() == "ml")
                        {
                            if (drug.Dosage >= 50) 
                            {
                                drugDose = Convert.ToDouble(drug.Dosage);
                            }
                        }
                        else if (drug.Comment != null && drug.Comment != "")
                        {
                            List strings = drug.Comment.Split('|').ToList();
                            foreach (var items in strings)
                            {
                                //单位=100|治疗量=200|U=200|u=200
                                List item = items.Split('=').ToList();
                                if (item[0] == drug.DosageUnit.Trim())
                                {
                                    double dose = Convert.ToDouble(drug.Dosage) * Convert.ToDouble(item[1]);
                                    allDrugDose += dose;
                                    break;
                                }
                            }
                        }
                        allDrugDose += drugDose;
                    }
                });
                template.SetObjValue(myOpeRecord, "OperationRecord.InAmount", allDrugDose.ToString(), allDrugDose.ToString(), allDrugDose.ToString() != myOpeRecord.InAmount ? true : false);
                DrawIndex++;
                myOpeRecord.FactOutputLiquidsList.ForEach(item =>
                {
                    if (item.DosageUnit.Trim() == "mL" || item.DosageUnit.Trim() == "ml" || item.DosageUnit.Trim() == "ML")
                    {
                        Double val = Convert.ToDouble(item.Dosage);
                        allOutDose += val;
                    }
                });
                template.SetObjValue(myOpeRecord, "OperationRecord.OutAmount", allOutDose.ToString(), allOutDose.ToString(), allOutDose.ToString() != myOpeRecord.OutAmount ? true : false);
                DrawIndex++;
                //myOpeRecord.FactOutputLiquidsList.ForEach(item =>
                //{
                //    if (item.DosageUnit.Trim() == "mL" || item.DosageUnit.Trim() == "ml" || item.DosageUnit.Trim() == "ML")
                //    {
                //        DrawIndex++;
                //        Double val = Convert.ToDouble(item.Dosage);
                //        y = StartRemarkRatio + getYPositionByListIndex(DrawIndex, StartRemarkRatio, EndRemarkRatio, remarkcount);
                //        ZUtil.DrawTextRemark(item.OutputLiquidsName + ":" + val + " " + item.DosageUnit, x + 0.01f, y, ZedControl, fontsize, "Out" + DrawIndex);
                //    }
                //});
            }
            catch (Exception ex)
            {
                PublicMethod.WriteLog(ex);
            }
        }
        #endregion
        #region 当前区域公用事件方法
        private bool IfInTimeExist(DateTime Begin, DateTime End)
        {
            DateTime lastime = myOpeRecord.lastPageBegin.AddSeconds(59);
            bool b = false;
            if (End == null)
            {
                if (Begin > myOpeRecord.pageBegin && Begin < lastime)
                {
                    b = true;
                }
            }
            else
            {
                if (Begin >= myOpeRecord.pageBegin && Begin <= lastime)
                {
                    b = true;
                }
                else if (End >= myOpeRecord.pageBegin && End <= lastime)
                {
                    b = true;
                }
                else if (Begin < myOpeRecord.pageBegin && End > lastime)
                {
                    b = true;
                }
            }
            return b;
        }
        /// 
        /// 根据顶部加药序号,确定数值生命体征的纵向位置(以1为单位)
        /// 
        /// 
        /// 
        public double getYPositionByListIndex(double index, double yTop, double yBottom, int rowCount)
        {
            double heightT = ZedControl.Height * (yBottom - yTop);
            double setpTemp = heightT / rowCount;
            //求一格在实际高度中的百分比
            double bfb = (setpTemp / heightT);
            //两线之间度*百分比得到一格的百分比高度
            double ygBFB = (yBottom - yTop) * bfb;
            double y = ygBFB * index;
            return y;
        }
        #endregion
    }
}