chr
2025-03-04 3f62d18e4361cd1d7a49c126765d95b2ad9c8246
PdmSwPlugin.PDM/PdmControl.xaml.cs
@@ -1,5 +1,6 @@
using log4net;
using Microsoft.Win32;
using NPOI.SS.Formula.PTG;
using NPOI.SS.UserModel;
using NPOI.Util;
using NPOI.XSSF.UserModel;
@@ -55,6 +56,8 @@
        private HttpClientCreator clientCreator { get; set; }
        private volatile PdmStatus workStatus;
        private TaskFactory taskFactory = LimitedConcurrencyLevelTaskSchedulerMsn.Factory;
        SldWorks ISwAppSetter.SwApp => SwApp;
@@ -904,79 +907,6 @@
            //throw new NotImplementedException();
        }
        public Dictionary<string, DrawInfo> GetAllProperties(List<string> ErrMsgs)
        {
            ConcurrentDictionary<string, DrawInfo> result = new ConcurrentDictionary<string, DrawInfo>();
            PdmBom topBom = model.BomTree[0];
            CountdownEvent counter = new CountdownEvent(1);
            _ = ThreadPool.QueueUserWorkItem(
                new WaitCallback(GetAll),
                new object[] {
                    topBom, result, counter, ErrMsgs, 0}
                );
            counter.Wait();
            counter.Dispose();
            return new Dictionary<string, DrawInfo>(result);
        }
        /// <summary>
        /// 获取全部属性
        /// </summary>
        /// <param name="param"></param>
        public void GetAll(object param)
        {
            object[] datas = param as object[];
            PdmBom bom = (PdmBom)datas[0];
            ModelDoc2 sldDoc = bom.doc;
            Component2 component = bom.component;
            ConcurrentDictionary<string, DrawInfo> result = (ConcurrentDictionary<string, DrawInfo>)datas[1];
            CountdownEvent counter = (CountdownEvent)datas[2];
            List<string> ErrMsgs = (List<string>)datas[3];
            int level = (int)datas[4];
            try
            {
                counter.TryAddCount();
                string filepath = bom.partNo;
                if (result.ContainsKey(filepath))
                {
                    return;
                }
                if (!bom.skipCheck)
                {
                    result[filepath] = GetSingleDrawInfo(bom);
                }
                ObservableCollection<PdmBom> children = bom.modules;
                if (children != null)
                {
                    foreach (PdmBom child in children)
                    {
                        _ = ThreadPool.QueueUserWorkItem(
                              new WaitCallback(GetAll),
                              new object[] { child, result, counter, ErrMsgs, 1 });
                    }
                }
                MaskAdorner.ShowMessage(content, filepath);
            }
            catch (Exception e)
            {
                bom.drawInfo.checkRuleResult = 2;
                bom.drawInfo.errMessages = new List<string> { e.Message };
                Logger.Error($"V{PdmUser.LoginUser.pluginVersion},[{bom.filePath}] Read MASS Properies Failed.", e);
            }
            finally
            {
                counter.Signal();
                if (level == 0)
                {
                    counter.Signal();
                }
            }
        }
        /// <summary>
        /// 处理质量,保留6位小数
        /// </summary>
@@ -1028,7 +958,10 @@
            }
            // 文件保存状态
            allProperties["图纸保存状态"] = sldDoc.GetSaveFlag().ToString();
            Dictionary<string, string> properties = CustomPropertyUtil.GetCustomProperties(sldDoc, true);
            Dictionary<string, string> properties = CustomPropertyUtil.GetCustomProperties2(sldDoc, true, new HashSet<string>
            {
                "重量"
            }, null);
            // 图纸属性
            if (properties != null)
            {
@@ -1039,18 +972,39 @@
            }
            if (drawExists)
            {
                string refPath = SwDMUtil.GetDrawingRef(drawFilePath, out string errMsg);
                if (refPath == null)
                string[] refs = SwDMUtil.GetDrawingRef2(drawFilePath, out string err, out int[] status);
                string refPath = "";
                if (refs != null && refs.Length > 0)
                {
                    Logger.Error($"V{PdmUser.LoginUser.pluginVersion}, [{drawFilePath}] Read slddrw Ref Path Failed.[{errMsg}]");
                    foreach (var rf in refs)
                    {
                        if (string.Equals(rf, filepath, StringComparison.CurrentCultureIgnoreCase))
                        {
                            refPath = rf;
                            refPath = Path.GetFileName(refPath);
                            break;
                        }
                    }
                }
                else
                {
                    refPath = Path.GetFileName(refPath);
                    Logger.Error($"V{PdmUser.LoginUser.pluginVersion}, [{drawFilePath}] Read slddrw Ref Path Failed.[{err}]");
                }
                //string refPath = SwDMUtil.GetDrawingRef(drawFilePath, out string errMsg);
                //if (refPath == null)
                //{
                //    Logger.Error($"V{PdmUser.LoginUser.pluginVersion}, [{drawFilePath}] Read slddrw Ref Path Failed.[{errMsg}]");
                //}
                //else
                //{
                //    refPath = Path.GetFileName(refPath);
                //}
                Logger.Debug($"V{PdmUser.LoginUser.pluginVersion},文档路径:【{filepath}】\r\n" +
                    $"工程图路径:【{drawFilePath}】\r\n" +
                    $"文件全称:【{allProperties["文件全称"]}】\r\n" +
                    $"Result:【{string.Join(",", refs ?? new string[] { })}】\r\n" +
                    $"Status:【{string.Join(",", status ?? new int[] { })}】\r\n" +
                    $"引用路径:【{refPath}】");
                allProperties["工程图引用文件"] = refPath;
            }
