using Highway.Assemble.common;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Windows.Forms;

namespace HighWayAssemble
{
    public partial class FrmDisplayView : Form
    {
        public static readonly log4net.ILog LogInfo = log4net.LogManager.GetLogger("RollingLogFileAppender"); //Logging 名字要在 App.config 中能找到
        [DllImport("kernel32.dll", EntryPoint = "SetProcessWorkingSetSize")]
        public static extern int SetProcessWorkingSetSize(IntPtr process, int minSize, int maxSize);
        FrmDisplayControl controller;
        public FrmDisplayView()
        {
            InitializeComponent();
            controller = new FrmDisplayControl(this);
        }

        #region ListView数据刷新
        private delegate void MESStateEvent(List<mesSoft> meslist);
        public void UpdateMesListView(List<mesSoft> meslist)
        {
            if (meslist == null)
            {
                return;
            }
            this.Invoke(new MESStateEvent(FreshMesListView), new object[] { meslist });
        }

        /*
         * foreach (ListViewItem v in adapter_list.Items)
                {
                    if (v.Text == mesID)
                    {
                        v.SubItems[4].Text = state > 0 ? "已连接" : "已断开";
                        break;
                    }
                }
         * 
         */
        /// <summary>
        /// 更新MES view列表
        /// </summary>
        private void FreshMesListView(List<mesSoft> meslist)
        {
            if (this.adapter_list.Items.Count > 0)
            {
                this.adapter_list.Items.Clear();
            }
            this.adapter_list.BeginUpdate();
            foreach (var v in meslist)
            {
                ListViewItem lvi = new ListViewItem();
                //lvi.ImageIndex = i;     //通过与imageList绑定，显示imageList中第i项图标
                lvi.Text = v.mesid;
                lvi.SubItems.Add(v.adapterName);
                lvi.SubItems.Add(v.AdatperIP);
                lvi.SubItems.Add(v.AdapterPort);
                lvi.SubItems.Add(v.State == 0 ? "未连接" : "已连接");
                this.adapter_list.Items.Add(lvi);
            }
            this.adapter_list.EndUpdate();
        }
        /// <summary>
        /// 刷新设备列表
        /// </summary>
        public void FreshEquipListView(List<Equip> equiplist)
        {
            if (equiplist == null)
            {
                return;
            }
            this.equip_list.Items.Clear();
            this.equip_list.BeginUpdate();
            foreach (var e in equiplist)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = e.deviceId;
                lvi.SubItems.Add(e.deviceName);
                lvi.SubItems.Add(e.connectstr);
                lvi.SubItems.Add(e.connectModeName);
                lvi.SubItems.Add(e.deviceType);
                lvi.SubItems.Add(e.collectid);
                lvi.SubItems.Add("未连接");
                //lvi.SubItems.Add("未初始化");
                this.equip_list.Items.Add(lvi);
            }

            this.equip_list.EndUpdate();
        }
        //更新传感器信息表
        public void FreshSensorListView(List<Sensor> sensorslist)
        {
            if (sensorslist == null)
            {
                return;
            }
            this.sensor_list.Items.Clear();
            this.sensor_list.BeginUpdate();

            foreach (var e in sensorslist)
            {
                ListViewItem lvi = new ListViewItem();
                lvi.Text = e.combineid;
                lvi.SubItems.Add(e.sensorName);
                lvi.SubItems.Add(e.sensorser);
                lvi.SubItems.Add(e.sensorTypeName);
                lvi.SubItems.Add(e.deviceId);
                lvi.SubItems.Add("");
                lvi.SubItems.Add("");
                lvi.SubItems.Add(e.readInterval);
                lvi.SubItems.Add(e.multData);
                lvi.SubItems.Add(e.timeout);
                lvi.SubItems.Add(e.returnImm);
                this.sensor_list.Items.Add(lvi);
            }

            this.sensor_list.EndUpdate();
        }
        #endregion

