using cn.edu.suda.sumcu.iot.data;
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;

namespace cn.edu.suda.sumcu.iot.form
{
    public partial class FrmDeviceConfig : Form
    {
        private FrmMain frmMain;            //存储主窗体句柄
        //“配置终端UE”的界面显示
        private TextBox[] dTextbox;         //文本框
        private Label[] dLabel;             //标签
        private Panel[] dPanel;             //将文本框和标签统一起来
        private FrameData frameDeviceAll = new FrameData();   //存储命令“A0、B0”对应的数据格式
        private FrameData frameDeviceBase = new FrameData();  //存储命令“A1、B1”对应的数据格式
        private FrameData frameDeviceServer = new FrameData();//存储命令“A2、B2”对应的数据格式
        private FrameData frameDeviceUser = new FrameData();  //存储命令“A3、B3”对应的数据格式
        ///-----------------------------------------------------------------
        /// <summary>                                                       
        /// 函 数 名:FrmDeviceConfig                           
        /// 功    能:不带参数的构造函数                                                                
        /// </summary>                                                      
        ///-----------------------------------------------------------------
        public FrmDeviceConfig()
        {
            InitializeComponent();
        }
        ///-----------------------------------------------------------------
        /// <summary>                                                       
        /// 函 数 名:FrmDeviceConfig                           
        /// 功    能:带参数的构造函数                                                                
        /// </summary>                                                      
        ///-----------------------------------------------------------------
        public FrmDeviceConfig(FrmMain frmMain): this()
        {
            this.frmMain = frmMain;
            //初始化不同命令数据格式的内容
            //“A0、B0”
            frameDeviceAll.addParameter("uint_8[2]", "cmd", "命令内容", "write");
            frameDeviceAll.addParameter("uint_8[30]", "equipName", "产品名称", "write");
            frameDeviceAll.addParameter("uint_8[20]", "equipID", "产品序列号", "write");
            frameDeviceAll.addParameter("uint_8[20]", "equipType", "产品型号", "write");
            frameDeviceAll.addParameter("uint_8[30]", "vendor", "生产厂家", "write");
            frameDeviceAll.addParameter("uint_8[4]", "softVer", "软件版本", "write");
            frameDeviceAll.addParameter("uint_64", "productTime", "生产时间", "write");
            frameDeviceAll.addParameter("uint_8[20]", "userName", "用户名", "write");
            frameDeviceAll.addParameter("uint_8[11]", "phone", "手机号", "write");
            frameDeviceAll.addParameter("uint_8[15]", "serverIP", "服务器IP", "write");
            frameDeviceAll.addParameter("uint_8[5]", "serverPort", "端口号", "write");
            frameDeviceAll.addParameter("uint_32", "sendFrequencySec", "发送频率（秒）", "write");
            frameDeviceAll.addParameter("uint_32", "resetCount", "复位次数", "write");
            frameDeviceAll.addParameter("byte[2]", "frameCmd", "帧格式命令", "write");
            //“A1、B1”
            frameDeviceBase.addParameter("uint_8[2]", "cmd", "命令内容", "write");
            frameDeviceBase.addParameter("uint_8[30]", "equipName", "产品名称", "write");
            frameDeviceBase.addParameter("uint_8[20]", "equipID", "产品序列号", "write");
            frameDeviceBase.addParameter("uint_8[20]", "equipType", "产品型号", "write");
            frameDeviceBase.addParameter("uint_8[30]", "vendor", "生产厂家", "write");
            frameDeviceBase.addParameter("uint_8[4]", "softVer", "软件版本", "write");
            frameDeviceBase.addParameter("uint_64", "productTime", "生产时间", "write");
            frameDeviceBase.addParameter("uint_8[20]", "userName", "用户名", "write");
            frameDeviceBase.addParameter("uint_8[11]", "phone", "手机号", "write");
            //“A2、B2”
            frameDeviceServer.addParameter("uint_8[2]", "cmd", "命令内容", "write");
            frameDeviceServer.addParameter("uint_8[15]", "serverIP", "服务器IP", "write");
            frameDeviceServer.addParameter("uint_8[5]", "serverPort", "端口号", "write");
            //“A3、B3”
            frameDeviceUser.addParameter("uint_8[2]", "cmd", "命令内容", "write");
            frameDeviceUser.addParameter("uint_32", "sendFrequencySec", "发送频率（秒）", "write");
            frameDeviceUser.addParameter("uint_32", "resetCount", "复位次数", "write");
        }

