using Opc.Ua;
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 Treasure.DataModel;
using Treasure.通讯协议;

namespace SampleOPCUAClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        List<ItemBase> itemBases = new List<ItemBase>();

        private void button1_Click(object sender, EventArgs e)
        {
            //连接OPC
            pro_OPCUAp = new Pro_OPCUA(textBox1.Text);
            isRunning = true;
            MessageBox.Show("连接完成");
        }
        Pro_OPCUA pro_OPCUAp;
        private void Form1_Load(object sender, EventArgs e)
        {
            itemBases = SystemConfigLoad<List<ItemBase>>("48.json");
        }

        /// <summary>
        /// 配置读取
        /// </summary>
        /// <param name="filename"></param>
        /// <returns></returns>
        public static T SystemConfigLoad<T>(string filename = "System.json")
        {
            try
            {
                using (var sr = new System.IO.StreamReader(System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, filename)))
                {
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(sr.ReadToEnd());
                }
            }
            catch (Exception ex)
            {
                return default(T);
            }
        }
        bool isRunning = false;
        private void button2_Click(object sender, EventArgs e)
        {
            if (pro_OPCUAp==null)
            {
                MessageBox.Show("请先建立连接");
                return;
            }
            //启动采集
            Task.Factory.StartNew(() =>
            {
                try
                {
                    //当设备启用时，进行数据采集
                    while (isRunning)
                    {
                        try
                        {
                            pro_OPCUAp.ReadItems(itemBases);

                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                            continue;
                        }
                    }
                }
                catch (Exception ex)
                {
                   Console.WriteLine(ex.ToString());
                }
            });
        }
        /// <summary>
        /// 订阅
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            //启动采集
            Task.Factory.StartNew(() =>
            {
                try
                {
                    //当设备启用时，进行数据采集
                        try
                        {
                            pro_OPCUAp.subscription(itemBases);

                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                        }
                    
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            });
        }
        /// <summary>
        /// 结构体
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            //启动采集
            Task.Factory.StartNew(() =>
            {
                List<string> items = new List<string>() { "ns=4;s=StationStatus1"};
                while (isRunning)
                {
                    for (int i = 0; i < items.Count; i++)
                    {
                        try
                        {
                            pro_OPCUAp.structItem(items[i]);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                            continue;
                        }
                    }
                    System.Threading.Thread.Sleep(2000);
                }
            });
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            isRunning = false;
        }

        private void button5_Click(object sender, EventArgs e)
        {
            if (pro_OPCUAp == null)
            {
                MessageBox.Show("请先建立连接");
                return;
            }
            //启动采集
            Task.Factory.StartNew(() =>
            {
                try
                {
                    //当设备启用时，进行数据采集
                    while (isRunning)
                    {
                        try
                        {
                            pro_OPCUAp.readAndWrite();
                            System.Threading.Thread.Sleep(2000);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.ToString());
                            System.Threading.Thread.Sleep(2000);
                            continue;
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            });
        }

        private void button6_Click(object sender, EventArgs e)
        {
            ExtensionObject[] AA = new ExtensionObject[3];
            WriteVar structs = new WriteVar
            {
                index = 0,
                Name = "AA",
                DataType = 0,
                StringValue = "",
                IntValue = 25,
                FloatValue = 0.0F
            };
            var result = pro_OPCUAp.GetValueByteFromObj(structs);
            AA[0] = result;

            WriteVar structs1 = new WriteVar
            {
                index = 0,
                Name = "BBB",
                DataType = 1,
                StringValue = "",
                IntValue = 0,
                FloatValue = 1.22F
            };
            var result1 = pro_OPCUAp.GetValueByteFromObj(structs1);
            AA[1] = result1;


            WriteVar structs2 = new WriteVar
            {
                index = 0,
                Name = "C",
                DataType = 2,
                StringValue = "WUXE",
                IntValue = 0,
                FloatValue = 0.0F
            };
            var result2= pro_OPCUAp.GetValueByteFromObj(structs2);
            AA[2] = result2;
            //byte[] re = new byte[23] { 3,0,0,0,56,56,56,0,0,0,0,0,0,0,0,128,0,0,0,0,0,0,0};
            for (int i = 0; i < AA.Length; i++)
            {
                AA[i] = new ExtensionObject { Body = getNewByte() };
            }
            pro_OPCUAp.WriteVarStruct(AA);
        }

        public byte[] getNewByte()
        {
            byte[] item = new byte[20];
            for (int i = 0; i < item.Length; i++)
            {
                item[i] = 0;
            }
            return item;
        }
    }
}
