using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using TStudyDigitalPen.AP;
using Newtonsoft.Json;
using System.Threading.Tasks;
using System.Web;
using System.Threading;
using System.Drawing.Imaging;
using System.IO;
using System.Text.Json;
using Fleck;
using System.Security.Policy;
using System.Net.Http;
using System.Xml.Linq;
namespace WindowsFormsApp
{
    public partial class Form1 : Form
    {

        static DigitalPenAP digitalPenAP;
        static List<SR_Pen_coordinate> Penesult = new List<SR_Pen_coordinate>();
        static List<string> penList = new List<string>();
        static object obj = new object();
        public static long ClassID=0;
        public static string apiUrl = "";

        //DigitalPenAP对象，负责与点阵笔通信，接收数据，发送指令

        //所有已连接笔的绘制窗口
        Dictionary<string, PenDraw> AllPenDrawsDic = new Dictionary<string, PenDraw>();
        public Form1()
        {
            InitializeComponent();
            // 加载 XML 文件
            XDocument xdoc = XDocument.Load("roomconfig.xml");
            // 读取 AppName 节点内容
            ClassID = Convert.ToInt64(xdoc.Element("Root")?.Element("Settings")?.Element("ClassID").Value);//房间号
            apiUrl = xdoc.Element("Root")?.Element("Settings")?.Element("apiUrl").Value;
            SaveDataOperater.DeletePenStatus();
            //SaveDataOperater.DropAllPenTable();
            WriteData();
        }

        public static async void WriteData()
        {
            while (true)
            {
                if (Penesult.Count > 0)
                {
                    try
                    {
                        GetPenDataInSql();
                    }
                    catch
                    { 
                    
                    }
                  
                    //Console.WriteLine(Penesult.Count);

                }
                await Task.Delay(500);
            }
        }


        private static void GetPenDataInSql()
        {
            lock (obj)
            {
                StringBuilder sb = new StringBuilder();
                var newList = penList.ToList();
                foreach (string penNo in newList)
                {
                    List<SR_Pen_coordinate> lt = Penesult.FindAll(c => c.penSerial == penNo);
                    if (lt.Count > 0)
                    {
                        foreach (SR_Pen_coordinate sr in lt)
                        {
                            sb.Append($@"INSERT INTO {"\"" + sr.penSerial + "\""} VALUES('{sr.penSerial}','{sr.pageSerial}',{sr.penType},{sr.cx},{sr.cy},{sr.force},{sr.flag},{sr.time},'{DateTime.Now}')");
                        }
                    }
                    Penesult.RemoveAll(c => c.penSerial == penNo);
                }
                if (sb.ToString() != "")
                {
                  
                        SaveDataOperater.InsertIntoTable(sb.ToString());
                   
                   
                }
            }
        }

