using Common.system;

using RobotpenGateway;

using System;
using System.Threading;

using XHWK.WKTool.Utils.pen;

namespace XHWK.WKTool.Utils.luobo
{
    internal class LuoBoPenUtil
    {
        #region 罗博智慧笔

        #region 值初始化

        private PenEventI penEvent = null;

        [System.Runtime.InteropServices.DllImport("kernel32.dll", CharSet = System.Runtime.InteropServices.CharSet.Auto)]
        public static extern void OutputDebugString(string message);

        public robotpenController.returnPointData Date { get => date; set => date = value; }

        public bool usbIsConnected = false;
        private eDeviceType deviceType = eDeviceType.Unknow;

        private int m_nDeviceW = 22600;

        private int m_nDeviceH = 16650;
        private robotpenController.returnPointData date = null;

        public bool isOpen = true;

        /// <summary>
        /// 是否为笔模式
        /// </summary>
        private bool IsPen = false;

        #endregion 值初始化

        public LuoBoPenUtil(PenEventI penEvent)
        {
            this.penEvent = penEvent;
        }

        /// <summary>
        /// 笔模式
        /// </summary>
        public void lb_device_hand()
        {
            IsPen = true;
            if (deviceType == eDeviceType.T8B_D2 || deviceType == eDeviceType.T8Y || deviceType == eDeviceType.T8S_LQ || deviceType == eDeviceType.T8C)
            {
                robotpenController.GetInstance().setDeviceMode(eDeviceMode.DEVICE_HAND);
            }
            else
            {
                //获取当前设备模式，根据模式切换鼠标和笔
                robotpenController.GetInstance()._Send(cmdId.SearchMode);
            }
        }

        /// <summary>
        /// 鼠标模式
        /// </summary>
        public void lb_device_mouse()
        {
            IsPen = false;
            if (deviceType == eDeviceType.T8B_D2 || deviceType == eDeviceType.T8Y || deviceType == eDeviceType.T8S_LQ || deviceType == eDeviceType.T8C)
            {
                robotpenController.GetInstance().setDeviceMode(eDeviceMode.DEVICE_MOUSE);
            }
            else
            {
                //获取当前设备模式，根据模式切换鼠标和笔
                robotpenController.GetInstance()._Send(cmdId.SearchMode);
            }
        }

        private void luobo_searchModeEvt(int modeType)
        {
            if (App.IsOutputInfoLog)
            {
                if (modeType == 1)
                {
                    LogHelper.WriteInfoLog("当前为笔模式");
                }
                else
                {
                    LogHelper.WriteInfoLog("当前为鼠标模式");
                }
            }
        }

        // 子节点设备状态改变事件
        private void luobo_nodeStatusEvt(NODE_STATUS ns)
        {
            string strStatus = string.Empty;
            switch (ns)
            {
                case NODE_STATUS.DEVICE_POWER_OFF:
                    {
                        strStatus = "DEVICE_POWER_OFF";
                    }
                    break;

                case NODE_STATUS.DEVICE_STANDBY:
                    {
                        strStatus = "DEVICE_STANDBY";
                    }
                    break;

                case NODE_STATUS.DEVICE_INIT_BTN:
                    {
                        strStatus = "DEVICE_INIT_BTN";
                    }
                    break;

                case NODE_STATUS.DEVICE_OFFLINE:
                    {
                        strStatus = "DEVICE_OFFLINE";
                    }
                    break;

                case NODE_STATUS.DEVICE_ACTIVE:
                    {
                        strStatus = "DEVICE_ACTIVE";
                        //deviceHand();
                    }
                    break;

                case NODE_STATUS.DEVICE_LOW_POWER_ACTIVE:
                    {
                        strStatus = "DEVICE_LOW_POWER_ACTIVE";
                    }
                    break;

                case NODE_STATUS.DEVICE_OTA_MODE:
                    {
                        strStatus = "DEVICE_OTA_MODE";
                    }
                    break;

                case NODE_STATUS.DEVICE_OTA_WAIT_SWITCH:
                    {
                        strStatus = "DEVICE_OTA_WAIT_SWITCH";
                    }
                    break;

                case NODE_STATUS.DEVICE_DFU_MODE:
                    {
                        strStatus = "DEVICE_DFU_MODE";
                    }
                    break;

                case NODE_STATUS.DEVICE_TRYING_POWER_OFF:
                    {
                        strStatus = "DEVICE_TRYING_POWER_OFF";
                    }
                    break;

                case NODE_STATUS.DEVICE_FINISHED_PRODUCT_TEST:
                    {
                        strStatus = "DEVICE_FINISHED_PRODUCT_TEST";
                    }
                    break;

                case NODE_STATUS.DEVICE_SYNC_MODE:
                    {
                        strStatus = "DEVICE_SYNC_MODE";
                    }
                    break;

                default:
                    {
                        strStatus = "UNKNOW";
                    }
                    break;
            }
        }