        #region 更新读取数据
        private delegate void FrmEvent(string combineid, string data);
        public void DealData(string id, string pData)
        {
            // string strdata = bytesToHexStr(pData, pData.Length);
            //string strdata = System.Text.Encoding.ASCII.GetString(pData);
            if (pData.Length < 1)
            {
                pData = "NoData";
            }
            this.Invoke(new FrmEvent(ListViewUpdate), new object[] { id, pData });
        }
        /// <summary>
        /// 更新读取数据
        /// </summary>
        /// <param name="combineid">传感器合并编号</param>
        /// <param name="data">数据</param>
        private void ListViewUpdate(string combineid, string data)
        {
            lock (this)
            {
                this.sensor_list.BeginUpdate();
                foreach (ListViewItem v in sensor_list.Items)
                {
                    if (v.Text == combineid)
                    {
                        v.SubItems[5].Text = DateTime.Now.ToString(@"yy-MM-dd HH:mm:ss");
                        v.SubItems[6].Text = data;
                        break;
                    }
                }
                this.sensor_list.EndUpdate();
            }
        }
        /// <summary>
        /// 软件版本信息
        /// </summary>
        /// <param name="versionInfo"></param>
        /// <param name="data"></param>
        private delegate void VersionEvent(string versionInfo, bool needupdate = false);
        public void SetVersionInfo(string versionInfo, bool needupdate = false)
        {
            this.Invoke(new VersionEvent(ShowVersion), new object[] { versionInfo, needupdate });
        }
        private void ShowVersion(string versionInfo, bool needupdate = false)
        {
            if (string.IsNullOrEmpty(versionInfo) || versionInfo.Length > 20)
            {
                return;
            }
            label_Version.Text = versionInfo;
            if (needupdate)
            {
                label_Version.BackColor = label_Version.BackColor == Color.CadetBlue ? Color.OrangeRed : Color.CadetBlue;

            }
        }
        #endregion
        #region 更新设备连接状态
        private delegate void EquipEvent(string equipID, int state);
        /// <summary>
        /// 更新设备状态
        /// </summary>
        /// <param name="equipID">设备编号</param>
        /// <param name="state">1连接正常,2与设备断开，3连接失败</param>
        public void equipState(string equipID, int state)
        {
            this.Invoke(new EquipEvent(EquipListViewUpdate), new object[] { equipID, state });
        }

        /// <summary>
        /// 更新读取数据
        /// </summary>
        /// <param name="equipID"></param>
        /// <param name="state"></param>
        public void EquipListViewUpdate(string equipID, int state)
        {
            lock (this)
            {
                this.equip_list.BeginUpdate();
                foreach (ListViewItem v in equip_list.Items)
                {
                    //if (v.Text == equipID)
                    //{
                    //    v.SubItems[6].Text = state == 1 ? "已连接" : "已断开";
                    //    break;
                    //}
                    if (v.Text == equipID)
                    {
                        if (state == 1)
                        {
                            v.SubItems[6].Text = "已连接";
                        }
                        else if (state == 2)
                        {
                            v.SubItems[6].Text = "连接异常";
                        }
                        else if (state == 0)
                        {
                            v.SubItems[6].Text = "已断开";
                        }
                        break;
                    }
                }
                this.equip_list.EndUpdate();
            }
        }


        #endregion