        private void InitPen()
        {
            //获取DigitalPenAP实例
            digitalPenAP = DigitalPenAP.GetInstance(certificates.MyLicense.Bytes);
            #region 设置笔事件处理函数
            //绑定坐标事件
            digitalPenAP.PenCoordinate += digitalPenAP_PenCoordinate;
            //绑定笔连接事件
            digitalPenAP.PenConnected += digitalPenAP_PenConnected;
            //绑定笔断开事件
            digitalPenAP.PenDisconnect += digitalPenAP_PenDisconnect;
            //绑定落笔事件
            digitalPenAP.PenDown += digitalPenAP_PenDown;
            //绑定抬笔事件
            digitalPenAP.PenUp += digitalPenAP_PenUp;
            //绑定笔信息事件
            digitalPenAP.PenInfo += DigitalPenAP_PenInfo;
            //绑定获取笔时间事件
            digitalPenAP.PenRTC += DigitalPenAP_PenRTC;
            //绑定蓝牙断连原因事件
            digitalPenAP.PenBluetoothDisconnectionReason += digitalPenAP_PenBluetoothDisconnectionReason;
            //绑定设置笔名字结果事件
            digitalPenAP.PenSetName += digitalPenAP_PenSetName;
            //绑定获取笔名字事件
            digitalPenAP.PenPenGetName += digitalPenAP_PenGetName;
            //绑定设置指示灯结果事件
            digitalPenAP.PenPenSetLed += digitalPenAP_PenSetLed;
            //绑定设置指示灯临时状态结果事件
            digitalPenAP.PenPenSetLedTemporary += digitalPenAP_PenSetLedTemporary;
            //绑定获取指示灯结果事件
            digitalPenAP.PenGetLed += digitalPenAP_PenGetLed;
            //绑定设置笔超时关机时间结果事件
            digitalPenAP.PenSetShutDownTime += digitalPenAP_PenSetShutDownTime;
            //绑定设置蜂鸣器结果事件
            digitalPenAP.PenSetBuzzer += digitalPenAP_PenSetBuzzer;
            //绑定获取笔超时关机时间事件
            digitalPenAP.PenGetShutDown += digitalPenAP_PenGetShutDown;
            //绑定获取笔迹分布事件
            digitalPenAP.PenGetHandwriting += digitalPenAP_PenGetHandwriting;
            //绑定电量上报事件
            digitalPenAP.ReceivePenBatteryChanged += digitalPenAP_ReceivePenBatteryChanged;
            #endregion

            //开启AP，接收笔数据
            //此函数在程序初始化时调用一次即可
            //系统会自己创建该文件目录以及在里面下自动生成log.txt; 最终 例：D:/a/demoLog/log.txt 、D:/a/demoLog/log.1.txt - D:/a/demoLog/log.*.txt
            char[] filePath = "D:/a/demoLog".ToCharArray();
            //第一个参数为0表示不生成指定路径的log，1表示生成
            //该日志会记录笔迹数据，长度最好是放大一些（不要超出unsigned int），示例一个文件最大10MB,最后参数标志该日志文件最多有n个（log.*.txt），所以最终最大可存储10MB * 11（log.txt + log.*.txt）的信息量（最新的数据）
            ERROR_CODE rc = digitalPenAP.Start(false, filePath, 10 * 1024 * 1024, 10);
            //判断返回值是否正确
            if (rc != ERROR_CODE.ERROR_OK)
            {
                MessageBox.Show("初始化失败" + rc.ToString());

            }
            else
            {

            }
            timer1.Start();
            timer2.Start();
        }
        private static string RTCToTimeString(ulong rtc)
        {
            DateTime dt = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
       
            TimeSpan timeSpan = new TimeSpan((long)rtc * 1000);
            DateTime now = dt.AddMilliseconds(rtc);
            return now.ToString("yyyy-MM-dd HH:mm:ss");
        }
        //笔时间 响应GetPenRTC函数
        private void DigitalPenAP_PenRTC(ulong time, string penSerial, int penType, ulong rtc)
        {
            MessageBox.Show(RTCToTimeString(rtc), penSerial);
        }

        //笔连接事件
        //收到此事件，说明点阵笔已经连接，此时调用GetPenData函数就可以正常获取点阵笔数据
        private void digitalPenAP_PenConnected(ulong time, string penSerial, int penType)
        {
            string x = penSerial;

            penList.Add(penSerial);
            SaveDataOperater.AddSqlTable(penSerial, ClassID);
            SaveDataOperater.UpdatePenStatus(penSerial, 1);

            //务必调用此函数获取笔数据
            digitalPenAP.GetPenData(penSerial);

            if (AllPenDrawsDic.ContainsKey(penSerial) == false)
            {
                var item = contextMenuStrip1.Items[0] as ToolStripDropDownItem;
                ToolStripItem subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "Info";
                item.DropDownItems.Add(subItem);

                item = contextMenuStrip1.Items[1] as ToolStripDropDownItem;
                subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "Mem";
                item.DropDownItems.Add(subItem);

                item = contextMenuStrip1.Items[2] as ToolStripDropDownItem;
                subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "GetRtc";
                item.DropDownItems.Add(subItem);

                item = contextMenuStrip1.Items[3] as ToolStripDropDownItem;
                subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "SetRtc";
                item.DropDownItems.Add(subItem);


                item = contextMenuStrip1.Items[4] as ToolStripDropDownItem;
                subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "SetPenName";
                item.DropDownItems.Add(subItem);

                item = contextMenuStrip1.Items[5] as ToolStripDropDownItem;
                subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "GetPenName";
                item.DropDownItems.Add(subItem);

                item = contextMenuStrip1.Items[6] as ToolStripDropDownItem;
                subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "SetPenLed";
                item.DropDownItems.Add(subItem);

                item = contextMenuStrip1.Items[7] as ToolStripDropDownItem;
                subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "SetPenLedTemporary";
                item.DropDownItems.Add(subItem);

                item = contextMenuStrip1.Items[8] as ToolStripDropDownItem;
                subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "GetPenLed";
                item.DropDownItems.Add(subItem);

                item = contextMenuStrip1.Items[9] as ToolStripDropDownItem;
                subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "SetPenBuzzer";
                item.DropDownItems.Add(subItem);

                item = contextMenuStrip1.Items[10] as ToolStripDropDownItem;
                subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "SetdownTime";
                item.DropDownItems.Add(subItem);

                item = contextMenuStrip1.Items[11] as ToolStripDropDownItem;
                subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "GetdownTime";
                item.DropDownItems.Add(subItem);

                item = contextMenuStrip1.Items[12] as ToolStripDropDownItem;
                subItem = new ToolStripMenuItem(penSerial);
                subItem.Click += SubItem_Click;
                subItem.Tag = "GetHandwritingDistribution";
                item.DropDownItems.Add(subItem);
                AddPen(penSerial);
            }
        }

