CSVBomManager.cs 12.2 KB
using OnlineStore.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Windows.Forms;

namespace OnlineStore.LoadCSVLibrary
{
    public class CSVBomManager : CSVReaderBase
    {

        public static Dictionary<string, ComponetInfo> allComMap = new Dictionary<string, ComponetInfo>();

        public static List<ComponetInfo> GetComList()
        {
            return new List<ComponetInfo>(allComMap.Values);
        }

        public static bool LoadAllCom()
        {
            string fileName = getFilePath();
            if (!Directory.Exists(fileName))
            {
                return false;
            }
            try
            {
                string bomName = Path.GetFileNameWithoutExtension(fileName); //-->BenXHCMS 
                List<ComponetInfo> list = ReadFile(fileName);
                Dictionary<string, ComponetInfo> map = new Dictionary<string, ComponetInfo>();
                foreach (ComponetInfo com in list)
                {
                    if (com == null || com.PartNum == null || com.Encapsulations == null)
                    {
                        continue;
                    }
                    if (map.ContainsKey(com.PartNum))
                    {
                        LogUtil.error("元器件库【" + bomName + "】【" + com.PartNum + "】重复");
                    }
                    else
                    {
                        map.Add(com.PartNum, com);
                    }
                }
            }
            catch (Exception ex)
            {
                LogUtil.error("加载出错:" + ex.ToString());
                return false;
            }
            return true;
        }

