using BarTenderPrint; using KeyBord; using Mesnac.Codd.Session; using Mesnac.Compressor.Data; using Mesnac.HighWay.ATC.Common; using Mesnac.HighWay.ATC.SqlSugar; using Mesnac.HighWay.ATC.SqlSugar.serviceImpl; using SqlSugar; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Linq.Expressions; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Timers; using System.Windows.Forms; using Mesnac.Compressor.Entity; using static FrmPrint.Login; using static log4net.Appender.RollingFileAppender; using static System.Windows.Forms.VisualStyles.VisualStyleElement; using static System.Windows.Forms.VisualStyles.VisualStyleElement.Button; using System.Collections; namespace FrmPrint { public partial class Form1 : Form { protected DbHandler db = new DbHandler(); DbHelper dbHelper = null; SerialEquip Com; string Port = System.Configuration.ConfigurationManager.AppSettings["Com"]; public delegate void Transit(string data); PrintManager printManager = new PrintManager(); public string UserName = "用户名"; private int timeInvel =int.Parse(System.Configuration.ConfigurationManager.AppSettings["LogOutTime"])*1000; private static INIFile iNIFile = new INIFile(System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "App.InI"); private List productInfos; List listOnit = new List(); public Form1() { InitializeComponent(); if (!timer1.Enabled) { timer1.Interval = timeInvel; timer1.Enabled = true; } CheckForIllegalCrossThreadCalls = false; printManager.RefreshShowMessageEvent += ShowMessage; BindClass(); //bindMachine(); getMachine(); //initUsbScanBarCode(); InitPort(); } private void SetRadiobutton() { try { radioButton1.ForeColor = Color.FromArgb(106, 203, 254); radioButton2.ForeColor = Color.FromArgb(106, 203, 254); //radioButton1.BackColor = Color.FromArgb(3, 27, 61); //radioButton2.BackColor = Color.FromArgb(3, 27, 61); } catch (Exception ex) { } } private void Form1_Load(object sender, EventArgs e) { this.WindowState = FormWindowState.Maximized; cb_machine.DropDownStyle = ComboBoxStyle.DropDown; if (iNIFile.IniReadValue("SystemConfig", "UserName") != "用户名") { iNIFile.IniWriteValue("SystemConfig", "UserName", "用户名"); } if (iNIFile.IniReadValue("SystemConfig", "PrintState") != "2") { iNIFile.IniWriteValue("SystemConfig", "PrintState", "2"); } //listener.Start(); //加载默认时间 lb_UserName.Text = UserName; lb_UserName.ForeColor = Color.Red; LoadTime(); //timer1.Enabled = true; } public void ShowMessage(string strMessage) { try { if (this.lst_OperInfo.Items.Count > 100) { this.lst_OperInfo.Items.Clear(); } bool scroll = false; if (this.lst_OperInfo.TopIndex == this.lst_OperInfo.Items.Count - (int)(this.lst_OperInfo.Height / this.lst_OperInfo.ItemHeight)) scroll = true; this.lst_OperInfo.Items.Add(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + strMessage); if (scroll) this.lst_OperInfo.TopIndex = this.lst_OperInfo.Items.Count - (int)(this.lst_OperInfo.Height / this.lst_OperInfo.ItemHeight); string tempstr = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ": " + strMessage + "\r\n"; } catch (Exception ex) { LogHelper.Error("空间名:" + ex.Source + ";" + '\n' + "方法名:" + ex.TargetSite + '\n' + "故障点:" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' + "错误提示:" + ex.Message); } } public void InitPort() { Com = new SerialEquip(Port); Com.OpenCom(null); Com.SerialData += Receive; } public void Receive(string Data) { try { ShowMessage(" "+ Data+"条码扫描成功!"); LogHelper.Info(Data + "条码扫描成功!"); //Thread.Sleep(5000); PrintPrepare(Data.Trim()); } catch(Exception ex) { LogHelper.Error("空间名:" + ex.Source + ";" + '\n' + "方法名:" + ex.TargetSite + '\n' + "故障点:" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' + "错误提示:" + ex.Message); } } private async void PrintPrepare(string Data) { if (string.IsNullOrEmpty(Data)) { ShowMessage("请确认条码是否正确!"); return; } if (Data.Length != 20) { ShowMessage("请确认条码是否正确!"); return; } //提示换班 //var date = DateTime.Now; //DateTime dt1 = DateTime.Parse(time2.Text + " "+ time4.Text); //DateTime dt2 = DateTime.Parse(time1.Text + " " + time3.Text); if (cb_machine.Text == "") { ShowMessage("请选择机种!"); return; } //if (date >= dt1) //{ // if (radioButton1.Checked) // { // ShowMessage("请切换班次!白班(08:00-20:00)夜班(20:00-08:00)"); // return; // } //} //else //{ // if (date < dt2 && date >= dt1) // { // if (radioButton2.Checked) // { // ShowMessage("请切换班次!白班(08:00-20:00)夜班(20:00-08:00)"); // return; // } // } //} Reresh(Data.Replace("\r", "")); if (iNIFile.IniReadValue("SystemConfig", "PrintState") == "1") { ShowMessage("上一个铭牌正在打印中,等待打印完成重新扫码..."); return; } #region 打印代码暂时屏蔽 //根据条码查询是否到当前工位 //ShowMessage("正在查询产品是否到达条码打印工位..."); //bool iFlag = await SelectPrintStation(Data.Replace("\r", "")); //if (!iFlag) //{ // return; //} //else //{ // ShowMessage("查询产品结果合格!"); //} //ShowMessage("正在查询产品结果是否合格..."); //查询结果是否合格 Print pt = new Print(); pt.barcode = Data; //查询当前机种信息 List TBDProductInfo = await geTbdProductInfos(cb_machine.Text); pt.Machine =int.Parse(TBDProductInfo[0].ProductID); if (radioButton1.Checked) { pt.Shift = "A"; } else { pt.Shift = "B"; } pt.starttime = time1.Text + " " + time3.Text; pt.endtime = time2.Text + " " + time4.Text; if (iNIFile.IniReadValue("SystemConfig", "UserName") != "管理员") { LogHelper.Info("查询" + Data + "产品序列号是否存在相同记录!"); var iflag = await SelectSameBarCode(pt.barcode, pt.Shift, pt.Machine.ToString(), pt.starttime, pt.endtime); if (!iflag) { return; } else { //先根据班次时间查询最大序列号,如果不存在则从0001生成 List baseBarcodePrintInfo = await printManager.SelectPrintInfoAsync("",pt.Shift, pt.Machine.ToString(), pt.starttime, pt.endtime); if (baseBarcodePrintInfo != null && baseBarcodePrintInfo.Count > 0) { //查询最大序列号生成 var max = baseBarcodePrintInfo.Max(x => x.SerialNo); ShowMessage("查询当前最大序列号" + max); pt.Serialnum = Convert.ToInt32(Convert.ToInt32(max.Substring(max.Length - 4, 4)) + 1).ToString().PadLeft(4, '0'); ShowMessage("生成新序列号" + pt.Serialnum); } else { //序列号0001 pt.Serialnum = "0001"; ShowMessage("生成新序列号" + pt.Serialnum); } } } //管理员补码 else { ShowMessage("补码功能开启,查询到当前用户名管理员"); List baseBarcodePrintInfo =await printManager.SelectPrintInfoAsync("", pt.Shift, pt.Machine.ToString(), pt.starttime, pt.endtime); if (baseBarcodePrintInfo != null && baseBarcodePrintInfo.Count > 0) { //查询最大序列号生成 var max = baseBarcodePrintInfo.Max(x => x.SerialNo); ShowMessage("查询当前最大序列号" + max); pt.Serialnum = Convert.ToInt32(Convert.ToInt32(max.Substring(max.Length - 4, 4)) + 1).ToString().PadLeft(4, '0'); pt.isRestart = 1; ShowMessage("生成新序列号" + pt.Serialnum); } else { //序列号0001 pt.Serialnum = "0001"; pt.isRestart = 1; ShowMessage("生成新序列号" + pt.Serialnum); } } //Print(pt); ThreadPool.QueueUserWorkItem(p => { Print(pt, TBDProductInfo); }); //ThreadPool.QueueUserWorkItem(new WaitCallback(Print), pt, baseBarcodePrintInfo); #endregion } private async Task SelectPrintStation(string ProductBarcode) { bool iFlag = false; try { Expression> exp = s1 => true; exp = exp.And(s1 => s1.ProductBarcode == ProductBarcode); Expression> order = (x) => x.BeginTime; List MaterialInfoList = await new BaseServices().Query(exp, order, true); if (MaterialInfoList != null && MaterialInfoList.Count > 0) { var TSYTraceState = MaterialInfoList.OrderByDescending(x => x.BeginTime).FirstOrDefault(); if (TSYTraceState.CurrentStationID == "33") { iFlag = true; return iFlag; } else { ShowMessage(ProductBarcode + "上工位未完成,查询产品未到达条码打印工位!"); iFlag = false; return iFlag; } } else { ShowMessage(ProductBarcode + "上工位未完成,查询产品未到达条码打印工位!"); iFlag = false; return iFlag; } } catch (Exception ex) { return iFlag; } } public async Task SelectBYStationAsync(string ProductBarcode) { bool bflag = false; try { Expression> exp = s1 => true; exp = exp.And(s1 => s1.ScanBarcode == ProductBarcode); List MaterialInfoList = await new BaseServices().Query(exp); if (MaterialInfoList != null && MaterialInfoList.Count > 0) { bflag = true; } else { ShowMessage(ProductBarcode + "上工位未完成!"); bflag = false; } return bflag; } catch (Exception ex) { return bflag; } } /// /// 查询工位合格信息 /// /// /// public bool GetStationNGBySemiBarCode(string ProductBarcode) { bool iFlag = false; try { List selectAllStation = SaveBarCode(ProductBarcode); if (selectAllStation != null || selectAllStation.Count > 0) { for (int i = 0; i < selectAllStation.Count; i++) { if (selectAllStation[i].TableName == "T_RP_StationPara_B130_1" && selectAllStation[i].State =="1") { selectAllStation.RemoveAll(x => x.TableName == "T_RP_StationPara_B130_2"); } else if(selectAllStation[i].TableName == "T_RP_StationPara_B130_2" && selectAllStation[i].State == "1") { selectAllStation.RemoveAll(x => x.TableName == "T_RP_StationPara_B130_1"); } if (selectAllStation[i].State == "2" || selectAllStation[i].State == "") { iFlag = false; ShowMessage(selectAllStation[i].StationName + "数据NG"); return iFlag; } } //selectAllStation = selectAllStation.FindAll(x => x.State == "2"); } return iFlag; } catch (Exception ex) { return iFlag; } } public List SaveBarCode(string P_Bar_Code) { List stationQualityList = null; try { SugarParameter[] pars = new BaseServices().GetParameters(new { BarCode = P_Bar_Code }); var dt2 = new BaseServices().UseStoredProcedure("pro_AllProductionQualityInfocopy ", pars); if (dt2 != null && dt2.Rows.Count > 0) { stationQualityList = new List(); StationQualityInfo stationQualityInfo = null; foreach (DataRow row in dt2.Rows) { stationQualityInfo = new StationQualityInfo(); stationQualityInfo.StationName = RowValue(row, "StationName", String.Empty); stationQualityInfo.TableName = RowValue(row, "TableName", String.Empty); stationQualityInfo.State = RowValue(row, "State", String.Empty); stationQualityList.Add(stationQualityInfo); } } return stationQualityList; } catch (Exception ex) { LogHelper.Error("空间名:" + ex.Source + ";" + '\n' + "方法名:" + ex.TargetSite + '\n' + "故障点:" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' + "错误提示:" + ex.Message); return stationQualityList; } } public static string RowValue(DataRow dr, string field, string defaultValue) { if (dr.Table.Columns.Contains(field)) { if (dr[field] != null && dr[field] != DBNull.Value) { return dr[field].ToString().Trim(); } } else { ICSharpCode.Core.LoggingService.Error("DataTable中不存在[" + field + "]列!"); } return defaultValue; } /// /// 更新barcode /// /// private void Reresh(string barcode) { if (this.InvokeRequired) { this.Invoke(new Transit(Reresh), barcode); return; } this.txt_barcode.Text = barcode.ToString(); } private async Task getMachine() { try { productInfos = await geTbdProductInfos(""); foreach (var item in productInfos)//数据库中获取的原始数据 { listOnit.Add(item.ProductName);//第一列是名称 } this.cb_machine.Items.AddRange(listOnit.ToArray()); } catch (Exception ex) { Console.WriteLine(ex); } } /// /// 机种绑定 /// private void bindMachine() { try { cb_machine.DisplayMember = "ProductName"; cb_machine.ValueMember = "ProductID"; cb_machine.DataSource = GetProductList(""); } catch { MessageBox.Show("机种绑定失败"); } } private async Task> geTbdProductInfos(string ProductName) { try { Expression> exp = (TBDProductInfo s1) => true; if (ProductName == "") { exp = exp.And((TBDProductInfo s1) => s1.ProductName != ""); } else { exp = exp.And((TBDProductInfo s1) => s1.ProductName == ProductName); } productInfos = await new BaseServices().Query(exp); return productInfos; } catch (Exception ex) { Console.WriteLine(ex); return null; } } public DataTable GetProductList(string ProductID) { DataTable result = null; try { Expression> exp = (TBDProductInfo s1) => true; if (ProductID == "") { exp = exp.And((TBDProductInfo s1) => s1.ProductID != ""); } else { exp = exp.And((TBDProductInfo s1) => s1.ProductID == ProductID); } result = new BaseServices().QueryDatatable(exp); return result; } catch (Exception ex) { LogHelper.Error("空间名:" + ex.Source + ";" + '\n' + "方法名:" + ex.TargetSite + '\n' + "故障点:" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' + "错误提示:" + ex.Message); return result; } } private void Print(object print, List baseBarcodePrintInfo) { lock (string.Empty) { //判断前工位是否全部合格 var pt = print as Print; if(pt==null) { return; } iNIFile.IniWriteValue("SystemConfig", "PrintState", "1"); printManager.Print(pt, baseBarcodePrintInfo); } } private async Task SelectSameBarCode(String BarCode, string ShiftID, string ProductID, string starttime, string endtime) { bool iflag = false; try { List baseBarcodePrintInfos = await printManager.SelectPrintInfoAsync(BarCode, ShiftID, ProductID.ToString(), starttime, endtime); if (baseBarcodePrintInfos != null && baseBarcodePrintInfos.Count > 0) { foreach (var item in baseBarcodePrintInfos) { ShowMessage("查询" + BarCode + "存在历史记录,序列号:" + item.SerialNo); LogHelper.Info("查询" + BarCode + "存在历史记录,序列号:" + item.SerialNo); return false; } } else { iflag = true; } return iflag; } catch (Exception ex) { LogHelper.Error("空间名:" + ex.Source + ";" + '\n' + "方法名:" + ex.TargetSite + '\n' + "故障点:" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' + "错误提示:" + ex.Message); return iflag; } } public void BindClass() { DataTable dt = new DataTable(); dt.Columns.Add("key", typeof(string)); dt.Columns.Add("value", typeof(string)); DataRow dr = dt.NewRow(); dr[0] = "01"; dr[1] = "早班"; dt.Rows.Add(dr); DataRow dr2 = dt.NewRow(); dr2[0] = "02"; dr2[1] = "中班"; dt.Rows.Add(dr2); DataRow dr3 = dt.NewRow(); dr3[0] = "03"; dr3[1] = "晚班"; dt.Rows.Add(dr3); this.cb_shift.DataSource = dt; this.cb_shift.DisplayMember = "value"; this.cb_shift.ValueMember = "key"; } private string getShift(string shift) { string shiftA = "A"; switch (shift) { case "01": shiftA = "A"; break; case "02": shiftA = "B"; break; case "03": shiftA = "C"; break; default: break; } return shiftA; } private string getDateString(string semiBarcode) { string datestring = "20"; if (string.IsNullOrEmpty(semiBarcode)) { datestring = DateTime.Now.ToString(); } else { string year = semiBarcode.Substring(1, 2); string month = semiBarcode.Substring(3, 2); string date = semiBarcode.Substring(5, 2); datestring += year + "-" + month + "-" + date; } return datestring; } private void btn_close_Click(object sender, EventArgs e) { this.Com.Comm.Close(); this.Close(); } private void btn_print_Click(object sender, EventArgs e) { //密码权限 Login login = new Login(this); login.ChangeText += new ChangeTextHandler(Change_Text); login.ShowDialog(); } private void Change_Text(string str) { if (iNIFile.IniReadValue("SystemConfig", "UserName") != str) { iNIFile.IniWriteValue("SystemConfig", "UserName", str); } lb_UserName.Text = str; UserName = str; lb_UserName.ForeColor = Color.LightGreen; } private void LoadTime() { int datetime = Convert.ToInt32(DateTime.Now.Hour.ToString()); if (datetime >= 8 && datetime < 20) { time1.Text = DateTime.Now.ToString("yyyy-MM-dd"); time3.Text = "08:00:00"; time2.Text = DateTime.Now.ToString("yyyy-MM-dd"); time4.Text = "20:00:00"; this.radioButton1.Checked = true; } else if (datetime >= 0 && datetime < 8) { time1.Text = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); time3.Text = "20:00:00"; time2.Text = DateTime.Now.ToString("yyyy-MM-dd"); time4.Text = "08:00:00"; this.radioButton2.Checked = true; } else { time1.Text = DateTime.Now.ToString("yyyy-MM-dd"); time3.Text = "20:00:00"; time2.Text = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"); time4.Text = "08:00:00"; this.radioButton2.Checked = true; } } private void cb_shift_SelectedIndexChanged(object sender, EventArgs e) { cb_shift.Visible = false; //cb_shift.Visible = true; } private void Form1_FormClosed(object sender, FormClosedEventArgs e) { try { this.Com.Comm.Close(); //System.Environment.Exit(System.Environment.ExitCode); } catch (Exception ex) { LogHelper.Error("空间名:" + ex.Source + ";" + '\n' + "方法名:" + ex.TargetSite + '\n' + "故障点:" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' + "错误提示:" + ex.Message); } finally { this.Dispose(); this.Close(); } } private void radioButton2_CheckedChanged(object sender, EventArgs e) { //夜班 //time1.Text = DateTime.Now.ToString("yyyy-MM-dd"); //time3.Text = "20:00:00"; //time2.Text = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"); //time4.Text = "08:00:00"; return; int datetime = Convert.ToInt32(DateTime.Now.Hour.ToString()); if (datetime >= 8 && datetime < 20) { time1.Text = DateTime.Now.ToString("yyyy-MM-dd"); time3.Text = "08:00:00"; time2.Text = DateTime.Now.ToString("yyyy-MM-dd"); time4.Text = "20:00:00"; //this.radioButton1.Checked = true; } else if (datetime >= 0 && datetime < 8) { time1.Text = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); time3.Text = "08:00:00"; time2.Text = DateTime.Now.ToString("yyyy-MM-dd"); time4.Text = "20:00:00"; //this.radioButton2.Checked = true; } else { time1.Text = DateTime.Now.ToString("yyyy-MM-dd"); time3.Text = "20:00:00"; time2.Text = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"); time4.Text = "08:00:00"; //this.radioButton2.Checked = true; } } private void radioButton1_CheckedChanged(object sender, EventArgs e) { //白班 //time1.Text = DateTime.Now.ToString("yyyy-MM-dd"); //time3.Text = "08:00:00"; //time2.Text = DateTime.Now.ToString("yyyy-MM-dd"); //time4.Text = "20:00:00"; return; int datetime = Convert.ToInt32(DateTime.Now.Hour.ToString()); if (datetime >= 8 && datetime < 20) { time1.Text = DateTime.Now.ToString("yyyy-MM-dd"); time3.Text = "08:00:00"; time2.Text = DateTime.Now.ToString("yyyy-MM-dd"); time4.Text = "20:00:00"; } else if (datetime >= 0 && datetime < 8) { time1.Text = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd"); time3.Text = "08:00:00"; time2.Text = DateTime.Now.ToString("yyyy-MM-dd"); time4.Text = "20:00:00"; } else { time1.Text = DateTime.Now.ToString("yyyy-MM-dd"); time3.Text = "20:00:00"; time2.Text = DateTime.Now.AddDays(1).ToString("yyyy-MM-dd"); time4.Text = "08:00:00"; } } private void timer1_Tick(object sender, EventArgs e) { try { if (iNIFile.IniReadValue("SystemConfig", "UserName") != "用户名") { iNIFile.IniWriteValue("SystemConfig", "UserName", "用户名"); } this.UserName = "用户名"; lb_UserName.Text = "用户名"; lb_UserName.ForeColor = Color.Red; } catch (Exception ex) { LogHelper.Error("空间名:" + ex.Source + ";" + '\n' + "方法名:" + ex.TargetSite + '\n' + "故障点:" + ex.StackTrace.Substring(ex.StackTrace.LastIndexOf("\\") + 1, ex.StackTrace.Length - ex.StackTrace.LastIndexOf("\\") - 1) + '\n' + "错误提示:" + ex.Message); } } List listNew = new List(); private void cb_machine_TextUpdate(object sender, EventArgs e) { //清空combobox this.cb_machine.Items.Clear(); //清空listNew listNew.Clear(); //遍历全部备查数据 foreach (var item in listOnit) { if (item.Contains(this.cb_machine.Text)) { //符合,插入ListNew listNew.Add(item); } } //combobox添加已经查到的关键词 this.cb_machine.Items.AddRange(listNew.ToArray()); //设置光标位置,否则光标位置始终保持在第一列,造成输入关键词的倒序排列 this.cb_machine.SelectionStart = this.cb_machine.Text.Length; //保持鼠标指针原来状态,有时候鼠标指针会被下拉框覆盖,所以要进行一次设置。 Cursor = Cursors.Default; //自动弹出下拉框 this.cb_machine.DroppedDown = true; } private void timer2_Tick(object sender, EventArgs e) { LoadTime(); //SetRadiobutton(); } } }