        private void AddPen(string penserial)
        {
            if (this.InvokeRequired)
            {
                Action<string> action = new Action<string>(AddPen);
                this.Invoke(action, new object[] { penserial });
            }
            else
            {
                //PenDraw penDraw = new PenDraw(penserial);
                //flowLayoutPanel1.Controls.Add(penDraw);
                //AllPenDrawsDic.Add(penserial, penDraw);
            }
        }

        private void DigitalPenAP_PenInfo(ulong time, string penSerial, int penType,string penMac, int batteryPercent, int memoryPercent, int memoryUsedInBytes, string hw, string sw)
        {
            //Debug.WriteLine($"{penSerial} {penMac} {batteryPercent} {memoryPercent} {memoryUsedInBytes}");
        }
        private async void Form1_Load(object sender, EventArgs e)
        {
            InitPen();
        }
        private static readonly object splLock = new object();
        private static readonly int maxCount = 500;

        void ProcessBusinessData(string taskName,string[] penList)
        {
        }
        private const int CANVAS_WIDTH = 800;
        private const int CANVAS_HEIGHT = 600;
        private const int MARGIN = 50;
        private  void digitalPenAP_PenDisconnect(ulong time, string penSerial, int penType)
        {
            try
            {
                SaveDataOperater.UpdatePenStatus(penSerial, 0);
            }
            catch
            { 
            
            }
            //penList.Remove(penSerial);
        }

        hdwrdist_list_t p_list = new hdwrdist_list_t();

        private void SubItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem item = sender as ToolStripMenuItem;

