CSVConfigReader.cs 9.8 KB
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
 

namespace OnlineStore.LoadCSVLibrary
{
    public class CSVConfigReader : CSVReaderBase
    {
        private static Dictionary<Type, Dictionary<string, string>> allItemProTitleMap = null;
        /// <summary>
        /// 获取一个类所有的《字段,AttributeName列名》集合 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private static Dictionary<string, string> GetProMapByType(Type type)
        {
            if (allItemProTitleMap == null)
            {
                allItemProTitleMap = new Dictionary<Type, Dictionary<string, string>>();
            }
            if (!allItemProTitleMap.ContainsKey(type))
            {
                allItemProTitleMap.Add(type, getProAttributeMap(type));
            }
            return allItemProTitleMap[type];
        }

        public static List<ConfigBase> ReadConfig(string filePath)
        {
            List<ConfigBase> configList = new List<ConfigBase>();
             
            string[] lines = ReadCSVFile(filePath);
            int index = 0;
            Dictionary<string, int> allTitleIndex = new Dictionary<string, int>();
            int typeIndex = -1;
            foreach (var line in lines)
            {
                if (index == 0)
                {
                    //根据配置表来读取数据
                    allTitleIndex = GetAllTitleIndex(line);
                    //必须有列【类型】
                    if (allTitleIndex.Count < 0 || !allTitleIndex.ContainsKey("类型"))
                    {
                        LogUtil.error("未找到必须列:类型,加载数据失败!");
                        throw new CVSFieldNotMatchingExection("未找到必须列:类型,加载数据失败!");
                    }
                    typeIndex = allTitleIndex["类型"];
                }
                else
                {
                    var array = line.Split(',');
                    //每一列必须有类型字段
                    string typeValue = array[typeIndex];
                    if (typeValue.Trim().Equals(""))
                    {
                        continue;
                    }
                    Type type = typeof(ConfigBase);
                    if (typeValue.Equals(ConfigItemType.DI) || typeValue.Equals(ConfigItemType.DO))
                    {
                        type = typeof(ConfigIO);
                    }
                    else if (typeValue.Equals(ConfigItemType.AXIS))
                    {
                        type = typeof(ConfigMoveAxis);
                    }
                      
                    Dictionary<string, string> proTitleMap = getProAttributeMap(type);
                    ConfigBase bllIns = (ConfigBase)type.Assembly.CreateInstance(type.FullName);
                    bllIns.ConfigStr = line;
                    //取得属性集合
                    PropertyInfo[] props = type.GetProperties();

                    int listIndex = 0;
                    List<string> proNameList = new List<string>(proTitleMap.Keys);
                    List<string> cvsTitleList = new List<string>(proTitleMap.Values);

                    List<string> checkFiledList = new List<string>(proNameList);
                    Dictionary<string, int> proIndexMap = new Dictionary<string, int>();
                    for (int i = 0; i<cvsTitleList.Count; i++)
                    {
                        proIndexMap.Add(cvsTitleList[i], i);
                    }
                    foreach (string key in cvsTitleList)
                    {
                        try
                        {
                            if (allTitleIndex.ContainsKey(key))
                            {
                                try
                                {
                                    int titIndex = allTitleIndex[key];
                                    string value = array[titIndex];
                                    //string proName = proNameList[listIndex];
                                    string proName = proNameList[proIndexMap[key]];
                                    checkFiledList.Remove(proName);
                                    PropertyInfo prop = props.First(c => c.Name == proName);//获取同名属性
                                    if (prop != null && !value.Equals(""))
                                    {
                                        if (value.Equals("") && prop.PropertyType.Name.ToLower().Contains("int"))
                                        {
                                            prop.SetValue(bllIns, Convert.ChangeType(-1, prop.PropertyType), null);//赋值****在这里需要考虑类型问题
                                        }
                                        else if (value.Equals("") && prop.PropertyType.Name.ToLower().Contains("byte"))
                                        {
                                            prop.SetValue(bllIns, Convert.ChangeType(0, prop.PropertyType), null);//赋值****在这里需要考虑类型问题
                                        }
                                        else
                                        {
                                            prop.SetValue(bllIns, Convert.ChangeType(value, prop.PropertyType), null);//赋值****在这里需要考虑类型问题
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    LogUtil.error("filepath=" + filePath + ",index=" + index + ",key=" + key + "出错:" + ex.ToString());
                                }
                                listIndex++;
                            }
                        }
                        catch (Exception ex)
                        {
                            LogUtil.error("filepath=" + filePath + ",index=" + index + ",key=" + key + "出错:" + ex.ToString());
                        }
                    }
                    bllIns.CheckField();
                    configList.Add(bllIns);
                }
                index++;
            }
            return configList;
        }

        public static DeviceConfig LoadConfig<T>(DeviceConfig config)
        {
            LogUtil.info("开始读取文件:" + config.ConfigFilePath);
            if (config == null || config.ConfigFilePath.Equals(""))
            {
                throw new Exception("没有配置配置文件路径");
                //return null;
            }
            List<ConfigBase> configBasesList = ReadConfig(config.ConfigFilePath);
            config.LoadConfig<T>(configBasesList);

            return config;
        }

        public static bool SaveConfig(string configStr, DeviceConfig config)
        {
            var type = config.GetType();
            //取得属性集合
            PropertyInfo[] props = type.GetProperties();
            string[] lines = ReadCSVFile(configStr);
            int index = 0;
            Dictionary<string, int> titleIndex = new Dictionary<string, int>();

            string[] newLines = new string[lines.Length];

            //  获取一个类所有的《字段,AttributeName列名》集合 
            Dictionary<string, string> proMap = GetProMapByType(typeof(ConfigBase));
            List<string> proNameList = new List<string>(proMap.Keys);
            List<string> csvNameList = new List<string>(proMap.Values);
            Dictionary<string, int> allTitleIndex = new Dictionary<string, int>();

            foreach (var line in lines)
            {
                newLines[index] = line;
                var array = line.Split(',');
                if (index == 0)
                {
                    allTitleIndex = GetAllTitleIndex(line);
                    newLines[index] = line;
                }
                else
                {
                    if (array.Length > 0 && array[0].ToString().Equals(ConfigItemType.PRO))
                    {
                        string[] newArray = array;
                        string proName = array[3];
                        string proValue = array[4];
                        string proSpeed = array[7];
                        try
                        {
                            PropertyInfo prop = props.First(c => c.Name == proName);//获取同名属性
                            if (prop != null)
                            {
                                string newValue = prop.GetValue(config).ToString();
                                newArray[4] = newValue;
                            }

                            if (int.TryParse(proSpeed,out _)) {
                                PropertyInfo propSpeed = props.First(c => c.Name == proName+"_speed");//获取同名属性
                                if (prop != null)
                                {
                                    string newValue = propSpeed.GetValue(config).ToString();
                                    newArray[7] = newValue;
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            LogUtil.error("出错:" + e.ToString());
                        }
                        string newLine = "";

                        foreach (string s in newArray)
                        { 
                            newLine = newLine + s + ",";
                        }
                        newLine = newLine.Substring(0, newLine.Length - 1);
                        newLines[index] = newLine;
                    }
                }
                index++;
            }
            return WriteCSVFile(configStr, newLines);
        } 
    }
}