using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SuperWebSocket;
using System.Web;
using System.Reflection;
using System.Web.Script.Serialization;
using System.Threading;
using System.IO;
using System.Drawing.Imaging;
using AForge.Imaging.Filters;
using Microsoft.Win32;

namespace ICS
{
    public partial class Form1 : Form
    {
        private Point mouseOff; // 鼠标移动位置变量
        private bool leftFlag; // 标签是否为左键

        static Form1 form;
        static string reValue;
        static Dictionary<string, WebSocketSession> sessionDics = new Dictionary<string, WebSocketSession>();
        public static WebSocketServer ws = null;
        public static log4net.ILog log = log4net.LogManager.GetLogger("ICS");
        private static bool isInited = false;
        protected Thread threadFindWindow; 
        private static bool isStoped = false;

        public Form1()
        {
            InitializeComponent();
            // 跨线程访问控件
            CheckForIllegalCrossThreadCalls = false;

            form = this;
            ws = new WebSocketServer();
            ws.NewSessionConnected += Ws_NewSessionConnected;
            ws.NewMessageReceived += Ws_NewMessageReceived;
            ws.SessionClosed += Ws_SessionClosed;
            Start();

            //设置开机自启动  
            //获取当前应用程序.exe的全路径
            string fileName = System.Reflection.Assembly.GetExecutingAssembly().Location;
            SetAutoRun(fileName, true);

            //threadFindWindow = new Thread(FindWindow);
            //threadFindWindow.Start();
        }

        public void Ws_NewSessionConnected(WebSocketSession session)
        {
            log.Info("与客户端:" + GetSessionName(session) + "创建新会话");
        }