        ///-----------------------------------------------------------------
        /// <summary>                                                       
        /// 函 数 名:DeviceConfig_Load:配置终端界面加载函数                              
        /// 功    能:完成配置终端界面的初始化工作                                                                  
        /// </summary>                                                      
        ///-----------------------------------------------------------------
        private void DeviceConfig_Load(object sender, EventArgs e)
        {
            //注册数据接收事件
            this.frmMain.frmRealtimeData.DeviceDataEvent += new FrmRealtimeData.DeviceData(deviceDataRecv);
            //设置下拉框默认显示的信息
            this.cBox_command.SelectedIndex = 0;
            this.cBox_IMSI.SelectedIndex = 0;
        }
        ///-----------------------------------------------------------------
        /// <summary>                                                       
        /// 函数名称：deviceDataRecv                                       
        /// 输入参数：imsi：接收到的终端imsi号；data：接收到的数据；                       
        /// 功  能：（1）读出数据并根据命令字解析出来显示
        ///         （2）将数据写入数据库
        /// 返  回：无
        /// </summary>                                                                                       
        ///-----------------------------------------------------------------
        private void deviceDataRecv(string imsi, byte[] data)
        {
            btn_confirmCommand.Enabled = true;      //使能确认命令按钮
            if (!cBox_IMSI.Items.Contains(imsi))    //若下拉表中无此imsi则添加
            {
                cBox_IMSI.Items.Add(imsi);
            }
            //若接收到的是选中的imsi
            if(cBox_IMSI.SelectedItem.ToString()=="all"||cBox_IMSI.SelectedItem.ToString()==imsi)
            {
                //this.frmMain.sQLDevice.insert();
                if (data[0] == 'A' && data[1] == '0')        //若为读取所有信息命令
                {
                    frameDeviceAll.byteToStruct(data);
                    for(int i=0;i<dTextbox.Length;i++)
                    {
                        dTextbox[i].Text = frameDeviceAll.Parameter[i].value;
                    }
                }
                else if (data[0] == 'A' && data[1] == '1')   //若为读取产品信息命令
                {
                    frameDeviceBase.byteToStruct(data);
                    for (int i = 0; i < dTextbox.Length; i++)
                    {
                        dTextbox[i].Text = frameDeviceBase.Parameter[i].value;
                    }
                }
                else if (data[0] == 'A' && data[1] == '2')   //若为读取服务器信息命令
                {
                    frameDeviceServer.byteToStruct(data);
                    for (int i = 0; i < dTextbox.Length; i++)
                    {
                        dTextbox[i].Text = frameDeviceServer.Parameter[i].value;
                    }
                }
                else if (data[0] == 'A' && data[1] == '3')   //若为读取用户信息命令
                {
                    frameDeviceUser.byteToStruct(data);
                    for (int i = 0; i < dTextbox.Length; i++)
                    {
                        dTextbox[i].Text = frameDeviceUser.Parameter[i].value;
                    }
                }
                else if (data[0] == 'B' && data[1] == '0')    //若为更改所有信息命令
                {
                    string s = Encoding.Default.GetString(data, 2, data.Length - 2);
                    if (s == "success")
                        this.frmMain.SetToolStripConnectStatusText("更改所有配置数据成功");
                }
                else if (data[0] == 'B' && data[1] == '1')    //若为更改产品信息命令
                {
                    string s = Encoding.Default.GetString(data, 2, data.Length - 2);
                    if (s == "success")
                        this.frmMain.SetToolStripConnectStatusText("更改产品信息成功");
                }
                else if (data[0] == 'B' && data[1] == '2')    //若为更改服务器信息命令
                {
                    string s = Encoding.Default.GetString(data, 2, data.Length - 2);
                    if (s == "success")
                        this.frmMain.SetToolStripConnectStatusText("更改服务器信息成功");
                }
                else if (data[0] == 'B' && data[1] == '3')    //若为更改用户信息命令
                {
                    string s = Encoding.Default.GetString(data, 2, data.Length - 2);
                    if (s == "success")
                        this.frmMain.SetToolStripConnectStatusText("更改用户数据成功");
                }
            }
        }

