chr
2024-10-09 1f645778ae80a3a8801b8bb4d0fcf8feb244ad43
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
using log4net;
using PdmSwPlugin.Commmon.Control;
using PdmSwPlugin.Commmon.Util.UI;
using PdmSwPlugin.Common;
using PdmSwPlugin.Common.Entity.DrawAudit;
using PdmSwPlugin.Common.Entity.Pdm;
using PdmSwPlugin.Common.Entity.System;
using PdmSwPlugin.Common.Interface;
using PdmSwPlugin.Common.Setting;
using PdmSwPlugin.Common.Util;
using PdmSwPlugin.Common.Util.Http;
using SolidWorks.Interop.sldworks;
using SolidWorks.Interop.swconst;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
 
namespace PdmSwPlugin.DrawApprove
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    [PdmSwPlugin(Title = "图纸审批")]
    public partial class DrawApproveControl : UserControl, ISwAppSetter, INotifyPropertyChanged, IActiveDocChangeHandler
    {
        #region ...
        public virtual event PropertyChangedEventHandler PropertyChanged;
 
        public virtual void RaisePropertyChanged(string name)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
        }
 
        public void RaiseAndSetIfChanged<T>(ref T old, T @new, [CallerMemberName] string propertyName = null)
        {
            old = @new;
            if (propertyName != null)
            {
                RaisePropertyChanged(propertyName);
            }
        }
        #endregion
 
        private static ILog Logger = LogManager.GetLogger("DrawApprove");
 
        SldWorks SwApp;
 
        SldWorks ISwAppSetter.SwApp => SwApp;
 
        private readonly HttpClient Client;
        private HttpClientCreator clientCreator { get; set; }
 
        /// <summary>
        /// 全部BOM树状结构
        /// </summary>
        private ObservableCollection<DrawAudit> _dataSource = new ObservableCollection<DrawAudit>();
        public ObservableCollection<DrawAudit> dataSource
        {
            get => _dataSource;
            set
            {
                RaiseAndSetIfChanged(ref _dataSource, value);
                if (value == null)
                {
                    StatusBarText = $"共 0 条";
                }
                else
                {
                    StatusBarText = $"共 {value.Count} 条";
                }
                RefreshSelectedCount();
            }
        }
 
        private string _SelectBomText = "已选中 0 条";
        public string SelectBomText
        {
            get => _SelectBomText;
            set => RaiseAndSetIfChanged(ref _SelectBomText, value);
        }
 
        private string _StatusBarText = "共 0 条";
 
        public string StatusBarText
        {
            get { return _StatusBarText; }
            set => RaiseAndSetIfChanged(ref _StatusBarText, value);
        }
 
 
 
        public DrawApproveControl() : this(null)
        {
 
        }
 
        public DrawApproveControl(SldWorks swAddin)
        {
            SwApp = swAddin;
            InitializeComponent();
            clientCreator = new HttpClientCreator(new HttpConfig(PluginSetting.Instance.BaseAddress));
            Client = clientCreator.GetClient();
            DataContext = this;
        }
 
        public void SetSwApp(SldWorks SwApp)
        {
            this.SwApp = SwApp;
        }
 
        /// <summary>
        /// 全选事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GlobalCheckBox_Checked(object sender, RoutedEventArgs e)
        {
            CheckBox cb = sender as CheckBox;
            List<DrawAudit> datas = dataSource.ToList();
            foreach (DrawAudit data in datas)
            {
                data.selected = cb.IsChecked.Value;
            }
            int count = cb.IsChecked.Value ? (dataSource == null ? 0 : dataSource.Count) : 0;
            SelectBomText = $"已选中 {count} 条";
        }
 
        private void RefreshSelectedCount()
        {
            if (dataSource == null || dataSource.Count <= 0)
            {
                SelectBomText = "已选中 0 条";
                return;
            }
            int count = dataSource.Where(e => e.selected).Count();
            SelectBomText = $"已选中 {count} 条";
        }
 
        /// <summary>
        /// 单个点选事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SingleCheckBox_Event(object sender, RoutedEventArgs e)
        {
            RefreshSelectedCount();
        }
 
 
 
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            MaskAdorner.ShowMask(content, "请求中,请稍后...");
            Task.Run(() =>
            {
                try
                {
                    List<DrawAudit> datas = RefreshList();
                    Dispatcher.Invoke(() =>
                    {
                        dataSource = new ObservableCollection<DrawAudit>(datas);
 
                    });
                }
                catch (Exception ex)
                {
                    Logger.Error($"V{PdmUser.LoginUser.pluginVersion}, UI update failed.", ex);
                    this.Error($"V{PdmUser.LoginUser.pluginVersion},UI更新列表失败!异常:{ex}");
                    dataSource = new ObservableCollection<DrawAudit>();
                }
                finally
                {
                    MaskAdorner.HideMask(content);
                }
            });
        }
 
        private void OpenDocMayError(string filePath, int docType, int option, string config)
        {
            int err = 0, warn = 0;
            SwApp.OpenDoc6(filePath, docType, option, config, ref err, ref warn);
            if (err == (int)swFileLoadError_e.swAddinInteruptError)
            {
                this.Error("打开失败!用户尝试打开文件,然后中断打开文件例程以打开其他文件");
            }
            else if (err == (int)swFileLoadError_e.swApplicationBusy)
            {
                this.Error("打开失败!Solidworks繁忙");
            }
            else if (err == (int)swFileLoadError_e.swFileCriticalDataRepairError)
            {
                this.Error("打开失败!文档存在严重数据损坏");
            }
            else if (err == (int)swFileLoadError_e.swFileNotFoundError)
            {
                this.Error("打开失败!无法找到文件;未加载文件或禁止显示引用的文件(即组件)");
            }
            else if (err == (int)swFileLoadError_e.swFileRequiresRepairError)
            {
                this.Error("打开失败!文档具有非关键自定义属性数据损坏");
            }
            else if (err == (int)swFileLoadError_e.swFutureVersion)
            {
                this.Error("打开失败!文档已保存在 SOLIDWORKS 的未来版本中");
            }
            else if (err == (int)swFileLoadError_e.swInvalidFileTypeError)
            {
                this.Error("打开失败!文件类型参数无效");
            }
            else if (err == (int)swFileLoadError_e.swLiquidMachineDoc)
            {
                this.Error("打开失败!由 Liquid Machines 加密的文件");
            }
            else if (err == (int)swFileLoadError_e.swLowResourcesError)
            {
                this.Error("打开失败!文件被打开并被阻止,因为系统内存不足,或者 GDI 句柄数已超过允许的最大值");
            }
            else if (err == (int)swFileLoadError_e.swNoDisplayData)
            {
                this.Error("打开失败!文件不包含显示数据");
            }
            else if (err == (int)swFileLoadError_e.swFileWithSameTitleAlreadyOpen)
            {
                this.Error("打开失败!具有相同名称的文档已打开");
                //SwApp.ActivateDoc3(filePath, false, 0, ref err);
                //if (err == 2)
                //{
                //    this.Error("需要重新生成已激活的文档");
                //}
                //else if (err == 1)
                //{
                //    this.Error("遇到不明错误,并且未激活文档");
                //}
            }
            else if (err != 0)
            {
                Logger.Error($"V{PdmUser.LoginUser.pluginVersion}, OpenDoc6 Failed,Error:{err}.See Solidworks Doc.");
            }
            else if (warn == 128)
            {
                SwApp.ActivateDoc3(filePath, false, 0, ref err);
                if (err == 2)
                {
                    this.Error("需要重新生成已激活的文档");
                }
                else if (err == 1)
                {
                    this.Error("遇到不明错误,并且未激活文档");
                }
            }
        }
 
        private void OpenDrw_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            DrawAudit da = btn.DataContext as DrawAudit;
            string filePath = GetRealFilePath(da.d2RelativePath);
            if (!File.Exists(filePath))
            {
                this.Error($"服务器中未找到工程图文件,路径:{filePath}");
                return;
            }
            OpenDocMayError(filePath, (int)swDocumentTypes_e.swDocDRAWING, (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly,
                "");
        }
 
        private string GetRealFilePath(string relativePath)
        {
            // string fileName = Path.GetFileName(dbPath);
            // string filePath = Path.Combine(PluginSetting.Instance.SwFilePath, dbPath);
            string filePath = PluginSetting.Instance.SwFilePath + relativePath;
            return filePath;
        }
 
        private void OpenDoc_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            DrawAudit da = btn.DataContext as DrawAudit;
            string filePath = GetRealFilePath(da.d3RelativePath);
            if (!File.Exists(filePath))
            {
                this.Error($"服务器中未找到图纸文件,路径:{filePath}");
                return;
            }
 
            OpenDocMayError(filePath, (int)FileExtentionChecker.Check(filePath, out _), (int)swOpenDocOptions_e.swOpenDocOptions_ReadOnly,
                 "");
        }
 
        public List<DrawAudit> RefreshList()
        {
            try
            {
                string statusArr = string.Empty;
                Dispatcher.Invoke(() =>
                {
                    List<string> arr = new List<string>();
                    if (subcb.IsChecked == true) arr.Add("submitted");
                    if (resubcb.IsChecked == true) arr.Add("resubmitted");
                    if (comcb.IsChecked == true) arr.Add("completed");
                    if (rejcb.IsChecked == true) arr.Add("rejected");
                    if (arr.Count > 0)
                    {
                        statusArr = $"'{string.Join("','", arr)}'";
                    }
                });
                Result<List<DrawAudit>> res = Client.GetSyncAction<List<DrawAudit>>("drawAudit/listWithTask2", new DrawAudit
                {
                    statusArr = statusArr
                });
                return res.HandleResult();
            }
            catch (Exception ex)
            {
                Logger.Error($"V{PdmUser.LoginUser.pluginVersion}, Get draw audit data list failed.", ex);
                this.Error($"V{PdmUser.LoginUser.pluginVersion},刷新列表失败!异常:{ex.Message}");
                return new List<DrawAudit>();
            }
        }
 
        public void CloseAuditedDoc(DrawAudit da)
        {
            try
            {
                string modelPath = GetRealFilePath(da.d3RelativePath);
                string drawingPath = GetRealFilePath(da.d2RelativePath);
                SwApp.CloseDoc(modelPath);
                SwApp.CloseDoc(drawingPath);
            }
            catch (Exception exx)
            {
                Logger.Error($"V{PdmUser.LoginUser.pluginVersion}, Auto close open doc failed.", exx);
            }
        }
 
        /// <summary>
        /// 单条数据通过按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Resolve_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            DrawAudit da = btn.DataContext as DrawAudit;
            if (da.status != "submitted" && da.status != "resubmitted")
            {
                this.Warning("请选择已提交的数据");
                return;
            }
            MessageBoxResult mr = MessageBox.Show($"确定通过物料【{da.materialCode}】的图纸审批吗?", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (mr == MessageBoxResult.OK)
            {
                MaskAdorner.ShowMask(content, "请求中,请稍候...");
                Task.Run(() =>
                {
                    try
                    {
                        string filePath = GetRealFilePath(da.d3RelativePath);
                        if (!File.Exists(filePath))
                        {
                            this.Error($"服务器中未找到图纸文件,路径:{filePath}");
                            return;
                        }
 
                        double[] massData = SwDMUtil.GetMassProperty(filePath, out string errMsg);
                        if (massData == null)
                        {
                            this.Error($"获取图纸一致性数据失败!{errMsg}");
                            return;
                        }
                        da.fileName = Path.GetFileName(filePath);
                        da.volume = NumberUtil.HandleMass(massData[3]);
                        da.surfaceArea = NumberUtil.HandleMass(massData[4]);
                        da.mass = NumberUtil.HandleMass(massData[5]);
                        da.pass = true;
                        Result<object> res = Client.PostSyncAction<object>(da, "drawAudit/complete");
                        object obj = res.HandleResult();
                        CloseAuditedDoc(da);
                        Dispatcher.Invoke(() =>
                        {
                            dataSource = new ObservableCollection<DrawAudit>(RefreshList());
                        });
                    }
                    catch (Exception ex)
                    {
                        Logger.Error($"V{PdmUser.LoginUser.pluginVersion}, Draw complete failed.", ex);
                        this.Error($"V{PdmUser.LoginUser.pluginVersion},审核失败!{ex.Message}");
                    }
                    finally
                    {
                        MaskAdorner.HideMask(content);
                    }
                });
            }
        }
 
        /// <summary>
        /// 单条数据撤销按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Reset_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            DrawAudit da = btn.DataContext as DrawAudit;
            if (da.status == "submitted" && da.status == "resubmitted")
            {
                this.Warning("请选择审核过的数据");
                return;
            }
            MessageBoxResult mr = MessageBox.Show($"确定撤销物料【{da.materialCode}】的图纸审批吗?", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if (mr == MessageBoxResult.OK)
            {
                MaskAdorner.ShowMask(content, "请求中,请稍候...");
                Task.Run(() =>
                {
                    try
                    {
                        Result<object> res = Client.PostSyncAction<object>(da, "drawAudit/reset");
                        object obj = res.HandleResult();
                        // CloseAuditedDoc(da);
                        Dispatcher.Invoke(() =>
                        {
                            dataSource = new ObservableCollection<DrawAudit>(RefreshList());
                        });
                    }
                    catch (Exception ex)
                    {
                        Logger.Error($"V{PdmUser.LoginUser.pluginVersion}, Draw Reset failed.", ex);
                        this.Error($"V{PdmUser.LoginUser.pluginVersion},撤销失败!{ex.Message}");
                    }
                    finally
                    {
                        MaskAdorner.HideMask(content);
                    }
                });
            }
        }
 
        /// <summary>
        /// 单条数据驳回按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Reject_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            DrawAudit da = btn.DataContext as DrawAudit;
            if (da.status != "submitted" && da.status != "resubmitted")
            {
                this.Warning("请选择已提交的数据");
                return;
            }
            //RejectWindow window = new RejectWindow($"{da.materialCode}驳回说明", da, Client, Logger, SwApp);
            //window.ShowDialog();
 
            XamlWindow window = new XamlWindow($"{da.materialCode}驳回说明", da, Client, Logger, SwApp);
            if (window.ShowDialog() == true)
            {
                CloseAuditedDoc(da);
            }
 
            //WebWindow window = new WebWindow(da);
            //window.ShowDialog();
 
            Dispatcher.Invoke(() =>
            {
                dataSource = new ObservableCollection<DrawAudit>(RefreshList());
            });
        }
 
        private void TextBlock_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // 检查是否是双击
            if (e.ClickCount == 2)
            {
                TextBlock textBlock = sender as TextBlock;
                DrawAudit data = textBlock.DataContext as DrawAudit;
                MaskAdorner.ShowMask(content, "请求中,请稍后...");
                Task.Run(() =>
                {
                    try
                    {
                        Result<List<DrawAuditHis>> res = Client.GetSyncAction<List<DrawAuditHis>>("drawAudit/listTaskHis", new DrawAudit
                        {
                            id = data.id
                        });
                        var datas = res.HandleResult();
                        Dispatcher.Invoke(() =>
                        {
                            //DrawAuditHisWindow window = new DrawAuditHisWindow(this, $"【{bom.partModel}】审核详情", datas);
                            RichHisWindow window = new RichHisWindow(this, $"【{data.materialCode}】审核详情", datas);
 
                            window.ShowDialog();
                        });
                    }
                    catch (Exception ex)
                    {
                        Logger.Error($"V{PdmUser.LoginUser.pluginVersion},Get draw audit history failed.", ex);
                        this.Error($"V{PdmUser.LoginUser.pluginVersion},获取审核历史失败!{ex.Message}");
                    }
                    finally
                    {
                        MaskAdorner.HideMask(content);
                    }
                });
            }
        }
 
        public void OnSwActiveDocChange(ModelDoc2 oldDoc, ModelDoc2 newDoc, Component2 comp)
        {
            string path = newDoc.GetPathName();
            Uri fileName;
            if (string.IsNullOrEmpty(path))
            {
                fileName = null;
            }
            else
            {
                fileName = new Uri(newDoc.GetPathName());
            }
            foreach (var e in dataSource)
            {
                var d2Path = new Uri(GetRealFilePath(e.d2RelativePath));
                var d3Path = new Uri(GetRealFilePath(e.d3RelativePath));
                e.IsOpening = fileName == d2Path || fileName == d3Path;
            }
        }
 
        public void OnSwActiveDocSaved(ModelDoc2 doc, Component2 comp)
        {
 
        }
 
        public void OnCustomPropertyChange(string propName, string Configuration, string oldValue, string NewValue, int valueType)
        {
 
        }
 
        public void OnDocDestroy(ModelDoc2 doc)
        {
 
        }
 
        public void AfterDocDestroy()
        {
 
        }
    }
}