using System.Reflection;
using JiShe.CollectBus.Common.BuildSendDatas;

namespace JiShe.CollectBus.Protocol.T1882018.SendData
{
    /// <summary>
    /// 构建188-2018下发报文
    /// </summary>
    public static class Telemetry1882018PacketBuilder
    {
        /// <summary>
        /// 构建报文的委托
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public delegate Telemetry1882018PacketResponse T1882018Delegate(Telemetry1882018PacketRequest request);

        /// <summary>
        /// 编码与方法的映射表
        /// </summary>
        public static readonly Dictionary<string, T1882018Delegate> T1882018ControlHandlers = new();

        static Telemetry1882018PacketBuilder()
        {
            // 初始化时自动注册所有符合命名规则的方法
            var methods = typeof(Telemetry1882018PacketBuilder).GetMethods(BindingFlags.Static | BindingFlags.Public);
            foreach (var method in methods)
            {
                if (method.Name.StartsWith("CTR") && method.Name.EndsWith("_Send"))
                {
                    string code = method.Name;
                    var delegateInstance = (T1882018Delegate)Delegate.CreateDelegate(typeof(T1882018Delegate), method);
                    T1882018ControlHandlers[code] = delegateInstance;
                }
            }
        }

        #region 读数据

        /// <summary>
        /// 读取计量数据
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static Telemetry1882018PacketResponse CTR_01_Send(Telemetry1882018PacketRequest request)
        {
            var itemCodeArr = request.ItemCode.Split('_');
            var c_data = itemCodeArr[0];//01
            var d_data = itemCodeArr[1];//91 或者 90
            var dataUnit = new List<string>() { "1F", d_data, "00" };
            var dataList = Build188SendData.Build188SendCommand(request.MeterAddress, c_data, dataUnit);

            return new Telemetry1882018PacketResponse() { Data = dataList };
        }
        #endregion

        #region 写数据
        /// <summary>
        /// 阀控
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public static Telemetry1882018PacketResponse CTR_04_Send(Telemetry1882018PacketRequest request)
        {
            var itemCodeArr = request.ItemCode.Split('_');
            var c_data = itemCodeArr[0];//01
            var d_data = itemCodeArr[1];//55 或者 99
            var dataUnit = new List<string>() { "A0", "17", "00", d_data };
            var dataList = Build188SendData.Build188SendCommand(request.MeterAddress, c_data, dataUnit);

            return new Telemetry1882018PacketResponse() { Data = dataList };
        }
        #endregion
    }
}