        ///-----------------------------------------------------------------
        /// <summary>                                                       
        /// 对    象:btn_confirmCommand_Click(“确认命令”按钮）                                           
        /// 事    件:Click(单击)                                                  
        /// 功    能:根据命令字，决定要回发到终端UE的数据内容
        /// </summary>                                                      
        /// <param name="sender"></param>                                   
        /// <param name="e"></param>                                        
        ///-----------------------------------------------------------------
        private void btn_confirmCommand_Click(object sender, EventArgs e)
        {
            byte[] sendData = null;
            string cmd = dTextbox[0].Text;      //保存命令信息
            switch (cmd)
            {
                case "A0":                     //若为读取命令
                case "A1":
                case "A2":
                case "A3":
                    sendData = Encoding.Default.GetBytes(cmd); break;
                case "B0":                    //若为更改所有信息命令
                    for (int i = 0; i < dTextbox.Length; i++)
                    {
                        frameDeviceAll.Parameter[i].value = dTextbox[i].Text;
                    }
                    sendData = frameDeviceAll.structToByte(); break;
                case "B1":                    //若为更改产品信息命令
                    for (int i = 0; i < dTextbox.Length; i++)
                    {
                        frameDeviceBase.Parameter[i].value = dTextbox[i].Text;
                    }
                    sendData = frameDeviceBase.structToByte(); break;
                case "B2":                    //若为更改服务器信息命令
                    for (int i = 0; i < dTextbox.Length; i++)
                    {
                        frameDeviceServer.Parameter[i].value = dTextbox[i].Text;
                    }
                    sendData = frameDeviceServer.structToByte(); break;
                case "B3":                    //若为更改用户信息命令
                    for (int i = 0; i < dTextbox.Length; i++)
                    {
                        frameDeviceUser.Parameter[i].value = dTextbox[i].Text;
                    }
                    sendData = frameDeviceUser.structToByte(); break;
            }
            //向终端回发配置信息
            if (cBox_IMSI.SelectedItem.ToString() == "all")
            {
                for (int i = 1; i < cBox_IMSI.Items.Count; i++)
                {
                    if (this.frmMain.frmRealtimeData.com.Send(cBox_IMSI.Items[i].ToString(), sendData) != 0)
                    {
                        this.frmMain.SetToolStripConnectStatusText("数据发送失败");
                    }
                }
            }
            else
            {
                if (this.frmMain.frmRealtimeData.com.Send(cBox_IMSI.SelectedItem.ToString(), sendData) != 0)
                {
                    this.frmMain.SetToolStripConnectStatusText("数据发送失败");
                }
            }

        }

        ///-----------------------------------------------------------------
        /// <summary>                                                       
        /// 对    象:cBox_command_SelectedIndexChanged                                      
        /// 事    件:选择下拉列表的命令之后触发                                                  
        /// 功    能:根据命令字，决定要显示的界面
        /// </summary>                                                      
        /// <param name="sender"></param>                                   
        /// <param name="e"></param>                                        
        ///-----------------------------------------------------------------
        private void cBox_command_SelectedIndexChanged(object sender, EventArgs e)
        {
            fPanel_deviceConfig.Controls.Clear();
            switch (cBox_command.SelectedIndex)
            {
                case 0:
                case 4:
                    createLabel(frameDeviceAll);      //若需要显示所有信息
                    break;
                case 1:
                case 5:
                    createLabel(frameDeviceBase);     //若需要显示产品信息
                    break;
                case 2:
                case 6:
                    createLabel(frameDeviceServer);   //若需要显示服务器信息
                    break;
                case 3:
                case 7:
                    createLabel(frameDeviceUser);     //若需要显示用户信息
                    break;
            }
            dTextbox[0].Text = cBox_command.SelectedItem.ToString().Substring(0, 2);

        }

