1
zrg
3 天以前 6eab75d496ba3d08bd849c5c7193789aa18da30a
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
using System;
using System.Data;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Configuration;
using gregn6Lib;
using BLL;
using System.Drawing;
 
namespace BarcodePrintEngine
{
    public partial class Gy_BarcodePrint : Form
    {
        public DBHelper oCn = new DBHelper();
 
        // 列索引常
        private const int COL_ID = 0;          
        private const int COL_BARCODE = 1;    
        private const int COL_MATERIALCODE = 2; 
        private const int COL_MATERIALNAME = 3;
        private const int COL_QTY = 4;        
        private const int COL_ISPRINTED = 5;   
        private const int COL_PRINTDATE = 6;  
        private const int COL_PRINTERNAME = 7; 
 
        // 报表相关
        private GridppReport Report;
        private DataGridView _printGrid;
        private int _selectColIndex = -1;
 
        // 自动打印防重入标志
        private bool isAutoPrinting = false;
 
        // 配置文件路径(设备别名和打印机共用)
        private readonly string deviceConfigPath;
 
        public Gy_BarcodePrint()
        {
            InitializeComponent();
 
            // 设置配置文件路径
            deviceConfigPath = AppDomain.CurrentDomain.BaseDirectory + "./Config/Device.config";
 
            this.StartPosition = FormStartPosition.CenterScreen;
            this.Load += Gy_BarcodePrint_Load;
 
            // 从配置文件加载打印机
            LoadDefaultPrinterFromConfig();
            InitGrids();
 
            // 绑定设备别名事件
            txtDeviceAlias.Leave += TxtDeviceAlias_Leave;
            txtDeviceAlias.KeyDown += TxtDeviceAlias_KeyDown;
            txtDeviceAlias.TextChanged += TxtDeviceAlias_TextChanged;
            txtPrinter.TextChanged += TxtPrinter_TextChanged;
 
            // 初始状态:按钮禁用,定时器未启动
            btnToggleAutoPrint.Enabled = false;
            timer1.Interval = 60000;
            timer1.Stop();
        }
 
        #region 配置文件读写(通用)
 
        /// <summary>
        /// 确保配置文件存在,若不存在则创建空的 appSettings 文件
        /// </summary>
        private void EnsureConfigFileExists(string configPath)
        {
            if (File.Exists(configPath)) return;
 
            string dir = Path.GetDirectoryName(configPath);
            if (!Directory.Exists(dir))
                Directory.CreateDirectory(dir);
 
            string content = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <appSettings>
  </appSettings>
</configuration>";
            File.WriteAllText(configPath, content, Encoding.UTF8);
        }
 
        /// <summary>
        /// 从指定配置文件读取键值
        /// </summary>
        private string GetConfigKey(string configPath, string key)
        {
            EnsureConfigFileExists(configPath);
            var config = ConfigurationManager.OpenMappedExeConfiguration(
                new ExeConfigurationFileMap { ExeConfigFilename = configPath },
                ConfigurationUserLevel.None);
            return config.AppSettings.Settings[key]?.Value ?? string.Empty;
        }
 
        /// <summary>
        /// 向指定配置文件写入键值
        /// </summary>
        private void SetConfigKey(string configPath, string key, string value)
        {
            EnsureConfigFileExists(configPath);
            var config = ConfigurationManager.OpenMappedExeConfiguration(
                new ExeConfigurationFileMap { ExeConfigFilename = configPath },
                ConfigurationUserLevel.None);
            if (config.AppSettings.Settings[key] == null)
                config.AppSettings.Settings.Add(key, value);
            else
                config.AppSettings.Settings[key].Value = value;
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");
        }
 
        #endregion
 
        #region 打印机配置(改用配置文件)
 
        /// <summary>
        /// 从配置文件加载默认打印机
        /// </summary>
        private void LoadDefaultPrinterFromConfig()
        {
            string saved = GetConfigKey(deviceConfigPath, "DefaultPrinter");
            if (!string.IsNullOrEmpty(saved) && PrinterSettings.InstalledPrinters.Cast<string>().Contains(saved))
                txtPrinter.Text = saved;
            else
                txtPrinter.Text = "(未选择)";
        }
 
        /// <summary>
        /// 保存默认打印机到配置文件
        /// </summary>
        private void SaveDefaultPrinterToConfig(string printerName)
        {
            SetConfigKey(deviceConfigPath, "DefaultPrinter", printerName);
        }
 