        private void Ws_NewMessageReceived(WebSocketSession session, string value)
        {
            log.Info("收到消息：" + value);
            reValue = value;
            try
            {                
                if (!string.IsNullOrWhiteSpace(value))
                {
                    if (!sessionDics.ContainsKey(value))
                        sessionDics.Add(value, session);
                    else
                        sessionDics[value] = session;
                }

                if (reValue.Contains("StartCapture"))
                {
                    // 初始化采集设备
                    if (isInited == false)
                    {
                        string initText = "{\"log\":\"0\",\"white_brightness\":\"240\"}";
                        int iResult = axIrisDevCtrl1.IrisInit(initText);
                        if (iResult == 0)
                        {
                            isInited = true;
                            log.Info("初始化成功！");
                        }
                        else
                        {
                            log.Info("初始化失败：" + iResult.ToString());
                            SendMsgToClient(reValue, "设备启动失败");
                            return;
                        }

                    }

                    axIrisDevCtrl1.Visible = true;
                    // 弹出界面
                    form.Show();
                    form.WindowState = FormWindowState.Normal;
                    form.Activate();
                    axIrisDevCtrl1.Focus();

                    // 开始采集
                    string eyeType = "3";
                    if (value.Length > 2) eyeType = value.Substring(value.Length - 1);
                    string collType = "{\"eyeType\":\"" + eyeType + "\"}";
                    axIrisDevCtrl1.StartCapture(collType);
                }
                else if (reValue.Contains("StopCapture"))
                {
                    int re = axIrisDevCtrl1.StopCapture();
                    if (re == 0)
                    {
                        isStoped = true;
                        this.Hide();
                    }
                }
                else if (reValue.Contains("Close"))
                {
                    axIrisDevCtrl1.StopCapture();
                    int re = axIrisDevCtrl1.IrisClose();
                    if (re == 0)
                    {
                        axIrisDevCtrl1.ReSet();
                        axIrisDevCtrl1.Visible = false;
                        isInited = false;
                        this.Hide();
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("Ws_NewMessageReceived 错误：" + ex.Message);
            }

        }

        public void Ws_SessionClosed(WebSocketSession session, SuperSocket.SocketBase.CloseReason value)
        {
            log.Info("与客户端:" + GetSessionName(session) + "的会话被关闭 原因：" + value.ToString());
            var msg = string.Format("{0:HH:MM:ss} {1} 离开聊天室", DateTime.Now, GetSessionName(session));
            axIrisDevCtrl1.Visible = false;
            SendToAll(session, msg);
        }

        /// <summary>
        /// 发送消息到客户端
        /// </summary>
        /// <param name="value"></param>
        /// <param name="msg"></param>
        public static void SendMsgToClient(string value, string msg)
        {
            try
            {
                if (sessionDics.ContainsKey(value))
                {
                    var webSocketSession = sessionDics[value];
                    if (webSocketSession != null)
                    {
                        webSocketSession.Send(msg);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error("SendMsgToClient 错误：" + ex.Message);
            }
        }

        /// <summary>
        /// 启动服务
        /// </summary>
        /// <returns></returns>
        public static void Start()
        {
            try
            {
                int port = Convert.ToInt32(ConfigHelper.GetAppConfig("port"));
                if (!ws.Setup("127.0.0.1", port))
                {
                    log.Error("设置WebSocket服务侦听地址失败");
                    return;
                }

                if (!ws.Start())
                {
                    log.Error("启动WebSocket服务侦听失败");
                    return;
                }
            }
            catch (Exception e)
            {
                log.Error("Start exceptrion: " + e.Message);
            }



        }

        /// <summary>
        /// 停止侦听服务
        /// </summary>
        public static void Stop()
        {
            try
            {
                if (ws != null)
                {
                    ws.Stop();
                }
            }
            catch (Exception e)
            {
                log.Error("Stop exceptrion: " + e.Message);
            }
        }

        public static string GetSessionName(WebSocketSession session)
        {
            return HttpUtility.UrlDecode(session.Path.TrimStart('/'));
        }

        public static void SendToAll(WebSocketSession session, string msg)
        {
            foreach (var sendSession in session.AppServer.GetAllSessions())
            {
                sendSession.Send(msg);
            }
        }




        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.Activate();
            axIrisDevCtrl1.Focus();
        }

        private void btn_hide_Click(object sender, EventArgs e)
        {
            this.Hide();
        }

        private void panel_title_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                mouseOff = new Point(-e.X, -e.Y); //得到变量的值
                leftFlag = true;                  //点击左键按下时标注为true;
            }
        }

        private void panel_title_MouseMove(object sender, MouseEventArgs e)
        {
            if (leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(mouseOff.X, mouseOff.Y);  //设置移动后的位置
                Location = mouseSet;
            }
        }

        private void panel_title_MouseUp(object sender, MouseEventArgs e)
        {

            if (leftFlag)
            {
                leftFlag = false;//释放鼠标后标注为false;
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Stop();
        }

        private void axIrisDevCtrl1_OnCapture(object sender, AxIrisDevCtrlLib._DIrisDevCtrlEvents_OnCaptureEvent e)
        {
            string sendMsg = "";
            try
            {
                new Thread(new ThreadStart(() =>
                {
                    form.Hide();
                    axIrisDevCtrl1.IrisClose();
                    axIrisDevCtrl1.ReSet();
                    axIrisDevCtrl1.Visible = false;
                    isInited = false;

                })).Start();
               
                if (e.result != 0)
                {
                    if(!isStoped) sendMsg = "采集失败";                    
                }
                else
                {                
                    string s = e.sIrisInfo;
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    Dictionary<string, object> jsonResult = (Dictionary<string, object>)serializer.DeserializeObject(e.sIrisInfo);

                    object flgResult;//0：成功;-1：质量不合格；-2：采集超时；其他：失败；
                    object hmzp_zy = null;//左眼虹膜图片base64编码
                    object hmzp_yy = null;//右眼虹膜图片base64编码
                    object cjtphs = null;//采集图片耗时
                    object sbxh = null;//设备型号
                    object sbbh = null;//设备编号
                    object zy_xxzlpf = null;//左眼图像质量评分
                    object yy_xxzlpf = null; //右眼图像质量评分
                    object sbcsdm = null; // 设备厂商代码（信用代码）

                    jsonResult.TryGetValue("flgResult", out flgResult);
                    jsonResult.TryGetValue("hmzp_zy", out hmzp_zy);
                    jsonResult.TryGetValue("hmzp_yy", out hmzp_yy);
                    jsonResult.TryGetValue("cjtphs", out cjtphs);
                    jsonResult.TryGetValue("sbxh", out sbxh);
                    jsonResult.TryGetValue("sbbh", out sbbh);
                    jsonResult.TryGetValue("zy_xxzlpf", out zy_xxzlpf);
                    jsonResult.TryGetValue("yy_xxzlpf", out yy_xxzlpf);
                    jsonResult.TryGetValue("sbcsdm", out sbcsdm);

                    if (flgResult.ToString() == "0")
                    {
                        if (hmzp_zy != null && hmzp_zy.ToString() != "")
                        {
                            sendMsg = hmzp_zy.ToString();
                        }

                        if (hmzp_yy != null && hmzp_yy.ToString() != "")
                        {
                            if (sendMsg == "") sendMsg = hmzp_yy.ToString();
                            else sendMsg = sendMsg + ";" + hmzp_yy.ToString();
                        }
                        sendMsg = "image" + sendMsg;
                    }
                }                
            }
            catch (Exception ex)
            {
                sendMsg = "ICS异常";
                log.Error("axIrisDevCtrl1_OnCapture 错误：" + ex.Message);
            }
            finally
            {
                SendMsgToClient(reValue, sendMsg);
            }
        }

        private void FindWindow()
        {
            while (true)
            {
                int re = MessageBoxHelper.FindAndKillWindow("警告");
                if (re == 1)
                {
                    isInited = false;
                    axIrisDevCtrl1.Visible = false;
                }
            }
        }

        private string toBase64deep8(string base64)
        {
            string base64Deep8 = "";
            try
            {
                Image img = Base64StringToImage(base64);
                Bitmap bitmap = (Bitmap)img;
                if (img.PixelFormat == PixelFormat.Format24bppRgb)
                {
                    Grayscale grayScaleFilter = new Grayscale(0.299, 0.587, 0.114);
                    bitmap = grayScaleFilter.Apply(bitmap);
                }
                base64Deep8 = ToBase64(bitmap);
            }
            catch (Exception ex)
            {
                log.Error("toBase64deep8 错误：" + ex.Message);
            }
            return base64Deep8;
        }

        private string ToBase64(Bitmap bmp)
        {
            try
            {
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                String strbaser64 = Convert.ToBase64String(arr);
                return strbaser64;
            }
            catch (Exception ex)
            {
               log.Error("ImgToBase64String 转换失败 Exception:" + ex.Message);
                return "";
            }
        }

        /// <summary>
        /// base64编码的文本转为图片
        /// </summary>
        public Bitmap Base64StringToImage(string basestr)
        {
            Bitmap bitmap = null;
            try
            {
                String inputStr = basestr;
                byte[] arr = Convert.FromBase64String(inputStr);
                MemoryStream ms = new MemoryStream(arr);
                Bitmap bmp = new Bitmap(ms);
                bmp.Save("E:\\img\\teee.bmp");
                ms.Close();
                ms.Dispose();
                bitmap = bmp;
            }
            catch (Exception ex)
            {
                //MessageBox.Show("Base64StringToImage 转换失败\nException：" + ex.Message);
            }

            return bitmap;
        }

        /// <summary>
        /// 应用程序开机自启动
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="isAutoRun"></param>
        public static void SetAutoRun(string fileName, bool isAutoRun)
        {
            RegistryKey reg = null;
            //设置默认管理员运行
            string admin_path = @"C:\Windows\System32\runas.exe /user:administrator /savecred ";
            try
            {
                if (!System.IO.File.Exists(fileName))
                    throw new Exception("该文件不存在!");
                string name = fileName.Substring(fileName.LastIndexOf(@"\") + 1);
                name = name.Split('.')[0];
                reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run", true);
                if (reg == null)
                    reg = Registry.LocalMachine.CreateSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
                object reg_obj = reg.GetValue(name);

                if (reg_obj != null && reg_obj.ToString().Contains(fileName))
                {
                    if (!isAutoRun)
                        reg.SetValue(name, false);
                }
                else
                {
                    if (isAutoRun)
                    {
                        //reg.SetValue(name, fileName);
                        //设置需要使用默认管理员运行
                        reg.SetValue(name, admin_path + fileName);
                    }
                    else
                        reg.SetValue(name, false);
                }
            }
            catch (Exception ex)
            {
                log.Error("自启动设置失败" + ex.StackTrace.ToString());
            }
            finally
            {
                if (reg != null)
                    reg.Close();
            }
        }

    }
}
