CSVPositionReader.cs 9.7 KB

using log4net;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
 

namespace OnlineStore.LoadCSVLibrary
{
    public class CSVPositionReader<T> : CSVReaderBase  where T : StorePostionBase
    { 
        /// <summary>
        /// 所有的位置集合,key=位置
        /// </summary>
        public static Dictionary<string, T> allPositionMap = new Dictionary<string, T>();

        public static List<string> hasReadFileList = new List<string>();

        /// <summary>
        /// 重新加载配置,会删除之前的所有信息,重新读取
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static Dictionary<String, T> ReloadCSVFile(string filePath)
        {
            allPositionMap = new Dictionary<string, T>();
            hasReadFileList = new List<string>();

            return AddCSVFile(filePath); 
        }
        public static List<string> getPositionKeyList()
        {
            return new List<string>(allPositionMap.Keys);
        }
        public static List<T> getPositionList()
        {
            List<T> list = new List<T>(allPositionMap.Values);
            return list;
        }
        /// <summary>
        /// 添加一个csv文件的数据到位置集合中
        /// </summary>
        /// <param name="filePath">cvs文件路径+文件名</param>  
        /// <returns></returns>
        public static Dictionary<String, T> AddCSVFile(string filePath)
        {
            if (hasReadFileList.Contains(filePath))
            {
                LOGGER.Error("文件" + filePath + "已经加载过,直接返回null");
                return null;
            }
            Type type = typeof(T);

            Dictionary<string, string> proTitleMap = getProAttributeMap(typeof(T));
            if (proTitleMap.Count <= 4)
            {
                LOGGER.Error(typeof(T).ToString() + "只读取到" + proTitleMap.Count + "个属性");
            }
            List<string> cvsTitleList = new List<string>(proTitleMap.Values);
            List<string> propertyList = new List<string>(proTitleMap.Keys);

            Dictionary<String, T> result = new Dictionary<String, T>();

            string[] lines =ReadCSVFile(filePath);
            int index = 0;
            Dictionary<string, int> titleIndex = new Dictionary<string, int>();
            foreach (var line in lines)
            {
                var array = line.Split(Spilt_Char);
                if (index == 0)
                {
                    titleIndex = GetTitleIndex(line, cvsTitleList); 
                }
                else
                {
                    try
                    {
                        if (array.Length >= titleIndex.Count)
                        {
                            if (array.Length > 0 && array[0].Equals(""))
                            {
                                continue;
                            }
                            var bllIns = type.Assembly.CreateInstance(type.FullName);
                            //取得属性集合
                            PropertyInfo[] props = type.GetProperties();

                            int listIndex = 0;
                            string PositionNum = "";
                            foreach (string key in cvsTitleList)
                            {
                                int titIndex = titleIndex[key];
                                string value = array[titIndex];
                                string proName = propertyList[listIndex];
                                PropertyInfo prop = props.First(c => c.Name == proName);//获取同名属性
                                if (prop != null)
                                {//如果属性存在
                                    prop.SetValue(bllIns, Convert.ChangeType(value, prop.PropertyType), null);//赋值****在这里需要考虑类型问题
                                }
                                if (proName.Equals("PositionNum"))
                                {
                                    PositionNum = value;
                                }
                                listIndex++;
                            }
                            result.Add(PositionNum, (T)bllIns);
                            if (allPositionMap.ContainsKey(PositionNum))
                            {
                                throw new PositionAlreadyExistingExection("仓位:" + PositionNum + "已存在!");
                            }
                            allPositionMap.Add(PositionNum, (T)bllIns);
                        }
                        else
                        {
                            LOGGER.Error("读取csv,index=" + index + ",数据格式不匹配!,line=" + line);
                        }
                    }
                    catch (Exception ex)
                    {
                        LOGGER.Debug( "CSV 读取行【" + line + "】行转换失败");
                    }
                }
                index++;
            }
            return result;
        }
        /// <summary>
        /// 根据Key获得一个位置信息
        /// </summary> 
        public static T GetPositon(string positionNum)
        {
            if (positionNum == null)
            {
                return null;
            }
            StorePostionBase result = null;
            if (allPositionMap.ContainsKey(positionNum))
            {
                result = allPositionMap[positionNum];
                return (T)result;
            }
            else
            {
                return null;
            }
        }

        public static bool SavePostion(string filePath, T position)
        {
            Type type = typeof(T);
            
            Dictionary<string, string> proTitleMap = getProAttributeMap(typeof(T));
            if (proTitleMap.Count <= 4)
            {
                LOGGER.Error(typeof(T).ToString() + "只读取到" + proTitleMap.Count + "个属性");
            }
            List<string> cvsTitleList = new List<string>(proTitleMap.Values);
            List<string> propertyList = new List<string>(proTitleMap.Keys);
            int positionNumIndex = propertyList.IndexOf("PositionNum");
            int csvIndex = -1;
            string[] lines = ReadCSVFile(filePath);
            int index = 0;
            Dictionary<string, int> titleIndex = new Dictionary<string, int>();

            foreach (var line in lines)
            {
                var array = line.Split(',');
                if (index == 0)
                {
                    titleIndex = GetTitleIndex(line, cvsTitleList);
                }
                else
                {
                    if (array.Length == titleIndex.Count)
                    {
                        if (csvIndex < 0)
                        {
                            csvIndex = titleIndex[cvsTitleList[positionNumIndex]];
                        }
                        string value = array[csvIndex];
                        if (value.Equals(position.PositionNum))
                        {
                            //更新缓存
                            allPositionMap.Remove(position.PositionNum);
                            allPositionMap.Add(position.PositionNum, position);
                            string newValue = PostionToString(position, titleIndex, proTitleMap);
                            lines[index] = newValue;
                            return WriteCSVFile(filePath, lines);
                        }
                    }
                }
                index++;
            }
            return true;
        } 

        private static string PostionToString(StorePostionBase position, Dictionary<string, int> titleIndex, Dictionary<string, string> proTitleMap)
        {
            //取得属性集合
            PropertyInfo[] props = typeof(T).GetProperties();
            List<string> cvsTitleList = new List<string>(proTitleMap.Values);
            List<string> propertyList = new List<string>(proTitleMap.Keys);
            String[] array = new String[titleIndex.Count];
            foreach (string proName in proTitleMap.Keys)
            {
                PropertyInfo prop = props.First(c => c.Name == proName);//获取同名属性
                if (prop != null)
                {//如果属性存在
                    string value = prop.GetValue(position, null).ToString();
                    int index = titleIndex[proTitleMap[proName]];
                    array[index] = value;
                }
            }

            string newStr = "";
            foreach (string str in array)
            { 
                if (newStr.Equals(""))
                {
                    newStr = str;
                }
                else
                {
                    newStr = newStr+Spilt_Char + str;
                }
            }
            return newStr;
        }

        //private void ReadTest( )
        //{
        //    Dictionary<string, string> dic = new Dictionary<string, string>();

        //    string path = Application.StartupPath + @"\Test.csv";
        //    dic.Add("AxisPosition", "中轴位置");
        //    dic.Add("ModbusHighPosition", "电钢高位");
        //    dic.Add("ModbusLowPosition", "电钢低位");

        //    Dictionary<string, KTKStorePostion> ddd = LoadCVSLibrary.CSVReaderHelper<KTKStorePostion>.ReadCVS(path, dic, typeof(KTKStorePostion));

        //    if (ddd != null)
        //    {
        //        MessageBox.Show("读取成功!");
        //    }
        //    else
        //    {
        //        MessageBox.Show("读取失败,请检查数据格式!");
        //    }
        //}

    }

   
}