CSVBomManager.cs 31.5 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using TSA_V.Common;
using TSA_V.DeviceLibrary;

namespace TSA_V.LoadCSVLibrary
{
    public class CSVBomManager : CSVReaderBase
    {

        /// <summary>
        /// 所有的位置集合,key=位置
        /// </summary>
        public static Dictionary<string, List< ComponetInfo>> allComMap = new Dictionary<string, List<ComponetInfo>>();

        public static List<ComponetInfo> GetComList(string bomName)
        {
            if (allComMap.ContainsKey(bomName))
            {
                return new List<ComponetInfo>(allComMap[bomName] );
            }
            else
            {
                string fileName = getFilePath(bomName);
                if (File.Exists(fileName))
                {
                    List<ComponetInfo> list = ReadFile(fileName); 
                    allComMap.Add(bomName, list);
                    return list;
                }
            }
            return null;
        }

        public static bool BomNameIsExists(string bomName)
        {
            if (allComMap.ContainsKey(bomName))
            {
                return true;
            } 
            return false;
        }

        public static void LoadAllCom()
        {

            allComMap = new Dictionary<string, List<ComponetInfo>>();
            string appPath = Application.StartupPath;
            string filePath = appPath + ConfigAppSettings.GetValue(Setting_Init.ComPath_Config);
            if (!Directory.Exists(filePath))
            {
                Directory.CreateDirectory(filePath);
            }
            //加载所有数据
            string[] fileList = Directory.GetFiles(filePath);
            if (fileList.Length <= 0)
            {
                return;
            }
            foreach (string fileName in fileList)
            {
                try
                {
                    string extension = Path.GetExtension(fileName); //-->.xml
                    if (extension.ToLower().Equals(".csv"))
                    {
                        string bomName = Path.GetFileNameWithoutExtension(fileName); //-->BenXHCMS 
                        List<ComponetInfo> list = ReadFile(fileName);
                        if (list.Count > 0)
                        {
                            allComMap.Add(bomName, list);
                        }
                    }
                }
                catch (Exception ex)
                {
                    LogUtil.error("加载出错:" + ex.ToString());
                }
            }
        }

        private static string getFilePath(string bomName)
        {
            string appPath = Application.StartupPath;
            string filePath = appPath + ConfigAppSettings.GetValue(Setting_Init.ComPath_Config);
            return filePath + bomName + ".csv";
        }
        /// <summary>
        /// 解析一行CSV数据
        /// </summary>
        /// <param name="csv">csv数据行</param>
        /// <returns></returns>
        public static string[] FromCsvLine(string csv)
        {

            var newstr = string.Empty;
            List<string> sList = new List<string>();

            bool isSplice = false;
            string[] array = csv.Split(new char[] { ',' });
            foreach (var str in array)
            {
                if (!string.IsNullOrEmpty(str) && str.IndexOf('"') > -1)
                {
                    var firstchar = str.Substring(0, 1);
                    var lastchar = string.Empty;
                    if (str.Length > 0)
                    {
                        lastchar = str.Substring(str.Length - 1, 1);
                    }
                    if (firstchar.Equals("\"") && !lastchar.Equals("\""))
                    {
                        isSplice = true;
                    }
                    if (lastchar.Equals("\""))
                    {
                        if (!isSplice)
                            newstr += str;
                        else
                            newstr = newstr + "," + str;

                        isSplice = false;
                    }
                }
                else
                {
                    if (string.IsNullOrEmpty(newstr))
                        newstr += str;
                }

                if (isSplice)
                {
                    //添加因拆分时丢失的逗号
                    if (string.IsNullOrEmpty(newstr))
                        newstr += str;
                    else
                        newstr = newstr + "," + str;
                }
                else
                {
                    sList.Add(newstr.Replace("\"", "").Trim());//去除字符中的双引号和首尾空格
                    newstr = string.Empty;
                }
            }
            return sList.ToArray();

        }
        /// <summary>
        /// 反转字符串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        private static string Reverse(string str)
        {
            string revStr = string.Empty;
            foreach (char chr in str)
            {
                revStr = chr.ToString() + revStr;
            }
            return revStr;
        }
        /// <summary>
        /// 替换CSV中的双引号转义符为正常双引号,并去掉左右双引号
        /// </summary>
        /// <param name="csvValue">csv格式的数据</param>
        /// <returns></returns>
        private static string ReplaceQuote(string csvValue)
        {
            string rtnStr = csvValue;
            if (!string.IsNullOrEmpty(csvValue))
            {
                //首尾都是"
                Match m = Regex.Match(csvValue, "^\"(.*?)\"$");
                if (m.Success)
                {
                    rtnStr = m.Result("${1}").Replace("\"\"", "\"");
                }
                else
                {
                    rtnStr = rtnStr.Replace("\"\"", "\"");
                }
            }
            return rtnStr;

        }
         
