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 System.Reflection;
using DevComponents.DotNetBar;
using System.IO;
using System.Threading.Tasks;
using AIMSModel;
using AIMSExtension;
using AIMSBLL;
using DataDictionary;
namespace AIMS.OperationAfter.UI
{
    public partial class frmQualityControlViewParent : Form
    {
        /// 
        /// 患者手术申请ID
        /// 
        public int PatientApplyId = -1;
        const int CLOSE_SIZE = 18;   //关闭图标尺寸
        public string PerortName;
        int i;
        int j;
        //患者信息
        DataRow vPatient = null;
        /// 
        /// 质控表集合
        /// 
        private List _qcList;
        /// 
        /// 质控表配置集合
        /// 
        List qcConfigs;
        /// 
        /// 质控记录
        /// 
        private QualityControlRecord qcr = null;
        /// 
        /// 选中的质控表
        /// 
        QualityControl selecQC = null;
        /// 
        /// 声明保存数据时的状态
        /// 
        public EditState _state;
        private bool valChang = false;
        public frmQualityControlViewParent()
        {
            InitializeComponent();
            panel2.Width = groupBox2.Width;
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
        }
        /// 
        /// 医疗文书窗体加载
        /// 
        /// 
        /// 
        private void frmQualityControlViewParent_Load_1(object sender, EventArgs e)
        {
            System.Drawing.Size mSize = SystemInformation.WorkingArea.Size;
            i = mSize.Height;
            j = mSize.Width;
            txtnameOrHnum.Text = "姓名或住院号关键字";
            txtnameOrHnum.ForeColor = Color.FromArgb(164, 164, 164);
            dtpSearchTime.Value = DateTime.Now;
            panel1.Visible = false;
        }
        /// 
        /// 手术间信息加载到treeview
        /// 
        private void FullTreeView()
        {
            treeViewPatient.Nodes.Clear();
            try
            {
                DateTime beginTime = Convert.ToDateTime(dtpSearchTime.Value.ToString("yyyy-MM-dd 00:00:00"));
                DateTime endTime = Convert.ToDateTime(dtpSearchTime.Value.ToString("yyyy-MM-dd 23:59:59"));
                DataTable vPlanedOpeList = BOperationApply.GetOperationFrontDataTable(beginTime.ToString("yyyy-MM-dd 00:00:00"), endTime.ToString("yyyy-MM-dd 23:59:59"));
                if (vPlanedOpeList.Rows.Count <= 0) return;
                string roomname = "";
                TreeNode roomnodenull = new TreeNode("空白单");
                TreeNode nonode = new TreeNode("无患者");
                nonode.ImageIndex = 2;
                roomnodenull.Nodes.Add(nonode);
                roomnodenull.Tag = -1;
                treeViewPatient.Nodes.Add(roomnodenull);
                foreach (DataRow po in vPlanedOpeList.Rows)
                {
                    if (po["OperationRoom"].ToString() != roomname)
                    {
                        roomname = po["OperationRoom"].ToString();
                        TreeNode roomnode = new TreeNode(roomname);
                        roomnode.Tag = po["OperationRoomId"].ToString();
                        treeViewPatient.Nodes.Add(roomnode);
                        foreach (DataRow vpo in vPlanedOpeList.Rows)
                        {
                            if (po["OperationRoom"].ToString() == vpo["OperationRoom"].ToString())
                            {
                                TreeNode sNode = new TreeNode(vpo["PatientName"].ToString() + "-" + "" );
                                sNode.Tag =  vpo;
                                roomnode.Nodes.Add(sNode);
                            }
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                //异常处理保存
                PublicMethod.WriteLog(exp, "");
            }
        }
        String templateName = string.Empty;
        /// 
        /// 添加医疗文书选项卡
        /// 
        public Form frmss;
        /// 
        /// 查询手术间患者
        /// 
        /// 
        /// 
        private void btnChoose_Click_1(object sender, EventArgs e)
        {
            this.treeViewPatient.AfterSelect -= new System.Windows.Forms.TreeViewEventHandler(this.treeViewPatient_AfterSelect);
            FullTreeView();
            treeViewPatient.ExpandAll();
            this.treeViewPatient.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeViewPatient_AfterSelect);
        }
        private void dtpSearchTime_ValueChanged(object sender, EventArgs e)
        {
            panel2.Width = groupBox2.Width;
            txtnameOrHnum.Text = "";
            this.treeViewPatient.AfterSelect -= new System.Windows.Forms.TreeViewEventHandler(this.treeViewPatient_AfterSelect);
            FullTreeView();
            treeViewPatient.ExpandAll();
            //if (treeViewPatient.Nodes.Count > 0) treeViewPatient.SelectedNode = treeViewPatient.Nodes[0];
            this.treeViewPatient.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeViewPatient_AfterSelect);
        }
        private void txtnameOrHnum_Leave(object sender, EventArgs e)
        {
            if (txtnameOrHnum.Text.Equals(""))
            {
                txtnameOrHnum.Text = "姓名或住院号关键字";
                txtnameOrHnum.ForeColor = Color.FromArgb(164, 164, 164);
            }
        }
        private void btnBeforeDay_Click(object sender, EventArgs e)
        {
            dtpSearchTime.Value = dtpSearchTime.Value.AddDays(-1);
        }
        private void btnAfterDay_Click(object sender, EventArgs e)
        {
            dtpSearchTime.Value = dtpSearchTime.Value.AddDays(1);
        }
        private void txtnameOrHnum_KeyUp(object sender, KeyEventArgs e)
        {
            this.treeViewPatient.AfterSelect -= new System.Windows.Forms.TreeViewEventHandler(this.treeViewPatient_AfterSelect);
            FullTreeView();
            if (treeViewPatient.Nodes.Count > 0)
            {
                treeViewPatient.ExpandAll();
                //treeViewPatient.SelectedNode = treeViewPatient.Nodes[0];
            }
            this.treeViewPatient.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeViewPatient_AfterSelect);
        }
        private void txtnameOrHnum_Click_1(object sender, EventArgs e)
        {
            txtnameOrHnum.Text = "";
            txtnameOrHnum.ForeColor = Color.Black;
        }
        private void txtnameOrHnum_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                FullTreeView();
                treeViewPatient.ExpandAll();
            }
        }
        /// 
        /// 赋值患者基本信息
        /// 
        /// 
        ///  
        private void treeViewPatient_AfterSelect(object sender, TreeViewEventArgs e)
        {
              vPatient = treeViewPatient.SelectedNode.Tag as DataRow;
            string whereString = "";
            //如果有患者就是读患者的记录,否则以日期为条件取记录
            if (vPatient != null)
            { 
                whereString = " and PatientId = '" + vPatient["PatientId"].ToString() + "'";
                LabPatient.Text = vPatient["PatientName"].ToString();
                labDepartment.Text = vPatient["ApplyDepName"].ToString();
                labHospitalNum.Text = vPatient["MdrecNo"].ToString();
            } 
            ControlExtension.ClearControl(panel5);
            panel4.Controls.Clear();
            panel1.Visible = true;
            //得到质控表集合
            _qcList = BQualityControl.Select(" IsValid = 1", null);
            this.toolStrip1.Items.Clear();
            foreach (QualityControl qc in _qcList)
            {
                QualityControlRecord qcrT = BQualityControlRecord.SelectSingle(" QCId = '" + qc.Id + "'" + whereString, null, RecursiveType.Child, 1);
                ToolStripButton toolStripButton = new ToolStripButton();
                //toolStripButton.Image = global::AIMSProperties.Resources.报表;
                toolStripButton.ImageTransparentColor = System.Drawing.Color.Magenta;
                toolStripButton.Name = "toolStripButton" + qc.Id;
                toolStripButton.Size = new System.Drawing.Size(123, 22);
                //如果已经填写过则打勾
                toolStripButton.Text = ((qc.Name.Length >= 5) ? qc.Name.Substring(0, 5) : qc.Name.Substring(0, qc.Name.Length)) + ((qcrT != null) ? " √" : "");
                toolStripButton.ToolTipText = qc.Name;
                toolStripButton.Tag = qc;
                toolStripButton.Click += ToolStripButton1_Click;
                this.toolStrip1.Items.Add(toolStripButton);
            }
            if (vPatient != null)
            {
                PatientApplyId = int.Parse(vPatient["ApplyId"].ToString());
            }
            if (this.toolStrip1.Items.Count > 0)
            {
                //暂时取消
                ToolStripButton1_Click(this.toolStrip1.Items[0], null);
            }
        }
        /// 
        /// 点击某个质控表
        /// 
        /// 
        /// 
        private void ToolStripButton1_Click(object sender, EventArgs e)
        {
            ToolStripButton tsb = sender as ToolStripButton;
            if (tsb != null)
            {
                selecQC = tsb.Tag as QualityControl;
                LoadQualityControl(selecQC);
            }
        }
        /// 
        /// 加载质控记录
        /// 
        /// 
        private void LoadQualityControl(QualityControl selecQC)
        {
            string whereString = "";
            if (vPatient != null)
            {
                whereString = " and PatientId = '" + vPatient["PatientId"].ToString() + "'";
            }
            else
            {
                whereString = " and (PatientId = '' or PatientId is NULL) and RecordTime = '" + DateTime.Now.ToShortDateString() + "' ";
            }
            //根据质控表得到质控记录
            qcr = BQualityControlRecord.SelectSingle(" QCId = '" + selecQC.Id + "'" + whereString, null, RecursiveType.Child, 1);
            labQCName.Text = selecQC.Name;
            if (qcr == null)
            {
                //新建质控记录
                _state = EditState.ADD;
                //增加手术的基本数据
                qcr = new QualityControlRecord();
                qcr.QualityControlDetailedRecordList = new List();
                //加载质控项配置
                qcConfigs = BQualityControlConfig.Select(" QCId = '" + selecQC.Id + "'", null, RecursiveType.Parent, 1);
                qcConfigs = qcConfigs.Where(s => s.QCIRef.IsValid == 1).ToList();
                qcConfigs.Sort();
                foreach (QualityControlConfig qcc in qcConfigs)
                {
                    if (qcc.QCIRef != null && qcc.QCIRef.IsValid == 1)
                    {
                        QualityControlDetailedRecord qcdr = new QualityControlDetailedRecord();
                        qcdr.RecordId = qcr.Id; //这个位置暂时是宿舍
                        qcdr.QCIId = qcc.QCIId;
                        //qcdr.QCValue = selecQC.Name;
                        qcdr.QCValue2 = "";
                        qcdr.QCIRef = qcc.QCIRef;
                        qcr.QualityControlDetailedRecordList.Add(qcdr);
                        qcdr.QCValue = int.Parse(qcc.MOrderBy.ToString()); //给排序值
                    }
                }
            }
            else
            {
                _state = EditState.EDIT;
                //加载质控项配置
                qcConfigs = BQualityControlConfig.Select(" QCId = '" + selecQC.Id + "'", null, RecursiveType.Parent, 1);
                qcConfigs = qcConfigs.Where(s => s.QCIRef.IsValid == 1).ToList();
                qcr.QualityControlDetailedRecordList = qcr.QualityControlDetailedRecordList.Where(s => s.QCIRef.IsValid == 1).ToList();
                qcConfigs.Sort();
                foreach (QualityControlDetailedRecord qcdr in qcr.QualityControlDetailedRecordList)
                {
                    QualityControlConfig c = qcConfigs.FirstOrDefault(s => s.QCIId == qcdr.QCIId);
                    if (c != null)
                    {
                        qcdr.QCValue = int.Parse(c.MOrderBy.ToString()); //给排序值
                    }
                }
            }
            //设置质控记录的公共信息,有患者信息才加载患者信息
            if (vPatient != null)
            { 
                LabPatient.Text = vPatient["PatientName"].ToString();
                labDepartment.Text = vPatient["ApplyDepName"].ToString();
                labHospitalNum.Text = vPatient["MdrecNo"].ToString();
                qcr.OperationName = "";// vPatient.OperationName; //拟施手术
                //qcr.DepartmentId = int.Parse( vPatient["ApplyDepId"].ToString());
                qcr.DepartmentName =  vPatient["ApplyDepName"].ToString();
                qcr.PatientId = int.Parse( vPatient["PatientId"].ToString());
                qcr.PatientName =  vPatient["PatientName"].ToString();
                qcr.InPatientNumber =  vPatient["MdrecNo"].ToString();
                qcr.OperationApplyId = int.Parse( vPatient["ApplyId"].ToString()); 
                qcr.OperatorId = PublicMethod.OperatorId;
                labDepartment.Text = qcr.DepartmentName;
                LabPatient.Text = qcr.PatientName;
                labHospitalNum.Text = qcr.InPatientNumber; 
            }
            else
            {
                labDepartment.Text = "";
                LabPatient.Text = "";
                labHospitalNum.Text = ""; 
            }
            qcr.QCId = selecQC.Id;
            qcr.QCRef = selecQC;
            #region 绑定组件
            txtRemask.Text = qcr.Remark;
            txtPointDeduction.Text = qcr.PointDeduction.ToString();
            txtPersonLiable.Tag = qcr.PersonLiableId;
            txtPersonLiable.Text = qcr.PersonLiable;
            txtPersonLiable1.Tag = qcr.PersonLiable1Id;
            txtPersonLiable1.Text = qcr.PersonLiable1;
            labRecordTime.Text = qcr.RecordTime.ToString();
            panel4.Controls.Clear();
            int rows = 0;
            int cols = 0;
            //循环加载质控项控件
            qcr.QualityControlDetailedRecordList.Sort(new OrderComparer());
            foreach (QualityControlDetailedRecord qcdr in qcr.QualityControlDetailedRecordList)
            {
                Panel panl = new Panel();
                panl.AutoSize = false;
                panl.Width = 400;
                panl.Height = 48;
                QualityControlConfig config = qcConfigs.FirstOrDefault(s => s.QCIId == qcdr.QCIId && s.QCId == selecQC.Id && s.QCIRef.IsValid == 1);
                if (config == null) continue;
                int span = 50;
                if (cols > 0) span = 200;
                panl.Location = new Point(cols * panl.Width + span, rows * (panl.Height + 3));
                panel4.Controls.Add(panl);
                if (config.ViewModel != "")
                {
                    string vm = config.ViewModel.Replace(",", ",");
                    string[] vms = vm.Split(',');
                    foreach (string v in vms)
                    {
                        RadioButton cb = new RadioButton();
                        cb.Text = v;
                        cb.AutoSize = false;
                        cb.Width = Convert.ToInt32(panl.Width * 0.1);
                        cb.Font = new System.Drawing.Font("微软雅黑", 10.5f);
                        cb.Dock = DockStyle.Left;
                        cb.Tag = qcdr;
                        if (qcdr.QCValue2 == v)
                        {
                            cb.Checked = true;
                        }
                        cb.CheckedChanged -= new EventHandler(txt_Leave);
                        cb.CheckedChanged += new EventHandler(txt_Leave);
                        cb.Click -= new EventHandler(radio_click);
                        cb.Click += new EventHandler(radio_click);
                        //给CheckBox控件生成CheckedChanged事件cb_CheckedChanged
                        panl.Controls.Add(cb);
                    }
                }
                Label lab = new Label();
                lab.AutoSize = false;
                lab.TextAlign = ContentAlignment.MiddleLeft;
                lab.Width = Convert.ToInt32(panl.Width * 0.8);
                lab.Text = qcdr.QCIRef.Name;
                lab.Font = new System.Drawing.Font("微软雅黑", 10.5f);
                lab.Dock = DockStyle.Left;
                panl.Controls.Add(lab);
                //如果已加载15行,则另起一列,最多显示3列
                rows++;
                if (rows == 15)
                {
                    rows = 0;
                    cols++;
                    if (cols == 3)
                    {
                        return;
                    }
                }
            }
            #endregion
            //计算扣分
            jskf();
        }
        private void radio_click(object sender, EventArgs e)
        {
            RadioButton control = (RadioButton)sender;
            if (control == null) return;
            if (!valChang)
            {
                control.Checked = false;
            }
            valChang = false;
            QualityControlDetailedRecord qcdr = control.Tag as QualityControlDetailedRecord;
            if (qcdr != null)
            {
                if (control.Checked)
                {
                    qcdr.QCValue2 = control.Text;
                }
                else
                {
                    qcdr.QCValue2 = "";
                }
                qcr.PointDeduction = 0;
                jskf();
            }
        }
        /// 
        /// 计算扣分
        /// 
        private void jskf()
        {
            //foreach (QualityControlDetailedRecord r in qcr.QualityControlDetailedRecordList)
            //{
            //    if (r.QCValue2 == "×")
            //    {
            //        qcr.PointDeduction += 1;
            //    }
            //}
            //txtPointDeduction.Text = qcr.PointDeduction.ToString();
        }
        private void txt_Leave(object sender, EventArgs e)
        {
            //值变了
            valChang = true;
        }
        private void PatientDocumentNew_FormClosing(object sender, FormClosingEventArgs e)
        {
            try
            {
                string PicturePath = Application.StartupPath;
                PicturePath += @"\PrintWorkerImage\";
                if (Directory.Exists(PicturePath) == false)//如果不存在就创建file文件夹 
                {
                    Directory.CreateDirectory(PicturePath);
                }
                else
                {
                    DeleteFolder(PicturePath);
                }
            }
            catch (Exception ex)
            {
                PublicMethod.WriteLog(ex);
            }
        }
        /// 清空指定的文件夹,但不删除文件夹
        /// 
        /// 
        public static void DeleteFolder(string dir)
        {
            foreach (string d in Directory.GetFileSystemEntries(dir))
            {
                if (File.Exists(d))
                {
                    FileInfo fi = new FileInfo(d);
                    if (fi.Attributes.ToString().IndexOf("ReadOnly") != -1)
                        fi.Attributes = FileAttributes.Normal;
                    File.Delete(d);//直接删除其中的文件  
                }
                else
                {
                    DirectoryInfo d1 = new DirectoryInfo(d);
                    if (d1.GetFiles().Length != 0)
                    {
                        DeleteFolder(d1.FullName);////递归删除子文件夹
                    }
                    Directory.Delete(d);
                }
            }
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            if (qcr != null)
            {
                if (selecQC == null)
                {
                    MessageBox.Show("还没有选中具体的质控表");
                    return;
                }
                if (txtPersonLiable.Text.Trim() == "")
                {
                    MessageBox.Show("责任人必须填写");
                    return;
                }
                if (txtPersonLiable1.Text.Trim() == "")
                {
                    MessageBox.Show("质控人必须填写");
                    return;
                }
                List noQCDR = qcr.QualityControlDetailedRecordList.Where(s => s.QCValue2 == "").ToList();
                if (qcr.QualityControlDetailedRecordList.Count == noQCDR.Count())
                {
                    //如果细项都没有选中,则不让往下进行
                    MessageBox.Show("详细记录没有勾选");
                    return;
                }
                try
                {
                    qcr.PointDeduction = int.Parse(txtPointDeduction.Text.ToString());
                }
                catch (Exception  )
                {
                    MessageBox.Show("扣分项必须是数值");
                    txtPointDeduction.Focus();
                    return;
                }
                try
                {
                    qcr.OperatorTime = DateTime.Now;
                    //qcr.PersonLiableId = txtPersonLiable.Tag.ToString();
                    qcr.PersonLiable = txtPersonLiable.Text;
                    //qcr.PersonLiable1Id = txtPersonLiable1.Tag.ToString();
                    qcr.PersonLiable1 = txtPersonLiable1.Text;
                    qcr.Remark = txtRemask.Text.Trim();
                    if (_state == EditState.ADD)
                    {
                        qcr.RecordTime = DateTime.Now;
                        int recordId = BQualityControlRecord.Insert(qcr);
                        foreach (QualityControlDetailedRecord qcdr in qcr.QualityControlDetailedRecordList)
                        {
                            qcdr.RecordId = recordId;
                            BQualityControlDetailedRecord.Insert(qcdr);
                        }
                        //给导航加标识
                        ToolStripItem[] items = this.toolStrip1.Items.Find("toolStripButton" + selecQC.Id, false);
                        foreach (ToolStripItem item in items)
                        {
                            item.Text = item.Text + " √";
                        }
                    }
                    else
                    {
                        BQualityControlRecord.Update(qcr);
                        foreach (QualityControlDetailedRecord qcdr in qcr.QualityControlDetailedRecordList)
                        {
                            BQualityControlDetailedRecord.Update(qcdr);
                        }
                    }
                    if (selecQC != null)
                    {
                        LoadQualityControl(selecQC);
                        //PublicMethod.ShowMessage("保存成功!");
                    }
                }
                catch (Exception exp)
                {
                    PublicMethod.WriteLog(exp);
                }
            }
        }
        private void tsbExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void txtPersonLiable_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            setDoctor((sender as TextBox), 1, false, true);
        }
        /// 
        /// 根据工作类型 选择医生术者赋值TextBox
        /// 
        /// 医生术者TextBox
        /// 工作类型
        public void setDoctor(TextBox controlTextBox, int workersType, bool isRadio = false, bool isAddItem = false)
        {
            //Worker work = null;
            //if (controlTextBox.Tag != null && controlTextBox.Tag.ToString() != "")
            //{
            //    string[] array = controlTextBox.Tag.ToString().Split(',');
            //    if (array.Length > 0) work = BWorkers.SelectSingle(Convert.ToInt32(array[0]), RecursiveType.None, 0);
            //}
            //frmSelectWorkers_New fsw = new frmSelectWorkers_New();
            //fsw._deptId = -1;
            //fsw._controlName = controlTextBox;
            //fsw.isRadio = isRadio;
            //fsw.isAddItem = isAddItem;
            //fsw._workersType = workersType;
            //fsw._patientType = (vPatient == null) ? null : vPatient.PatientType;            
            //fsw.ShowDialog();
        }
        private void toolStripButton1_Click_1(object sender, EventArgs e)
        {
            try
            {
                if (qcr != null)
                {
                    //foreach (QualityControlDetailedRecord qcdr in qcr.QualityControlDetailedRecordList)
                    //{
                    //    if (qcdr.Id != null)
                    //    {
                    //        BQualityControlDetailedRecord.Delete(qcdr);
                    //    }
                    //}
                    BQualityControlDetailedRecord.Delete(" RecordId = " + qcr.Id, null);
                    if (qcr.Id != null)
                    {
                        BQualityControlRecord.Delete(qcr);
                        //给导航加标识
                        if (selecQC != null)
                        {
                            LoadQualityControl(selecQC);
                            ToolStripItem[] items = this.toolStrip1.Items.Find("toolStripButton" + selecQC.Id, false);
                            foreach (ToolStripItem item in items)
                            {
                                item.Text = item.Text.Replace("√", "").Trim();
                            }
                            MessageBox.Show("删除成功!");
                        }
                    }
                }
            }
            catch (Exception exp)
            {
                MessageBox.Show("保存失败,请查看日志");
                PublicMethod.WriteLog(exp);
            }
        }
    }
}