using System;
using System.Data;
using System.Web;
using System.Web.Configuration;
using System.Xml.Linq;
using System.Web.Script.Serialization;
using System.Speech.Synthesis;
using System.Text;
using System.Threading.Tasks;
namespace BeginScreen
{
    /// 
    /// WaitingHandler 的摘要说明
    /// 
    public class WaitingHandler : HandlerBase
    {
        //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 = "20px";
        private string fontFamily = "微软雅黑";
        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 + "WaitConfig.xml";
            xmlOpe = XElement.Load(baseDirectory);
            #endregion
        }
        public string GetHtml(HttpContext context)
        {
            //设置显示信息的开始和结束时间
            InitConfig();
            SetViewTime();
            currentPage = int.Parse(xmlOpe.Element("currentPage").Value);
            PatientNames = xmlOpe.Element("PatientName").Value;
            OpeTime = xmlOpe.Element("OpeTime").Value;
            DeptId = xmlOpe.Element("DeptId").Value;
            messageStr = "";
            DataTable dt = new DataTable();
            dt = PublicMethod.GetPlanNoticeNew1(_beginDate, _endDate, OpeTime == "" ? "5" : OpeTime, DeptId);
            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();
            return body;
        }
        public void GetOpenFile(HttpContext context)
        {
            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";
        }
        #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 = "";
            curPage -= 1;
            startRecond = curPage * PageSum;
            endRecond = startRecond + PageSum;
            string tdRows = "";
            for (int i = startRecond; i < endRecond; i++)
            {
                try
                {
                    string tdRow = "
";
                    if (i >= dSum)
                    {
                        tdRow += "| ";
                    }
                    else
                    {
                        string intApplyID = dts.Rows[i]["ApplyId"].ToString();
                        string OperationRoom = dts.Rows[i]["OperationRoom"].ToString();
                        string vchrOpeStatus = GetOpeStatus(dts.Rows[i]);
                        if (vchrOpeStatus == "") continue;
                        string rowStyle = "";
                        if (i % 2 == 0)
                        {
                            rowStyle = " height='35px' bgcolor='" + rowEvenBgColor + "'  style='font-size:" +  fontSize + ";font-family:" + fontFamily + ";' "; 
                        }
                        else
                        {
                            rowStyle = " height='35px' bgcolor='" + rowOddBgColor + "'   style='font-size:" +    fontSize + "; font-family:" + fontFamily + ";' "; 
                        }
                        switch (vchrOpeStatus)
                        {
                            case "等待手术": 
                                break;
                            case "手术准备": 
                                break;
                            case "手术中": 
                                break;
                            case "手术结束": 
                                break;
                            case "术后恢复":
                                break;
                            case "手术结束转恢复室":
                                break;
                            case "手术结束安返病房":
                                break;
                            case "转入复苏室":
                                break;
                            case "离开复苏室":
                                break;
                            default:
                                break;
                        }
                        tdRow += " | ";
                        tdRow += " | " + dts.Rows[i]["ApplyDepName"] + "";
                        tdRow += " | " + dts.Rows[i]["SickBed"] + "";
                        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 += " |  " + PatientName + "";
                        tdRow += " | " + vchrOpeStatus + "";
                    } 
                    tdRow += " | 
";
                    tdRows += tdRow;
                }
                catch (Exception)
                {
                }
            }
            //显示备注等
            body += tdRows;
            GetT_Inform();
        }
        /// 
        ///     获取通知档的内容
        /// 
        private void GetT_Inform()
        {
            DataRow dr = PublicMethod.GetMessigeData();
            if (dr != null)
            {
                if (dr["Contents"] != null && dr["Contents"].ToString().Trim() != "")
                {
                    messageStr = dr["Contents"].ToString().Trim();
                }
                systemType = "0";
                if (dr["Id"] != null && dr["Id"].ToString().Trim() != "")
                {
                    messId = Convert.ToInt32(dr["Id"].ToString().Trim());
                }
                //var task = Task.Factory.StartNew(() =>
                //{
                //    using (var speechSyn = new SpeechSynthesizer())
                //    {
                //        //speechSyn.Volume = ;//语速
                //        //speechSyn.Rate = -;//音量
                //        speechSyn.SetOutputToDefaultAudioDevice();
                //        speechSyn.SetOutputToWaveFile("E:\\AIMS\\BeginScreen\\static\\Record.wav");//"D:\\Record.wav"
                //        speechSyn.Speak(messageStr );
                //    }
                //});
                //Task.WaitAll(task); 
            } 
        }
        private void SetViewTime()
        {
            _beginDate = PublicMethod.ServerTime().Date.AddSeconds(1);
            _endDate = PublicMethod.ServerTime().Date.AddHours(23).AddMinutes(59).AddSeconds(59);
        }
        public static string GetOpeStatus(DataRow dts)
        {
            //--0.【等待手术】   “已排程”“待访视”“已访视”
            //--1.【术前准备】   点击“手术转入”
            //--2.【手术进行中】 点击“手术开始”
            //--3.【术后恢复】   点击“手术结束”
            //--4.【离开手术室】 从点击手术结束
            //--5.【转入复苏室】 麻醉恢复记录单点击“转入”
            //--6.【离开手术室】 点击“转出”恢复室 
            string OpeStatus = dts["State"].ToString();
            string InRoomTime = dts["InRoomTime"].ToString();
            string OperationBeginTime = dts["OperationBeginTime"].ToString();
            string OperationEndTime = dts["OperationEndTime"].ToString();
            string OutRoomTime = dts["OutRoomTime"].ToString();
            string Temp = "";
            if (OpeStatus  == "等待手术")
            {
                Temp = "等待手术";
            }
            if (OpeStatus == "手术中" && InRoomTime != "" && OperationBeginTime == "" && OperationEndTime == "" && OutRoomTime == "")
            {
                Temp = "手术准备";
            }
            if (OpeStatus == "手术中" && InRoomTime != "" && OperationBeginTime != "" && OperationEndTime == "" && OutRoomTime == "")
            {
                Temp = "手术进行中";
            }
            if (OpeStatus == "手术中" && InRoomTime != "" && OperationBeginTime != "" && OperationEndTime != "" && OutRoomTime == "")
            {
                if (DateTime.Now < Convert.ToDateTime(OperationEndTime))
                {
                    Temp = "手术进行中";
                }
                else
                {
                    Temp = "术后恢复";
                }
            }
            if (InRoomTime != "" && OperationBeginTime != "" && OperationEndTime != "" && OutRoomTime != "")
            {
                if (DateTime.Now < Convert.ToDateTime(OutRoomTime))
                {
                    Temp = "术后恢复";
                }
                else if (dts["Pulse"].ToString() == "病房")
                {
                    Temp = "手术结束安返病房";
                }
                else if (dts["Pulse"].ToString() == "恢复室")
                {
                    Temp = "手术结束转恢复室";
                }
                else
                {
                    Temp = "手术结束";
                }
            }
            //if (OpeStatus == "4" && InRoomTime != "" && OutRoomTime == "")
            //{
            //    Temp = "转入复苏室";
            //}
            //if (OpeStatus == "5" && InRoomTime != "" && OutRoomTime != "")
            //{
            //    Temp = "离开复苏室";
            //}
            return Temp;
        }
    }
}