            switch (item.Tag.ToString()) {
                case "Info":
                    digitalPenAP.GetPenInfo(item.Text);
                    break;
                case "Mem":
                    digitalPenAP.ClearPenMemory(item.Text);
                    break;
                case "GetRtc":
                    digitalPenAP.GetPenRTC(item.Text);
                    break;
                case "SetRtc":
                    {
                        Form form = new Form();
                        form.Text = "设置时间";
                        DateTimePicker dateTimePicker = new DateTimePicker();
                        dateTimePicker.Format = DateTimePickerFormat.Custom;
                        dateTimePicker.CustomFormat = "yyyy-MM-dd HH:mm:ss";
                        dateTimePicker.MinDate = new DateTime(2018, 1, 1);
                        dateTimePicker.Dock = DockStyle.Fill;
                        form.Controls.Add(dateTimePicker);
                        form.StartPosition = FormStartPosition.CenterParent;
                        form.ShowDialog();
                        DateTime result = dateTimePicker.Value;
                        TimeSpan ts = result - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
                        var rtc = Convert.ToUInt64(ts.TotalSeconds * 1000);
                        digitalPenAP.SetPenRTC(item.Text, rtc);
                    }
                    break;
                case "SetPenName": //设置笔名
                    {
                        FrmSetPenName frmSetPenName = new FrmSetPenName("SetPenName", item.Text);
                        frmSetPenName.SpeedChangeClickEvent += FrmSetPenName_SpeedChangeClickEvent;
                        if (DialogResult.OK == frmSetPenName.ShowDialog()) { 
                        
                        }
                    }
                    break;
                case "GetPenName":  //获取笔名
                    {
                        digitalPenAP.GetCurrentPenNameExpose(item.Text);
                    }
                    break;
                case "SetPenLed":  //设置指示灯
                    {
                        FrmSetPenName frmSetPenName = new FrmSetPenName("SetPenLed", item.Text);
                        frmSetPenName.SpeedChangeClickEvent += FrmSetPenName_SpeedChangeClickEvent;
                        if (DialogResult.OK == frmSetPenName.ShowDialog())
                        {

                        }
                    }
                    break;
                case "SetPenLedTemporary":  //设置临时指示灯
                    {
                        FrmSetPenName frmSetPenName = new FrmSetPenName("SetPenLedTemporary", item.Text);
                        frmSetPenName.SpeedChangeClickEvent += FrmSetPenName_SpeedChangeClickEvent;
                        if (DialogResult.OK == frmSetPenName.ShowDialog())
                        {

                        }
                    }
                    break;
                case "GetPenLed":  //获取指示灯
                    {
                        digitalPenAP.GetCurrentPenLedExpose(item.Text);
                    }
                    break;
                case "SetPenBuzzer":  //设置蜂鸣器
                    {
                        FrmSetPenName frmSetPenName = new FrmSetPenName("SetPenBuzzer", item.Text);
                        frmSetPenName.SpeedChangeClickEvent += FrmSetPenName_SpeedChangeClickEvent;
                        if (DialogResult.OK == frmSetPenName.ShowDialog())
                        {

                        }
                    }
                    break;
                case "SetdownTime": //设置关机时间
                    {
                        FrmSetPenName frmSetPenName = new FrmSetPenName("SetdownTime", item.Text);
                        frmSetPenName.SpeedChangeClickEvent += FrmSetPenName_SpeedChangeClickEvent;
                        if (DialogResult.OK == frmSetPenName.ShowDialog())
                        {

                        }
                    }
                    break;
                case "GetdownTime":  //获取关机时间
                    {
                        digitalPenAP.GetShutdownTimeExpose(item.Text);
                    }
                    break;
                case "GetHandwritingDistribution":  //获取笔迹分布时间
                    {
                        hdwrdist_set_ts_t p_ts = new hdwrdist_set_ts_t
                        {
                            is_get_all = true,
                            st_rtc = (uint)GetCurrentRtc(),
                            day = 9,
                        };
                        var list = new hdwrdist_list_unit_t[480];
                        for (int i = 0; i < 480; i++)
                        {
                            var ht = new hdwrdist_list_unit_t { hdwr_evt_cnt = 0, rtc = 0 };
                            list[i] = ht;
                        }
                        p_list.list_cnt = 0;
                        p_list.list = list;
                        digitalPenAP.GetCurrentHandwritingDistributionExpose(item.Text, ref p_ts, ref p_list);
                    }
                    break;
            }
        }

