using System.Text;

namespace Khd.Core.Plc
{
    /// <summary>
    /// Plc帮助类
    /// </summary>
    public static class StaticPlcHelper
    {
        /// <summary>
        /// 进行高低位转换后，写入Plc地址
        /// </summary>
        /// <param name="plc"> plc </param>
        /// <param name="address"> 写入地址 </param>
        /// <param name="valueString"> 值 </param>
        /// <param name="len"> 长度 </param>
        public static void WriteToPoint(this Plc.S7.Plc plc, string address, object? valueString, string? len)
        {
            if (len == null)
            {
                throw new ArgumentException("StaticPlcHelper Ex len is null");
            }
            if (valueString == null)
            {
                throw new ArgumentException("StaticPlcHelper Ex valueString is null");
            }
            plc.Write(address, GetValue(len, valueString));
        }

        /// <summary>
        /// 写入RFID
        /// </summary>
        /// <param name="plc"> plc </param>
        /// <param name="address"> 读取地址 </param>
        /// <param name="len"> 长度 </param>
        /// <returns> 读取到的RFID </returns>
        public static void WriteRFID(this Plc.S7.Plc plc, string address, string value,int len = 15)
        {
            string[] adds = address.Split(".");
            int db = int.Parse(adds[0].Replace("DB", ""));
            int startByteAdr = int.Parse(adds[1].Replace("DBX", ""));

            // 将 value 转换为字节数组，确保其长度符合要求
            byte[] byteArray = Encoding.ASCII.GetBytes(value);
            if (byteArray.Length > len)
            {
                throw new ArgumentException($"Value length exceeds the specified length of {len} bytes.");
            }

            // 填充字节数组到指定长度
            byte[] dataToWrite = new byte[len];
            Array.Copy(byteArray, dataToWrite, byteArray.Length);



            plc.Write(S7.DataType.DataBlock, db, startByteAdr, dataToWrite);
          
        }



        /// <summary>
        /// 读取RFID
        /// </summary>
        /// <param name="plc"> plc </param>
        /// <param name="address"> 读取地址 </param>
        /// <param name="len"> 长度 </param>
        /// <returns> 读取到的RFID </returns>
        public static string? ReadRFID(this Plc.S7.Plc plc, string address, int len = 36)
        {
            string[] adds = address.Split(".");
            int db = int.Parse(adds[0].Replace("DB", ""));
            int startByteAdr = int.Parse(adds[1].Replace("DBX", ""));
            var result = (byte[]?)plc.Read(S7.DataType.DataBlock, db, startByteAdr, S7.VarType.Byte, len);
            if (result == null)
            {
                return null;
            }
            string res = Encoding.UTF8.GetString(result).Replace("\0", "").Replace("$", "").Replace("\\u", "").Trim();

            if (res.Contains("JYHB"))
            {
                return res[res.IndexOf('J')..].Substring(0, 12);
            }
            else if (res.Contains('C'))
            {
                return res[res.IndexOf('C')..];
            }
            else
            {
                return "";
            }
        }


        /// <summary>
        /// 电气写入点位高低位转换
        /// </summary>
        /// <param name="len">点位地址位长度</param>
        /// <param name="value">写入数值</param>
        /// <returns></returns>
        public static object GetValue(string? len, object value)
        {
            if (len == "2")
            {
                return Convert.ToInt16(value);
            }
            if (len == "4")
            {
                return Convert.ToInt32(value);
            }
            if (len == "6")
            {
                return Convert.ToByte(value);
            }
            if (len == "8")
            {
                return Convert.ToString(value);
            }
            if (len == "10")
            {
                return Convert.ToBoolean(value);
            }
            if (len == "12")
            {
                return Convert.ToSingle(value);
            }
            throw new ArgumentException("StaticPlcHelper Ex len is not support");
        }
    }
}