        #region 定时刷新适配列表
        /// <summary>
        /// 定时器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
            }
            //UpdateAdapterList();
        }
        /// <summary>
        /// 重新刷新适配器列表
        /// </summary>
        private void UpdateAdapterList()
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
            if (Environment.OSVersion.Platform == PlatformID.Win32NT)
            {
                SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
            }
            //    Tcpser.Init();
            //    FreshAdapterListView();
            //    FreshEquipListView();
            //    FreshSensorListView();
        }
        #endregion

        private void FrmDisplay_FormClosed(object sender, FormClosedEventArgs e)
        {
            notifyIcon1.Dispose();  //修改程序最小化托盘，关闭程序时图标不被释放BUG
            try
            {
                //CatLib.App.Terminate();
                System.Environment.Exit(System.Environment.ExitCode);
                //controller.AppClosed();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                this.Dispose();
                this.Close();
            }
        }

        private void FrmDisplayView_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("您将退出系统,是否继续？", "系统提示", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
        }

        public void SetFromName(string fromName)
        {
            if (!string.IsNullOrEmpty(fromName))
            {
                this.Text = fromName;
            }

        }

        private void Label1_Click(object sender, EventArgs e)
        {
            ShowMessageBox("是否下载更新？若确定本软件将关闭！", "更新提示", () =>
            {
                controller.AppClosed();
                Process m_Process = null;
                m_Process = new Process();
                m_Process.StartInfo.FileName = "自动更新.exe";
                m_Process.Start();
                //LogInfo.Debug("用户更新退出");
                Process.GetCurrentProcess().Kill();
            }, 48);
        }

        private void FrmDisplayView_Load(object sender, EventArgs e)
        {
            // MessageBox.Show("dsasdasd");
            controller.StartLoad();
            controller.GetVersionInfo();
        }

        #region 托盘设置
        private void NotifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (WindowState == FormWindowState.Minimized)
            {
                //还原窗体显示    
                WindowState = FormWindowState.Normal;
                //激活窗体并给予它焦点
                this.Activate();
                //任务栏区显示图标
                this.ShowInTaskbar = true;
                //托盘区图标隐藏
                notifyIcon1.Visible = false;
            }
        }

        private void FrmDisplayView_SizeChanged(object sender, EventArgs e)
        {
            //判断是否选择的是最小化按钮
            if (WindowState == FormWindowState.Minimized)
            {
                //隐藏任务栏区图标
                this.ShowInTaskbar = false;
                //图标显示在托盘区
                notifyIcon1.Visible = true;
            }
        }

        private void 显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            WindowState = FormWindowState.Normal;
        }

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("是否确认退出程序？", "退出", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
            {
                // 关闭所有的线程
                this.Dispose();
                this.Close();
            }
        }
        #endregion
        private void Label_CollectID_Click(object sender, EventArgs e)
        {
            // controller.LoadCollectID();
        }

        private delegate void CollectID(string Collectid, string CollectName);
        /// <summary>
        /// 更新设备状态
        /// </summary>
        /// <param name="Collectid">设备编号</param>
        /// <param name="state">1连接正常,2与设备断开，3连接失败</param>
        public void SetCollectID(string Collectid, string CollectName)
        {
            this.Invoke(new CollectID(SetCollectIDShow), new object[] { Collectid, CollectName });
        }
        private void SetCollectIDShow(string id, string name)
        {
            label_CollectID.Text = "软件编号：" + id;
            //notifyIcon1.Text = "汇集：" + id;
            notifyIcon1.Text = name;
        }


        private delegate void MessageBoxDel(string info, string caption, Action Okaction = null, int icon = 0, Action Cancelaction = null);
        /// <summary>
        /// 更新设备状态
        /// </summary>
        /// <param name="equipID">设备编号</param>
        /// <param name="state">1连接正常,2与设备断开，3连接失败</param>
        public void ShowMessageBox(string info, string caption, Action Okaction = null, int icon = 0, Action Cancelaction = null)
        {
            this.Invoke(new MessageBoxDel(MessageBoxPanel), new object[] { info, caption, Okaction, icon, Cancelaction });
        }
        /// <summary>
        /// 显示 提示 框
        /// </summary>
        /// <param name="info"></param>
        /// <param name="caption"></param>
        /// <param name="icon"></param>
        /// <returns></returns>
        private void MessageBoxPanel(string info, string caption, Action Okaction = null, int icon = 0, Action Cancelaction = null)
        {
            if (MessageBox.Show(info, caption
                , MessageBoxButtons.OKCancel, (MessageBoxIcon)icon, MessageBoxDefaultButton.Button2) == DialogResult.OK)

            {
                Okaction?.Invoke();
            }
            else
            {
                Cancelaction?.Invoke();
            }
        }

    }
}