        private void luobo_switchModeEvt(int modeType)
        {
            if (modeType == 1)
            {
                if (App.IsOutputInfoLog)
                {
                    LogHelper.WriteInfoLog("当前为笔模式");
                }
                if (!IsPen)
                {
                    lb_device_mouse();
                }
            }
            else
            {
                if (App.IsOutputInfoLog)
                {
                    LogHelper.WriteInfoLog("当前为鼠标模式");
                }
                if (IsPen)
                {
                    lb_device_hand();
                }
            }
        }

        //初始化笔服务
        public void InitlbPen()
        {
            try
            {
                robotpenController.GetInstance()._ConnectInitialize(eDeviceType.Gateway, IntPtr.Zero);
                robotpenController.GetInstance().deviceChangeEvt += new robotpenController.DeviceChange(luobo_deviceChangeEvt);
                robotpenController.GetInstance().searchModeEvt += luobo_searchModeEvt;
                robotpenController.GetInstance().nodeStatusEvt += luobo_nodeStatusEvt;
                robotpenController.GetInstance().switchModeEvt += luobo_switchModeEvt;
                robotpenController.GetInstance().keyPressEvt += new robotpenController.KeyPress(luobo_keyPressEvt);

                robotpenController.returnPointData datad = new robotpenController.returnPointData(luobo_bigDataReportEvt1);
                robotpenController.GetInstance().initDeletgate(ref datad);

                CheckUsbConnect();
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrLog("设备初始化失败：" + ex.Message, ex);
            }
        }

        /// <summary>
        /// 设备插拔消息，更新listview
        /// </summary>
        /// <param name="bStatus">
        /// </param>
        /// <param name="uPid">
        /// </param>
        private void luobo_deviceChangeEvt(bool bStatus, ushort uPid)
        {
            //throw new NotImplementedException();
            Console.WriteLine(@"luobo_deviceChangeEvt");
            try
            {
                if (App.IsOutputInfoLog)
                {
                    LogHelper.WriteInfoLog
                    (
                        string.Format
                        (
                            "设备状态{0} PID = {1}",
                            bStatus,
                            uPid
                        )
                    );
                }
            }
            catch (Exception)
            {
            }
            CheckUsbConnect();
        }

        /// <summary>
        /// 书写
        /// </summary>
        /// ///
        /// <param name="bIndex">
        /// </param>
        /// <param name="bPenStatus">
        /// </param>
        /// <param name="bx">
        /// </param>
        /// <param name="by">
        /// </param>
        /// <param name="bPress">
        /// </param>
        private void luobo_bigDataReportEvt1(byte bIndex, byte bPenStatus, short bx, short by, short bPress)
        {
            if (bx == 0 && by == 0 && bPenStatus == 0 && bPress == 0)
            {
                return;
            }
            if (penEvent != null)
            {
                penEvent.penPointEvent(bIndex, bPenStatus, bx, by, bPress, m_nDeviceW, m_nDeviceH);
            }
        }

