using System;
using System.Data;
using System.Web;
using System.Web.Configuration;
using System.Xml.Linq;
using System.Web.Script.Serialization;
namespace BeginScreen
{
    /// 
    /// RelationsWaitingAreaBigScreenHandler 的摘要说明
    /// 
    public class RelationsWaitingAreaBigScreenSYDHandler : Handler1
    {
        static int glop = 1;
        private DateTime _beginDate;
        private DateTime _endDate;
        private int dSum; //数据表的总记录
        private int startRecond; //起始记录
        private int endRecond; //结束记录
        private static int PageSum = 9; //每页显示的记录数
        private int countPage; //总页数
        private int currentPage; //当前页
        private DataTable dts;
        #region 配置文件的属性
        public static XElement xmlOpe = null;
        private string fontSize = "27px";
        private string fontFamily = "黑体";
        private string bodyBgColor = "#000000";
        private string titleBgColor = "#62D377";
        private string titleColBgColor = "#2D9131";
        private string bottomBgColor = "#2D9131";
        private string rowOddBgColor = "#000000";
        private string rowEvenBgColor = "#000000";
        private string opeBeforColor = "DodgerBlue";
        //private string opeInColor = "red";
        private string opeInColor = "yellow";
        private string opeAfterColor = "rgb(32, 218, 112)";
        private string opeInColor1 = "Orange";
        private string opeAfterColor1 = "Wheat";
        private string defaultColor = "LightSkyBlue";           //1
        private string PatientNames = "";
        private string OpeTime = "";
        private string DeptId = "";
        #endregion
        private string body = "";
        private string messageStr = "";
        private string systemType = "";
        private string sendType = "";
        private int messId = 0;
        private static void InitConfig()
        {
            #region 加载配置文件
            string baseDirectory = AppDomain.CurrentDomain.BaseDirectory + "ConfigBigScreen.xml";
            xmlOpe = XElement.Load(baseDirectory);
            #endregion
        }
        public string GetHtml(HttpContext context)
        {
            //try
            //{
            //设置显示信息的开始和结束时间
            InitConfig();
            SetViewTime();
            currentPage = int.Parse(xmlOpe.Element("currentPage").Value);
            PatientNames = xmlOpe.Element("PatientName").Value;
            OpeTime = xmlOpe.Element("OpeTime").Value;
            DeptId = xmlOpe.Element("DeptId").Value;
            DataTable dt = new DataTable();
            dt = PublicMethod.GetPlanNoticeNew1(_beginDate, _endDate, OpeTime == "" ? "5" : OpeTime, DeptId);
            //DataRow[] sqzb = dt.Select("Szstate = '0' and InRoomTime  is not null and OperationBeginTime is null and OperationEndTime is null and OutRoomTime is null");
            //DataRow[] ssjxz = dt.Select("Szstate = '0' and InRoomTime is not null and OperationBeginTime is not null and OperationEndTime is null and OutRoomTime is null");
            //DataRow[] ssjxz1 = dt.Select("Szstate = '0' and InRoomTime is not null and OperationBeginTime is not null and  OperationEndTime is not null and OutRoomTime is null");
            //DataRow[] shhf = dt.Select("InRoomTime is not null and OperationBeginTime is not null and OperationEndTime is not null and'" + DateTime.Now + "' < OutRoomTime");
            //DataRow[] lkssj = dt.Select("InRoomTime is not null and OperationBeginTime is not null and OperationEndTime is not null and '" + DateTime.Now + "' > OutRoomTime");
            //DataRow[] hfsjl = dt.Select(" Szstate = '4' and InRoomTime is not null  ");
            //DataRow[] lkhfsjl = dt.Select(" Szstate = '5' and InRoomTime is not null  and outRoomTime is not null ");
            //DataRow[] sqdd = dt.Select("SQstate = '2' and  PlanOperationTime is not null and SQOperationRoomId is not null  ");
            //dts = dt.Clone();
            //foreach (DataRow row in sqzb)
            //{
            //    dts.Rows.Add(row.ItemArray);
            //}
            //foreach (DataRow row in ssjxz)
            //{
            //    dts.Rows.Add(row.ItemArray);
            //}
            //foreach (DataRow row in ssjxz1)
            //{
            //    dts.Rows.Add(row.ItemArray);
            //}
            //foreach (DataRow row in shhf)
            //{
            //    dts.Rows.Add(row.ItemArray);
            //}
            //foreach (DataRow row in lkssj)
            //{
            //    dts.Rows.Add(row.ItemArray);
            //}
            //foreach (DataRow row in hfsjl)
            //{
            //    dts.Rows.Add(row.ItemArray);
            //}
            //foreach (DataRow row in lkhfsjl)
            //{
            //    dts.Rows.Add(row.ItemArray);
            //}
            //foreach (DataRow row in sqdd)
            //{
            //    dts.Rows.Add(row.ItemArray);
            //}
            dts = dt;
            //总记录数
            dSum = dts.Rows.Count;
            countPage = GetPageCount();
            string tdRows = string.Empty;
            if (HttpContext.Current.Request["WorkerCurrentPage"] != null && HttpContext.Current.Request["WorkerCurrentPage"] != "")
            {
                LoadWaitNurseOpe(Convert.ToInt32(HttpContext.Current.Request["WorkerCurrentPage"]));
            }
            JavaScriptSerializer jss = new JavaScriptSerializer();
            message1 msg = new message1(true, body, messageStr, systemType, sendType, messId, countPage.ToString(), "");
            context.Response.Write(jss.Serialize(msg));//返回给前台页面  
            context.Response.End();
            //}
            //catch (Exception exp)
            //{
            //    body = " 
";
            //    body += "
";
            //    PublicMethod.WriteLog(exp);
            //}
            return body;
        }
        public void GetOpenFile(HttpContext context)
        {
            TestMoveMouse();
            context.Response.Write("");//返回给前台页面  
            context.Response.End();
        }
        public string GetOpenFile1(HttpContext context)
        {
            string fileid = HttpContext.Current.Request["fileid"];
            context.Response.Write(context.Application[fileid]);//返回给前台页面  
            context.Response.End();
            return "1";
        }
        [System.Runtime.InteropServices.DllImport("user32")]
        private static extern int mouse_event(int dwFlags, int dx, int dy, int dwData, int dwExtraInfo);
        //移动鼠标 
        const int MOUSEEVENTF_MOVE = 0x0001;
        //模拟鼠标左键按下 
        const int MOUSEEVENTF_LEFTDOWN = 0x0002;
        //模拟鼠标左键抬起 
        const int MOUSEEVENTF_LEFTUP = 0x0004;
        //模拟鼠标右键按下  
        const int MOUSEEVENTF_RIGHTDOWN = 0x0008;
        //模拟鼠标右键抬起 
        const int MOUSEEVENTF_RIGHTUP = 0x0010;
        //模拟鼠标中键按下 
        const int MOUSEEVENTF_MIDDLEDOWN = 0x0020;
        //模拟鼠标中键抬起 
        const int MOUSEEVENTF_MIDDLEUP = 0x0040;
        //标示是否采用绝对坐标 
        const int MOUSEEVENTF_ABSOLUTE = 0x8000;
        //模拟鼠标滚轮滚动操作,必须配合dwData参数
        const int MOUSEEVENTF_WHEEL = 0x0800;
        public static void TestMoveMouse()
        {
            //Console.WriteLine("模拟鼠标移动5个像素点。");
            mouse_event(MOUSEEVENTF_MOVE, -5000, -5000, 0, 0);//相对当前鼠标位置x轴和y轴分别移动50像素
            mouse_event(MOUSEEVENTF_MOVE, 0, 200, 0, 0);//相对当前鼠标位置x轴和y轴分别移动50像素
            //mouse_event(MOUSEEVENTF_WHEEL, 0, 0, -20, 0);//鼠标滚动,使界面向下滚动20的高度
            mouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);//相对当前鼠标位置x轴和y轴分别移动50像素
            mouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);//相对当前鼠标位置x轴和y轴分别移动50像素
            //mouse_event(MOUSEEVENTF_ABSOLUTE, 0, 0, 0, 0);//相对当前鼠标位置x轴和y轴分别移动50像素
            //mouse_event(MOUSEEVENTF_MOVE, 0, 0, 0, 0);//相对当前鼠标位置x轴和y轴分别移动50像素
            //var screenHeight = System.Windows.SystemParameters.PrimaryScreenHeight;
            //var screenWidth = System.Windows.SystemParameters.PrimaryScreenWidth;
        }
        #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 void LoadWaitNurseOpe(int curPage)
        {
            //每次去查询时,要更新一下记录总数,RecondSum,每一页显示的记录数为,PageSum ,
            body = "";
            messageStr = "";
            systemType = "";
            sendType = "";
            ///创建表
            //CreateTable();
            //创建表头
            //insertTitle();
            ///创建列名
            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 = "";
                    #region 内容的着色设置
                    if (i >= dSum)
                    {
                        tdRow += "| ";
                    }
                    else
                    {
                        string intApplyID = dts.Rows[i]["OperationApplyId"].ToString();
                        string OperationRoom = dts.Rows[i]["SqOperationRoom"].ToString();// dts.Rows[i]["SZOperationRoom"].ToString() == "" ? dts.Rows[i]["SqOperationRoom"].ToString() : dts.Rows[i]["SZOperationRoom"].ToString();
                        string vchrOpeStatus = PublicMethod.GetOpeStatus(dts.Rows[i]);
                        if (vchrOpeStatus == "") continue;
                        string rowStyle = "";
                        if (i % 2 == 0)
                        {
                            rowStyle = "bgcolor='" + rowEvenBgColor + "' align=left 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=left valie=middle style='border-bottom:1px solid #629069;height:50px;font-size:" +
                                fontSize + ";font-weight:bold; vertical-align: middle;font-family:\"" + fontFamily + "\"; ";
                        }
                        switch (vchrOpeStatus)
                        {
                            case "等待手术":
                                rowStyle += " color:" + defaultColor + ";'";
                                break;
                            case "手术准备":
                                rowStyle += " color:" + opeBeforColor + ";'";  //2
                                break;
                            case "手术进行中":
                                rowStyle += " color:" + opeInColor + ";'";     //3
                                break;
                            case "术后恢复":
                                rowStyle += " color:" + opeAfterColor + ";'";  //4
                                break;
                            case "手术结束转恢复室":
                                OperationRoom = dts.Rows[i]["PACUBed"].ToString();
                                rowStyle += " color:" + opeInColor1 + ";'";   //6
                                break;
                            case "手术结束安返病房":
                                rowStyle += " color:" + opeAfterColor1 + ";'";  //57
                                break;
                            case "转入复苏室":
                                //OperationRoom = dts.Rows[i]["PACUBed"].ToString();
                                rowStyle += " color:" + opeInColor1 + ";'";   //6
                                //OperationRoom = dts.Rows[i]["PACUBed"].ToString();
                                break;
                            case "离开复苏室":
                                //OperationRoom = dts.Rows[i]["PACUBed"].ToString();
                                rowStyle += " color:" + opeAfterColor1 + ";'";  //57
                                break;
                            case "手术结束":
                                rowStyle += " color:" + opeAfterColor1 + ";'";  //57
                                break;
                            default:
                                break;
                        }
                    #endregion
                        //注释时间列改为从床号 LM
                        //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 = "- -";
                        tdRow += " | ";
                        tdRow += " | ";
                        tdRow += "" + dts.Rows[i]["DepartmentName"] + " | ";
                        string PatientName = "";
                        if (PatientNames == "")
                        {
                            PatientName = dts.Rows[i]["PatientName"].ToString();
                        }
                        else
                        {
                            string name = dts.Rows[i]["PatientName"].ToString().Length < 2 ? "" : dts.Rows[i]["PatientName"].ToString().Substring(2);
                            PatientName = dts.Rows[i]["PatientName"].ToString().Substring(0, 1) + PatientNames + name;
                        }
                        tdRow += "" + dts.Rows[i]["Bed"] + " | ";
                        //tdRow += " " + PatientName + " |  " + OperationRoom + "";
                        //tdRow += " |  " + vchrFactBeginTime + "";
                        tdRow += " | ";
                    }
                    tdRow += "" + vchrOpeStatus + " | 
";
                    tdRows += tdRow;
                }
                //显示备注等
                body += tdRows;
                //body += viewRemark();
                GetT_Inform();
                //插入底部
                insertBottom();
            }
            catch (Exception exp)
            {
                throw;
            }
        }
        /// 
        ///     显示备注
        /// 
        private string viewRemark()
        {
            string str = "";
            str += "";
            str += "| ";
            str += " ";
            str += "";
            str += "";
            str += " ";
            //str += GetT_Inform();
            str += " ";
            str += " ";
            str += " ";
            str += " | 
";
            return str;
        }
        /// 
        ///     获取通知档的内容
        /// 
        private void GetT_Inform()
        {
            messageStr = "";
            systemType = "";
            sendType = "";
            DeptId = xmlOpe.Element("DeptId").Value;
            DataRow dr = PublicMethod.getMessigeData(DeptId);
            if (dr != null)
            {
                if (dr["Contents"] != null && dr["Contents"].ToString().Trim() != "")
                {
                    messageStr = dr["Contents"].ToString().Trim();
                }
                if (dr["SystemType"] != null && dr["SystemType"].ToString().Trim() != "")
                {
                    systemType = dr["SystemType"].ToString().Trim();
                }
                else
                {
                    systemType = "0";
                }
                if (dr["SendType"] != null && dr["SendType"].ToString().Trim() != "")
                {
                    sendType = dr["SendType"].ToString().Trim();
                }
                else
                {
                    sendType = "0";
                }
                if (dr["Id"] != null && dr["Id"].ToString().Trim() != "")
                {
                    messId = Convert.ToInt32(dr["Id"].ToString().Trim());
                }
            }
            //string messige = PublicMethod.getMessige();
            //if (messige.Trim() == "") return "";
            //body += " | ";
            //body += " | 
";
            //return "";
            //return messige;
        }
        private void SetViewTime()
        {
            _beginDate = PublicMethod.ServerTime().Date.AddSeconds(1);
            _endDate = PublicMethod.ServerTime().Date.AddHours(23).AddMinutes(59).AddSeconds(59);
        }
        #region 创建大屏公告列表
        private void CreateTable()
        {
            //body += "";
            body += "";
            body += "{title}";
            body += "{columens}";
            body += "{rows}";
            body += "
";
        }
        /// 
        ///     定义列
        /// 
        /// 
        /// 
        private void insertCols(string[] colNames, string[] colWidths)
        {
            string colString = "";
            string colContent = "";
            colString += "{td}
";
            for (int i = 0; i < colNames.Length; i++)
            {
                colContent += "" + colNames[i] +
                              "";
            }
            colString = colString.Replace("{td}", colContent);
            body = body.Replace("{columens}", colString);
        }
        /// 
        ///     插入表头
        /// 
        private void insertTitle()
        {
            if (countPage == 0)
            {
                currentPage = 0;
            }
            string titleStr = "";
            titleStr += " | ";
            titleStr += "| ";
            titleStr += " " + WebConfigurationManager.AppSettings["BigScreenHospitalName"].ToString();
            titleStr += "今日手术 " + PublicMethod.ServerTime().ToString("yyyy-MM-dd HH:mm") + "\n(第" + currentPage + "屏/共" + countPage + "屏)   | 
";
            body = body.Replace("{title}", titleStr);
        }
        /// 
        ///     插入表底部
        /// 
        private void insertBottom()
        {
            string bottomStr = "";
            bottomStr += "";
            bottomStr += "| ";
            bottomStr += " | 
";
            //body = body.Replace("{Bootom}", bottomStr);
            body += bottomStr;
        }
        #endregion
    }
}