using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Xml.Linq;
using System.Web.Script.Serialization;
using System.Text;
using System.Net;
using System.Xml;
namespace BeginScreen
{
    /// 
    /// OpeRoomPlanNoticeHandler 的摘要说明
    /// 
    public class OpeRoomPlanNoticeHandler : Handler1
    {
        private DateTime dtpBeginDate;
        private DateTime dtpEndDate;
        private int dSum = 0; //数据表的总记录
        private int startRecond; //起始记录
        private int endRecond = 0; //结束记录
        private int PageSum = 9; //每页显示的记录数
        private static int countPage = 0; //总页数
        private int WorkerCurrentPage = 1; //当前页
        private DataTable dts;
        private DataTable dtsnew;
        private string opeInColor1 = "Orange";
        private DataTable InfoDataTable = new DataTable();
        #region 配置文件的属性
        public XElement xmlOpe = null;
        private string fontFamily = "黑体";
        private string fontSize = "24px";
        private string rowOddBgColor = "#000000";
        private string rowEvenBgColor = "#000000";
        private string opeBeforColor = "#f4fd04";
        private string opeInColor = "#fd0001";
        //private string opeInColor = "lime";
        private string opeAfterColor = "rgb(32, 218, 112)";
        private string defaultColor = "LightSkyBlue";
        private string OpeTime = "";
        private string DeptId = "";
        string clientip = "";
        string strIp = "";
        string stRoomName = "";
        string RoomId = "";
        #endregion
        public void GetHtml(HttpContext context)
        {
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory + "ConfigNoticeXML.xml";
            xmlOpe = XElement.Load(baseDirectory);
            WorkerCurrentPage = int.Parse(xmlOpe.Element("WorkerCurrentPage").Value);
            OpeTime = xmlOpe.Element("OpeTime").Value;
            DeptId = xmlOpe.Element("DeptId").Value;
            SetViewTime();
            DataTable dt = new DataTable();
            dt = PublicMethod.GetPlanNoticeNew(dtpBeginDate, dtpEndDate, OpeTime == "" ? "5" : OpeTime, DeptId); 
            dts = dt; 
            //总记录数
            dSum = dts.Rows.Count;
            countPage = GetPageCount();
            //currentPage = 1;
            //首先判断数据库中的记录数是否大于每一屏显示的数 chengxg@yahoo.cn;
            string tdRows = string.Empty;
            if (HttpContext.Current.Request["WorkerCurrentPage"] != null && HttpContext.Current.Request["WorkerCurrentPage"] != "")
            {
                tdRows = LoadWaitNurseOpe(Convert.ToInt32(HttpContext.Current.Request["WorkerCurrentPage"]));
            }
            JavaScriptSerializer jss = new JavaScriptSerializer();
            message msg = new message(true, tdRows, countPage.ToString(), WorkerCurrentPage.ToString());
            context.Response.Write(jss.Serialize(msg));//返回给前台页面  
            context.Response.End();
        }
        #region 计算总页数
        public int GetPageCount()
        {
            if (PageSum == 0)
                PageSum = 9; //每页显示的记录条数为"0",则默认为"20" 
            if (dSum % PageSum == 0)
                return (dSum / PageSum);
            else
                return (dSum / PageSum) + 1;
        }
        #endregion 
        private string LoadWaitNurseOpe(int curPage)
        {
            ///创建表
            //CreateTable();
            //插入表头
            //InsertTitle();
            ///创建列名{ "状态", "手术间","科室", "时间", "姓名", "手术名称", "手术医生", "麻醉医生", "洗手护士", "巡回护士" };
            //string[] colsName = { "", "术间", "科室", "姓名", "手术名称", "手术医生", "麻醉医生", "护士", "时间", "状态" };
            //string[] colsWidth = { "1%", "5%", "13%", "8%", "19%", "9%", "14%", "14%", "8%", "9%" };
            //InsertCols(colsName, colsWidth);
            curPage -= 1;
            startRecond = curPage * PageSum;
            endRecond = startRecond + PageSum;
            try
            {
                //状态vchrOpeStatus 手术间vchrOperatingRoomName 时间BeginTime 姓名vchrPatientName 
                //手术名称vchrOperationName术者 麻醉者 器械 巡回
                string tdRows = "";
                for (int i = startRecond; i < endRecond; i++)
                {
                    string tdRow = "
";
                    if (i >= dSum)
                    {
                        tdRow += "| ";
                    }
                    else
                    {
                        #region 内容的着色设置
                        string rowStyle = "";
                        if (i % 2 == 0)
                        {
                            rowStyle = "bgcolor='" + rowEvenBgColor +
                                       "' align=center valie=middle style='border-bottom:1px solid #629069; height:50px; font-size:" +
                                       fontSize + ";font-weight:bold; vertical-align: middle; font-family:\"" + fontFamily + "\"; ";
                        }
                        else
                        {
                            rowStyle = "bgcolor='" + rowOddBgColor +
                                       "' align=center valie=middle style='border-bottom:1px solid #629069; height:50px; font-size:" +
                                       fontSize + ";font-weight:bold;  vertical-align: middle; font-family:\"" + fontFamily + "\"; ";
                        }
                        string intApplyID = dts.Rows[i]["ApplyId"].ToString();
                        string vchrOpeStatus = dts.Rows[i]["State"].ToString();//PublicMethod.GetOpeStatus(dts.Rows[i]);
                        if (vchrOpeStatus == "") continue;
                        string opeStatu = "";
                        string vchrFactBeginTime = "";
                        vchrFactBeginTime = dts.Rows[i]["OperationBeginTime"].ToString();// == "" ? dts.Rows[i]["OrderOperationTime"].ToString() : dts.Rows[i]["InRoomTime"].ToString();
                        if (vchrFactBeginTime.Trim().ToString() != "")
                        {
                            vchrFactBeginTime = Convert.ToDateTime(vchrFactBeginTime).ToString("HH:mm");
                        }
                        else vchrFactBeginTime = "- -";
                        string OperationRoom = dts.Rows[i]["OperationRoom"].ToString();// dts.Rows[i]["SZOperationRoom"].ToString() == "" ? dts.Rows[i]["SqOperationRoom"].ToString() : dts.Rows[i]["SZOperationRoom"].ToString();
                        switch (vchrOpeStatus)
                        {
                            case "等待手术":
                                opeStatu = "等待手术";
                                rowStyle += " color:" + defaultColor + ";'";
                                OperationRoom = dts.Rows[i]["OperationRoom"].ToString();
                                break;
                            case "手术准备":
                                opeStatu = "手术准备";
                                rowStyle += " color:" + opeBeforColor + ";'";  //2
                                OperationRoom = dts.Rows[i]["OperationRoom"].ToString();
                                break;
                            case "手术进行中":
                                opeStatu = "手术中";
                                rowStyle += " color:" + opeInColor + ";'";
                                OperationRoom = dts.Rows[i]["OperationRoom"].ToString();
                                break;
                            case "术后恢复":
                                opeStatu = "手术结束";
                                rowStyle += " color:" + opeAfterColor + ";'";
                                OperationRoom = dts.Rows[i]["OperationRoom"].ToString();
                                break; 
                            case "手术结束":
                                opeStatu = "手术结束";
                                rowStyle += " color:" + opeAfterColor + ";'";
                                OperationRoom = dts.Rows[i]["OperationRoom"].ToString();
                                //OperationRoom = dts.Rows[i]["PACUBed"].ToString();
                                break;
                            case "手术拒绝":
                                opeStatu = "手术拒绝";
                                rowStyle += " color:#B559F5;'";
                                break;
                            default:
                                break;
                        }
                        #endregion
                        tdRow += " | ";
                        tdRow += " | " + OperationRoom + "";
                        #region 科室和申请科室
                        string Depatrtment = dts.Rows[i]["ApplyDepName"].ToString() ;
                        tdRow += " | " + Depatrtment + "";
                        #endregion
                        tdRow += " | " + dts.Rows[i]["PatientName"] + "";
                        string SZOperation = dts.Rows[i]["OperationInfo"].ToString()  ;
                        tdRow += " | " + SZOperation + "";
                        #region 读取医生的条件
                        string SZOperationDoctor = dts.Rows[i]["OperationDoctor"].ToString();
                        tdRow += " | " + SZOperationDoctor + "";
                        #endregion
                        #region 读取麻醉医生2
                        string SZAnesthesiaDoctor = dts.Rows[i]["AnesthesiaDoctor"].ToString() ;
                        SZAnesthesiaDoctor = SZAnesthesiaDoctor == "" ? "- -" : SZAnesthesiaDoctor;
                        if (SZAnesthesiaDoctor.Contains(','))
                        {
                            SZAnesthesiaDoctor = SZAnesthesiaDoctor.Replace(',', '/');
                        }
                        tdRow += " | " + SZAnesthesiaDoctor + "";
                        #endregion
                        #region 读取器械护士巡回护士
                        string SZTourNurse = dts.Rows[i]["TourNurse"].ToString();
                        string SZInstrumentNurse = dts.Rows[i]["InstrumentNurse"].ToString();
                        if (SZInstrumentNurse == "") SZInstrumentNurse = "- -";
                        if (SZTourNurse == "") SZTourNurse = "- -";
                        tdRow += " | " + SZInstrumentNurse + "/" + SZTourNurse + "";
                        #endregion
                        tdRow += " | " + vchrFactBeginTime + "";
                        tdRow += " | " + opeStatu + "";
                    }
                    tdRow += " | 
";
                    tdRows += tdRow;
                }
                //htmlbody = tdRows == "" ? htmlbody : body.Replace("{rows}", tdRows);
                return tdRows;
            }
            catch (Exception exp)
            {
                return "";
                throw;
            }
        }
        private void SetViewTime()
        {
            dtpBeginDate = PublicMethod.ServerTime().Date.AddSeconds(1);
            dtpEndDate = PublicMethod.ServerTime().Date.AddHours(23).AddMinutes(59).AddSeconds(59);
            //dtpBeginDate = Convert.ToDateTime("2018-01-16 00:00:01");
            //dtpEndDate = Convert.ToDateTime("2018-01-16 23:59:59");
        }
        public void GetHtmlTime(HttpContext context)
        {
            DateTime dt = PublicMethod.ServerTime();
            context.Response.Write(dt.ToString());//返回给前台页面  
            context.Response.End();
        }
        #region 手术间信息相关信息显示
        public void GetCurrentOperator(HttpContext context)
        {
            GetRoomNameByIp(context);
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory + "ConfigNoticeXML.xml";
            xmlOpe = XElement.Load(baseDirectory);
            WorkerCurrentPage = int.Parse(xmlOpe.Element("WorkerCurrentPage").Value);
            OpeTime = xmlOpe.Element("OpeTime").Value;
            SetViewTime();
            // string  dtpBeginDate = PublicMethod.ServerTime().ToString("yyyy-MM-dd 00:00:00");
            dtsnew = PublicMethod.GetOperationRoomPlan(dtpBeginDate, dtpEndDate, OpeTime == "" ? "5" : OpeTime, stRoomName);
            //总记录数
            dSum = dtsnew.Rows.Count;
            countPage = GetPageCount();
            //currentPage = 1;
            //首先判断数据库中的记录数是否大于每一屏显示的数 chengxg@yahoo.cn;
            string tdRows = string.Empty;
            if (HttpContext.Current.Request["WorkerCurrentPage"] != null && HttpContext.Current.Request["WorkerCurrentPage"] != "")
            {
                tdRows = LoadWaitNurseOpe1(Convert.ToInt32(HttpContext.Current.Request["WorkerCurrentPage"]));
            }
            //GetCurrentOperationOperatorInfo();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            message msg = new message(true, tdRows, countPage.ToString(), WorkerCurrentPage.ToString());
            context.Response.Write(jss.Serialize(msg));//返回给前台页面  
            context.Response.End();
        }
        private void GetRoomNameByIp(HttpContext context)
        {
            clientip = "192.168.0.1";//context.Request.UserHostAddress.ToString(); //
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory + "IPAndRoom.xml";
            XmlDocument doc = new XmlDocument();
            doc.Load(baseDirectory);
            XmlElement rootElem = doc.DocumentElement;   //获取根节点  
            XmlNodeList ipNodes = rootElem.GetElementsByTagName("IpAdress"); //获取person子节点集合  
            foreach (XmlNode node in ipNodes)
            {
                strIp = ((XmlElement)node).GetAttribute("name");
                if (clientip == strIp)
                {
                    XmlNodeList subRoomNameNodes = ((XmlElement)node).GetElementsByTagName("RoomName");  //获取age子XmlElement集合  
                    if (subRoomNameNodes != null)
                    {
                        stRoomName = subRoomNameNodes[0].InnerText;
                        DataTable Roomdt = PublicMethod.GetRoomInfo(stRoomName);
                        if (Roomdt.Rows.Count > 0)
                        {
                            RoomId = Roomdt.Rows[0]["Id"].ToString();
                        }
                    }
                }
            }
        }
        public void GetRoomName(HttpContext context)
        {
            if (stRoomName == "")
            {
                clientip = "192.168.0.1"; //context.Request.UserHostAddress.ToString(); //
                string baseDirectory = AppDomain.CurrentDomain.BaseDirectory + "IPAndRoom.xml";
                XmlDocument doc = new XmlDocument();
                doc.Load(baseDirectory);
                XmlElement rootElem = doc.DocumentElement;   //获取根节点  
                XmlNodeList ipNodes = rootElem.GetElementsByTagName("IpAdress"); //获取person子节点集合  
                foreach (XmlNode node in ipNodes)
                {
                    strIp = ((XmlElement)node).GetAttribute("name");
                    if (clientip == strIp)
                    {
                        XmlNodeList subRoomNameNodes = ((XmlElement)node).GetElementsByTagName("RoomName");  //获取age子XmlElement集合  
                        if (subRoomNameNodes != null)
                        {
                            stRoomName = subRoomNameNodes[0].InnerText;
                        }
                        break;
                    }
                }
            }
            context.Response.Write(stRoomName);//返回给前台页面  
            context.Response.End();
        }
        private string LoadWaitNurseOpe1(int curPage)
        {
            string name = System.Configuration.ConfigurationManager.AppSettings["RowCount"].ToString();
            int PageSum = 0;
            string rheight = "";
            string[] names = name.Split(',');
            for (int i = 0; i < names.Length; i++)
            {
                PageSum = int.Parse(names[0].ToString());
                rheight = names[1].ToString();
            }
            rowEvenBgColor = "RoyalBlue";  //  CornflowerBlue
            rowOddBgColor = "RoyalBlue";
            curPage -= 1;
            startRecond = curPage * PageSum;
            endRecond = startRecond + PageSum;
            try
            {
                //状态vchrOpeStatus 手术间vchrOperatingRoomName 时间BeginTime 姓名vchrPatientName 
                //手术名称vchrOperationName术者 麻醉者 器械 巡回
                string tdRows = "";
                for (int i = startRecond; i < endRecond; i++)
                {
                    string rowStyle = "";
                    if (i % 2 == 0)
                    {
                        rowStyle = "style= 'background-color:" + rowOddBgColor + ";border-bottom:2px solid black;height:" + rheight + ";font-weight:bolder; vertical-align: middle; '";
                    }
                    else
                    {
                        rowStyle = "style='background-color:" + rowEvenBgColor + ";border-bottom:2px solid black;height:" + rheight + ";font-weight:bolder;  vertical-align: middle; '";
                    }
                    string tdRow = "";
                    if (i >= dSum)
                    {
                        tdRow += "| ";
                    }
                    else
                    {
                        tdRow += " | ";
                        #region 科室和申请科室
                        string Depatrtment = dtsnew.Rows[i]["ApplyDepName"].ToString() ;
                        Depatrtment = Depatrtment.Replace("病区", "");
                        tdRow += " | " + Depatrtment + "";
                        #endregion
                        tdRow += " | " + dtsnew.Rows[i]["Bed"] + "床" + "";
                        tdRow += " | " + dtsnew.Rows[i]["PatientName"] + "";
                        tdRow += " | " + dtsnew.Rows[i]["sex"] + "";
                        tdRow += " | " + dtsnew.Rows[i]["Age"] + "";
                        string SZDiagnose = dtsnew.Rows[i]["SZDiagnose"].ToString() == "" ? dtsnew.Rows[i]["SQDiagnose"].ToString() : dtsnew.Rows[i]["SZDiagnose"].ToString();
                        if (SZDiagnose.Length > 13)
                        {
                            SZDiagnose = SZDiagnose.Substring(0, 12) + "...";
                        }
                        tdRow += " | " + SZDiagnose + "";
                        string SZOperation = dtsnew.Rows[i]["OperationInfo"].ToString();
                        if (SZOperation.Length > 13)
                        {
                            SZOperation = SZOperation.Substring(0, 12) + "...";
                        }
                        tdRow += " | " + SZOperation + "";
                    }
                    tdRow += " | 
";
                    tdRows += tdRow;
                }
                //htmlbody = tdRows == "" ? htmlbody : body.Replace("{rows}", tdRows);
                return tdRows;
            }
            catch (Exception exp)
            {
                return "";
                throw;
            }
        }
        public void GetCurrentOperationOperatorInfo(HttpContext context)
        {
            GetRoomNameByIp(context);
           
            if (RoomId == "") return;
            DataTable dt = PublicMethod.GetCurrentRoomPatientsInfo(int.Parse(RoomId), DateTime.Now.ToString("yyyy-MM-dd 00:00:00"));
            foreach (DataRow item in dt.Rows)
            {
                string OperationDoctorId = item["SZOperationDoctorId"].ToString() == "" ? item["SQOperationDoctorId"].ToString() : item["SZOperationDoctorId"].ToString();
                if (OperationDoctorId != "")
                {
                    string[] doctorids = OperationDoctorId.Split(',');
                    for (int i = 0; i < doctorids.Length; i++)
                    {
                        if (i == 0)
                        {
                            GetWorkInfo(1, "主刀", int.Parse(doctorids[i]));
                        }
                    }
                }
                string Assistant1 = item["SZAssistant1Id"].ToString() == "" ? item["SQAssistant1Id"].ToString() : item["SZAssistant1Id"].ToString();
                if (Assistant1 != "")
                {
                    //一助
                    string[] assistant1ids = Assistant1.Split(',');
                    for (int i = 0; i < assistant1ids.Length; i++)
                    {
                        if (i == 0)
                        {
                            GetWorkInfo(2, "第一助手", int.Parse(assistant1ids[i]));
                        }
                    }
                }
                string Assistant2 = item["SZAssistant2Id"].ToString() == "" ? item["SQAssistant2Id"].ToString() : item["SZAssistant2Id"].ToString();
                if (Assistant2 != "")
                {
                    string[] assistant2ids = Assistant2.Split(',');
                    for (int i = 0; i < assistant2ids.Length; i++)
                    {
                        if (i == 0)
                        {
                            GetWorkInfo(3, "第二助手", int.Parse(assistant2ids[i]));
                        }
                    }
                }
                string Assistant3 = item["SZAssistant3Id"].ToString() == "" ? item["SQAssistant3Id"].ToString() : item["SZAssistant3Id"].ToString();
                if (Assistant3 != "")
                {
                    string[] assistant3ds = Assistant3.Split(',');
                    for (int i = 0; i < assistant3ds.Length; i++)
                    {
                        if (i == 0)
                        {
                            GetWorkInfo(4, "第三助手", int.Parse(assistant3ds[i]));
                        }
                    }
                }
                string AnesthesiaDoctorId = item["SZAnesthesiaDoctorId"].ToString() == "" ? item["SQAnesthesiaDoctorId"].ToString() : item["SZAnesthesiaDoctorId"].ToString();
                if (AnesthesiaDoctorId != "")
                {
                    string[] anesthesiaDoctorids = AnesthesiaDoctorId.Split(',');
                    for (int i = 0; i < anesthesiaDoctorids.Length; i++)
                    {
                        if (i == 0)
                        {
                            GetWorkInfo(5, "麻醉", int.Parse(anesthesiaDoctorids[i]));
                        }
                        if (i == 1)
                        {
                            GetWorkInfo(6, "麻醉", int.Parse(anesthesiaDoctorids[i]));
                        }
                    }
                }
                string InstrumentNurseId = item["SZInstrumentNurseId"].ToString() == "" ? item["SQInstrumentNurseId"].ToString() : item["SZInstrumentNurseId"].ToString();
                if (InstrumentNurseId != "")
                {
                    string[] instrumentNurseids = InstrumentNurseId.Split(',');
                    for (int i = 0; i < instrumentNurseids.Length; i++)
                    {
                        if (i == 0)
                        {
                            GetWorkInfo(7, "洗手护士", int.Parse(instrumentNurseids[i]));
                        }
                    }
                }
                string TourNurseId = item["SZTourNurseId"].ToString() == "" ? item["SQTourNurseId"].ToString() : item["SZTourNurseId"].ToString();
                if (TourNurseId != "")
                {
                    string[] tourNurseids = TourNurseId.Split(',');
                    for (int i = 0; i < tourNurseids.Length; i++)
                    {
                        if (i == 0)
                        {
                            GetWorkInfo(8, "巡回护士", int.Parse(tourNurseids[i]));
                        }
                    }
                }
            }
            if (sql != "")
            {
                sql = sql.Substring(0, sql.Length - 5);
                InfoDataTable = PublicMethod.GetCurrentRoomPatientsInfo(sql);
            }
            string json = DatasetJson(InfoDataTable);
            context.Response.Write(json);//返回给前台页面  
            context.Response.End();
        }
        string sql = "";
        public void GetWorkInfo(int index, string name, int Id)
        {
            sql += "    select " + index + " as Id, '" + name + "' as 角色,w.Name as Workname,w.ElectronicSignature,bd.Name as teachname,d.Name as departName, r.Name as rolename,w.Remark from Workers w   left join BasicDictionary bd on w.JobTitleId = bd.Id  left join Roles r  on r.Id = w.RoleId  left join Departments d on d.Id = w.DepartmentId where w.Id =" + Id + " union";
        }
        /// 
        /// 解析DataTable成Json格式
        /// 
        /// 
        /// 
        public static string DatasetJson(DataTable dt)
        {
            StringBuilder jsonBuilder = new StringBuilder();
            jsonBuilder.Append("[");
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonBuilder.Append("{");
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonBuilder.Append("\"");
                    jsonBuilder.Append(dt.Columns[j].ColumnName);
                    jsonBuilder.Append("\":\"");
                    jsonBuilder.Append(dt.Rows[i][j].ToString().Trim());
                    jsonBuilder.Append("\",");
                }
                if (dt.Columns.Count > 0)
                {
                    jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
                }
                jsonBuilder.Append("},");
            }
            if (dt.Rows.Count > 0)
            {
                jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
            }
            jsonBuilder.Append("]");
            return jsonBuilder.ToString();
        }
        #endregion
        public void testGetRoomNameByIp(HttpContext context)
        {
            clientip = context.Request.UserHostAddress.ToString();
            JavaScriptSerializer jss = new JavaScriptSerializer();
            message msg = new message(true, clientip, "1", "1");
            context.Response.Write(jss.Serialize(msg));//返回给前台页面  
            context.Response.End();
        }
    }
}