        private void FrmSetPenName_SpeedChangeClickEvent(string name,string penserial, string speedStr,string speedType,int interval= 0, int buzzcount = 0, int onoff = 0, int oncevalid = 0)
        {
            if (name== "SetPenName")
            {
                digitalPenAP.SetCurrentPenNameExpose(penserial, speedStr);

            }
            else if (name == "SetPenLed"|| name == "SetPenLedTemporary")
            {
                var ledstate = LED_STATE_E.BLUE_LIGHT_ON;

                var ledtype = LED_TYPE_E.BLE_CONNECT_LED;

                switch (speedStr)
                {
                    case "BLUE_LIGHT_ON":
                        ledstate=LED_STATE_E.BLUE_LIGHT_ON;break;
                    case "BLUE_LIGHT_FLASHING":
                        ledstate = LED_STATE_E.BLUE_LIGHT_FLASHING; break;
                    case "GREEN_LIGHT_ON":
                        ledstate = LED_STATE_E.GREEN_LIGHT_ON; break;
                    case "GREEN_LIGHT_FLASHING":
                        ledstate = LED_STATE_E.GREEN_LIGHT_FLASHING; break;
                    case "RED_LIGHT_ON":
                        ledstate = LED_STATE_E.RED_LIGHT_ON; break;
                    case "RED_LIGHT_FLASHING":
                        ledstate = LED_STATE_E.RED_LIGHT_FLASHING; break;
                    case "YELLOW_LIGHT_ON":
                        ledstate = LED_STATE_E.YELLOW_LIGHT_ON; break;
                    case "YELLOW_LIGHT_FLASHING":
                        ledstate = LED_STATE_E.YELLOW_LIGHT_FLASHING; break;
                    case "PINK_LIGHT_ON":
                        ledstate = LED_STATE_E.PINK_LIGHT_ON; break;
                    case "PINK_LIGHT_FLASHING":
                        ledstate = LED_STATE_E.PINK_LIGHT_FLASHING; break;
                    case "LIGHT_BLUE_LIGHT_ON":
                        ledstate = LED_STATE_E.LIGHT_BLUE_LIGHT_ON; break;
                    case "LIGHT_BLUE_LIGHT_FLASHING":
                        ledstate = LED_STATE_E.LIGHT_BLUE_LIGHT_FLASHING; break;
                    case "WHITE_LIGHT_ON":
                        ledstate = LED_STATE_E.WHITE_LIGHT_ON; break;
                    case "WHITE_LIGHT_FLASHING":
                        ledstate = LED_STATE_E.WHITE_LIGHT_FLASHING; break;
                }

                switch (speedType)
                {
                    case "POWER_ON_LED":
                        ledtype = LED_TYPE_E.POWER_ON_LED; break;
                    case "BLE_CONNECT_LED":
                        ledtype = LED_TYPE_E.BLE_CONNECT_LED; break;
                    case "LOW_POWER_WARNING_LED":
                        ledtype = LED_TYPE_E.LOW_POWER_WARNING_LED; break;
                    case "CHARGING_LED":
                        ledtype = LED_TYPE_E.CHARGING_LED; break;
                    case "STORAGE_FULL_LED":
                        ledtype = LED_TYPE_E.STORAGE_FULL_LED; break;
                }
                if (name == "SetPenLed")
                {
                    led_list_unit_s led_List_Unit_S = new led_list_unit_s
                    {
                        state = (byte)ledstate,
                        type = (byte)ledtype
                    };
                    digitalPenAP.SetCurrentPenLedExpose(penserial, ref led_List_Unit_S);
                }
                else
                {
                    led_tmp_state_s led_tmp_state = new led_tmp_state_s
                    {
                        type = (byte)ledtype,
                        state = (byte)ledstate,
                        is_enable = buzzcount==1?true:false,
                        is_contd = onoff == 1 ? true : false,
                        time_sec =(byte)interval,
                    };
                    digitalPenAP.SetCurrentPenLedTemporaryExpose(penserial, ref led_tmp_state);
                }
            }
            else if(name == "SetdownTime")
            {
                digitalPenAP.SetShutdownTimeExpose(penserial,(ushort)Convert.ToInt32(speedStr));
            }
            else if (name == "SetPenBuzzer")
            {
                tsdpen_buzzer_set_t tsdpen_Buzzer_Set_T = new tsdpen_buzzer_set_t
                {
                    onoff = (uint)onoff,
                    buzz_freq =(uint)Convert.ToInt32(speedStr),
                    buzz_time = (uint)Convert.ToInt32(speedType),
                    buzz_interval_ms = (uint)interval,
                    once_buzz_count =(uint)buzzcount,
                    once_valid =(uint)oncevalid
                };

                digitalPenAP.SetCurrentPenBuzzerExpose(penserial, ref tsdpen_Buzzer_Set_T);
            }
        }

        private  void digitalPenAP_PenDown(ulong time, string penSerial, int penType)
        {
            
            //if (AllPenDrawsDic.ContainsKey(penSerial) == true)
            //{
            //    AllPenDrawsDic[penSerial].OnPenDown(time, penSerial, penType);

                SR_Pen_coordinate sr = new SR_Pen_coordinate();
                sr.penSerial = penSerial;
                sr.cy = 0;
                sr.cx = 0;
                sr.time = time;
                sr.force = 0;
                sr.flag = 0;
                Penesult.Add(sr);
            //}

        }


        private WebSocketServer _server;
        private List<IWebSocketConnection> _allSockets;
        private bool _isRunning = false;
        public void socketGo() {
            _allSockets = new List<IWebSocketConnection>();
            _server = new WebSocketServer("ws://0.0.0.0:9000");

            _server.Start(socket =>
            {
                socket.OnOpen = () =>
                {

                    _allSockets.Add(socket);
                };

                socket.OnClose = () =>
                {
                    _allSockets.Remove(socket);
                };

                socket.OnMessage = message =>
                {
                    //socket.Send($"服务器收到：{message}"); 
                };
            });
        }