@@ -1084,13 +1038,14 @@
            ConcurrentDictionary<string, DrawInfo> result = new ConcurrentDictionary<string, DrawInfo>();
            PdmBom topBom = model.BomTree[0];
            CountdownEvent counter = new CountdownEvent(1);
            Task.Run(() =>
            taskFactory.StartNew(() =>
            {
                GetAllByTask(new object[] {
                topBom, result, counter, ErrMsgs, 0 });
            });
            counter.Wait();
            counter.Dispose();
            // 不需要手动释放
            //counter.Dispose();
            return new Dictionary<string, DrawInfo>(result);
        }
@@ -1131,7 +1086,7 @@
                {
                    foreach (PdmBom child in children)
                    {
                        Task.Run(() =>
                        taskFactory.StartNew(() =>
                        {
                            GetAllByTask(new object[] { child, result, counter, ErrMsgs, 1 });
                        });
@@ -1155,44 +1110,6 @@
            }
        }
        /// <summary>
        /// 对当前展示的BOM结构进行规则检查
        /// </summary>
        /// <returns>是否全部通过</returns>
        public bool DoCheckRule(out List<string> messages)
        {
            messages = new List<string>();
            bool allSuccess = true;
            Dictionary<string, DrawInfo> properties = GetAllProperties(messages);
            MaskAdorner.ShowMessage(content, "正在请求数据...");
            Result<Dictionary<string, DrawInfo>> result = Client.PostSyncAction<Dictionary<string, DrawInfo>>(
                new PdmBomParam
                {
                    needCheckProperties = properties
                }, "wpf/bom/openApi/checkRule2");
            Dictionary<string, DrawInfo> checkResult = result.HandleResult();
            foreach (string key in properties.Keys)
            {
                properties[key].checkRuleResult = checkResult[key].checkRuleResult;
                properties[key].errMessages = checkResult[key].errMessages;
                var msgs = checkResult[key].errMessages;
                if (!properties[key].HistoryData && !checkResult[key].checkRuleOk)
                {
                    // 不是历史数据并且有未通过的,标记为false
                    allSuccess = false;
                }
                if (!properties[key].HistoryData && msgs != null && msgs.Count > 0)
                {
                    foreach (string msg in msgs)
                    {
                        messages.Add($"物料【{key}】未通过规则检查!{msg}");
                    }
                }
            }
            return allSuccess;
        }
        public bool DoCheckRuleAsync(out List<string> messages)
        {
            var temp = new List<string>();
@@ -1202,16 +1119,19 @@
            // var factory = LimitedConcurrencyLevelTaskScheduler.Factory;
            CountdownEvent counter = new CountdownEvent(properties.Count);
            int iii = 0;
            var start = DateTime.Now;
            Logger.Debug("DoCheckRuleAsync Start...");
            foreach (KeyValuePair<string, DrawInfo> property in properties)
            {
                /// 这个方法最快,但不好管控,因为不知道属性字典有多大
                Task.Run(() =>
                /// Task.Run 这个方法最快,但不好管控,因为不知道属性字典有多大
                /// taskFactory.StartNew 稳定一点吗?
                taskFactory.StartNew(() =>
                {
                    string key = property.Key;
                    iii++;
                    try
                    {
                        Logger.Error($"{key} checking rule...");
                        Logger.Debug($"{key} checking rule...");
                        DrawInfo checkResult;
                        Result<DrawInfo> result = Client.PostSyncAction<DrawInfo>(property.Value, "wpf/bom/openApi/checkRuleSingle");
                        checkResult = result.HandleResult();
@@ -1407,6 +1327,7 @@
            counter.Wait();
            counter.Dispose();
            messages = temp;
            Logger.Debug($"DoCheckRuleAsync Ended in {(DateTime.Now - start).TotalMilliseconds}ms.");
            return allSuccess;
        }
@@ -1415,7 +1336,7 @@
            IntPtr winformWindow = Process.GetCurrentProcess().MainWindowHandle;
            if (winformWindow != null)
                new WindowInteropHelper(exWin) { Owner = winformWindow };
            exWin.Show();
            exWin.ShowDialog();
        }
        /// <summary>
@@ -1585,7 +1506,7 @@
                    ConcurrentQueue<string> pathCache = new ConcurrentQueue<string>(boms.Select(b => b.filePath).ToList());
                    foreach (PdmBom bom in boms)
                    {
                        Task.Run(() =>
                        taskFactory.StartNew(() =>
                        {
                            try
                            {
@@ -1825,7 +1746,7 @@
                    if (errs.Count > 0)
                    {
                        MultiExWindow exWin = new MultiExWindow(this, "检查结果", errs);
                        exWin.ShowDialog();
                        ShowExWindow(exWin);
                    }
                    else if (bom.checkRuleResult == 3)
                    {
@@ -2165,5 +2086,10 @@
        {
        }
        public void DisabledHandler()
        {
        }
    }
}