using HelperDB;
using Newtonsoft.Json;
using AIMSExtension;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;
namespace DrawGraph
{
    [Serializable, JsonObject(MemberSerialization.OptOut)]
    public class BaseInfoTopManage : AreaManageBase
    {
        private OperationRecord myOpeRecord = null;
        public BaseInfoTopManage()
        {
            //自己要用的手术对象
            myOpeRecord = null;
        }
        public BaseInfoTopManage(object _operationRecor, ZedGraphControl _zedControl, TemplateManage _template, string _name) : base(_operationRecor, _zedControl, _template, _name)
        {
            init();
        }
        public void init()
        {
            //自己要用的手术对象
            myOpeRecord = OpeRecord as OperationRecord;
        }
        #region 重写的事件
        /// 
        /// 鼠标点击画板
        /// 
        /// 
        /// 
        public override void MouseDown(ZedGraphControl sender, MouseEventArgs e)
        {
        }
        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)
        {
        }
        public SelectDictValue aSyncSelectDict = null;
        public override void Bind()
        {
            init();
            aSyncSelectDict = SelectDictValue.CreateInstance();
            myOpeRecord.clearAddObj(ZedControl);
            setPageTime(myOpeRecord.InRoomTime.Value);
            setXAxisTime(ZedControl.GraphPane, myOpeRecord.pageBegin, EVERY_PAGE_TIME_SPAN);
            GetcurrentPage();
            #region 单独赋值绑定 
            if (myOpeRecord.InRoomTime != null)
            {
                template.SetObjValue(myOpeRecord, "OperationRecord.InRoomTime", myOpeRecord.InRoomTime.Value.ToString("yyyy-MM-dd"), myOpeRecord.InRoomTime.ToString());
            } 
            if (myOpeRecord.currentPage != 0)
            {
                template.SetObjValue(myOpeRecord, "OperationRecord.currentPage", myOpeRecord.currentPage.ToString(), myOpeRecord.currentPage.ToString());
            }
            if (myOpeRecord.pageCount != 0)
            {
                template.SetObjValue(myOpeRecord, "OperationRecord.pageCount", myOpeRecord.pageCount.ToString(), myOpeRecord.pageCount.ToString());
            }
            #endregion
            List ables = PackManage.ListPob.Where(s => s is AbleEditPackObj).ToList();
            foreach (PackObjBase pack in ables)
            {
                AbleEditPackObj ableEdit = pack as AbleEditPackObj;
                SetAbleEditView(ableEdit);
            }
        }
        /// 
        /// 设置可编辑组件的显示样式
        /// 
        /// 
        private void SetAbleEditView(AbleEditPackObj ableEdit)
        {
            string span = "";
            double spanSum = Math.Round((float)(ableEdit.OneUnitCount / 12));
            for (int i = 0; i < spanSum; i++)
            {
                span += " ";
            }
            string text = "", value = "";
            if (ableEdit != null)
            {
                switch (ableEdit.ControlType)
                {
                    case EControlType.Directory:
                        value = ableEdit.PackValue;
                        text = DBManage.GetDictionaryValuesById(ableEdit.PackValue, ableEdit.ControlTitleText);
                        //设置属性的值
                        template.SetObjValue(OpeRecord, ableEdit.ClassDataSourceName, text, value);
                        break;
                    default:
                        break;
                }
            }
        }
        /// 
        /// 初始画的后置方法
        /// 
        public override void FollowUpMethod()
        {
            init();
        }
        #endregion 重写的事件结束
        #region 初始化时间轴
        /// 
        /// 设置页面的开始时间和结束时间
        /// 
        /// 手术信息对象
        private void setPageTime(DateTime begin)
        {
            if (myOpeRecord.pageCount == 0)
            {
                myOpeRecord.pageCount = 1;
                myOpeRecord.sharpBegin = getSharpTime(begin);
                myOpeRecord.pageBegin = getPageBegin(begin, collectInterval, ref EVERY_PAGE_TIME_SPAN);
                myOpeRecord.lastPageBegin = myOpeRecord.pageBegin.AddHours(EVERY_PAGE_TIME_SPAN / 60);
            }
        }
        /// 
        /// 根据采集间隔,确定页面时间跨度和页面开始时间
        /// 
        /// 给定时间(文本)
        /// 采集间隔(分钟)
        /// 页面时间跨度
        /// 页面显示的开始时间
        private DateTime getPageBegin(DateTime dt, double collectInterval, ref double timeSpan)
        {
            try
            {
                DateTime pageBegin = dt.Date.AddHours(dt.Hour);
                int ci = (int)(collectInterval * 60);
                if (ci <= 30)
                {
                    if (dt.Minute >= 30)
                    {
                        pageBegin = pageBegin.AddMinutes(30);
                    }
                    timeSpan = 30;
                }
                else if (ci <= 60)
                {
                    timeSpan = 60;
                }
                else
                {
                    timeSpan = 240;
                    TimeSpan ts = pageBegin - myOpeRecord.sharpBegin;
                    int h = ts.Hours;
                    h /= 4;
                    pageBegin = myOpeRecord.sharpBegin.AddHours(h * 4);
                }
                return pageBegin;
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }
        /// 
        /// 获取系统的整点时刻
        /// 
        /// 
        private DateTime getSharpTime(DateTime dt)
        {
            int ci = (int)dt.Minute;
            if (ci >= 50)
            {
                dt = DateTime.Parse(dt.ToString("yyyy-MM-dd HH:50:00"));
            }
            else if (ci >= 40)
            {
                dt = DateTime.Parse(dt.ToString("yyyy-MM-dd HH:40:00"));
            }
            else if (ci >= 30)
            {
                dt = DateTime.Parse(dt.ToString("yyyy-MM-dd HH:30:00"));
            }
            else if (ci >= 20)
            {
                dt = DateTime.Parse(dt.ToString("yyyy-MM-dd HH:20:00"));
            }
            else if (ci >= 10)
            {
                dt = DateTime.Parse(dt.ToString("yyyy-MM-dd HH:10:00"));
            }
            else if (ci < 10)
            {
                dt = DateTime.Parse(dt.ToString("yyyy-MM-dd HH:00:00"));
            }
            //if (ci >= 30)
            //{
            //    dt = DateTime.Parse(dt.ToString("yyyy-MM-dd HH:30:00")); 
            //}
            //else if (ci < 30)
            //{
            //    dt = DateTime.Parse(dt.ToString("yyyy-MM-dd HH:00:00"));
            //}
            return dt;
        }
        private void setXAxisTime(GraphPane myPane, DateTime begin, double pageSpan)
        {
            myPane.XAxis.Scale.Min = new XDate(begin);
            myPane.X2Axis.Scale.Min = myPane.XAxis.Scale.Min;
            myPane.XAxis.Scale.Max = new XDate(begin.AddMinutes(pageSpan));
            myPane.X2Axis.Scale.Max = myPane.XAxis.Scale.Max;
        }
        #endregion
        /// 
        /// 响应可编辑区域的点击事件
        /// 
        /// 
        /// 
        public override void editAr_Click(object sender, EventArgs e)
        {
            try
            {
                //传过来的数据是不是可编辑的
                AbleEditPackObj aEdit1S = sender as AbleEditPackObj;
                if (aEdit1S == null) return;
                //先把所有WINFORM组件隐藏
                foreach (PackObjBase pack in PackManage.ListPob)
                {
                    AbleEditPackObj aEdit = pack as AbleEditPackObj;
                    if (aEdit != null)
                    {
                        aEdit.IsVisible = false;
                    }
                }
                SelectDictValue.Hidden();
                //这句话很重要,只操作自己管理器里的组件
                AbleEditPackObj aEdit1 = PackManage.ListPob.FirstOrDefault(s => s.PackTag == aEdit1S.PackTag) as AbleEditPackObj;
                //指定的组件显示
                if (aEdit1 != null)
                {
                    aEdit1.IsVisible = !aEdit1.IsVisible;
                    Control conl = aEdit1.CControl;
                    conl.Leave -= new EventHandler(txt_Leave);
                    conl.DoubleClick -= Conl_DoubleClick;
                    //根据数据源名称进行不同的事件处理
                    switch (aEdit1.ClassDataSourceName)
                    {
                        case "OperationRecord.Height":
                            ((TextBox)conl).BorderStyle = BorderStyle.Fixed3D;
                            ((TextBox)conl).Focus();
                            ((TextBox)conl).Select(((TextBox)conl).Text.Length, 1);
                            conl.Leave += new EventHandler(txt_Leave);
                            break;
                        case "OperationRecord.Weight": //体重
                            ((TextBox)conl).BorderStyle = BorderStyle.Fixed3D;
                            ((TextBox)conl).Focus();
                            ((TextBox)conl).Select(((TextBox)conl).Text.Length, 1);
                            conl.Leave += new EventHandler(txt_Leave);
                            break;
                        case "OperationRecord.AnaesthesiaMethodId":
                            Anaes_Click(aEdit1, e);
                            break;
                        case "OperationRecord.ASALevel": //ASA分级
                            TYZD_Click(aEdit1, e, true);
                            break;
                        case "OperationRecord.OperationSiteId": //手术体位
                            TYZD_Click(aEdit1, e);
                            break;
                        case "OperationRecord.Fasting": //术前禁食
                            conl.Leave += new EventHandler(txt_Leave);
                            break;
                        case "OperationRecord.SpecialCase": //特殊情况 
                            ((TextBox)conl).BorderStyle = BorderStyle.Fixed3D;
                            ((TextBox)conl).Focus();
                            ((TextBox)conl).Select(((TextBox)conl).Text.Length, 1);
                            conl.Leave += new EventHandler(txt_Leave);
                            conl.DoubleClick += Conl_DoubleClick;
                            break;
                        case "OperationRecord.BloodType": //血型 
                            TYZD_Click(aEdit1, e); 
                            break;
                        case "OperationRecord.Applydiagnose": //手术诊断 
                            opeDisease_Click(aEdit1, e);
                            break;
                        case "OperationRecord.Applyoperation": //手术诊断 
                            ope_Click(aEdit1, e);
                            break;
                            //default:
                            //    //在此处写日志
                            //    aEdit1.IsVisible = !aEdit1.IsVisible;
                            //    MessageBox.Show("没找到-" + aEdit1.ClassDataSourceName + "-属性的事件");
                            //    break;
                    }
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show(exp.Message);
            }
            finally
            {
            }
        }
        private void Conl_DoubleClick(object sender, EventArgs e)
        {
            //frmSelectDictionary fsd = new frmSelectDictionary();
            //fsd._control = sender as TextBox;
            //fsd._dictionaryName = "特殊情况";
            //fsd.isRadio = false;
            //fsd.isShowText = true;
            //fsd.ShowDialog();
        }
        #region 可编辑区域响应事件
        //通用字典分组窗体打开
        private void TYZD_Click(AbleEditPackObj sender, EventArgs e, bool isRadio = false)
        {
            AbleEditPackObj ableEdit = sender;
            if (ableEdit == null) return;
            try
            {
                if (myOpeRecord != null)
                {
                    SelDict(sender, e, ableEdit.ControlTitleText, isRadio);
                }
            }
            catch (Exception ex)
            {
                AIMSExtension.PublicMethod.WriteLog(ex);
            }
        }
        private void SelDict(AbleEditPackObj sender, EventArgs e, string _DictType, bool isRadio = false)
        {
            AbleEditPackObj ableEdit = sender;
            if (ableEdit == null) return;
            ableEdit.CControl.TextChanged -= new EventHandler(CControl_TextChanged);
            ableEdit.CControl.TextChanged += new EventHandler(CControl_TextChanged);
            ableEdit.CControl.MouseDown -= new MouseEventHandler(CControl_MouseDown);
            ableEdit.CControl.MouseDown += new MouseEventHandler(CControl_MouseDown);
            ableEdit.CControl.KeyUp -= new KeyEventHandler(CControl_KeyUp);
            ableEdit.CControl.KeyUp += new KeyEventHandler(CControl_KeyUp);
            if (myOpeRecord != null)
            {
                Control conl = sender.CControl;
                if (conl is TextBox)
                {
                    ((TextBox)conl).BorderStyle = BorderStyle.Fixed3D;
                    ((TextBox)conl).Focus();
                    if (sender.PackValue != null && sender.PackValue.Trim() != "" && isRadio == false)
                    {
                        if (((TextBox)conl).Text.LastIndexOf(',') != sender.PackText.Length)
                            ((TextBox)conl).Text = ((TextBox)conl).Text + ",";
                    }
                        ((TextBox)conl).Select(((TextBox)conl).Text.Length, 1);
                }
                aSyncSelectDict.Show(template, OpeRecord, sender, _DictType, isRadio);
            }
        }
        private void CControl_TextChanged(object sender, EventArgs e)
        {
            if (myOpeRecord != null)
            {
                Control conl = sender as Control;
                aSyncSelectDict.ShowSel(conl, OpeRecord);
            }
        }
        private void CControl_KeyUp(object sender, KeyEventArgs e)
        {
            if (myOpeRecord != null)
            {
                Control conl = sender as Control;
                if (conl.Text != SelectDictValue.Value)
                    if (e.KeyCode == Keys.Delete || e.KeyCode == Keys.Back)
                    {
                        aSyncSelectDict.DelSel(conl, OpeRecord);
                    }
            }
        }
        private void CControl_MouseDown(object sender, MouseEventArgs e)
        {
            if (myOpeRecord != null)
            {
                TextBox conl = sender as TextBox;
                string leftStr = conl.Text.Substring(0, conl.SelectionStart);
                string rightStr = conl.Text.Substring(conl.SelectionStart, conl.Text.Length - conl.SelectionStart);
                int startIndex = 0;
                int endLength = conl.Text.Length;
                if (leftStr.Contains(","))
                {
                    int beginindex = leftStr.LastIndexOf(',');
                    startIndex = beginindex + 1;
                    if (rightStr.Contains(","))
                    {
                        endLength = rightStr.IndexOf(",") + (leftStr.Length - beginindex);
                    }
                }
                else
                {
                    if (rightStr.Contains(","))
                    {
                        endLength = rightStr.IndexOf(",") + leftStr.Length + 1;
                    }
                }
                conl.Select(startIndex, endLength);
            }
        }
        private void ope_Click(AbleEditPackObj sender, EventArgs e)
        {
            AbleEditPackObj ableEdit = sender;
            if (ableEdit == null) return;
            try
            {
                if (myOpeRecord != null)
                {
                    SelDict(sender, e, ableEdit.ControlTitleText);
                }
            }
            catch (Exception ex)
            {
                AIMSExtension.PublicMethod.WriteLog(ex);
            }
        }
        private void opeDisease_Click(AbleEditPackObj sender, EventArgs e)
        {
            AbleEditPackObj ableEdit = sender;
            if (ableEdit == null) return;
            try
            {
                if (myOpeRecord != null)
                {
                    SelDict(sender, e, ableEdit.ControlTitleText);
                }
            }
            catch (Exception ex)
            {
                AIMSExtension.PublicMethod.WriteLog(ex);
            }
        }
        private void Anaes_Click(AbleEditPackObj sender, EventArgs e)
        {
            AbleEditPackObj ableEdit = sender;
            if (ableEdit == null) return;
            try
            {
                if (myOpeRecord != null)
                {
                    SelDict(sender, e, ableEdit.ControlTitleText);
                }
            }
            catch (Exception ex)
            {
                AIMSExtension.PublicMethod.WriteLog(ex);
            }
        }
        private void txt_Leave(object sender, EventArgs e)
        {
            Control control = (Control)sender;
            if (control == null) return;
            AbleEditPackObj ableEdit = control.Tag as AbleEditPackObj;
            if (ableEdit == null) return;
            try
            {
                string DataSourceName = ableEdit.ClassDataSourceName;
                //Console.WriteLine(DataSourceName);
                //拿到数据源(格式:OperationRecord.PatientRef.Bed)
                bool updateOk = true;
                string text = control.Text.Trim();
                string value = control.Text.Trim();
                if (!updateOk)
                {
                    ableEdit.IsVisible = !ableEdit.IsVisible;
                }
                else
                {
                    if (DataSourceName == "OperationRecord.Fasting")
                    {
                        foreach (Control conl in control.Controls)
                        {
                            CheckBox chBox = conl as CheckBox;
                            if (chBox.Checked)
                            {
                                text = "是";
                                value = "1";
                            }
                            else
                            {
                                text = "否";
                                value = "0";
                            }
                        }
                    }
                    //设置属性的值
                    ableEdit.IsVisible = !ableEdit.IsVisible;
                    template.SetObjValue(OpeRecord, DataSourceName, text, value, true);
                    ((TextBox)control).BorderStyle = BorderStyle.None;
                }
            }
            catch (Exception ex)
            {
                //写日志
                PublicMethod.WriteLog(ex);
            }
            finally
            {
            }
        }
        #endregion
        //得到当前页数
        private void GetcurrentPage()
        {
            DateTime EndTime = OperationRecord.getOpeMaxTime(myOpeRecord);
            EndTime = DateTime.Parse(EndTime.ToString("yyyy-MM-dd HH:mm"));
            TimeSpan tsp = (TimeSpan)(EndTime - myOpeRecord.sharpBegin);
            double db = tsp.TotalHours / 4;
            if (db == ((int)tsp.TotalHours / 4))
                myOpeRecord.currentPage = (int)db;
            else
                myOpeRecord.currentPage = (int)db + 1;
            if (myOpeRecord.currentPage == 0) myOpeRecord.currentPage = 1;
        }
    }
}