        /// <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, List<string>> proTitleMap = getProAttributeMaps(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> propIndexMap = new Dictionary<string, int>();
            foreach (var line in lines)
            {
                var newLine = line.Replace("\"", "");
                var array = newLine.Split(Spilt_Char);
                array = FromCsvLine(line);
                if (index == 0)
                {
                    propIndexMap = GetProTitleIndex(line, proTitleMap);
                }
                else
                {
                    try
                    {
                        if (array.Length >= propIndexMap.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 proName in propertyList)
                            {
                                if (propIndexMap.ContainsKey(proName))
                                {
                                    int titIndex = propIndexMap[proName];
                                    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";
                                        }
                                        //if (proName == "PositionX" || proName == "PositionY") {
                                        //    value = Regex.Match(value, @"\d+\.\d+|\d+").Value;
                                        //    if (value == "")
                                        //        value = "0";                                        
                                        //}

                                        //如果属性存在
                                        prop.SetValue(bllIns, Convert.ChangeType(value, prop.PropertyType), null);//赋值****在这里需要考虑类型问题 
                                    }
                                }
                                listIndex++;
                            }
                            ComponetInfo com = (ComponetInfo)bllIns;
                            com.Id = index ;
                            comList.Add(com);
                        }
                        else
                        {
                            LOGGER.Error("读取csv,index=" + index + ",数据格式不匹配!,line=" + line);
                        }
                    }
                    catch (Exception ex)
                    {
                        LOGGER.Debug("CSV 读取行【" + line + "】行转换失败");
                    }
                }
                index++;
            }

            #region 旧代码
            //Dictionary<string, string> pnposlist = new Dictionary<string, string>();
            //HashSet<string> usedposlist = new HashSet<string>();
            //List<ComponetInfo> componetlist = new List<ComponetInfo>();
            //int Id = 1;
            //foreach (var com in comList)
            //{
            //    if (string.IsNullOrWhiteSpace(com.PositionNum))
            //        continue;

            //    string[] strarr = GetPositionNum(com.PositionNum);
            //    string[] intarr = com.ComCount.Split(';');
            //    if (strarr.Length != +intarr.Length)
            //    {
            //        MessageBox.Show($"{com.PN}的数量分组{intarr.Length}和位置分组{strarr.Length},不统一!");
            //        return new List<ComponetInfo>();
            //    }
            //    else if (intarr.Length == 1 && strarr.Length == 1)
            //    {
            //        com.Id = Id;
            //        componetlist.Add(com);
            //        Id++;
            //        continue;
            //    }
            //    int j = 0;
            //    foreach (var item in strarr)
            //    {
            //        ComponetInfo componet = new ComponetInfo();
            //        string tagno = com.TagNo;
            //        int comid = Id + 1;
            //        if (j != 0)
            //        {
            //            tagno = "";
            //            comid = 0;
            //        }
            //        componet.Id = comid;
            //        componet.TagNo = tagno;
            //        componet.PositionX = com.PositionX;
            //        componet.PositionNum = item;
            //        componet.PN = com.PN;
            //        componet.Text = com.Text;
            //        componet.ComCount = intarr[j];
            //        componet.ComponentDes = com.ComponentDes;
            //        componet.Notes = com.Notes;
            //        componetlist.Add(componet);
            //        if (!string.IsNullOrEmpty(com.PositionNum))
            //        {
            //            usedposlist.Add(com.PositionNum);
            //            pnposlist[com.PN] = com.PositionNum;
            //        }
            //        j++;
            //        Id++;
            //    }
            //    //if (!string.IsNullOrEmpty(com.PositionNum))
            //    //{
            //    //    usedposlist.Add(com.PositionNum);
            //    //    pnposlist[com.PN] = com.PositionNum;
            //    //}
            //}
            //List<ComponetInfo> componedate = componetlist.Where(m => !m.PositionNum.Contains(";")).ToList();
            //foreach (var com in componedate)
            //{

            //    if (string.IsNullOrWhiteSpace(com.PositionNum) && !string.IsNullOrWhiteSpace(com.PN))
            //    {
            //        if (pnposlist.ContainsKey(com.PN))
            //            com.PositionNum = pnposlist[com.PN];
            //        else
            //        {
            //            foreach (var p in CSVPositionReader<TSAVPosition>.allPositionMap)
            //            {
            //                if (usedposlist.Contains(p.Value.PositionNum))
            //                    continue;
            //                com.PositionNum = p.Value.PositionNum;
            //                pnposlist[com.PN] = com.PositionNum;
            //                usedposlist.Add(com.PositionNum);
            //                break;
            //            }
            //        }
            //    }
            //    //if (String.IsNullOrEmpty(com.PositionNum) || String.IsNullOrEmpty(com.PN))
            //    //{
            //    //    LOGGER.Error("读取csv,数据不完整,跳过数据,line=" + com.TagNo);
            //    //    continue;
            //    //}
            //}

            #endregion

            return CreateCompone(comList);
        }


        public static List<ComponetInfo> CreateCompone(List<ComponetInfo> comList)
        {
            Dictionary<string, string> pnposlist = new Dictionary<string, string>();
            HashSet<string> usedposlist = new HashSet<string>();
            List<ComponetInfo> componetlist = new List<ComponetInfo>();
            #region 将解析好的excel内容,生成到List<ComponetInfo>            
            int Id = 1;
            foreach (var com in comList)
            {
                if (string.IsNullOrWhiteSpace(com.PositionNum)) continue;

                string[] strarr = GetPositionNum(com.PositionNum);
                string[] intarr = com.ComCount.Split(';');

                if (strarr.Length != intarr.Length)
                {
                    MessageBox.Show($"{com.PN}的数量分组{intarr.Length}和位置分组{strarr.Length},不统一!");
                    return new List<ComponetInfo>();
                }

                for (int j = 0; j < strarr.Length; j++)
                {
                    componetlist.Add(new ComponetInfo
                    {
                        Id = (j==0)?Id:-1,
                        TagNo = com.TagNo,
                        PositionX = com.PositionX,
                        PositionY= com.PositionY,
                        PositionNum = strarr[j],
                        PN = com.PN,
                        Text = com.Text,
                        ComCount = intarr[j],
                        ComponentDes = com.ComponentDes,
                        Notes = com.Notes
                    });
                }

                Id ++ ;
                if (!string.IsNullOrEmpty(com.PositionNum))
                {
                    usedposlist.Add(com.PositionNum);
                    pnposlist[com.PN] = com.PositionNum;
                }
            }
            #endregion
            foreach (var com in componetlist)
            {

                if (string.IsNullOrWhiteSpace(com.PositionNum) && !string.IsNullOrWhiteSpace(com.PN))
                {
                    if (pnposlist.ContainsKey(com.PN))
                        com.PositionNum = pnposlist[com.PN];
                    else
                    {
                        foreach (var p in CSVPositionReader<TSAVPosition>.allPositionMap)
                        {
                            if (usedposlist.Contains(p.Value.PositionNum))
                                continue;
                            com.PositionNum = p.Value.PositionNum;
                            pnposlist[com.PN] = com.PositionNum;
                            usedposlist.Add(com.PositionNum);
                            break;
                        }
                    }
                }
                //if (String.IsNullOrEmpty(com.PositionNum) || String.IsNullOrEmpty(com.PN))
                //{
                //    LOGGER.Error("读取csv,数据不完整,跳过数据,line=" + com.TagNo);
                //    continue;
                //}
            }
            return componetlist;
        }
        public static string[] GetPositionNum(string configPosition )
        {
            string[] strings=configPosition.Split(';');
            string[] strarr=new string[strings.Length];
            int i = 0;
            foreach (var item in strings)
            {
                TSAVPosition p = CSVPositionReader<TSAVPosition>.GetPositonByNum(item);
                if (p != null)
                {
                   // return p.PositionNum;
                    strarr[i] = p.PositionNum;
                }
                else
                {
                    strarr[i] = "";
                }
                i++;
            }
            return strarr;
        }
        

        public static bool UpdateComponet(string bomName, ComponetInfo com)
        {
            if (!allComMap.ContainsKey(bomName))
            {
                return false;
            }
            List<ComponetInfo> oldList = allComMap[bomName];
            for (int index = 0; index < oldList.Count; index++)
            {
                if (oldList[index].IsSameCom(com))
                {
                    oldList[index] = com;
                    break;
                }
            }

            if (SaveBomToFile(bomName, oldList))
            {
                allComMap[bomName] = oldList;
                return true;
            }

            return false;
        }

        public static bool SaveBomToFile(string bomName, List<ComponetInfo> positionList)
        {
            string filePath = getFilePath(bomName);
            System.Type type = typeof(ComponetInfo); 
            Dictionary<string, List<string>> proTitleMap = getProAttributeMaps(typeof(ComponetInfo));
           
            List<string> propertyList = new List<string>(proTitleMap.Keys);
            Dictionary<string, int> propIndexMap = new Dictionary<string, int>();
            string[] lines = new string[positionList.Count + 1];
            if (File.Exists(filePath))
            { 
                string[] readLines = ReadCSVFile(filePath);
                foreach (var line in readLines)
                {
                    lines[0] = line;
                    var array = line.Split(',');
                    propIndexMap = GetProTitleIndex(line, proTitleMap);
                    break;
                }
            }
            else
            {
                string line = "";
                propIndexMap = new Dictionary<string, int>();
                int proIndex = 0;
                   foreach(string pro in propertyList)
                {
                    List<string> csvList = proTitleMap[pro];
                    string title = csvList[0];
                    propIndexMap.Add(pro, proIndex);
                    line += title + ",";
                    proIndex++;
                }

                lines[0] = line;

            }
            int index = 1;

            foreach (ComponetInfo position in positionList)
            {
                string newValue = ObjToString(position, propIndexMap);
                lines[index] = newValue;
                index++;
            }

            return WriteCSVFile(filePath, lines);
        }

     

        private static string ObjToString(ComponetInfo position, Dictionary<string, int> propIndexMap)
        {
            //取得属性集合
            PropertyInfo[] props = typeof(ComponetInfo).GetProperties(); 
            List<string> propertyList = new List<string>(propIndexMap.Keys);
            String[] array = new String[propIndexMap.Count];

            foreach (string proName in propertyList)
            {
                PropertyInfo prop = props.First(c => c.Name == proName);//获取同名属性
                if (prop != null)
                {//如果属性存在
                    string value = prop.GetValue(position, null).ToString();
                    int index = propIndexMap[proName];
                    array[index] = value;
                }
            }

            string newStr = "";
            foreach (string str in array)
            {
                newStr += str + Spilt_Char;
            }
            return newStr;
        }
         
        public static bool AddBom(string bomName, List<ComponetInfo> comList)
        {
            try
            {
                RemoveBom(bomName);
                string filePath = getFilePath(bomName);
                if (File.Exists(filePath))
                {
                    //删除原来的文件
                    File.Delete(filePath);
                    LogUtil.error("新增元器件库:" + bomName + ",发现文件【" + filePath + "】已存在,删除原来的文件");
                } 
 
                allComMap.Add(bomName, comList);
                return SaveBomToFile(bomName, comList);
            }
            catch (Exception ex)
            {
                LogUtil.error("增加元器件库出错 :【" + bomName + "】" + ex.ToString());
                return false;
            }
        }

        public static void RemoveBom(string bomName)
        { 
            string fileName = getFilePath(bomName);
            if (allComMap.ContainsKey(bomName))
            {
                allComMap.Remove(bomName);
            }
            if (File.Exists(fileName))
            { 
                File.Delete(fileName);
            }
        }

        public static List<ComponetInfo> RemoveCom(string bomName, ComponetInfo obj)
        {
            string fileName = getFilePath(bomName);
            File.Delete(bomName);
            if (allComMap.ContainsKey(bomName))
            {
                int delIndex = -1;
                List<ComponetInfo> list = allComMap[bomName];
                for (int index = 0; index < list.Count; index++)
                {
                    if (list[index].IsSameCom(obj))
                    {
                        delIndex = index;
                        break;
                    }
                }
                if (delIndex >= 0)
                {
                    list.RemoveAt(delIndex);
                    for (int i = 0; i < list.Count; i++)
                    {
                        list[i].Id = i + 1;
                    }
                    AddBom(bomName, list);
                }
                return list;

            }

            return null;
        }
        public static List<ComponetInfo> AddCom(string bomName, ComponetInfo obj)
        {
            string fileName = getFilePath(bomName);
            File.Delete(bomName);
            if (allComMap.ContainsKey(bomName))
            {
                List<ComponetInfo> list = allComMap[bomName];
                list.Add(obj);
                for(int i = 0; i < list.Count; i++)
                {
                    list[i].Id = i + 1;
                }
                AddBom(bomName, list);
                LogUtil.info($"元器件库[{bomName}]新增元器件[{obj.TagNo}-{obj.PN}]");

                ////更新此元器件库对应的程序
                //BoardManager.AddCom(bomName, obj);

                return list;
            }

            return null;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bomName"></param>
        /// <param name="pointInfo"></param>
        /// <param name="issamecom">为true时执行新的查询元器件库逻辑,不影响之前的引用逻辑</param>
        /// <returns></returns>
        public static ComponetInfo GetCom(string bomName, SMTPointInfo pointInfo,bool issamecom=false)
        {
            if (allComMap.ContainsKey(bomName))
            {
                List<ComponetInfo> map = allComMap[bomName];
                foreach (ComponetInfo obj in map)
                {
                    if (issamecom)
                    {
                        if (obj.IsSameComAndCount(pointInfo))
                        {
                            return obj;
                        }
                    }
                    else
                    {
                        if (obj.IsSameCom(pointInfo))
                        {
                            return obj;
                        }
                    }
                   
                }
                foreach (ComponetInfo obj in map)
                {
                    if (obj.PN.Equals(pointInfo.PN))
                    {
                        return obj;
                    }
                }
            }
            return null;
        }

        public static bool canRemoveCom(string bomName, ComponetInfo obj)
        {
            List<ComponetInfo> list = CSVBomManager.GetComList(bomName);
            //已使用的元器件不能删除
            foreach (BoardInfo board in BoardManager.boardList)
            {
                if (board.bomName.Equals(bomName))
                {
                    foreach (SMTPointInfo p in board.smtList)
                    {
                        if ((!String.IsNullOrEmpty(obj.TagNo)))
                        {
                            if (p.TagNo.Equals(obj.TagNo))
                            {
                                return false;
                            }
                        }
                        else if (p.PN.Equals(obj.PN))
                        {
                            List<ComponetInfo> pnlist = (from m in list where m.Id != obj.Id && m.PN.Equals(p.PN) select m).ToList();
                            if (pnlist.Count <= 0)
                            {
                                return false;
                            }
                        }
                    }

                }
            }
            return true;
        }

        /// <summary>
        /// 更新元器件数量,优先用位号查找,未找到时用Pn查找
        /// </summary> 
        public static bool UpdateCount(string bomName, SMTPointInfo smtPoint, int count)
        {
            List<ComponetInfo> comList = CSVBomManager.GetComList(bomName);
            if (comList == null)
            {
                return false;
            } 

            bool updateOk = false;
           for(int i=0;i<comList.Count;i++)
            {
                if (comList[i].IsSameCom(smtPoint))
                {
                    comList[i].ComCount = count.ToString();
                    updateOk = true;
                    break;
                }  
            }

            if (!updateOk)
            {
                for (int i = 0; i < comList.Count; i++)
                {
                    if (comList[i].PN.Equals(smtPoint.PN))
                    {
                        comList[i].ComCount = count.ToString();
                        updateOk = true;
                        break;
                    }
                }
            }

            CSVBomManager.SaveBomToFile(bomName, comList);
            return true;
        }
        /// <summary>
        /// 减去此电路板使用的元器件数量
        /// </summary>
        /// <param name="currBoard"></param>
        public static bool DelUseCount(DeviceLibrary.BoardInfo currBoard, List<ComponetInfo> useComponets)
        {
            try
            {
                string bomName = currBoard.bomName;
                List<ComponetInfo> comList = CSVBomManager.GetComList(bomName);
                if (comList == null)
                {
                    return false;
                }
                //Dictionary<string, int> useCount = new Dictionary<string, int>();
                //int index = 0;
                //List<SMTPointInfo> list = currBoard.GetSmtList();
                //foreach (SMTPointInfo smt in list)
                //{
                //    if (index > maxIndex)
                //    {
                //        break;
                //    }
                //    ComponetInfo com = CSVBomManager.GetCom(BoardManager.CurrBoard.bomName, smt);
                //    if (useCount.ContainsKey(com.PN))
                //    {
                //        useCount[com.PN]++;
                //    }
                //    else
                //    {
                //        useCount.Add(com.PN, 1);
                //    }
                //    index++;
                //}
                List<ComponetInfo> newList = new List<ComponetInfo>();
                foreach (ComponetInfo obj in comList)
                { 
                    List<ComponetInfo> list = (from m in useComponets where m.Id.Equals(obj.Id) select m).ToList(); 
                    if (list.Count > 0)
                    {
                        obj.ComCount = (int.Parse(obj.ComCount) - list.Count).ToString();
                        if (int.Parse(obj.ComCount) < 0)
                        {
                            obj.ComCount = "0";
                        }
                    }
                    newList.Add(obj); 
                }
                if (allComMap.ContainsKey(bomName))
                {
                    allComMap[bomName] = newList;
                }
                CSVBomManager.SaveBomToFile(bomName, newList);
            }
            catch (Exception ex)
            {

            }
            return true;
        }
        public static string AutoAddBomList(string bomName, List<ComponetInfo> comList)
        {
            string newBomName = bomName;
            //自动新增元器件库  
            if (CSVBomManager.BomNameIsExists(bomName))
            {
                bomName = bomName + DateTime.Now.ToString("-MM-dd-HH-mm-ss");
                if (CSVBomManager.BomNameIsExists(bomName))
                {
                    for (int i = 1; i <= 100; i++)
                    {
                        string testName = bomName + "-" + i;
                        if (!CSVBomManager.BomNameIsExists(testName))
                        {
                            bomName = testName;
                            break;
                        }
                    }
                }
            }
            Dictionary<string, ComponetInfo> comMap = new Dictionary<string, ComponetInfo>();
            foreach (ComponetInfo obj in comList)
            {
                string key = obj.PN + "-" + obj.PositionNum;                
                if (comMap.ContainsKey(key))
                {
                    continue;
                }
                //obj.TagNo = "";
                comMap.Add(key, obj);
            }
            List<ComponetInfo> list = new List<ComponetInfo>(comMap.Values);
            for (int i = 0; i < list.Count; i++)
            {
                list[i].Id = i + 1;
            }
            CSVBomManager.AddBom(bomName, list);

            return bomName;
        }

    }
}