using cn.edu.suda.sumcu.iot.form;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WebSocketSharp;
using WebSocketSharp.Server;
using cn.edu.suda.sumcu.iot.json;
using System.Runtime.Serialization.Json;
using cn.edu.suda.sumcu.iot.data;
using System.Data;
using System.Web.Script.Serialization;
using System.Collections;
using cn.edu.suda.sumcu.iot.state;
using cn.edu.suda.sumcu.iot.util;
using System.Net.Mail;
using System.Net;
using System.Xml;
using System.Web;

namespace cn.edu.suda.sumcu.iot.wsServices
{
    public class WsServices : WebSocketBehavior
    {
        public delegate void UeReSend(string imsi, FrameData frame);
        public static event UeReSend ueReSendEvent;    //数据回发委托事件   
        public static FrmMain frmMain = null;          //使用此主界面来访问数据库
        public static string myhardaddr = "";
        public string restr = "";
        public FrmRealtimeData frmRealData;
        public delegate void showInfor(string Message, string flag, string nameSource);   //创建一个委托对象
        showInfor showMesssge;                            //为委托对象绑定一个动作
        protected override void OnMessage(MessageEventArgs e)
        {
            JsomTemp jsontemp = null;//用来存放history命令的json格式
            JsonCommand answer = new JsonCommand();
            JsonCommand jsonRecv = null;//收到的Json数据
            JavaScriptSerializer serializer = null;
            string sTmp = "";
            answer.command = "status";
            answer.source = "CS-Monitor";
            answer.password = "";
            this.restr = "";
            DateTime timetemp = DateTime.Now;

            //将客户端发送的Json字符串转为Json对象
            try
            {
                serializer = new JavaScriptSerializer();  //实例化一个js处理对象
                jsonRecv                            //将Json字符串反序列化为Json对象
                    = serializer.Deserialize<JsonCommand>(e.Data);
                string nameSource = jsonRecv.source;
                if (showMesssge == null)
                {
                    frmRealData = FrmRealtimeData.getInstance();
                    showMesssge += frmRealData.showMessage;
                }
                showMesssge(e.Data, "TextAsk", nameSource);
            }
            catch
            {
                answer.value = "NOT COMMAND 1";
                goto OnMessage_exit_error1;
            }

            try
            {
                SQLCommand sqlnull = null;
                //判断接收到的Json命令类型
                switch (jsonRecv.command)
                {

                    //收到CS-Client/Web网页/APP/微信的数据请求命令
                    case "ask":
                        try
                        {
                            //（1）获得需要回发的数据表dr
                            int currentRow = Convert.ToInt32(jsonRecv.value);
                            int totalRows = frmMain.sQLUp.count();
                            //currentRow = totalRows;//【191009】修改Up上限后会影响查询功能
                            if (currentRow == 0)
                                currentRow = totalRows;//【20200909】如果当前记录为0
                            if (totalRows < currentRow) goto OnMessage_exit_error1;
                            DataTable dt = frmMain.sQLUp.selectRow(currentRow);
                            if (dt == null || dt.Rows.Count == 0)
                            {
                                answer.value = "NOT COMMAND 2";
                                goto OnMessage_exit_error1;
                            }
                            DataRow dr = dt.Rows[0];
                            //（2）通过dr获得结构数据对象tmpFrmStruct
                            FrameData tmpFrmStruct = null;
                            string cmd = dr["cmd"].ToString();
                            if (frmMain.g_commandsFrame.ContainsKey(cmd))
                            {
                                tmpFrmStruct = frmMain.g_commandsFrame[cmd];
                            }
                            else
                                return;
                            tmpFrmStruct.dataRowToStruct(dr);
                            //（3）实例并初始化要发送的Json对象
                            JsonCommand2 reData = new JsonCommand2();
                            reData.command = "reAsk";
                            reData.source = "CS-Monitor";
                            reData.currentRow = currentRow;
                            reData.totalRows = totalRows;
                            reData.password = "";
                            reData.data = tmpFrmStruct.Parameter;
                            //（4）将Json对象转换为Json字符串
                            string dataString3 = serializer.Serialize(reData);
                            string reAskNameSource = jsonRecv.source;
                            //（5）将数据发送出去
                            Send(dataString3);
                            if (showMesssge == null)
                            {
                                frmRealData = FrmRealtimeData.getInstance();
                                showMesssge += frmRealData.showMessage;
                            }
                            showMesssge(dataString3, "TextResponse", reAskNameSource);
                        }
                        catch
                        {
                            answer.value = "NOT COMMAND 3";
                            goto OnMessage_exit_error1;
                        }
                        break;
                    //收到Web网页的IMSI请求10条历史数据命令
                    case "askIMSI":
                        try
                        {
                            //（1）获得需要回发的数据表dr
                            string imsi = jsonRecv.value;
                            DataTable dt = frmMain.sQLUp.selectRowByIMSI(imsi);
                            if (dt == null || dt.Rows.Count == 0)
                            {
                                answer.value = "NOT COMMAND 2";
                                goto OnMessage_exit_error1;
                            }
                            List<List<FrameData.ParameterInfo>> dataResult = new List<List<FrameData.ParameterInfo>>();
                            JsonCommand2 reData = new JsonCommand2();
                            for (var i = 0; i < dt.Rows.Count; i++)
                            {
                                var dr = dt.Rows[i];
                                //（2）通过dr获得结构数据对象tmpFrmStruct
                                FrameData tmpFrmStruct = null;
                                string cmd = dr["cmd"].ToString();
                                if (frmMain.g_commandsFrame.ContainsKey(cmd))
                                {
                                    tmpFrmStruct = frmMain.g_commandsFrame[cmd];
                                }
                                else
                                    continue;
                                // tmpFrmStruct.Parameter = new List<FrameData.ParameterInfo>();
                                tmpFrmStruct.dataRowToStruct(dr);
                                //  paramList=new tmpFrmStruct.Parameter();
                                var paramList = tmpFrmStruct.Clone().Parameter;
                                //（3）实例并初始化要发送的Json对象
                                dataResult.Add(tmpFrmStruct.Clone().Parameter);
                            }
                            reData.dataResult = dataResult;
                            reData.command = "reAskimsi";
                            reData.source = "CS-Monitor";
                            reData.password = "";
                            //（4）将Json对象转换为Json字符串
                            string dataString3 = serializer.Serialize(reData);
                            string reAskNameSource = jsonRecv.source;
                            //（6）将数据发送出去
                            Send(dataString3);
                            if (showMesssge == null)
                            {
                                frmRealData = FrmRealtimeData.getInstance();
                                showMesssge += frmRealData.showMessage;
                            }
                            showMesssge(dataString3, "TextResponse", reAskNameSource);
                        }
                        catch
                        {
                            answer.value = "NOT COMMAND 3";
                            goto OnMessage_exit_error1;
                        }
                        break;
                    //【20200808】收到微信小程序发来的历史数据请求命令zw
                    case "askHty":
                        try
                        {
                            //（1）获得需要回发的数据表dr
                            string imsiww = Convert.ToString(jsonRecv.value);
                            DataTable dt = frmMain.sQLUp.selectIMSI(imsiww);
                            int totalRows = dt.Rows.Count;
                            if (dt == null || dt.Rows.Count == 0)
                            {
                                answer.value = "NOT COMMAND 2";
                            }
                            int numcount = 0;
                            if (totalRows >= 10)
                            {
                                numcount = 10;
                            }
                            else
                                numcount = totalRows;
                            //（2）实例并初始化要发送的Json对象
                            JsonCommand3 reData = new JsonCommand3();
                            reData.command = "reAskHty";
                            reData.source = "CS-Monitor";
                            reData.password = "";
                            reData.totalRows = totalRows;
                            for (int i = 0; i < numcount; i++)
                            {
                                DataRow dr = dt.Rows[totalRows - i - 1];
                                //（3）通过dr获得结构数据对象tmpFrmStruct
                                FrameData tmpFrmStruct = null;
                                string cmd = dr["cmd"].ToString();
                                if (frmMain.g_commandsFrame.ContainsKey(cmd))
                                {
                                    tmpFrmStruct = frmMain.g_commandsFrame[cmd];
                                }
                                else
                                    return;
                                reData.time.Add(Convert.ToString(dr[0]));
                                reData.temp.Add(Convert.ToString(dr[1]));
                                reData.signalpower.Add(Convert.ToString(dr[2]));
                            }
                            //（4）将Json对象转换为Json字符串
                            string dataString3 = serializer.Serialize(reData);
                            string reAskNameSource = jsonRecv.source;
                            //（5）将数据发送出去
                            Send(dataString3);
                            if (showMesssge == null)
                            {
                                frmRealData = FrmRealtimeData.getInstance();
                                showMesssge += frmRealData.showMessage;
                            }
                            showMesssge(dataString3, "TextResponse", reAskNameSource);
                        }
                        catch
                        {
                            answer.value = "NOT COMMAND 3";
                            goto OnMessage_exit_error1;
                        }
                        break;
                    //【20200812】收到微信小程序发来的imsi请求命令zw
                    case "askImsi":
                        try
                        {
                            //（1）获得需要回发的数据表dr
                            DataTable dt = frmMain.sQLUp.selectIMSIlist();   //获得imsi号数据表
                            //（2）实例并初始化要发送的Json对象
                            JsonCommand4 reData = new JsonCommand4();
                            reData.command = "reAskIMSI";
                            reData.source = "CS-Monitor";
                            reData.password = "";
                            reData.imsilist.Add("手动输入");
                            for (int i = 0; i < dt.Rows.Count; i++)
                            {
                                reData.imsilist.Add(dt.Rows[i]["IMSI"].ToString().Trim());
                            }
                            reData.totalRows = reData.imsilist.Count;
                            //（4）将Json对象转换为Json字符串
                            string dataString4 = serializer.Serialize(reData);
                            string reAskNameSource = jsonRecv.source;
                            //（5）将数据发送出去
                            Send(dataString4);
                            if (showMesssge == null)
                            {
                                frmRealData = FrmRealtimeData.getInstance();
                                showMesssge += frmRealData.showMessage;
                            }
                            showMesssge(dataString4, "TextResponse", reAskNameSource);
                        }
                        catch
                        {
                            answer.value = "NOT COMMAND 3";
                            goto OnMessage_exit_error1;
                        }
                        break;
                    //收到CS-Client/Web网页/APP/微信的回发数据
                    case "send":
                        JsonCommand2 json2        //将Json字符串反序列化为Json对象
                             = serializer.Deserialize<JsonCommand2>(e.Data);
                        FrameData tmpFrameData = new FrameData();
                        tmpFrameData.Parameter = json2.data;
                        if (ueReSendEvent != null)
                            ueReSendEvent(json2.dest, tmpFrameData);
                        //（4）实例并初始化要发送的Json对象f
                        answer.command = "status";
                        answer.source = "CS-Monitor";
                        answer.password = "";
                        answer.value = "SUCCESS";
                        //（5）Json对象转为Json字符串
                        sTmp = serializer.Serialize(answer);
                        //（6）将数据发送出去
                        Send(sTmp);
                        break;


                    

                    //case "delete_history"://【200510】删除历史
                    //    jsontemp = serializer.Deserialize<JsomTemp>(e.Data);
                    //    timetemp = DateTime.ParseExact(jsontemp.begintime, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                    //    string sqldelete = "delete  from Up where currentTime>='" + jsontemp.begintime + "0000'" + " and currentTime<='" + jsontemp.endtime + "2400'" + " and gatewayhardaddr=" + jsontemp.gateway;
                    //    frmMain.sQLUp.ExecuteNonQuery(sqldelete);
                    //    //【20200812】删除旧Up表
                    //    for (; timetemp < DateTime.Now; timetemp = timetemp.AddDays(1.0))
                    //    {
                    //        sqldelete = "drop table [Up-" + timetemp.ToString("yyyyMMdd") + "]";
                    //        frmMain.sQLUp.ExecuteNonQuery(sqldelete);
                    //    }

                    //    break;


                    ////用来传输节点的历史数据
                    //case "history"://【191009】修改命令，给Up表添加了时间之后，又实现了根据时间读写发送的功能
                    //    string sqlstrhistory = "";
                    //    bool flag = true;//用于判断数据库中的数据是否为空
                    //    //jsonRecv 
                    //    //nodetype6,nodeaddr6,nodedata6,
                    //    jsontemp = serializer.Deserialize<JsomTemp>(e.Data);
                    //    timetemp = DateTime.ParseExact(jsontemp.begintime, "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);

                    //    sqlstrhistory = "select currentTime,nodetype" + jsontemp.node + ",nodeaddr" + jsontemp.node + ",upperbound" + jsontemp.node + ",lowerbound" + jsontemp.node + ",nodedata" + jsontemp.node + " from Up where currentTime>='" + jsontemp.begintime + "0000'" + " and currentTime<='" + jsontemp.endtime + "2400'" + " and gatewayhardaddr=" + jsontemp.gateway + " order by currentTime desc";
                    //    DataTable myhistorydt = frmMain.sQLUp.ExecuteQueryReturnDT(sqlstrhistory);

                    //    //【20200812】查询历史数据时将查询日期期间所有表，并将查询结果拼接
                    //    for (; timetemp < DateTime.Now; timetemp = timetemp.AddDays(1.0))
                    //    {
                    //        sqlstrhistory = "select currentTime,nodetype" + jsontemp.node + ",nodeaddr" + jsontemp.node + ",upperbound" + jsontemp.node + ",lowerbound" + jsontemp.node + ",nodedata" + jsontemp.node + " from [Up-" + timetemp.ToString("yyyyMMdd") + "] where currentTime>='" + jsontemp.begintime + "0000'" + " and currentTime<='" + jsontemp.endtime + "2400'" + " and gatewayhardaddr=" + jsontemp.gateway + " order by currentTime desc";
                    //        DataTable historytemp = frmMain.sQLUp.ExecuteQueryReturnDT(sqlstrhistory);
                    //        myhistorydt.Merge(historytemp);  //拼接表
                    //    }
                    //    //-------------------------------------------------------------
                    //    var historyjs = new StringBuilder();
                    //    historyjs.Append("{\"" + "command" + "\":" + "\"" + "rehistory" + "\",\"data1\":[");//添加command变量
                    //    if (myhistorydt.Rows.Count > 0)
                    //    {
                    //        for (int i = 0; i < myhistorydt.Rows.Count; i++)
                    //        {
                    //            if (myhistorydt.Rows[i][5].ToString() == "0")//如果数据不存在，跳过
                    //            {
                    //                continue;
                    //            }
                    //            historyjs.Append("{");
                    //            for (int j = 0; j < myhistorydt.Columns.Count; j++)
                    //            {
                    //                if (j < myhistorydt.Columns.Count - 1)
                    //                {
                    //                    String Columntemp = myhistorydt.Columns[j].ColumnName.ToString();
                    //                    if (Columntemp.Equals("currentTime"))
                    //                    {
                    //                        //给时间组帧
                    //                        String temp1 = myhistorydt.Rows[i][j].ToString();
                    //                        String temp2 = temp1.Substring(0, 4) + "-" + temp1.Substring(4, 2) + "-" + temp1.Substring(6, 2) + " " + temp1.Substring(8, 2) + ":" + temp1.Substring(10, 2) + ":" + temp1.Substring(12, temp1.Length - 12);
                    //                        historyjs.Append("\"" + Columntemp + "\":" + "\"" + temp2 + "\",");
                    //                    }
                    //                    else
                    //                    {
                    //                        historyjs.Append("\"" + Columntemp + "\":" + "\"" + myhistorydt.Rows[i][j].ToString() + "\",");
                    //                    }
                    //                }
                    //                else if (j == myhistorydt.Columns.Count - 1)
                    //                {
                    //                    historyjs.Append("\"" + myhistorydt.Columns[j].ColumnName.ToString() + "\":" + "\"" + myhistorydt.Rows[i][j].ToString() + "\"");
                    //                }
                    //            }
                    //            if (i == myhistorydt.Rows.Count - 1)
                    //            {
                    //                historyjs.Append("}]}");
                    //                flag = false;
                    //            }
                    //            else
                    //            {
                    //                historyjs.Append("},");
                    //            }
                    //        }
                    //    }
                    //    else
                    //    {
                    //        flag = false;
                    //        historyjs.Append("]}");
                    //    }
                    //    if (flag)
                    //    {
                    //        string a = historyjs[historyjs.Length - 1].ToString();
                    //        if (historyjs[historyjs.Length - 1].ToString() == ",")
                    //        {
                    //            historyjs.Remove(historyjs.Length - 1, 1);
                    //        }
                    //        historyjs.Append("]}");
                    //    }
                    //    string rejssql = historyjs.ToString();
                    //    Send(rejssql);
                    //    break;


                  
                    //    //【200110】 history界面的endtime和begintime
                    //    string sqlbegintime, sqlendtime, begintime, endtime;
                    //    sqlbegintime = "select TOP(1)currentTime  from Up where gatewayhardaddr =" + jsonRecv.value.ToString()+ "order by currentTime" ;
                    //    sqlendtime = "select TOP(1)currentTime  from Up where gatewayhardaddr =" + jsonRecv.value.ToString()+ "order by currentTime desc";
                    //    begintime = frmMain.sQLUp.ExecuteQueryReturnDT(sqlbegintime).Rows[0][0].ToString();
                    //    begintime = begintime.Substring(0, 4) + "-" + begintime.Substring(4, 2) + "-" + begintime.Substring(6, 2);
                    //    endtime = frmMain.sQLUp.ExecuteQueryReturnDT(sqlendtime).Rows[0][0].ToString();
                    //    endtime = endtime.Substring(0, 4) + "-" + endtime.Substring(4, 2) + "-" + endtime.Substring(6, 2);

                    //    var reasknode = new StringBuilder();
                    //    reasknode.Append("{\"" + "command" + "\":" + "\"" + "reasknode\"" +
                    //        ",\"begin\":\"" + begintime + "\"," +
                    //        "\"end\":\"" + endtime + "\"," + 
                    //        "\"data1\":\"");//添加command变量
                    //    string nodetemp = "";
                    //    for (int i = 0; i < 10; i++)
                    //    {
                    //        nodetemp += nodelist[i].ToString();
                    //    }
                    //    reasknode.Append(nodetemp + "\"}");//添加command变量
                    //    nodetemp = reasknode.ToString();
                    //    Send(nodetemp);
                    //    break;

                    //【200110】修改原来的结构
                    case "runningtime":
                        string runningtimetemp="",runtimesql;
                        DataTable runtimedt;
                        runtimesql = "select TABLE_NAME  from INFORMATION_SCHEMA.Tables where TABLE_NAME='RunningTime'";
                        runtimedt = frmMain.sQLUp.ExecuteQueryReturnDT(runtimesql);
                        if (runtimedt.Rows.Count == 0)
                        {
                            runtimesql = "CREATE TABLE [dbo].[RunningTime] ([Time] NVARCHAR(50) NOT NULL, PRIMARY KEY CLUSTERED ([Time] ASC));";
                            frmMain.sQLUp.ExecuteNonQuery(runtimesql);
                        }
                        SQLCommand runtime = new SQLCommand(System.Configuration.
                        ConfigurationManager.AppSettings["connectionString"], "RunningTime");
                        runtimesql = "select TOP(1)* from RunningTime order by Time desc";
                        runtimedt = runtime.ExecuteQueryReturnDT(runtimesql);
                        if (runtimedt.Rows.Count == 0)
                        {
                            runningtimetemp = Convert.ToString((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
                            runtimesql = "insert into RunningTime values('" + runningtimetemp + "')";
                            runtime.ExecuteNonQuery(runtimesql);
                        }
                        else
                        {
                            runningtimetemp = runtimedt.Rows[0][0].ToString();
                        }
                        restr = "{\"" + "command" + "\":" + "\"" + "rerunningtime" + "\",\"timestamp\":\"" +
                            runningtimetemp + "\"}";
                        Send(restr);
                        break;

                    //【200110】设置重置时间
                    //【20200608】周瑞琦，将时间格式改为时间戳
                    case "updaterunningtime":
                        string upruntimesql;
                        SQLCommand upruntime = new SQLCommand(System.Configuration.
                        ConfigurationManager.AppSettings["connectionString"], "RunningTime");
                        int timestamp = Convert.ToInt32((DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000);
                        string uprunningtimetemp = timestamp.ToString();
                        //uprunningtimetemp = "1591384550";//测试用
                        upruntimesql = "delete from RunningTime";
                        upruntime.ExecuteNonQuery(upruntimesql);
                        upruntimesql = "insert into RunningTime values('" + uprunningtimetemp + "')";
                        upruntime.ExecuteNonQuery(upruntimesql);
                        restr = "{\"" + "command" + "\":" + "\"" + "rerunningtime" + "\",\"timestamp\":\"" +
                                uprunningtimetemp + "\"}";
                        Send(restr);
                        break;

                    case "warningsperday":
                        int warningcount = 0;
                        int week = 0;
                        int day = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
                        var warningstringobj = new StringBuilder();
                        string wanringsperdaysql = "";
                        restr = DateTime.Now.DayOfWeek.ToString();
                        switch (DateTime.Now.DayOfWeek.ToString())
                        {
                            case "Monday":
                                week = 1;
                                break;
                            case "Tuesday":
                                week = 2;
                                break;
                            case "Wednesday":
                                week = 3;
                                break;
                            case "Thursday":
                                week = 4;
                                break;
                            case "Friday":
                                week = 5;
                                break;
                            case "Saturday":
                                week = 6;
                                break;
                            case "Sunday":
                                week = 7;
                                break;
                        }
                        warningstringobj.Append("{\"" + "command" + "\":" + "\"" + "rewarningsperday" + "\",\"data\":[");
                        for (int i = 1; i <= 7; i++)
                        {
                            week--;
                            if (week <= 0)
                                week = 7;
                            wanringsperdaysql = "select nodedata1,nodedata2,nodedata3,nodedata4,nodedata5,nodedata6,nodedata7,nodedata8,nodedata9,nodedata10," +
                                "upperbound1,upperbound2,upperbound3,upperbound4,upperbound5,upperbound6,upperbound7,upperbound8,upperbound9,upperbound10," +
                                "lowerbound1,lowerbound2,lowerbound3,lowerbound4,lowerbound5,lowerbound6,lowerbound7,lowerbound8,lowerbound9,lowerbound10" +
                                " from Up where currentTime>='" + DateTime.Now.AddDays(-i).ToString("yyyyMMdd") + "000000' and currentTime<='"
                                + DateTime.Now.AddDays(-i).ToString("yyyyMMdd") + "999999'";
                            DataTable warningperdaydt = frmMain.sQLUp.ExecuteQueryReturnDT(wanringsperdaysql);
                            for(int j=0;j< warningperdaydt.Rows.Count; j++)
                            {
                                for(int k = 0; k < 10; k++)//计算报警数
                                {
                                    double datasqltemp = double.Parse(warningperdaydt.Rows[j][k].ToString());
                                    double uptemp = double.Parse(warningperdaydt.Rows[j][k+10].ToString());
                                    double lowtemp= double.Parse(warningperdaydt.Rows[j][k + 20].ToString());
                                    if ((datasqltemp < lowtemp || datasqltemp > uptemp) && datasqltemp != 0)
                                        warningcount++;
                                }
                            }
                            warningstringobj.Append("{\"week\":\"" + week.ToString() + "\",");//添入星期
                            warningstringobj.Append("\"num\":\"" + warningcount.ToString() + "\"},");
                            warningcount = 0;
                        }
                        if (warningstringobj[warningstringobj.Length - 1].ToString() == ",")
                            warningstringobj.Remove(warningstringobj.Length - 1, 1);
                        warningstringobj.Append("]}");
                        restr = warningstringobj.ToString();
                        Send(restr);
                        break;

                    ////【191026】范远照改
                    //case "settingemail":
                    //    myState.mailinterval = float.Parse(jsonRecv.source.ToString());
                    //    myState.lastsendmailtime = DateTime.Now.AddHours(0 - myState.mailinterval).ToString("MMddHHmm");
                    //    SQLCommand newemail = new SQLCommand(System.Configuration.ConfigurationManager.AppSettings["connectionString"], "Mail");
                    //    jsonRecv = serializer.Deserialize<JsonCommand>(e.Data);
                    //    int eflag = 1;
                    //    string emailsql = "";
                    //    if (jsonRecv.password == "1")
                    //        emailsql = "insert into Mail values('" + jsonRecv.value + "')";
                    //    else
                    //        emailsql = "delete from Mail where MailAddress='" + jsonRecv.value + "'";
                    //    eflag = newemail.ExecuteNonQuery(emailsql);
                    //    if (eflag == -1 || eflag == 0)//增加已存在/删除不存在的/修改失败
                    //    {

                    //        //返回错误结果代码
                    //    }
                    //    break;

                    ////【191026】范远照改
                    //case "settingphone":
                    //    SQLCommand newphone = new SQLCommand(System.Configuration.ConfigurationManager.AppSettings["connectionString"], "Phone");
                    //    jsonRecv = serializer.Deserialize<JsonCommand>(e.Data);
                    //    int pflag = 1;
                    //    string phonesql = "";
                    //    if (jsonRecv.password == "1")
                    //        phonesql = "insert into Phone values('" + jsonRecv.value + "')";
                    //    else
                    //        phonesql = "delete from Phone where Phone='" + jsonRecv.value + "'";
                    //    eflag = newphone.ExecuteNonQuery(phonesql);
                    //    if (pflag == -1 || eflag == 0)//增加已存在/删除不存在的/修改失败
                    //    {
                    //        //返回错误结果代码
                    //    }
                    //    break;


                    ////【191028】沈泽昊改，返回给客户端Phone中存储的number，设置发送短信的标志
                    //case "askphone":
                    //    if (jsonRecv.value == "ON")
                    //    {
                    //        myState.phoneflag = "ON";
                    //    }
                    //    else if (jsonRecv.value == "OFF")
                    //    {
                    //        myState.phoneflag = "OFF";
                    //    }
                    //    string phonesqlstr = "select * from Phone";
                    //    DataTable phonenumberdt = frmMain.sQLUp.ExecuteQueryReturnDT(phonesqlstr);
                    //    var phonetemp = new StringBuilder();
                    //    phonetemp.Append("{\"" + "command" + "\":" + "\"" + "reaskphone" +
                    //        "\",\"state\":\"" + myState.phoneflag + "\",\"data\":[");//添加command变量
                    //    //赋值状态
                    //    for (int i = 0; i < phonenumberdt.Rows.Count; i++)
                    //    {
                    //        phonetemp.Append("{");
                    //        for (int j = 0; j < phonenumberdt.Columns.Count; j++)
                    //        {
                    //            if (j < phonenumberdt.Columns.Count - 1)
                    //            {
                    //                phonetemp.Append("\"" + phonenumberdt.Columns[j].ColumnName.ToString() + "\":" + "\"" + phonenumberdt.Rows[i][j].ToString() + "\",");
                    //            }
                    //            else if (j == phonenumberdt.Columns.Count - 1)
                    //            {
                    //                phonetemp.Append("\"" + phonenumberdt.Columns[j].ColumnName.ToString() + "\":" + "\"" + phonenumberdt.Rows[i][j].ToString() + "\"");
                    //            }
                    //        }
                    //        if (i == phonenumberdt.Rows.Count - 1)
                    //        {
                    //            phonetemp.Append("}");
                    //        }
                    //        else
                    //        {
                    //            phonetemp.Append("},");
                    //        }
                    //    }
                    //    phonetemp.Append("]}");
                    //    phonesqlstr = phonetemp.ToString();
                    //    Send(phonesqlstr);
                    //    break;


                    ////【191028】沈泽昊改，返回Mail中存储的邮件地址
                    //case "askemail":
                    //    string mailsqlstr = "select * from Mail";
                    //    DataTable mailnumberdt = frmMain.sQLUp.ExecuteQueryReturnDT(mailsqlstr);
                    //    var mailtemp = new StringBuilder();
                    //    mailtemp.Append("{\"command\":\"reaskmail\",\"emailnterval\":\"" + myState.mailinterval.ToString()+
                    //        "\",\"data\":[");//添加command变量
                    //    //赋值状态
                    //    for (int i = 0; i < mailnumberdt.Rows.Count; i++)
                    //    {
                    //        mailtemp.Append("{");
                    //        for (int j = 0; j < mailnumberdt.Columns.Count; j++)
                    //        {
                    //            if (j < mailnumberdt.Columns.Count - 1)
                    //            {
                    //                mailtemp.Append("\"" + mailnumberdt.Columns[j].ColumnName.ToString() + "\":" + "\"" + mailnumberdt.Rows[i][j].ToString() + "\",");
                    //            }
                    //            else if (j == mailnumberdt.Columns.Count - 1)
                    //            {
                    //                mailtemp.Append("\"" + mailnumberdt.Columns[j].ColumnName.ToString() + "\":" + "\"" + mailnumberdt.Rows[i][j].ToString() + "\"");
                    //            }
                    //        }
                    //        if (i == mailnumberdt.Rows.Count - 1)
                    //        {
                    //            mailtemp.Append("}");
                    //        }
                    //        else
                    //        {
                    //            mailtemp.Append("},");
                    //        }
                    //    }
                    //    mailtemp.Append("]}");
                    //    mailsqlstr = mailtemp.ToString();
                    //    Send(mailsqlstr);
                    //    break;


                   

                    default:
                        answer.value = "NOT COMMAND 4";
                        goto OnMessage_exit_error1;
                }
            }
            catch
            {
                answer.value = "NOT COMMAND 5";
                goto OnMessage_exit_error1;
            }
            goto OnMessage_exit;//至此，执行成功，退出函数
        OnMessage_exit_error1:
            //Json对象转为Json字符串
            sTmp = serializer.Serialize(answer);
            //将数据发送出去
            Send(sTmp);
            goto OnMessage_exit;
        OnMessage_exit:
            return;

        }
        protected override void OnClose(CloseEventArgs e)
        {

        }

        protected override void OnError(WebSocketSharp.ErrorEventArgs e)
        {

        }

        protected override void OnOpen()
        {

        }

    }
}