        #endregion
 
        #region 窗体加载 – 读取配置、加载数据,但不启动定时器
        private void Gy_BarcodePrint_Load(object sender, EventArgs e)
        {
            // 读取设备别名
            string alias = GetConfigKey(deviceConfigPath, "DeviceAlias");
            txtDeviceAlias.Text = alias ?? "";
 
            // 加载数据(按别名过滤)
            LoadData();
 
            // 检查条件更新启动按钮状态
            UpdateStartButtonState();
 
            LogService.Write("条码打印程序启动,等待用户启动自动打印服务。");
        }
        #endregion
 
        #region 启动/停止自动打印按钮
        private void btnToggleAutoPrint_Click(object sender, EventArgs e)
        {
            if (timer1.Enabled)
            {
                // 正在运行 → 准备停止,先确认
                DialogResult result = MessageBox.Show(
                    "确认停止自动打印程序吗?",
                    "确认停止",
                    MessageBoxButtons.YesNo,
                    MessageBoxIcon.Question
                );
                if (result == DialogResult.Yes)
                {
                    timer1.Stop();
                    btnToggleAutoPrint.Text = "启动";
                    btnToggleAutoPrint.BackColor = Color.LightGreen;
                    LogService.Write("自动打印服务已停止。");
                }
                // 如果用户取消,不执行任何操作
            }
            else
            {
                // 未运行 → 启动
                if (!IsPrinterAndAliasValid())
                {
                    MessageBox.Show("请先选择有效的打印机并填写设备别名。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                timer1.Start();
                btnToggleAutoPrint.Text = "停止";
                btnToggleAutoPrint.BackColor = Color.Orange;
                LogService.Write("自动打印服务已启动。");
            }
        }
 
        /// <summary>
        /// 检查打印机和别名是否有效
        /// </summary>
        private bool IsPrinterAndAliasValid()
        {
            string printer = txtPrinter.Text.Trim();
            string alias = txtDeviceAlias.Text.Trim();
            bool printerOk = !string.IsNullOrEmpty(printer) && printer != "(未选择)" && PrinterSettings.InstalledPrinters.Cast<string>().Contains(printer);
            bool aliasOk = !string.IsNullOrEmpty(alias);
            return printerOk && aliasOk;
        }
 
        /// <summary>
        /// 更新启动按钮的启用状态
        /// </summary>
        private void UpdateStartButtonState()
        {
            if (!timer1.Enabled)
            {
                // 停止状态
                bool canStart = IsPrinterAndAliasValid();
                btnToggleAutoPrint.Enabled = canStart;
                if (canStart)
                {
                    btnToggleAutoPrint.Text = "启动";
                    btnToggleAutoPrint.BackColor = Color.LightGreen;
                }
                else
                {
                    // 当条件不满足时,按钮不可用,颜色可置灰或恢复默认
                    btnToggleAutoPrint.Text = "启动";
                    btnToggleAutoPrint.BackColor = SystemColors.Control; // 或保留绿色但禁用,视觉上灰色会覆盖
                }
            }
            else
            {
                // 运行状态
                btnToggleAutoPrint.Enabled = true;
                btnToggleAutoPrint.Text = "停止";
                btnToggleAutoPrint.BackColor = Color.Orange;
            }
        }
 
        private void TxtPrinter_TextChanged(object sender, EventArgs e)
        {
            if (timer1.Enabled)
            {
                timer1.Stop();
                btnToggleAutoPrint.Text = "启动";
                LogService.Write("打印机变更,自动打印服务已自动停止。");
            }
            UpdateStartButtonState();
        }
 
        private void TxtDeviceAlias_TextChanged(object sender, EventArgs e)
        {
            if (timer1.Enabled)
            {
                timer1.Stop();
                btnToggleAutoPrint.Text = "启动";
                LogService.Write("设备别名变更,自动打印服务已自动停止。");
            }
            UpdateStartButtonState();
        }
        #endregion
 
        #region 设备别名 – 保存与刷新
        private void TxtDeviceAlias_Leave(object sender, EventArgs e)
        {
            SaveDeviceAlias();
        }
 
        private void TxtDeviceAlias_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                SaveDeviceAlias();
                e.SuppressKeyPress = true;
            }
        }
 