        /// <summary>
        /// 判断是否有设备连接
        /// </summary>
        public void CheckUsbConnect()
        {
            usbIsConnected = false;
            Thread.Sleep(200);
            int nDeviceCount = robotpenController.GetInstance()._GetDeviceCount();
            if (App.IsOutputInfoLog)
            {
                LogHelper.WriteInfoLog(string.Format("当前有 {0} 个设备", nDeviceCount));
            }
            if (nDeviceCount > 0)
            {
                for (int i = 0; i < nDeviceCount; ++i)
                {
                    ushort npid = 0;
                    ushort nvid = 0;
                    string strDeviceName = string.Empty;
                    eDeviceType dtype = eDeviceType.Unknow;
                    if (robotpenController.GetInstance()._GetAvailableDevice(i, ref npid, ref nvid, ref strDeviceName, ref dtype))
                    {
                        if (!usbIsConnected)
                        {
                            usbIsConnected = true;
                            deviceType = dtype;
                            robotpenController.GetInstance()._ConnectInitialize(deviceType, IntPtr.Zero);
                            int nRes = robotpenController.GetInstance()._ConnectOpen();
                            if (nRes != 0)
                            {
                                //LogHelper.WriteInfoLog(string.Format(@"x={0},y={1},s={2},p={3}", bx, by, bPenStatus, bPress));
                                LogHelper.WriteErrLog("设备自动连接失败，请重新插拔设备或尝试手动连接!", null);
                                usbIsConnected = false;
                                break;
                            }

                            robotpenController.GetInstance()._Send(cmdId.GetConfig);
                            App.BoardStatus = true;
                            try
                            {
                                int banWidth = robotpenController.GetInstance().getWidth();
                                int banHeight = robotpenController.GetInstance().getHeight();
                                if (banWidth > 0 && banHeight > 0)
                                {
                                    if (banWidth > banHeight)
                                    {
                                        m_nDeviceW = banWidth;
                                        m_nDeviceH = banHeight;
                                    }
                                    else
                                    {
                                        m_nDeviceW = banHeight;
                                        m_nDeviceH = banWidth;
                                    }
                                }
                                if (App.IsOutputInfoLog)
                                {
                                    LogHelper.WriteInfoLog
                                    (
                                        string.Format
                                        (
                                            "手写板宽度为：{0} 高度为：{1}",
                                            m_nDeviceW,
                                            m_nDeviceH
                                        )
                                    );
                                }
                            }
                            catch (Exception ex)
                            {
                                LogHelper.WriteErrLog("手写板大小获取失败：" + ex.Message, ex);
                            }
                            UpdateDevStatus();
                            if (App.IsOutputInfoLog)
                            {
                                LogHelper.WriteInfoLog(string.Format("设备类型：{0}", deviceType.ToString()));
                            }

                            new Thread(new ThreadStart(new Action(() =>
                            {
                                Thread.Sleep(500);

                                robotpenController.GetInstance()._Send(cmdId.SearchMode);
                            }))).Start();
                        }
                    }
                }
            }
            else
            {
                App.BoardStatus = false;
                UpdateDevStatus();
            }
        }

        /// <summary>
        /// 按键回调函数
        /// </summary>
        /// <param name="Value">
        /// </param>
        private void luobo_keyPressEvt(eKeyPress Value)
        {
            switch (Value)
            {
                case eKeyPress.CLICK:
                    break;

                case eKeyPress.DBCLICK:
                    break;

                case eKeyPress.PAGEUP:
                    //last_button_Click(null, null);
                    break;

                case eKeyPress.PAGEDOWN:
                    //next_btn_Click(null, null);
                    break;

                case eKeyPress.CREATEPAGE://关机键
                    break;

                case eKeyPress.KEY_A:
                    break;

                case eKeyPress.KEY_B:
                    break;

                case eKeyPress.KEY_C:
                    break;

                case eKeyPress.KEY_D:
                    break;

                case eKeyPress.KEY_E:
                    break;

                case eKeyPress.KEY_F:
                    break;

                case eKeyPress.KEY_UP:
                    //last_button_Click(null, null);
                    break;

                case eKeyPress.KEY_DOWN:
                    //next_btn_Click(null, null);
                    break;

                case eKeyPress.KEY_YES:
                    break;

                case eKeyPress.KEY_NO:
                    break;

                case eKeyPress.KEY_CANCEL:
                    break;

                case eKeyPress.KEY_OK:
                    break;

                case eKeyPress.PAGEUPCLICK://上一页
                    //last_button_Click(null, null);
                    break;

                case eKeyPress.PAGEUPDBCLICK://双击上一页
                    break;

                case eKeyPress.PAGEUPPRESS://长按上一页
                    break;

                case eKeyPress.PAGEDOWNCLICK://下一页
                    //next_btn_Click(null, null);
                    break;

                case eKeyPress.PAGEDOWNDBCLICK://双击下一页
                    break;

                case eKeyPress.PAGEDOWNPRESS://长按下一页
                    break;
            }
        }

        /// <summary>
        /// 更新设备状态显示
        /// </summary>
        public void UpdateDevStatus()
        {
            if (penEvent != null)
            {
                penEvent.penStatusEvent();
            }
        }

        #endregion 罗博智慧笔
    }
}
