using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AIMSBLL;
using AIMSModel;
using DrawGraph;
using AIMSExtension;
using DevComponents.DotNetBar.Controls;
namespace AIMS.PublicUI.UI
{
    public partial class frmFactOutputLiquidsNew : Form
    {
        public frmFactOutputLiquidsNew()
        {
            InitializeComponent();
        }
        /// 
        /// 手术记录
        /// 
        public DrawGraph.OperationRecord _record;
        /// 
        /// 图表控件
        /// 
        public DrawGraph.ZedGraphControl zgcAnaesRecord;
        /// 
        /// 出量集合
        /// 
        public List _outputList;
        /// 
        /// 计量单位集合
        /// 
        public List _unitList; 
        public delegate void OutsParamHandler(); 
        public event OutsParamHandler OutParam;
        int LastColumnIndex = 0;// e.ColumnIndex 
        public int OutputLiquidTypeId;
        private void frmFactOutputLiquidsNew_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < dgvOutput.Columns.Count; i++)
            {
                dgvOutput.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
            }
            Initial();
            dgvEvents_RowsAdded(null, null);
        }
        /// 
        /// 初始化公共成员
        /// 
        private void Initial()
        {
            _unitList = BBasicDictionary.GetBasicDictionaryByName("给药单位").SubItem;
            _outputList = BOutputLiquids.Select(" IsValid=1", null);
            _unitList.Insert(0, new BasicDictionary() { Id = -1, Name = "" });
            #region 增加常用出量显示  
            foreach (OutputLiquids type in _outputList)
            {
                int index = this.dgvOutput.Rows.Add();
                this.dgvOutput.Rows[index].Cells["OutputName"].Value = type.Name;
                this.dgvOutput.Rows[index].Cells["OutputName"].Tag = type.Id;
                this.dgvOutput.Rows[index].Cells["DoseUnit"].Value = "ml";
                dgvOutput.CurrentCell = this.dgvOutput.Rows[index].Cells[2];
                dgvOutput.BeginEdit(true);
                if (index == 3) break;
            }
            #endregion
            _outputList.Insert(0, new OutputLiquids() { Id = -1, Name = "" });
            if (_record.FactOutputLiquidsList.Count > 0)
            {
                FullDGV(_record.FactOutputLiquidsList);
            }
        }
        private void FullDGV(List list)
        {
            //添加出量
            if (list.Count > 0)
            {
                foreach (FactOutputLiquids item in list)
                {
                    bool k = false;
                    foreach (DataGridViewRow row in dgvOutput.Rows)
                    {
                        OutputLiquids type = null;
                        if (row.Cells["OutputName"].Tag != null)
                        {
                            type = BOutputLiquids.SelectSingle(Convert.ToInt32(row.Cells["OutputName"].Tag));
                        }
                        if (type != null)
                        {
                            if (type.Id == item.OutputLiquidsId && row.Cells["Dose"].EditedFormattedValue.ToString() == "")
                            {
                                row.Tag = item.Id;
                                row.Cells["Dose"].Value = ((double)item.Dosage).ToString();
                                row.Cells["DoseUnit"].Value = item.DosageUnit;
                                if (Convert.ToDateTime(item.BeginTime).ToString().Length > 0)
                                {
                                    row.Cells["BeginTime"].Value = item.BeginTime;
                                }
                                if (item.IsContinue > 0)
                                {
                                    row.Cells["Continue"].Value = "-->";
                                }
                                if (Convert.ToDateTime(item.EndTime).ToString().Length > 0)
                                {
                                    if (item.EndTime != item.BeginTime)
                                    {
                                        row.Cells["EndTime"].Value = item.EndTime;// Convert.ToDateTime(item.EndTime); 
                                    }
                                }
                                if (Convert.ToDateTime(item.EndTime).ToString().Length > 0 && item.EndTime > item.BeginTime)
                                {
                                    row.Cells["Continue"].Value = "-->";
                                    row.Cells["EndTime"].Value = item.EndTime;
                                }
                                row.Cells["Remark"].Value = item.Remark;
                                k = true;
                                break;
                            }
                        }
                    }
                    if (k) continue;
                    int index = this.dgvOutput.Rows.Add();
                    this.dgvOutput.Rows[index].Tag = item.Id;
                    this.dgvOutput.Rows[index].Cells["Remark"].Value = item.Remark;
                    this.dgvOutput.Rows[index].Cells["OutputName"].Value = item.OutputLiquidsName;
                    this.dgvOutput.Rows[index].Cells["OutputName"].Tag = item.OutputLiquidsId;
                    this.dgvOutput.Rows[index].Cells["Dose"].Value = (double)item.Dosage;
                    this.dgvOutput.Rows[index].Cells["DoseUnit"].Value = item.DosageUnit;
                    if (Convert.ToDateTime(item.BeginTime).ToString().Length > 0)
                    {
                        this.dgvOutput.Rows[index].Cells["BeginTime"].Value = item.BeginTime;
                    }
                    if (item.IsContinue > 0)
                    {
                        this.dgvOutput.Rows[index].Cells["Continue"].Value = "-->";
                    }
                    if (Convert.ToDateTime(item.EndTime).ToString().Length > 0)
                    {
                        if (item.EndTime != item.BeginTime)
                        {
                            this.dgvOutput.Rows[index].Cells["EndTime"].Value = item.EndTime;
                        }
                    }
                }
            }
        }
        private void dgvEvents_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e)
        {
            DataGridViewComboEditTipBoxCell nameCell;
            DataGridViewComboBoxCell unitCell;
            if (e == null)
            {
                nameCell = dgvOutput.Rows[dgvOutput.Rows.Count - 1].Cells["OutputName"] as DataGridViewComboEditTipBoxCell;
                unitCell = dgvOutput.Rows[dgvOutput.Rows.Count - 1].Cells["DoseUnit"] as DataGridViewComboBoxCell;
            }
            else
            {
                nameCell = dgvOutput.Rows[e.RowIndex].Cells["OutputName"] as DataGridViewComboEditTipBoxCell;
                unitCell = dgvOutput.Rows[e.RowIndex].Cells["DoseUnit"] as DataGridViewComboBoxCell;
            }
            foreach (var item in _outputList)
            {
                nameCell.Items.Add(item.Name);
            }
            unitCell.DataSource = _unitList;
            unitCell.DisplayMember = "Name";
            unitCell.ValueMember = "Name";
        }
        private void dgvOutput_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvOutput.CurrentCell != null)
            {
                if (LastColumnIndex == 1 && dgvOutput.CurrentCell.ColumnIndex != 1)
                {
                    if (dgvOutput.CurrentCell.ColumnIndex == 3)
                    {
                        dgvOutput.CurrentCell = dgvOutput.CurrentRow.Cells[2];
                        dgvOutput.BeginEdit(true);
                    }
                }
                LastColumnIndex = dgvOutput.CurrentCell.ColumnIndex;
                //点击开始时间时显示时间
                if (dgvOutput.CurrentCell.ColumnIndex == 4 && dgvOutput.CurrentCell.EditedFormattedValue.ToString() == "")
                {
                    dgvOutput.CurrentCell.Value = DateTime.Now;
                    SendKeys.Send("{Tab}");
                }
                //点击Sign列时显示持续事件标记
                if (dgvOutput.CurrentCell.ColumnIndex == 5)
                {
                    if (dgvOutput.CurrentCell.EditedFormattedValue.ToString() == "" && dgvOutput.CurrentRow.Cells["BeginTime"].EditedFormattedValue.ToString() != "")
                    {
                        dgvOutput.CurrentCell.Value = "-->";
                        btnSave.Focus();
                        SendKeys.Send("{Tab}");
                    }
                    else
                    {
                        dgvOutput.CurrentCell.Value = "";
                        dgvOutput.CurrentRow.Cells["EndTime"].Value = "";
                        btnSave.Focus();
                    }
                }
                //点击结束时间时判断是否持续事件,并显示时间
                if (dgvOutput.CurrentCell.ColumnIndex == 6)
                {
                    if (dgvOutput.CurrentRow.Cells[5].EditedFormattedValue.ToString() != "" && dgvOutput.CurrentCell.EditedFormattedValue.ToString() == "")
                    {
                        dgvOutput.CurrentCell.Value = DateTime.Now;
                        btnSave.Focus();
                        //SendKeys.Send("{Tab}");
                    }
                }
            }
        }
        private bool ValidTimeTxt(string dgvTimeTxt, ref string message)
        {
            bool k = true;
            if (dgvTimeTxt == "")
            {
                return k;
            }
            if (!dgvTimeTxt.Contains("-") || !dgvTimeTxt.Contains(":") || !dgvTimeTxt.Contains(" "))
            {
                return false;
            }
            if (dgvTimeTxt.IndexOf("-") < 1 || dgvTimeTxt.IndexOf(":") < 1 || dgvTimeTxt.IndexOf(" ") < 1)
            {
                return false;
            }
            try
            {
                string[] ym = dgvTimeTxt.Split(' ');
                string[] sym = ym[0].Split('-');
                string[] hm = ym[1].Split(':');
                int month = Convert.ToInt16(sym[0]);
                int day = Convert.ToInt16(sym[1]);
                int hh = Convert.ToInt16(hm[0]);
                int mm = Convert.ToInt16(hm[1]);
                if (month > 12 || month < 0)
                {
                    k = false;
                    message = "请填写正确的月份(1-12)";
                }
                if (day > 31 || day < 0)
                {
                    k = false;
                    message = "请填写正确的日期(1-31)";
                }
                if (hh > 23 || hh < 0)
                {
                    k = false;
                    message = "请填写正确的小时(0-23)";
                }
                if (mm > 59 || hh < 0)
                {
                    k = false;
                    message = "请填写正确的小时(0-59)";
                }
            }
            catch
            {
                k = false;
            }
            return k;
        }
        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (dgvOutput.CurrentRow != null)
            {
                if (dgvOutput.CurrentRow.Tag != null)
                {
                    int id = Convert.ToInt32(dgvOutput.CurrentRow.Tag);
                    FactOutputLiquids er = _record.FactOutputLiquidsList.Where(b => b.Id == id).ToList()[0];
                    //er.IsValid = 0;
                    BFactOutputLiquids.Delete(er);
                    er.clearAddObj(zgcAnaesRecord);
                    _record.FactOutputLiquidsList.Remove(er);
                    OutParam(); 
                    dgvOutput.Rows.Remove(dgvOutput.CurrentRow);
                }
                else
                {
                    if (dgvOutput.CurrentRow.Cells["OutputName"].Value != null)
                    {
                        dgvOutput.Rows.Remove(dgvOutput.CurrentRow);
                    }
                }
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            #region 保存时验证
            foreach (DataGridViewRow dr in dgvOutput.Rows)
            {
                if (dr.Cells[1].EditedFormattedValue.ToString() != "" && dr.Cells[2].EditedFormattedValue.ToString() != "")
                {
                    if (dr.Cells["DoseUnit"].EditedFormattedValue.ToString() == "")
                    {
                        MessageBox.Show("保存失败!\n\r" + "请输入:" + dr.Cells[0].EditedFormattedValue.ToString() + ":" + dr.Cells["OutputName"].EditedFormattedValue.ToString() + "的计量单位!");
                        dgvOutput.CurrentCell = dr.Cells["DoseUnit"];
                        dgvOutput.BeginEdit(true);
                        return;
                    }
                }
            }
            #endregion  
            foreach (DataGridViewRow dr in dgvOutput.Rows)
            {
                if (dr.Cells["OutputName"].EditedFormattedValue.ToString() == "" || dr.Cells["Dose"].EditedFormattedValue.ToString() == "")
                {
                    continue;
                }
                string OutputName = dr.Cells["OutputName"].EditedFormattedValue.ToString().Trim();
                int outId = 0;
                OutputLiquids OutputLiquidsRef = null;
                OutputLiquidsRef = BOutputLiquids.SelectSingle(" Name='" + OutputName + "'", null, RecursiveType.None, 0);
                if (OutputLiquidsRef == null)
                {
                    OutputLiquidsRef = new OutputLiquids();
                    OutputLiquidsRef.Name = OutputName;
                    OutputLiquidsRef.HelpCode = PublicMethod.GetFirstLetter(OutputName);
                    OutputLiquidsRef.IsValid = 1;
                    OutputLiquidsRef.OperatorNo = PublicMethod.OperatorNo;
                    OutputLiquidsRef.OperateDate = DateTime.Now;
                    OutputLiquidsRef.Id = BOutputLiquids.Insert(OutputLiquidsRef);
                }
                outId = OutputLiquidsRef.Id.Value;
                //实例化OutputLiquids对象
                FactOutputLiquids liquids = new FactOutputLiquids();
                liquids.OutputLiquidsName = OutputName;
                liquids.PatientId = _record.PatientId.Value;
                liquids.OutputLiquidsId = outId;
                liquids.OutputLiquidsTypeId = OutputLiquidTypeId;
                liquids.Dosage = Convert.ToDecimal(dr.Cells["Dose"].Value);
                liquids.DosageUnit = dr.Cells["DoseUnit"].EditedFormattedValue.ToString();
                if (dr.Cells["BeginTime"].EditedFormattedValue.ToString() != "")
                {
                    liquids.BeginTime = Convert.ToDateTime(dr.Cells["BeginTime"].Value.ToString());
                }
                liquids.EndTime = dr.Cells["EndTime"].EditedFormattedValue.ToString() != "" ? Convert.ToDateTime(dr.Cells["EndTime"].Value.ToString()) : liquids.BeginTime;
                liquids.IsContinue = dr.Cells["Continue"].EditedFormattedValue.ToString() != "" ? 1 : 0;
                liquids.Remark = dr.Cells["Remark"].EditedFormattedValue.ToString();
                liquids.OperatorNo = PublicMethod.OperatorNo;
                liquids.OperatorName = PublicMethod.OperatorName;
                liquids.OperateDate = DateTime.Now;
                if (dr.Tag == null)
                {
                    ////将事件对象保存到集合
                    int id = BFactOutputLiquids.Insert(liquids);
                    liquids.Id = id;
                    _record.FactOutputLiquidsList.Add(liquids);
                    //将新增的事件Id保存到Row
                    dr.Tag = id;
                }
                else
                {
                    liquids.Id = Convert.ToInt32(dr.Tag);
                    //将修改的事件保存到集合
                    foreach (FactOutputLiquids eventRecord in _record.FactOutputLiquidsList)
                    {
                        if (eventRecord.Id == liquids.Id)
                        {
                            //eventRecord.clearAddObj(zgcAnaesRecord);
                            _record.FactOutputLiquidsList.Remove(eventRecord);
                            _record.FactOutputLiquidsList.Add(liquids);
                            break;
                        }
                    }
                    //修改时间对象
                    BFactOutputLiquids.Update(liquids);
                }
            }
            OutParam();
            new frmMessageBox().Show();
            //this.Close(); 
        }
        #region DataGridView数字单元格验证 GZ
        public DataGridViewTextBoxEditingControl dgvTxt = null; // 声明 一个文本 CellEdit
        private void dgvOutput_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            //判断类型
            if (dgvOutput.CurrentRow.Index != -1 && dgvOutput.CurrentCell.ColumnIndex == 1)
            {
                ComboBox comboBox = (ComboBox)e.Control;
                comboBox.SelectedIndexChanged -= new EventHandler(dgvComboBox_SelectedIndexChanged);
                comboBox.SelectedIndexChanged += new EventHandler(dgvComboBox_SelectedIndexChanged);
            }
            if (dgvTxt != null && (dgvOutput.CurrentCell.ColumnIndex == 4))
            {
                dgvTxt.KeyPress -= new KeyPressEventHandler(dgvTxt_KeyPress); // 绑定事件
            }
            if (dgvTxt != null && (dgvOutput.CurrentCell.ColumnIndex == 7))
            {
                dgvTxt = (DataGridViewTextBoxEditingControl)e.Control; // 得到单元格
                dgvTxt.KeyPress -= new KeyPressEventHandler(dgvTxt_KeyPress); // 绑定事件
            }
            if (dgvOutput.CurrentCell.ColumnIndex == 2)
            {
                dgvTxt = (DataGridViewTextBoxEditingControl)e.Control; // 得到单元格
                dgvTxt.KeyPress -= new KeyPressEventHandler(dgvTxt_KeyPress); // 绑定事件
                dgvTxt.KeyPress += new KeyPressEventHandler(dgvTxt_KeyPress); // 绑定事件
                if (dgvOutput.CurrentRow.Cells[4].Value == null || dgvOutput.CurrentRow.Cells[4].Value.ToString() == "")
                {
                    dgvOutput.CurrentRow.Cells[4].Value = DateTime.Now;
                }
            }
            if (e.Control.GetType().Equals(typeof(DevComponents.DotNetBar.Controls.DataGridViewDateTimeInputEditingControl)))
                ((DevComponents.DotNetBar.Controls.DataGridViewDateTimeInputEditingControl)e.Control).DateTimeSelectorVisibility = DevComponents.Editors.DateTimeAdv.eDateTimeSelectorVisibility.DateSelector;
        }
        /// 
        /// DataGridViewComboBoxCell单元格改变选择的事件
        /// 
        /// 
        /// 
        void dgvComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            //ComboBox cbo = (ComboBox)sender;
            //if (cbo.SelectedIndex > 0)
            //{
            //    if (cbo.SelectedValue is OutputLiquids)
            //    {
            //        dgvOutput.CurrentCell.Tag = ((OutputLiquids)cbo.SelectedValue).Id;
            //    }
            //    else
            //    {
            //        dgvOutput.CurrentCell.Tag = cbo.SelectedValue;
            //    }
            //    //dgvOutput.CurrentCell.Tag = cbo.SelectedValue;
            //    OutputLiquids ot = BOutputLiquids.SelectSingle(Convert.ToInt32(dgvOutput.CurrentCell.Tag));
            //    #region 增加常用出量后取消此功能 20160816 GZ
            //    //dgvOutput.CurrentRow.Cells["DoseUnit"].Value = BBasicDictionary.SelectSingle(" Id=(select Id from BasicDictionary where Explain='剂量' and IsValid=1 and Name = '" + ot.Unit + "')", null).Id;
            //    //dgvOutput.CurrentRow.Cells["BeginTime"].Value = PublicMethod.ServerTime().ToString("MM-dd HH:mm");
            //    #endregion
            //}
        }
        void dgvTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (dgvOutput.CurrentRow.Cells[1].EditedFormattedValue.ToString() == "")
            {
                e.Handled = true;
                return;
            }
            if (e.KeyChar < 48 || e.KeyChar > 57)
            {
                if (e.KeyChar != 46 && e.KeyChar != 8 && e.KeyChar != 13)
                {
                    e.Handled = true;
                }
            }
            else
            {
                try
                {
                    dgvOutput.CurrentRow.Cells["DoseUnit"].Value = "ml";
                    if (dgvOutput.CurrentRow.Cells["BeginTime"].EditedFormattedValue.ToString() == "")
                    {
                        dgvOutput.CurrentRow.Cells["BeginTime"].Value = DateTime.Now;
                    }
                }
                catch (Exception)
                {
                }
            }
            if (e.KeyChar == 8 || e.KeyChar == 46)
            {
                return;
            }
            TextBox tb = sender as TextBox;
            int n = tb.Text.IndexOf(".");
            if (n < 0)
            {
                if (tb.Text.Length > 5)
                {
                    e.Handled = true;
                }
            }
            else
            {
                if (tb.Text.Substring(n).Length > 2)
                {
                    e.Handled = true;
                }
                if (n > 6)
                {
                    e.Handled = true;
                }
            }
        }
        #endregion
        private void frmFactOutputLiquidsNew_FormClosing(object sender, FormClosingEventArgs e)
        {
            //List UpdateRecordList = GetEventsList();
            //if (UpdateRecordList.Count > 0)
            //{
            //    DialogResult dialogResult = MessageBox.Show("记录尚未保存,是否保存当前记录?", "系统提示", MessageBoxButtons.YesNo);
            //    if (dialogResult == DialogResult.Yes)
            //    {
            //        btnSave_Click(null, null);
            //    }
            //}
            ////this.Hide();
            ////e.Cancel = true;
        }
        public bool equelEvents(FactOutputLiquids oldDrug, FactOutputLiquids newDrug)
        {
            bool b = true;
            if (oldDrug.Remark != newDrug.Remark) b = false;
            if (oldDrug.Dosage != newDrug.Dosage) b = false;
            if (oldDrug.BeginTime != null && newDrug.BeginTime != null && oldDrug.BeginTime.ToString("yyyy-MM-dd HH:mm") != newDrug.BeginTime.ToString("yyyy-MM-dd HH:mm")) b = false;
            if (oldDrug.EndTime != newDrug.EndTime && oldDrug.EndTime.ToString("HH:mm") != newDrug.EndTime.ToString("HH:mm")) b = false;
            return b;
        }
        /// 
        /// 当前单元格内容发生改变时,将改变提交
        /// 
        /// 
        /// 
        private void dgvDrugs_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            if (dgvOutput.IsCurrentCellDirty)
            {
                dgvOutput.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }
        private void dgvOutput_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            if (e.Exception.Message == "DataGridViewComboBoxCell 值无效。")
            {
                //try
                //{
                //    object value = _dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;
                //    if (!((DataGridViewComboBoxCell)_dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex]).Items.Contains(value))
                //    {
                //        ((DataGridViewComboBoxCell)_dataGridView.Rows[e.RowIndex].Cells[e.ColumnIndex]).Items.Add(value);
                //        e.ThrowException = false;
                //    }
                //}
                //catch (Exception)
                //{
                //    e.ThrowException = false;
                //}
            }
        }
        private void panel2_Paint(object sender, PaintEventArgs e)
        {
        }
    }
}