        private async void digitalPenAP_PenUp(ulong time, string penSerial, int penType)
        {
           //if (AllPenDrawsDic.ContainsKey(penSerial) == true)
           // {
           //     AllPenDrawsDic[penSerial].OnPenUp(time, penSerial, penType);

                SR_Pen_coordinate sr = new SR_Pen_coordinate();
                sr.penSerial = penSerial;
                sr.cy = 0;
                sr.cx = 0;
                sr.time = time;
                sr.force = 0;
                sr.flag = 2;
                Penesult.Add(sr);
            //}

        }
        private  void digitalPenAP_PenCoordinate(ulong time, string penSerial, int penType, string pageSerial, int cx, int cy, ushort force)
        {
            //if (AllPenDrawsDic.ContainsKey(penSerial) == true)
            //{
            //AllPenDrawsDic[penSerial].OnPenCoordinate(time, penSerial, penType, pageSerial, cx, cy, force);

            //}
            SR_Pen_coordinate sr = new SR_Pen_coordinate();
            sr.penSerial = penSerial;
            sr.pageSerial = pageSerial;
            //sr.cy = cy / (4600 / 400);
            //sr.cx = cx / (4600 / 400);
            sr.cy = cy;
            sr.cx = cx;
            sr.time = time;
            sr.force = force;
            sr.flag = 1;
            Penesult.Add(sr);
        }

        //蓝牙断开的原因事件的回调函数
        private static void digitalPenAP_PenBluetoothDisconnectionReason(string penSerial,ref tsdpen_rsp_bluetooth_disconnection_reason_t evt)
        {
            //Console.WriteLine("Pen_BluetoothDisconnectionReason:\t{0}\t{1}", penSerial, JsonConvert.SerializeObject(evt));
        }
        //设置笔名事件的回调函数
        private static void digitalPenAP_PenSetName(string penSerial, ref tsdpen_rsp_set_pen_name_t evt)
        {

            //MessageBox.Show(string.Format("Pen_SetName:\nPenSerial:\t{0}\nres:\t{1}", penSerial, evt.res));

        }
        //获取笔名事件的回调函数
        private static void digitalPenAP_PenGetName(string penSerial, ref tsdpen_rsp_get_pen_name_t evt)
        {
            var name = System.Text.Encoding.Default.GetString(evt.name, 0, evt.name.Length);
            //MessageBox.Show(string.Format("Pen_PenGetName:\nPenSerial:\t{0}\nres:\t{1}\nname:\t{2}", penSerial, evt.res, name));
        }
        //设置指示灯事件的回调函数
        private static void digitalPenAP_PenSetLed(string penSerial, ref tsdpen_rsp_set_pen_led_state_t evt)
        {
            //Console.WriteLine("Pen_PenSetLed:\t{0}\t{1}", penSerial, JsonConvert.SerializeObject(evt));
            //MessageBox.Show(string.Format("PenSetLed:\nPenSerial:\t{0}\nres:\t{1}", penSerial, evt.res));
        }
        //设置临时指示灯事件的回调函数
        private static void digitalPenAP_PenSetLedTemporary(string penSerial, ref tsdpen_rsp_set_pen_led_state_t evt)
        {

            //Console.WriteLine("Pen_PenSetLedTemporary:\t{0}\t{1}", penSerial, JsonConvert.SerializeObject(evt));
            //MessageBox.Show(string.Format("Pen_PenSetLedTemporary:\nPenSerial:\t{0}\nres:\t{1}", penSerial, evt.res));
        }
        //获取指示灯信息事件的回调函数
        private static void digitalPenAP_PenGetLed(string penSerial, ref tsdpen_rsp_get_pen_led_state_t evt)
        {
            //Console.WriteLine("Pen_GetLed:\t{0}\t{1}", penSerial, JsonConvert.SerializeObject(evt));
            //MessageBox.Show(string.Format("Pen_GetLed:\nPenSerial:\t{0}\nres:\t{1}\n{2}", penSerial, evt.res, JsonConvert.SerializeObject(evt.details)));
        }
        //设置定时关机时间事件的回调函数
        private static void digitalPenAP_PenSetShutDownTime(string penSerial, ref tsdpen_rsp_set_timeout_val_t evt)
        {
            //Console.WriteLine("Pen_SetShutDownTime:\t{0}\t{1}", penSerial, JsonConvert.SerializeObject(evt));
            //MessageBox.Show(string.Format("Pen_SetShutDownTime:\nPenSerial:\t{0}\nres:\t{1}", penSerial, evt.res));
        }
        //设置蜂鸣器事件的回调函数
        private static void digitalPenAP_PenSetBuzzer(string penSerial, ref tsdpen_rsp_set_buzzer_t evt)
        {
            //MessageBox.Show(string.Format("Pen_SetBuzzer:\nPenSerial:\t{0}\nres:\t{1}", penSerial, evt.res));
        }
        //获取定时关机时间事件的回调函数
        private static void digitalPenAP_PenGetShutDown(string penSerial, ref tsdpen_rsp_get_timeout_val_t evt)
        {
            //MessageBox.Show(string.Format("Pen_GetShutDown:\nPenSerial:\t{0}\nres:\t{1}\ntime:\t{2}", penSerial, evt.res, evt.ttv));
        }
        //获取笔迹分布时间的回调函数
        private static void digitalPenAP_PenGetHandwriting(string penSerial, ref tsdpen_rsp_get_pen_hdwrdist_t evt)
        {
            //MessageBox.Show(string.Format("Pen_GetHandwriting:\nPenSerial:\t{0}\nres:\t{1}\np_list:\t{2}", penSerial, evt.res, JsonConvert.SerializeObject(evt.p_list) ));
        }
        //电量上报事件
        private static void digitalPenAP_ReceivePenBatteryChanged(string penSerial, ref tsdpen_battery_changed_t evt)
        {

            var set = JsonConvert.SerializeObject(evt);
            try
            {
                SaveDataOperater.UpdatePenCharge(penSerial, evt.charge);
            }
            catch { 
            
            }
   
            //Console.WriteLine("Pen_BatteryChanged:\t{0}\t{1}", penSerial, JsonConvert.SerializeObject(evt));
        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            digitalPenAP.Stop();
        }
  