        ///以下为内部函数
        ///-----------------------------------------------------------------
        /// <summary>                                                       
        /// 函数名称：createLabel                                     
        /// 传入参数：frame：包含需要创建的控件的参数                                                 
        /// 函数返回：无      
        /// 函数功能：根据MainForm.g_frmStruct动态创建实时数据文本框和历史数据文本框
        /// </summary>                                                                                          
        ///-----------------------------------------------------------------
        private void createLabel(FrameData frame)
        {
            int i;
            if (frame.Parameter.Count() > 0)
            {
                //重新定义标签与文本框
                dTextbox = new TextBox[frame.Parameter.Count()];
                dLabel = new Label[frame.Parameter.Count()];
                dPanel = new Panel[frame.Parameter.Count()];
                //tabControl1.TabPages[0].BackColor = Color.AliceBlue;
                //设置底色
                fPanel_deviceConfig.BackColor = Color.AliceBlue;
                //创建标签和文本框，并设置属性和内容
                for (i = 0; i < frame.Parameter.Count(); i++)
                {
                    try
                    {
                        dPanel[i] = new Panel();
                        dPanel[i].Width = 450;
                        dPanel[i].Height = 30;
                        dLabel[i] = new Label();
                        dLabel[i].Width = 120;
                        dLabel[i].Height = 30;
                        dLabel[i].Font = new System.Drawing.Font
                            ("宋体", 10.8F, FontStyle.Bold);
                        dLabel[i].TextAlign =
                            ContentAlignment.MiddleRight;
                        dLabel[i].Text =
                            frame.Parameter[i].otherName;

                        dTextbox[i] = new TextBox();
                        dTextbox[i].Width = 300;
                        dTextbox[i].Height = 30;
                        dTextbox[i].Font = new System.Drawing.Font
                            ("宋体", 10.8F, FontStyle.Bold);
                        dTextbox[i].Left = dPanel[i].Left + 120;
                        dTextbox[i].ForeColor = Color.White;

                        //设置不同数据类型的文本框颜色不同
                        switch (frame.Parameter[i].type)
                        {
                            case "byte":
                            case "int_8":
                            case "sbyte":
                            case "uint_8":
                                dTextbox[i].BackColor = Color.Red; break;
                            case "short":
                            case "int_16":
                            case "ushort":
                            case "uint_16":
                                dTextbox[i].BackColor = Color.Orange; break;
                            case "int":
                            case "int_32":
                            case "uint":
                            case "uint_32":
                                dTextbox[i].BackColor = Color.Yellow;
                                dTextbox[i].ForeColor = Color.Black; break;
                            case "long":
                            case "int_64":
                            case "ulong":
                            case "uint_64":
                                dTextbox[i].BackColor = Color.Green; break;
                            case "float":
                                dTextbox[i].BackColor = Color.Cyan; break;
                            case "double":
                                dTextbox[i].BackColor = Color.DarkBlue; break;
                            default:
                                if (frame.Parameter[i].type.Contains("byte[") || frame.Parameter[i].type.Contains("uint_8["))
                                {
                                    dTextbox[i].BackColor = Color.MediumPurple; break;
                                }
                                else
                                {
                                    break;
                                }
                        }
                        if (frame.Parameter[i].wr == "read")
                        {
                            dTextbox[i].BackColor = Color.LightGray;
                            dTextbox[i].Enabled = false;
                        }
                        //设置文本框和标签框等依附的控件
                        dTextbox[i].Parent = dPanel[i];
                        dLabel[i].Parent = dPanel[i];
                        dPanel[i].Parent = fPanel_deviceConfig;
                        //this.Refresh();
                        //this.Show();
                        //dPanel[i].Show();
                    }
                    catch
                    {
                        MessageBox.Show("自动生成文本框和标签框失败！");
                    }
                }
            }
        }

    }



}
