using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace MES.Utility.Network.S7netplus.ORM
{
    public class S7Write<T> where T : class, new()
    {
        private S7Client opcClient;
        private T entity;
        private Dictionary<string, PropertyInfo> dict;
        private Dictionary<string, int> strLengthDict;

        /// <summary>
        /// 构造方法，传入参数
        /// </summary>
        /// <param name="opcClient"></param>
        /// <param name="entity"></param>
        public S7Write(S7Client opcClient, T entity)
        {
            this.opcClient = opcClient;
            this.entity = entity;
            //默认取出所有的只写或者可读可写的属性
            GetAllKeyList(out dict, out strLengthDict);
        }


        /// <summary>
        /// 获得所有具有可写属性的数据
        /// </summary>
        /// <returns></returns>
        private void GetAllKeyList(out Dictionary<string, PropertyInfo> dict, out Dictionary<string, int> strLengthDict)
        {
            dict = new Dictionary<string, PropertyInfo>();
            strLengthDict = new Dictionary<string, int>();


            //获取entity对象的所有属性
            PropertyInfo[] properties = typeof(T).GetProperties();
            //得到所有添加注解的属性
            foreach (PropertyInfo info in properties)
            {
                //判断是否具有HttpController属性
                object[] attr = info.GetCustomAttributes(false);
                if (attr.Length == 0)
                {
                    continue;
                }
                //从注解数组中取第一个注解(一个属性可以包含多个注解)
                S7PLCAttribute myattr = attr[0] as S7PLCAttribute;
                if (myattr == null)
                    continue;
                if (myattr.Type == S7NodeType.ReadAndWrite || myattr.Type == S7NodeType.WriteOnly)
                {
                    dict.Add(myattr.Address, info);
                    strLengthDict.Add(myattr.Address, myattr.StrLength);
                }
            }
        }

        /// <summary>
        ///  执行写入数据，将对象中的数据写入到OPC服务中
        /// </summary>
        /// <param name="message">返回写入过程中出现的错误信息</param>
        /// <returns></returns>
        public bool Execute()
        {
            if (dict.Count == 0)
            {
                return false;
            }
            if (!opcClient.IsConnected)
                return false;
            //循环写入
            try
            {
                bool flag;
                foreach (KeyValuePair<string, PropertyInfo> keyValue in dict)
                {
                    //判断当前keyValue是什么类型
                    if (keyValue.Value.PropertyType == typeof(ushort))
                    {
                        flag = opcClient.Plc.WriteInt16(keyValue.Key, (ushort)keyValue.Value.GetValue(entity));
                        if (!flag)
                        {
                            return false;
                        }
                    }
                    else if (keyValue.Value.PropertyType == typeof(int))
                    {
                        flag = opcClient.Plc.WriteInt32(keyValue.Key, (int)keyValue.Value.GetValue(entity));
                        if (!flag)
                        {
                            return false;
                        }
                    }
                    else if (keyValue.Value.PropertyType == typeof(float))
                    {
                        flag = opcClient.Plc.WriteSingle(keyValue.Key, (float)keyValue.Value.GetValue(entity));
                        if (!flag)
                        {
                            return false;
                        }
                    }
                    else if (keyValue.Value.PropertyType == typeof(string))
                    {
                        flag = opcClient.Plc.WriteString(keyValue.Key, (string)keyValue.Value.GetValue(entity), strLengthDict[keyValue.Key]);
                        if (!flag)
                        {
                            return false;
                        }
                    }

                }
                return true;
            }
            catch
            {
                return false;
            }

        }


        /// <summary>
        /// 传入Lambda表达式，指定写入的数据
        /// </summary>
        /// <param name="columns"></param>
        /// <returns></returns>
        public S7Write<T> WriteField(Expression<Func<T, object>> columns)
        {
            Dictionary<string, PropertyInfo> dict = new Dictionary<string, PropertyInfo>();
            Dictionary<string, int> strLengthDict = new Dictionary<string, int>();


            string lambda = columns.Body.ToString();
            int index1 = lambda.IndexOf('(');
            int index2 = lambda.IndexOf(')');
            string str = lambda.Substring(index1 + 1, index2 - index1 - 1);
            List<string> keyList = str.Split(',').Select(it => it.Split('=')[0].Trim()).ToList();

            //获取entity对象的所有属性
            PropertyInfo[] properties = typeof(T).GetProperties();
            //得到所有添加注解的属性
            foreach (PropertyInfo info in properties)
            {
                //判断是否具有HttpController属性
                Object[] attr = info.GetCustomAttributes(false);
                if (attr.Length == 0)
                {
                    continue;
                }
                //从注解数组中取第一个注解(一个属性可以包含多个注解)
                S7PLCAttribute myattr = attr[0] as S7PLCAttribute;
                if (myattr == null)
                    continue;
                if (myattr.Type == S7NodeType.ReadAndWrite || myattr.Type == S7NodeType.WriteOnly)
                {
                    string name = info.Name;
                    if (keyList.Contains(name))
                    {
                        dict.Add(myattr.Address, info);
                        strLengthDict.Add(myattr.Address, myattr.StrLength);
                    }
                }
            }
            this.dict = dict;
            this.strLengthDict = strLengthDict;
            return this;
        }
    }
}
