using AIMSBLL;
using AIMSModel;
using DevComponents.DotNetBar; 
using DrawGraph;
using AIMSExtension;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DataDictionary;
namespace AIMS.OperationAanesthesia
{
    public partial class frmBloodGasAnalysisNew : Form
    {
        public frmBloodGasAnalysisNew()
        {
            InitializeComponent();
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
        }
        /// 
        /// 图表控件
        /// 
        public DrawGraph.ZedGraphControl zgcAnaesRecord;
        public DrawGraph.OperationRecord _record;
        /// 
        /// 血气分析对象
        /// 
        FactBloodGasAnalysis Analysis;
        private EditState CurrentState;
        /// 
        /// 窗体加载
        /// 
        /// 
        /// 
        private void frmAnalysis_Load(object sender, EventArgs e)
        {
            ControlExtension.ClearControl(panel1);
            //ControlExtension.EnabledControl(panel1, false);
            radioButton1.Checked = true;
            this.Text = "血气分析";
            dgvAnalysis.AutoGenerateColumns = false;
            BindBloodListDict();
            BindDgv();
            dgvAnalysis.PaintEnhancedSelection = false;
            this.AnalysisBeginTime.Value = DateTime.Now;
        }
        /// 
        /// 绑定血气分析字典
        /// 
        private void BindBloodListDict()
        {
            List bloodGasAnalysisDicts = BBloodGasAnalysisDict.Select(" IsValid=1 and isShow=1 order by orderby asc ", null, RecursiveType.None, 0);
            int y = -30;
            int x = 0;
            for (int i = 0; i < bloodGasAnalysisDicts.Count; i++)
            {
                if (i % 8 == 0)
                {
                    y += 35;
                    x = 0;
                }
                x += 5;
                System.Windows.Forms.Label lab = new System.Windows.Forms.Label();
                //lab.AutoSize = true;
                lab.Font = new System.Drawing.Font("微软雅黑", 10f);
                lab.Location = new System.Drawing.Point(x, y);
                lab.Size = new System.Drawing.Size(80, 26);
                lab.TextAlign = ContentAlignment.MiddleCenter;
                lab.Text = bloodGasAnalysisDicts[i].ShowName.ToString().Trim();
                panel2.Controls.Add(lab);
                x += 82;
                TextBox lb = new TextBox();
                lb.Tag = bloodGasAnalysisDicts[i];
                //设定位置
                lb.Size = new System.Drawing.Size(55, 26);
                lb.Font = new System.Drawing.Font("微软雅黑", 10.5f);
                lb.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtPH_KeyDown);
                lb.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.dgvTxt_KeyPress);
                lb.Leave += lb_Leave;
                lb.Location = new Point(x, y);
                panel2.Controls.Add(lb);
                x += 55;
                System.Windows.Forms.DataGridViewTextBoxColumn colum = new System.Windows.Forms.DataGridViewTextBoxColumn();
                colum.HeaderText = bloodGasAnalysisDicts[i].ShowName;
                colum.Name = bloodGasAnalysisDicts[i].ShowName;
                colum.Width = 80;
                this.dgvAnalysis.Columns.Add(colum);
            }
            System.Windows.Forms.DataGridViewTextBoxColumn columouthe = new System.Windows.Forms.DataGridViewTextBoxColumn();
            columouthe.DataPropertyName = "AnalysisResult";
            columouthe.HeaderText = "分析结果";
            columouthe.Name = "value";
            columouthe.Width = 120;
            this.dgvAnalysis.Columns.Add(columouthe);
        }
        void lb_Leave(object sender, EventArgs e)
        {
            TextBox t = sender as TextBox;
            if (t.Text == "")
            {
                return;
            }
            BloodGasAnalysisDict bg = t.Tag as BloodGasAnalysisDict;
            if (decimal.Parse(t.Text) < bg.LowLimit || decimal.Parse(t.Text) > bg.HighLimit)
            {
                t.Font = new Font(t.Font, t.Font.Style | FontStyle.Bold);
                t.ForeColor = Color.Red;
            }
            else
            {
                t.ForeColor = Color.Black;
            }
        }
        /// 
        /// 绑定数据到Datagridview
        /// 
        private void BindDgv()
        {
            List list = BFactBloodGasAnalysis.Select(" OperationRecordId=@OperationRecordId", new ParameterList("@OperationRecordId", _record.Id), RecursiveType.None, 0);
            dgvAnalysis.DataSource = list;
            foreach (DataGridViewRow item in dgvAnalysis.Rows)
            {
                FactBloodGasAnalysis bloodGasAnalysis = _record.FactBloodGasAnalysisList.Where((a) => a.Id.ToString() == item.Cells[0].Value.ToString()).ToList()[0];
                if (bloodGasAnalysis.FactBloodGasAnalysisDataList != null)
                {
                    foreach (var dicval in bloodGasAnalysis.FactBloodGasAnalysisDataList)
                    {
                        if (dicval.Value != null)
                        {
                            try
                            {//To:item.Cells[dicval.Name]  会报错;FactBloodGasAnalysis字段名称没有FactBloodGasAnalysisData  Name值  最优解决办法:sql 查询数据表字段名称返回字段集合去过滤 
                                //Date:20220228  By:Leftyer  
                                //Detail: 解决方法最简单的使用了异常捕获;抛异常后继续执行 
                                item.Cells[dicval.Name].Value = double.Parse(dicval.Value.ToString());
                                //if (dicval.DictRef.LowLimit != null && dicval.DictRef.HighLimit != null)
                                //{
                                //    if (dicval.DictRef.LowLimit.ToString() != "" && dicval.DictRef.HighLimit.ToString() != "")
                                //    {
                                //        if (dicval.Value < dicval.DictRef.LowLimit || dicval.Value > dicval.DictRef.HighLimit)
                                //        {
                                //            item.Cells[dicval.Name].Style.ForeColor = Color.Red;
                                //            item.Cells[dicval.Name].Style.Font = new Font("微软雅黑", 10.5f, FontStyle.Bold);
                                //        }
                                //    }
                                //}
                            }
                            catch (Exception ex)
                            {//
                                PublicMethod.WriteLog(ex);
                                continue;
                            }
                        }
                    }
                }
            }
            dgvAnalysis.ClearSelection();
        }
        /// 
        /// 添加
        /// 
        /// 
        /// 
        private void tsbAddAnalysis_Click(object sender, EventArgs e)
        {
            CurrentState = EditState.ADD;
            //tsbCancel_Click(null, null);
            ControlExtension.EnabledControl(panel1, true);
            AnalysisBeginTime.Value = DateTime.Now;
        }
        /// 
        /// 血气分析
        /// 
        /// 
        private void setDateAnalysis()
        {
            //if (txtPH.Text != "") Analysis.PH = Decimal.Parse(txtPH.Text); 
            Analysis.BloodGasType = radioButton1.Checked == true ? Analysis.BloodGasType = "动脉血气" : "静脉血气";
            Analysis.AnalysisResult = txtBloodResult.Text.Trim() == null ? "" : txtBloodResult.Text.Trim();
            Analysis.RecordTime = AnalysisBeginTime.Value;
            Analysis.OperationRecordId = _record.Id;
            Analysis.OperatorId = PublicMethod.OperatorId;
            Analysis.OperatorTime = DateTime.Now;
        }
        /// 
        /// 修改
        /// 
        /// 
        /// 
        private void tsbModifyAnalysis_Click(object sender, EventArgs e)
        {
            if (!(dgvAnalysis.SelectedRows.Count > 0))
            {
                MessageBox.Show("请选择列表中的一项");
                return;
            }
            CurrentState = EditState.EDIT;
            ControlExtension.EnabledControl(panel1, true);
            this.Text = "修改血气分析";
            Analysis = _record.FactBloodGasAnalysisList.Where(c => c.Id == Convert.ToInt32(dgvAnalysis.SelectedRows[0].Cells["Id"].Value)).ToList()[0];
            if (Analysis.BloodGasType == "动脉血气") { radioButton1.Checked = true; } else { radioButton2.Checked = true; }
            AnalysisBeginTime.Text = Analysis.RecordTime.Value.ToString();
            txtBloodResult.Text = Analysis.AnalysisResult;
            foreach (Control ctrl in panel2.Controls)
            {
                if (ctrl is TextBox)
                {
                    TextBox textBox = (ctrl as TextBox);
                    if (textBox.Tag != null)
                    {
                        try
                        {
                            BloodGasAnalysisDict dict = (BloodGasAnalysisDict)textBox.Tag;
                            List recordData =
                            Analysis.FactBloodGasAnalysisDataList.Where(a => a.DictId == dict.Id).ToList();
                            if (recordData != null && recordData.Count > 0)
                                textBox.Text = double.Parse(recordData[0].Value.ToString()).ToString();
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
            }
        }
        /// 
        /// 取消
        /// 
        /// 
        /// 
        private void tsbCancel_Click(object sender, EventArgs e)
        {
            CurrentState = EditState.BROWSE;
            ControlExtension.ClearControl(panel1);
            ControlExtension.EnabledControl(panel1, false);
        }
        /// 
        /// 关闭
        /// 
        /// 
        /// 
        private void tsbExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        /// 
        /// 保存
        /// 
        /// 
        /// 
        private void tsbSave_Click(object sender, EventArgs e)
        {
            if (!InputValid()) return;
            if (Analysis == null) Analysis = new FactBloodGasAnalysis();
            Analysis.OperationRecordId = _record.Id;
            if (Analysis.Id == null)
            {
                setDateAnalysis();
                Analysis.Id = BFactBloodGasAnalysis.Insert(Analysis);
                _record.FactBloodGasAnalysisList.Add(Analysis);
            }
            else
            {
                BFactBloodGasAnalysisData.Delete(" RecordId=" + Analysis.Id, null);
                if(zgcAnaesRecord != null)
                Analysis.clearAddObj(zgcAnaesRecord);
                setDateAnalysis();
                BFactBloodGasAnalysis.Update(Analysis);
            }
            if (Analysis.Id != null)
            {
                Analysis.FactBloodGasAnalysisDataList = new List();
                foreach (Control ctrl in panel2.Controls)
                {
                    if (ctrl is TextBox)
                    {
                        TextBox textBox = (ctrl as TextBox);
                        if (textBox.Tag != null)
                        {
                            try
                            {
                                BloodGasAnalysisDict dict = (BloodGasAnalysisDict)textBox.Tag;
                                FactBloodGasAnalysisData recordData = new FactBloodGasAnalysisData();
                                recordData.RecordId = Analysis.Id;
                                recordData.DictId = dict.Id;
                                recordData.Name = dict.ShowName;
                                recordData.Value = Convert.ToDecimal(textBox.Text);
                                recordData.Id = BFactBloodGasAnalysisData.Insert(recordData);
                                recordData.DictRef = dict;
                                Analysis.FactBloodGasAnalysisDataList.Add(recordData);
                                //if (dict.IsWarning == 1 && dict.LowLimit != null && dict.HighLimit != null)
                                //    if (recordData.Value < dict.LowLimit || recordData.Value > dict.HighLimit)
                                //    {
                                //        message += "  " + dict.Name + "的值:" + recordData.Value + " 超出报警范围(" + dict.LowLimit + "~" + dict.HighLimit + ")   \n\r";
                                //    }
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                        }
                    }
                }
            }
            //if (message != "")
            //{
            //    MessageBox.Show(message + "请注意!", "系统提示");
            //}
            CurrentState = EditState.BROWSE;
            ControlExtension.ClearControl(panel1);
            //ControlExtension.EnabledControl(panel1, false);
            Analysis = null;
            BindDgv();
        }
        /// 
        /// 输入验证
        /// 
        /// 
        private bool InputValid()
        {
            bool b = true;
            foreach (Control ctrl in panel2.Controls)
            {
                if (ctrl is TextBox)
                {
                    TextBox textBox = (ctrl as TextBox);
                    if (textBox.Tag != null)
                    {
                        try
                        {
                            string Value = textBox.Text;
                            if (Value != null && Value != "" && Value.Trim() != "" && Value.Trim() != "-")
                            {
                                double douValue;
                                if (double.TryParse(Value, out douValue) == false)
                                {
                                    MessageBox.Show("请输入正确的数值!", "系统提示");
                                    textBox.Focus();
                                    b = false;
                                }
                            }
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
            }
            return b;
        }
        /// 
        /// 删除血气分析
        /// 
        /// 
        /// 
        private void tsbDelConsumable_Click(object sender, EventArgs e)
        {
            if (dgvAnalysis.SelectedRows.Count <= 0)
            {
                MessageBox.Show("请选择要删除的血气分析信息", "删除血气分析信息", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            DialogResult dr = MessageBox.Show("确定要删除该血气分析信息吗?", "删除血气分析信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
            {
                try
                {
                    FactBloodGasAnalysis Blood = _record.FactBloodGasAnalysisList.Where(c => c.Id == Convert.ToInt32(dgvAnalysis.SelectedRows[0].Cells["ID"].Value)).ToList()[0];
                    BFactBloodGasAnalysisData.Delete(" RecordId=" + Blood.Id, null);
                    BFactBloodGasAnalysis.Delete(Blood);
                    if (zgcAnaesRecord != null)
                        Blood.clearAddObj(zgcAnaesRecord);
                    _record.FactBloodGasAnalysisList.Remove(Blood);
                    ControlExtension.ClearControl(panel1);
                    CurrentState = EditState.BROWSE;
                }
                catch (Exception exp)
                {
                    PublicMethod.WriteLog(exp, ""); return;
                }
                BindDgv();
            }
        }
        /// 
        /// 设置自增列
        /// 
        /// 
        /// 
        private void dgvAnalysis_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, dgvAnalysis.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
            dgvAnalysis.RowHeadersDefaultCellStyle.Font,
            rectangle,
            dgvAnalysis.RowHeadersDefaultCellStyle.ForeColor,
            TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
        /// 
        /// TabIndex顺序
        /// 
        /// 
        /// 
        private void txtPH_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                this.SelectNextControl(this.ActiveControl, true, true, true, true);  //需设置textBox的TabIndex顺序属性
            }
        }
        void dgvTxt_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar < 48 || e.KeyChar > 57)
            {
                if (e.KeyChar != 46 && e.KeyChar != 45 && e.KeyChar != 8 && e.KeyChar != 13)
                {
                    e.Handled = true;
                }
            }
            TextBox tb = sender as TextBox;
            if (e.KeyChar == 46)
            {
                int n = tb.Text.LastIndexOf(".");
                if (n > 0) e.Handled = true;
            }
            //if (e.KeyChar == 45 || e.KeyChar == '-')
            //{
            //    int n = tb.Text.LastIndexOf(".");
            //    if (n > 0) e.Handled = true;
            //    e.Handled = true;
            //}
        }
        private void frmBloodGasAnalysisNew_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (CurrentState == EditState.ADD || CurrentState == EditState.EDIT)
            {
                DialogResult dialogResult = MessageBox.Show("记录尚未保存,是否保存当前记录?", "系统提示", MessageBoxButtons.YesNo);
                if (dialogResult == DialogResult.Yes)
                {
                    tsbSave_Click(null, null);
                }
            }
        }
    }
    public enum EditState
    {
        /// 
        /// 浏览
        /// 
        BROWSE,
        /// 
        /// 增加
        /// 
        ADD,
        /// 
        /// 修改
        /// 
        EDIT
    }
}