        private static ulong GetCurrentRtc()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToUInt64(ts.TotalSeconds * 1000);
        }

        private void flowLayoutPanel1_Paint(object sender, PaintEventArgs e)
        {

        }

        /// <summary>
        /// 点阵笔上报电量
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void timer1_Tick(object sender, EventArgs e)
        {

            List<PenStatus> lt = SaveDataOperater.GetAllPenStatus();
            var jsonContent = System.Text.Json.JsonSerializer.Serialize(lt);
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    var content = new StringContent(jsonContent, Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.PostAsync(WindowsFormsApp.Form1.apiUrl + "/sdk/v1/dotmatrix/pen/report", content);
                    response.EnsureSuccessStatusCode();
                    ServerResult sr = JsonConvert.DeserializeObject<ServerResult>(await response.Content.ReadAsStringAsync());
                }
            }
            catch
            {
            }
        }
        /// <summary>
        /// 获取用户列表数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void timer2_Tick(object sender, EventArgs e)
        {
            GetDataToServer();
        }


        private async void GetDataToServer()
        {
            try
            {
                //拉取用户ID
                using (HttpClient client = new HttpClient())
                {
                    var content = new StringContent("", Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.GetAsync(WindowsFormsApp.Form1.apiUrl + "/sdk/v1/class/student/pens?classId=" + ClassID);
                    response.EnsureSuccessStatusCode();
                    ServerResult sr = JsonConvert.DeserializeObject<ServerResult>(await response.Content.ReadAsStringAsync());
                    if (sr.success)
                    {
                        List<StudentPen> lt = JsonConvert.DeserializeObject<List<StudentPen>>(sr.data.ToString());
                        SaveDataOperater.DeleteStudentInfo();
                        if (lt.Count > 0)
                            SaveDataOperater.AddStudentInfo(lt);
                    }
                }

                //拉取模板数据
                using (HttpClient client = new HttpClient())
                {
                    var content = new StringContent("", Encoding.UTF8, "application/json");
                    HttpResponseMessage response = await client.GetAsync(WindowsFormsApp.Form1.apiUrl + "/sdk/v1/dotmatrix/page/sync");
                    response.EnsureSuccessStatusCode();

                    ServerResult sr = JsonConvert.DeserializeObject<ServerResult>(await response.Content.ReadAsStringAsync());
                    if (sr.success)
                    {
                        List<TempListiInfoServer> lt = System.Text.Json.JsonSerializer.Deserialize<List<TempListiInfoServer>>(sr.data.ToString());
                        SaveDataOperater.DeleteTempListiInfo();
                        SaveDataOperater.AddTempListiInfo(lt);
                    }
                }
            }
            catch
            {

            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            GetDataToServer();
        }
    }
}


