using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using static JiShe.CollectBus.Common.Consts.T37612012PacketItemCodeConst;

namespace JiShe.CollectBus.Common.Helpers
{
    public static class DataFieldHelper
    {
        public static string GetDataField(string dataField)
        {
            if (string.IsNullOrWhiteSpace(dataField))
            {
                return string.Empty;
            }

            if (dataField.Contains("."))
            {
                return dataField.Split('.')[0];
            }

            return dataField;
        }

        /// <summary>
        /// 数据字段映射
        /// </summary>
        public static Dictionary<string, string> DataFieldDic = new Dictionary<string, string>();

        /// <summary>
        /// 创建数据字段映射
        /// </summary>
        /// <returns></returns>
        public static Dictionary<string, string> CreateDataFieldMapping()
        {
            if (DataFieldDic.Count > 0)
                return DataFieldDic;
            var dataFieldMapping = new Dictionary<string, string>();
            Type dataType = typeof(ConstGatherDataType);
            Type fieldType = typeof(DataFieldConst);

            foreach (FieldInfo gatherField in dataType.GetFields(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy))
            {
                if (gatherField.IsLiteral && !gatherField.IsInitOnly)
                {
                    // 获取ConstGatherDataType的字段值作为key
                    string key = (string)gatherField.GetValue(null)!;

                    // 查找DataFieldConst中同名字段
                    FieldInfo dataField = fieldType.GetField(gatherField.Name,
                        BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)!;

                    if (dataField != null)
                    {
                        string value = (string)dataField.GetValue(null)!;
                        dataFieldMapping[key] = value;
                    }
                }
            }

            return dataFieldMapping;
        }

        /// <summary>
        /// 根据采集数据类型获取数据字段
        /// 返回null表示 无效字段
        /// </summary>
        /// <param name="docDataType"></param>
        /// <returns></returns>
        public static string? GetDataFieldByGatherDataType(this string gatherDataType)
        {
            if (CreateDataFieldMapping().TryGetValue(gatherDataType, out string? column))
            {
                return column;
            }
            return null;
        }


    }
}