        private void SaveDeviceAlias()
        {
            string alias = txtDeviceAlias.Text.Trim();
            SetConfigKey(deviceConfigPath, "DeviceAlias", alias);
            LoadData(); // 刷新数据
            LogService.Write($"设备别名已更新为:{alias}");
        }
        #endregion
 
        #region 定时器 Tick – 自动打印逻辑
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (isAutoPrinting) return;
            isAutoPrinting = true;
 
            try
            {
                this.Invoke(new Action(() =>
                {
                    string alias = txtDeviceAlias.Text.Trim();
                    if (string.IsNullOrEmpty(alias))
                    {
                        LogService.Write("自动打印: 未设置设备别名,跳过");
                        return;
                    }
 
                    if (string.IsNullOrEmpty(txtPrinter.Text) || txtPrinter.Text == "(未选择)")
                    {
                        LogService.Write("自动打印: 未选择打印机,跳过");
                        return;
                    }
 
                    string templateName = GetConfigKey(AppDomain.CurrentDomain.BaseDirectory + "./Config/PWD.config", "PrintTemplate");
                    if (string.IsNullOrEmpty(templateName) || templateName == "undefined")
                    {
                        LogService.Write("自动打印: 未配置打印模板,跳过");
                        return;
                    }
 
                    string safeAlias = alias.Replace("'", "''");
 
                    string sql = $@"
                        SELECT 
                            a.HItemId AS id,
                            a.HBarCode AS 条码编号,
                            a.HQty AS 数量,
                            a.HIsPrintSuccess AS 是否打印成功,
                            a.HLastPrintDate AS 打印时间,
                            a.HPrintName AS 打印机名称
                        FROM Gy_BarCodeBill_Split a
                        INNER JOIN Gy_Material b ON a.HMaterID = b.HItemID
                        WHERE a.HIsPrintSuccess = 0 AND ISNULL(a.HPrintName,'') = '{safeAlias}'
                        ORDER BY a.HItemId";
 
                    DataSet ds = oCn.RunProcReturn(sql, "AutoPrintQuery");
                    if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                        return;
 
                    List<string> barcodeList = new List<string>();
                    List<int> idList = new List<int>();
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        string barcode = dr["条码编号"].ToString().Trim();
                        if (string.IsNullOrEmpty(barcode)) continue;
                        barcodeList.Add(barcode.Replace("'", "''"));
                        idList.Add(Convert.ToInt32(dr["id"]));
                    }
 
                    if (barcodeList.Count == 0) return;
 
                    string inClause = string.Join(",", barcodeList.Select(b => "'" + b + "'"));
                    string viewSql = $@"
                        SELECT 
                            条码编号,
                            物料代码,
                            物料名称,
                            规格型号,
                            批号,
                            数量,
                            供应商,
                            组托单号,
                            生产日期,
                            源单单号
                        FROM h_v_IF_BarCodeBillList_Split
                        WHERE 条码编号 IN ({inClause})";
 
                    DataSet dsView = oCn.RunProcReturn(viewSql, "AutoPrintView");
                    if (dsView == null || dsView.Tables.Count == 0 || dsView.Tables[0].Rows.Count == 0)
                        return;
 
                    DataTable dtPrint = new DataTable();
                    dtPrint.Columns.Add("条码编号", typeof(string));
                    dtPrint.Columns.Add("物料代码", typeof(string));
                    dtPrint.Columns.Add("物料名称", typeof(string));
                    dtPrint.Columns.Add("规格型号", typeof(string));
                    dtPrint.Columns.Add("批号", typeof(string));
                    dtPrint.Columns.Add("数量", typeof(string));
                    dtPrint.Columns.Add("供应商", typeof(string));
                    dtPrint.Columns.Add("组托单号", typeof(string));
                    dtPrint.Columns.Add("生产日期", typeof(string));
                    dtPrint.Columns.Add("源单单号", typeof(string));
 
                    foreach (DataRow dr in dsView.Tables[0].Rows)
                    {
                        DataRow newRow = dtPrint.NewRow();
                        newRow["条码编号"] = dr["条码编号"].ToString();
                        newRow["物料代码"] = dr["物料代码"].ToString();
                        newRow["物料名称"] = dr["物料名称"].ToString();
                        newRow["规格型号"] = dr["规格型号"].ToString();
                        newRow["批号"] = dr["批号"].ToString();
                        object qty = dr["数量"];
                        newRow["数量"] = qty == DBNull.Value ? "0" : Convert.ToDecimal(qty).ToString("0");
                        newRow["供应商"] = dr["供应商"].ToString();
                        newRow["组托单号"] = dr["组托单号"].ToString();
                        object prodDate = dr["生产日期"];
                        newRow["生产日期"] = prodDate == DBNull.Value ? "" : Convert.ToDateTime(prodDate).ToString("yyyy-MM-dd");
                        newRow["源单单号"] = dr["源单单号"].ToString();
                        dtPrint.Rows.Add(newRow);
                    }
 
                    DataGridView tempGrid = new DataGridView();
                    tempGrid.DataSource = dtPrint;
                    DataGridViewCheckBoxColumn selectCol = new DataGridViewCheckBoxColumn();
                    selectCol.HeaderText = "选择";
                    selectCol.Name = "选择";
                    tempGrid.Columns.Insert(0, selectCol);
                    foreach (DataGridViewRow row in tempGrid.Rows)
                    {
                        row.Cells["选择"].Value = true;
                    }
 
                    Sub_SetReport(templateName, tempGrid);
                    Report.Printer.PrinterName = txtPrinter.Text.Trim();
                    //Report.PrintPreview(true);  // 弹出预览窗口
                    Report.Print(false);
 
                    if (idList.Count > 0)
                    {
                        string ids = string.Join(",", idList);
                        string updateSql = $@"UPDATE Gy_BarCodeBill_Split SET HIsPrintSuccess = 1, HLastPrintDate = GETDATE() WHERE HItemId IN ({ids})";
                        oCn.RunProc(updateSql);
                    }
 
                    LoadData();
                    LogService.Write($"自动打印完成,共打印 {barcodeList.Count} 个条码。");
                }));
            }
            catch (Exception ex)
            {
                LogService.Write("自动打印异常:" + ex.Message);
            }
            finally
            {
                isAutoPrinting = false;
            }
        }
        #endregion
 
        #region 打印机选择(使用配置文件)
        private void btnSelectPrinter_Click(object sender, EventArgs e)
        {
            using (PrintDialog pd = new PrintDialog())
            {
                pd.PrinterSettings = new PrinterSettings();
                if (pd.ShowDialog() == DialogResult.OK)
                {
                    string printer = pd.PrinterSettings.PrinterName;
                    txtPrinter.Text = printer;
                    SaveDefaultPrinterToConfig(printer);
                }
            }
        }
        #endregion
 
        #region 表格初始化
        private void InitGrids()
        {
            grdUnprinted.ColumnCount = 8;
            grdUnprinted.Columns[COL_ID].HeaderText = "ID";
            grdUnprinted.Columns[COL_ID].Visible = false;
            grdUnprinted.Columns[COL_BARCODE].HeaderText = "条码编号";
            grdUnprinted.Columns[COL_BARCODE].Width = 200;
            grdUnprinted.Columns[COL_MATERIALCODE].HeaderText = "物料代码";
            grdUnprinted.Columns[COL_MATERIALCODE].Width = 120;
            grdUnprinted.Columns[COL_MATERIALNAME].HeaderText = "物料名称";
            grdUnprinted.Columns[COL_MATERIALNAME].Width = 200;
            grdUnprinted.Columns[COL_QTY].HeaderText = "数量";
            grdUnprinted.Columns[COL_QTY].Width = 70;
            grdUnprinted.Columns[COL_ISPRINTED].HeaderText = "是否打印";
            grdUnprinted.Columns[COL_ISPRINTED].Width = 100;
            grdUnprinted.Columns[COL_PRINTDATE].HeaderText = "打印时间";
            grdUnprinted.Columns[COL_PRINTDATE].Width = 150;
            grdUnprinted.Columns[COL_PRINTERNAME].HeaderText = "打印机名称";
            grdUnprinted.Columns[COL_PRINTERNAME].Width = 200;
 
            grdUnprinted.ReadOnly = true;
            grdUnprinted.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            grdUnprinted.MultiSelect = true;
 
 
            grdPrinted.ColumnCount = 8;
            grdPrinted.Columns[COL_ID].HeaderText = "ID";
            grdPrinted.Columns[COL_ID].Visible = false;
            grdPrinted.Columns[COL_BARCODE].HeaderText = "条码编号";
            grdPrinted.Columns[COL_BARCODE].Width = 200;
            grdPrinted.Columns[COL_MATERIALCODE].HeaderText = "物料代码";
            grdPrinted.Columns[COL_MATERIALCODE].Width = 120;
            grdPrinted.Columns[COL_MATERIALNAME].HeaderText = "物料名称";
            grdPrinted.Columns[COL_MATERIALNAME].Width = 200;
            grdPrinted.Columns[COL_QTY].HeaderText = "数量";
            grdPrinted.Columns[COL_QTY].Width = 70;
            grdPrinted.Columns[COL_ISPRINTED].HeaderText = "是否打印";
            grdPrinted.Columns[COL_ISPRINTED].Width = 100;
            grdPrinted.Columns[COL_PRINTDATE].HeaderText = "打印时间";
            grdPrinted.Columns[COL_PRINTDATE].Width = 180;
            grdPrinted.Columns[COL_PRINTERNAME].HeaderText = "打印机名称";
            grdPrinted.Columns[COL_PRINTERNAME].Width = 200;
 
            grdPrinted.ReadOnly = true;
            grdPrinted.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            grdPrinted.MultiSelect = true;
 
        }
        #endregion
 
        #region 加载数据
        private void LoadData()
        {
            try
            {
                string alias = txtDeviceAlias.Text.Trim();
                if (string.IsNullOrEmpty(alias))
                {
                    grdUnprinted.Rows.Clear();
                    grdPrinted.Rows.Clear();
                    return;
                }
                string safeAlias = alias.Replace("'", "''");
 
                string sql = $@"
                    SELECT 
                        a.HItemId AS id,                    
                        a.HBarCode AS 条码编号,
                        b.HNumber AS 物料代码,
                        b.HName AS 物料名称,
                        a.HQty AS 数量,
                        a.HIsPrintSuccess AS 是否打印成功,
                        a.HLastPrintDate AS 打印时间,
                        a.HPrintName AS 打印机名称
                    FROM Gy_BarCodeBill_Split a
                    INNER JOIN Gy_Material b ON a.HMaterID = b.HItemID
                    WHERE ISNULL(a.HPrintName,'') = '{safeAlias}'
                    ORDER BY a.HItemId";
 
                DataSet ds = oCn.RunProcReturn(sql, "LoadBarCodeSplit");
                if (ds == null || ds.Tables.Count == 0 || ds.Tables[0].Rows.Count == 0)
                {
                    grdUnprinted.Rows.Clear();
                    grdPrinted.Rows.Clear();
                    return;
                }
 
                grdUnprinted.Rows.Clear();
                grdPrinted.Rows.Clear();
 
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    object[] rowData = new object[8];  // 8列
                    rowData[COL_ID] = dr["id"];
                    rowData[COL_BARCODE] = dr["条码编号"].ToString();
                    rowData[COL_MATERIALCODE] = dr["物料代码"]?.ToString() ?? "";
                    rowData[COL_MATERIALNAME] = dr["物料名称"]?.ToString() ?? "";
 
                    // 数量(索引4)
                    object qtyObj = dr["数量"];
                    if (qtyObj == DBNull.Value || qtyObj == null)
                        rowData[COL_QTY] = "0";
                    else
                    {
                        try { decimal qty = Convert.ToDecimal(qtyObj); rowData[COL_QTY] = qty.ToString("0"); }
                        catch { rowData[COL_QTY] = qtyObj.ToString(); }
                    }
 
                    // 是否打印(索引5)
                    bool isPrinted = (dr["是否打印成功"] != DBNull.Value && Convert.ToBoolean(dr["是否打印成功"]));
                    rowData[COL_ISPRINTED] = isPrinted ? "是" : "否";
 
                    // 打印时间(索引6)
                    rowData[COL_PRINTDATE] = dr["打印时间"] == DBNull.Value ? "" : Convert.ToDateTime(dr["打印时间"]).ToString("yyyy-MM-dd HH:mm");
 
                    // 打印机名称(索引7)
                    rowData[COL_PRINTERNAME] = dr["打印机名称"].ToString();
 
                    if (isPrinted)
                        grdPrinted.Rows.Add(rowData);
                    else
                        grdUnprinted.Rows.Add(rowData);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("加载数据失败:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                LogService.Write("LoadData异常:" + ex.Message);
            }
        }
        #endregion
 
        #region 打印功能(通用)
        public static String GetConfigKey_Print(String configPath, String key)
        {
            Configuration ConfigurationInstance =ConfigurationManager.OpenMappedExeConfiguration(
                    new ExeConfigurationFileMap()
                    {
                        ExeConfigFilename = configPath
                    },
                    ConfigurationUserLevel.None);
 
            if (ConfigurationInstance.AppSettings.Settings[key] != null)
                return ConfigurationInstance.AppSettings.Settings[key].Value;
            else
                return string.Empty;
        }
 
        private void Sub_SetReport(string templateName, DataGridView grid)
        {
            Report = new GridppReport();
            string fullPath = Pub_Class.ClsPub.AppPath + @"" + templateName + ".grf";
            Report.LoadFromFile(fullPath);
            Report.BeforePostRecord += new _IGridppReportEvents_BeforePostRecordEventHandler(ReportBeforePostRecord);
            Report.FetchRecord += new _IGridppReportEvents_FetchRecordEventHandler(ReportFetchRecordByDataTable);
 
            _printGrid = grid;
            _selectColIndex = Fun_GetCol("选择", grid);
        }
 
        private void ReportBeforePostRecord() { }
 
        private void ReportFetchRecordByDataTable()
        {
            try
            {
                DataTable dt = null;
 
                // 从 DataGridView 的数据源中获取 DataTable
                if (_printGrid.DataSource is DataTable)
                {
                    dt = (DataTable)_printGrid.DataSource;
                }
                else if (_printGrid.DataSource is DataView)
                {
                    dt = ((DataView)_printGrid.DataSource).Table;
                }
                else if (_printGrid.DataSource is BindingSource)
                {
                    var bs = (BindingSource)_printGrid.DataSource;
                    if (bs.DataSource is DataTable) dt = (DataTable)bs.DataSource;
                    else if (bs.DataSource is DataView) dt = ((DataView)bs.DataSource).Table;
                }
 
                if (dt == null)
                {
                    LogService.Write("打印数据源不是 DataTable/DataView,无法填充报表");
                    return;
                }
            
                Utility.FillRecordToReport(Report, dt);
            }
            catch (Exception ex)
            {
                LogService.Write("ReportFetchRecordByDataTable异常:" + ex.Message);
            }
        }
 
        private int Fun_GetCol(string colName, DataGridView grid)
        {
            for (int i = 0; i < grid.Columns.Count; i++)
            {
                if (grid.Columns[i].HeaderText == colName)
                    return i;
            }
            return -1;
        }
 
        private DataGridView GetCurrentGrid()
        {
            if (tabControl1.SelectedTab == tabPageUnprinted)
                return grdUnprinted;
            else if (tabControl1.SelectedTab == tabPagePrinted)
                return grdPrinted;
            else
                return null;
        }
        #endregion
 
        #region 手动打印按钮
        private void btnPrintBarcode_Click(object sender, EventArgs e)
        {
            DataGridView currentGrid = GetCurrentGrid();
            if (currentGrid == null || currentGrid.SelectedRows.Count == 0)
            {
                MessageBox.Show("请先在当前页签中选择要打印的行。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
 
            if (string.IsNullOrEmpty(txtPrinter.Text) || txtPrinter.Text == "(未选择)")
            {
                MessageBox.Show("请先选择打印机。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
 
            if (!PrinterSettings.InstalledPrinters.Cast<string>().Contains(txtPrinter.Text))
            {
                MessageBox.Show("所选打印机不可用,请重新选择。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
 
            string templateName = GetConfigKey_Print(AppDomain.CurrentDomain.BaseDirectory + "./Config/PWD.config", "PrintTemplate");
            if (string.IsNullOrEmpty(templateName) || templateName == "undefined")
            {
                MessageBox.Show("未配置打印模板(PrintTemplate),请在配置文件中设置。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
 
            try
            {
                List<string> barcodeList = new List<string>();
                List<int> idList = new List<int>();
 
                foreach (DataGridViewRow row in currentGrid.SelectedRows)
                {
                    object barcodeObj = row.Cells[COL_BARCODE].Value;
                    if (barcodeObj == null || barcodeObj == DBNull.Value) continue;
                    string barcode = barcodeObj.ToString().Trim();
                    if (string.IsNullOrEmpty(barcode)) continue;
 
                    object idObj = row.Cells[COL_ID].Value;
                    if (idObj == null || idObj == DBNull.Value) continue;
                    int id;
                    try { id = Convert.ToInt32(idObj); }
                    catch { continue; }
 
                    barcodeList.Add(barcode.Replace("'", "''"));
                    idList.Add(id);
                }
 
                if (barcodeList.Count == 0)
                {
                    MessageBox.Show("选中行中无有效的条码编号。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
 
                string inClause = string.Join(",", barcodeList.Select(b => "'" + b + "'"));
                string viewSql = $@"
                    SELECT 
                        条码编号,
                        物料代码,
                        物料名称,
                        规格型号,
                        批号,
                        数量,
                        供应商,
                        组托单号,
                        生产日期,
                        源单单号
                    FROM h_v_IF_BarCodeBillList_Split
                    WHERE 条码编号 IN ({inClause})";
 
                DataSet dsView = oCn.RunProcReturn(viewSql, "ViewData");
                if (dsView == null || dsView.Tables.Count == 0 || dsView.Tables[0].Rows.Count == 0)
                {
                    MessageBox.Show("未查询到有效的条码详情,请检查数据。", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
 
                DataTable dtPrint = new DataTable();
                dtPrint.Columns.Add("条码编号", typeof(string));
                dtPrint.Columns.Add("物料代码", typeof(string));
                dtPrint.Columns.Add("物料名称", typeof(string));
                dtPrint.Columns.Add("规格型号", typeof(string));
                dtPrint.Columns.Add("批号", typeof(string));
                dtPrint.Columns.Add("数量", typeof(string));
                dtPrint.Columns.Add("供应商", typeof(string));
                dtPrint.Columns.Add("组托单号", typeof(string));
                dtPrint.Columns.Add("生产日期", typeof(string));
                dtPrint.Columns.Add("源单单号", typeof(string));
 
                foreach (DataRow dr in dsView.Tables[0].Rows)
                {
                    DataRow newRow = dtPrint.NewRow();
                    newRow["条码编号"] = dr["条码编号"].ToString();
                    newRow["物料代码"] = dr["物料代码"].ToString();
                    newRow["物料名称"] = dr["物料名称"].ToString();
                    newRow["规格型号"] = dr["规格型号"].ToString();
                    newRow["批号"] = dr["批号"].ToString();
                    object qty = dr["数量"];
                    newRow["数量"] = qty == DBNull.Value ? "0" : Convert.ToDecimal(qty).ToString("0");
                    newRow["供应商"] = dr["供应商"].ToString();
                    newRow["组托单号"] = dr["组托单号"].ToString();
                    object prodDate = dr["生产日期"];
                    newRow["生产日期"] = prodDate == DBNull.Value ? "" : Convert.ToDateTime(prodDate).ToString("yyyy-MM-dd");
                    newRow["源单单号"] = dr["源单单号"].ToString();
                    dtPrint.Rows.Add(newRow);
                }
 
                DataGridView tempGrid = new DataGridView();
                tempGrid.DataSource = dtPrint;
                DataGridViewCheckBoxColumn selectCol = new DataGridViewCheckBoxColumn();
                selectCol.HeaderText = "选择";
                selectCol.Name = "选择";
                tempGrid.Columns.Insert(0, selectCol);
                foreach (DataGridViewRow row in tempGrid.Rows)
                {
                    row.Cells["选择"].Value = true;
                }
 
                Sub_SetReport(templateName, tempGrid);
                Report.Printer.PrinterName = txtPrinter.Text.Trim();
                //Report.PrintPreview(true);  // 弹出预览窗口
                Report.Print(false);
 
                bool isUnprinted = (tabControl1.SelectedTab == tabPageUnprinted);
                if (isUnprinted && idList.Count > 0)
                {
                    string ids = string.Join(",", idList);
                    string alias = txtDeviceAlias.Text.Trim().Replace("'", "''");
                    string updateSql = $@"UPDATE Gy_BarCodeBill_Split  SET HIsPrintSuccess = 1, HLastPrintDate = GETDATE() WHERE HItemId IN ({ids})";
                    oCn.RunProc(updateSql);
                    LoadData();
                }
                else if (!isUnprinted)
                {
                    MessageBox.Show("已打印记录重新打印完成(仅打印,不改变状态)。", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
 
                MessageBox.Show("打印完成。", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                MessageBox.Show("打印出错:" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                LogService.Write("打印异常:" + ex.Message);
            }
        }
        #endregion
 
        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            timer1?.Stop();
            timer1?.Dispose();
        }
    }
}