        public static string getFilePath()
        {
            string appPath = Application.StartupPath;
            string fileName = appPath + ConfigAppSettings.GetValue(Setting_Init.ComPath_Config);
            return fileName;
        }
        /// <summary>
        /// 添加一个csv文件的数据到位置集合中
        /// </summary>
        /// <param name="filePath">cvs文件路径+文件名</param>  
        /// <returns></returns>
        public static List<ComponetInfo> ReadFile(string filePath)
        {
            System.Type type = typeof(ComponetInfo);
            List<ComponetInfo> comList = new List<ComponetInfo>();
            Dictionary<string, string> proTitleMap = getProAttributeMap(typeof(ComponetInfo));

            List<string> cvsTitleList = new List<string>(proTitleMap.Values);
            List<string> propertyList = new List<string>(proTitleMap.Keys);

            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;

                            foreach (string key in cvsTitleList)
                            {
                                if (titleIndex.ContainsKey(key))
                                {
                                    int titIndex = titleIndex[key];
                                    string value = array[titIndex];
                                    string proName = propertyList[listIndex];
                                    PropertyInfo prop = props.First(c => c.Name == proName);//获取同名属性
                                    if (prop != null)
                                    {
                                        string typeName = prop.PropertyType.Name;
                                        //判断值是否为空
                                        if (value.Equals("") && (typeName.ToUpper().Equals("INT32") || typeName.ToUpper().Equals("DOUBLE")))
                                        {
                                            value = "0";
                                        }
                                        //如果属性存在
                                        prop.SetValue(bllIns, Convert.ChangeType(value, prop.PropertyType), null);//赋值****在这里需要考虑类型问题 
                                    }
                                }
                                listIndex++;
                            }
                            comList.Add((ComponetInfo)bllIns);
                        }
                        else
                        {
                            LogUtil.error("读取csv,index=" + index + ",数据格式不匹配!,line=" + line);
                        }
                    }
                    catch (Exception ex)
                    {
                        LogUtil.error("CSV 读取行【" + line + "】行转换失败");
                    }
                }
                index++;
            }
            return comList;
        }

        public static bool SaveComponet(ComponetInfo com)
        {
            if (!allComMap.ContainsKey(com.PartNum))
            {
                return false;
            }
            System.Type type = typeof(ComponetInfo);

            Dictionary<string, string> proTitleMap = getProAttributeMap(typeof(ComponetInfo));

            List<string> cvsTitleList = new List<string>(proTitleMap.Values);
            List<string> propertyList = new List<string>(proTitleMap.Keys);
            int IdIndex = propertyList.IndexOf("PartNum");
            int csvIndex = -1;
            string filePath = getFilePath();


            int idIndex = propertyList.IndexOf("PartNum");
            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[idIndex]];
                        }
                        string value = array[csvIndex];
                        if (value.Equals(com.PartNum))
                        {
                            //更新缓存
                            allComMap.Remove(com.PartNum);
                            allComMap.Add(com.PartNum, com);
                            string newValue = ObjToString(com, titleIndex, proTitleMap);
                            lines[index] = newValue;
                            return WriteCSVFile(filePath, lines);
                        }
                    }
                }
                index++;
            }
            return true;
        }
        
        private static string ObjToString(ComponetInfo position, Dictionary<string, int> titleIndex, Dictionary<string, string> proTitleMap)
        {
            //取得属性集合
            PropertyInfo[] props = typeof(ComponetInfo).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;
        }

        /// <summary>
        /// 获取此文件第一行的数据
        /// </summary> 
        private static string GetHeaderString(List<string> cvsValues)
        {
            string newStr = "";
            foreach (string str in cvsValues)
            {
                if (newStr.Equals(""))
                {
                    newStr = str;
                }
                else
                {
                    newStr = newStr + Spilt_Char + str;
                }
            }
            return newStr;
        }

        /// <summary>
        /// 增加一个元器件库
        /// </summary> 
        public static bool SaveToFile()
        {
            try
            {
                List<ComponetInfo> comList = new List<ComponetInfo>();
                string filePath = getFilePath();
                System.Type type = typeof(ComponetInfo);

                Dictionary<string, string> proTitleMap = getProAttributeMap(typeof(ComponetInfo));

                List<string> cvsTitleList = new List<string>(proTitleMap.Values);
                List<string> propertyList = new List<string>(proTitleMap.Keys);

                Dictionary<string, int> titleIndexMap = new Dictionary<string, int>();
                int titleIndex = 0;
                foreach (string str in cvsTitleList)
                {
                    titleIndexMap.Add(str, titleIndex);
                    titleIndex++;
                }
                string[] lines = new string[comList.Count + 1];
                lines[0] = GetHeaderString(cvsTitleList);
                int index = 1;
                Dictionary<string, ComponetInfo> map = new Dictionary<string, ComponetInfo>();
                foreach (ComponetInfo com in comList)
                {
                    map.Add(com.PartNum, com);
                    lines[index] = ObjToString(com, titleIndexMap, proTitleMap);
                    index++;
                }
                bool result = WriteCSVFile(filePath, lines);
                LogUtil.info("保存物料库列表到文件 SaveToFile :" + result);
                return true;
            }
            catch (Exception ex)
            {
                LogUtil.error("SaveToFile 出错" + ex.ToString());
                return false;
            }
        } 
        public static bool RemoveCom(ComponetInfo obj)
        {
            if (allComMap.ContainsKey(obj.PartNum))
            {
                allComMap.Remove(obj.PartNum);
                SaveToFile();
                return true;
            } 
            return false;
        }

        public static ComponetInfo GetCom(string partNum)
        { 
            if (allComMap.ContainsKey(partNum))
            {
                return allComMap[partNum];
            } 
            return null;
        } 
    }
    public class ComponetInfo
    {
        public ComponetInfo()
        {
        }
        /// <summary>
        ///物料编号
        /// </summary>
        [CSVAttribute("物料编号")]
        public string PartNum { get; set; }

        /// <summary>
        /// 描述
        /// </summary>
        [CSVAttribute("描述")]
        public string Describe { get; set; }
        /// <summary>
        ///产品
        /// </summary>
        [CSVAttribute("产品")]
        public string ProductName { get; set; }

        /// <summary>
        ///封装
        /// </summary>
        [CSVAttribute("封装")]
        public string Encapsulations { get; set; } 
    }
}