using GalaSoft.MvvmLight.Command; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Data; using System.Drawing.Printing; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Windows.Navigation; using System.Windows; using System.Windows.Controls; namespace MES.Plugin.ReceiptsPrint.ViewModels { public class ReceiptsPrintVM : ViewModelPlugin { public ReceiptsPrintVM() { ResetAll(); InitPrinter(); InitReceipts(); } #region 标签补打 //public RelayCommand PrintCommandUpfight { get; set; } private RelayCommand printCommandUpfight; public RelayCommand PrintCommandUpfight { get { return printCommandUpfight ?? (printCommandUpfight = new RelayCommand(ExcutePrintCommandUpFight)); } } void ExcutePrintCommandUpFight() { //Views.ReceiptsUpFight rf = new ReceiptsUpFight(this.Framework); //rf.ShowDialog(); this.Framework.FrameworkContext.Add("CurrentReceiptsSource", CurrentReceiptsSource.Key); openBorrowMachine(); } #endregion #region 重置 private RelayCommand resetCommand; public RelayCommand ResetCommand { get { return resetCommand ?? (resetCommand = new RelayCommand(ExecuteResetCommand)); } } void ExecuteResetCommand() { ResetAll(); MessageInvoker.ShowSuccess("数据重置成功!"); } private void ResetAll() { this.Req_Header_Id = null; this.ReceiptsDtl.Clear(); } #endregion #region 回车 private RelayCommand queryMitemCommand; public RelayCommand QueryMitemCommand { get { return queryMitemCommand ?? (queryMitemCommand = new RelayCommand(ExcuteQueryMitemCommand)); } } void ExcuteQueryMitemCommand() { QureyReceiptsDtl(); } #endregion #region 单据来源 #region 系统单据来源 private IList<KeyValuePair<string, string>> receiptsSource; public IList<KeyValuePair<string, string>> ReceiptsSource { get { return receiptsSource; } set { if (receiptsSource != value) { receiptsSource = value; NotifyPropertyChanged("ReceiptsSource"); } } } #endregion #region 当前选择的单据来源 private KeyValuePair<string, string> currentReceiptsSource; public KeyValuePair<string, string> CurrentReceiptsSource { get { return currentReceiptsSource; } set { if (currentReceiptsSource.Key != value.Key) { currentReceiptsSource = value; NotifyPropertyChanged("CurrentReceiptsSource"); } } } #endregion private void InitReceipts() { IList<string> receipts = new List<string>(); //receipts.Add("送货单"); receipts.Add("跨库存调拨单"); this.ReceiptsSource = new List<KeyValuePair<string, string>>(); foreach (var item in receipts) { KeyValuePair<string, string> receiptsource = new KeyValuePair<string, string>(item, item); this.ReceiptsSource.Add(receiptsource); if (receiptsource.Key == Title) { this.CurrentReceiptsSource = receiptsource; } else { if (receiptsource.Key == "跨库存调拨单") { this.CurrentReceiptsSource = receiptsource; } } } } #endregion #region LabelDtl 标签详细列表 private ObservableCollection<Models.LabelModel> labelDtl; public ObservableCollection<Models.LabelModel> LabelDtl { get { if (labelDtl == null) { labelDtl = new ObservableCollection<Models.LabelModel>(); } return labelDtl; } set { if (labelDtl != value) { labelDtl = value; NotifyPropertyChanged("LabelDtl"); } } } #endregion #region 初始化打印机 #region 系统可用打印机 private IList<KeyValuePair<string, string>> prints; public IList<KeyValuePair<string, string>> Prints { get { return prints; } set { if (prints != value) { prints = value; NotifyPropertyChanged("Prints"); } } } #endregion #region 用户选择的打印机 private KeyValuePair<string, string> selectPrinter; public KeyValuePair<string, string> SelectPrinter { get { return selectPrinter; } set { if (selectPrinter.Key != value.Key) { selectPrinter = value; NotifyPropertyChanged("SelectPrinter"); } } } #endregion public void InitPrinter() { IList<string> printers = new List<string>(); foreach (string printerName in PrinterSettings.InstalledPrinters) { if (!printers.Contains(printerName)) { printers.Add(printerName); } } this.prints = new List<KeyValuePair<string, string>>(); //设置本机默认打印 string defaultPrintName = (new System.Drawing.Printing.PrintDocument()).PrinterSettings.PrinterName; foreach (string name in printers) { KeyValuePair<string, string> print = new KeyValuePair<string, string>(name, name); this.prints.Add(print); if (print.Key == defaultPrintName) { this.SelectPrinter = print; } } } #endregion #region LablePrintStatus 状态 private LablePrintStatus lablePrintStatus = LablePrintStatus.NONE; public LablePrintStatus LablePrintStatus { get { return lablePrintStatus; } set { if (lablePrintStatus != value) { lablePrintStatus = value; NotifyPropertyChanged("LablePrintStatus"); } } } #endregion #region 打印 private RelayCommand printCommand; public RelayCommand PrintCommand { get { return printCommand ?? (printCommand = new RelayCommand(ExecutePrintCommand)); } } void ExecutePrintCommand() { if (SavePrintLabels() && BartenderPrint()) { foreach (var ea in LabelDtl) { ea.PrintTime = DateTime.Now; ea.Status = Models.LablePrintStatusTransfer.TransferToChinese(LablePrintStatus.CREATED); } LablePrintStatus = LablePrintStatus.PRINTED; MessageInvoker.ShowSuccess("打印成功!"); } LabelDtl.Clear(); } private bool SavePrintLabels() { try { if (ReceiptsDtl.Count == 0) { MessageInvoker.ShowError("没有需要打印的单据!"); return false; } else { for (int i = 0; i < ReceiptsDtl.Count; i++) { if (ReceiptsDtl[i].PRINTNUM.ToString() == "") { MessageInvoker.ShowError("必须填写最小包装数!"); return false; } } } int divRem; for (int i = 0; i < ReceiptsDtl.Count; i++) { Math.DivRem(Convert.ToInt32(ReceiptsDtl[i].REQUEST_QTY), Convert.ToInt32(ReceiptsDtl[i].QUANTITY), out divRem); for (int j = 0; j < Convert.ToInt32(ReceiptsDtl[i].PRINTNUM); j++) { LabelDtl.Add(new Models.LabelModel() { ItemCode = ReceiptsDtl[i].ERP_REQUIRE_ITEM_NUM.ToString(), ItemDesc = ReceiptsDtl[i].ERP_REQUIRE_ITEM_DESC.ToString(), LableNo = Guid.NewGuid().ToString().Replace("-", string.Empty).ToUpper(), Unit = ReceiptsDtl[i].UOM.ToString(), LotNo = ReceiptsDtl[i].BATCH_NO.ToString(), ProductDate = Convert.ToDateTime(ReceiptsDtl[i].MADE_DATE), SupplierShortCode = ReceiptsDtl[i].SUPPLIER_SHORT_CODE.ToString(), LabelQty = Convert.ToInt32(ReceiptsDtl[i].PRINTNUM) == j + 1 && divRem != 0 ? divRem : Convert.ToInt32(ReceiptsDtl[i].QUANTITY), Status = Models.LablePrintStatusTransfer.TransferToChinese(LablePrintStatus.CREATED), PRINTNUM = Convert.ToInt32(ReceiptsDtl[i].PRINTNUM), ITEM_ID = ReceiptsDtl[i].ITEM_ID.ToString(), REQUEST_QTY = ReceiptsDtl[i].REQUEST_QTY, QUANTITY = Convert.ToInt32(ReceiptsDtl[i].QUANTITY), //最小包装数量 }); } } decimal[] qty_list = new decimal[LabelDtl.Count]; string[] mitem_list = new string[LabelDtl.Count]; decimal[] totalqty_list = new decimal[LabelDtl.Count]; string[] batch_list = new string[LabelDtl.Count]; string[] made_list = new string[LabelDtl.Count]; string[] inv_list = new string[LabelDtl.Count]; string[] district_list = new string[LabelDtl.Count]; string[] loc_list = new string[LabelDtl.Count]; string[] uom_list = new string[LabelDtl.Count]; string[] label_list = new string[LabelDtl.Count]; decimal[] qty_quantity_list = new decimal[LabelDtl.Count]; for (int i = 0; i < LabelDtl.Count; i++) { qty_list[i] = LabelDtl[i].PRINTNUM; mitem_list[i] = LabelDtl[i].ITEM_ID; totalqty_list[i] = LabelDtl[i].REQUEST_QTY; batch_list[i] = LabelDtl[i].LotNo; made_list[i] = LabelDtl[i].ProductDate.ToString("yyyy-MM-dd"); inv_list[i] = LabelDtl[i].INV_ID; district_list[i] = LabelDtl[i].DISTRICT_ID; loc_list[i] = LabelDtl[i].LOC_ID; uom_list[i] = LabelDtl[i].Unit; label_list[i] = LabelDtl[i].LableNo; qty_quantity_list[i] = LabelDtl[i].QUANTITY; } var contract = new MessageContract(); contract.InvokeMethod = "Inv_Print_by_Receipts"; contract.MessageToken = Assembly.GetExecutingAssembly().GetName().Name; contract.Context["InvOrgId"] = this.Framework.FrameworkContext[FrameworkSymbol.SYS_INFO_KEY_INV_ORG_ID]; contract.Context["p_user_code"] = this.Framework.FrameworkContext[FrameworkSymbol.SYS_INFO_KEY_USER_CODE]; contract.Context["p_src_bill_type"] = this.CurrentReceiptsSource.Key; contract.Context["p_src_bill_no"] = this.Req_Header_Id; contract.Context["p_supplier_id"] = Guid.NewGuid().ToString().Replace("-", string.Empty).ToUpper(); contract.Context["p_mitem_id"] = JsonConvert.SerializeObject(mitem_list, Formatting.None); contract.Context["p_total_qty"] = JsonConvert.SerializeObject(totalqty_list, Formatting.None); contract.Context["p_qty_list"] = JsonConvert.SerializeObject(qty_list, Formatting.None); contract.Context["p_qty_quantity_list"] = JsonConvert.SerializeObject(qty_quantity_list, Formatting.None); contract.Context["p_batch_no"] = JsonConvert.SerializeObject(batch_list, Formatting.None); contract.Context["p_date_req"] = JsonConvert.SerializeObject(made_list, Formatting.None); contract.Context["p_inv_id"] = JsonConvert.SerializeObject(inv_list, Formatting.None); contract.Context["p_district_id"] = JsonConvert.SerializeObject(district_list, Formatting.None); contract.Context["p_loc_id"] = JsonConvert.SerializeObject(loc_list, Formatting.None); contract.Context["p_uom"] = JsonConvert.SerializeObject(uom_list, Formatting.None); contract.Context["p_label_no"] = JsonConvert.SerializeObject(label_list, Formatting.None); var msgContract = this.Framework.DataService.DoRequest(contract, false); if (!msgContract.IsSucess) { MessageInvoker.ShowError(msgContract.ErrorMessage ?? "未处理错误"); return false; } } catch (Exception ex) { MessageInvoker.ShowError(ex.Message); TraceHelper.TraceException(ex); return false; } return true; } private bool BartenderPrint() { //选择打印机 if (string.IsNullOrWhiteSpace(SelectPrinter.Key)) { MessageInvoker.ShowError("请选择打印机!"); return false; } //判断用户是否勾选打印行 IList<string> list = new List<string>(); ObservableCollection<Models.LabelModel> model = new ObservableCollection<Models.LabelModel>(LabelDtl); if (model.Count < 1) { MessageInvoker.ShowError("没有需要打印的物料标签行!"); return false; } int printIndex = 0; foreach (var label in model) { try { list.Add(string.Format("{0}|{1}|{2}|{3}|{4}|{5}|{6}|{7}|{8}|{9}|{10}|{11}|{12}|{13}|{14}|{15}|{16}", "LB]" + label.Supplier_Code + "]" + label.LotNo + "]" + label.ItemCode + "]" + label.LabelQty + "]" + label.LableNo,//LB|供应商编码|生产批号|14位物料编码信息|数量|标签GUID label.ItemCode,//物料编码 label.SupplierShortCode,//供应商名称 label.ItemDesc,//物料描述 label.Plan_qty,//排产量 label.LabelQty,//包装量 label.Mo_Name,//工单名 label.Inv_desc,//送货仓库 label.Datetime_sche_start,//排产时间 label.Org_code,//排产线体 label.Delivery_barcode,//送货单号 string.Empty, string.Empty, string.Empty, string.Empty, string.Empty, (printIndex + 1) )); printIndex++; } catch (Exception ex) { MessageInvoker.ShowError("获取打印数据失败!"); return false; } } string strInstallPath = AppDomain.CurrentDomain.BaseDirectory; string templatePath = strInstallPath + "\\Labels\\物料标签-厂外.btw"; string dataPath = strInstallPath + "\\Labels\\data.txt"; StreamWriter sw = new StreamWriter(dataPath, false, Encoding.Default); for (int i = 0; i < list.Count; i++) { sw.WriteLine(list[i]); } sw.Flush(); sw.Close(); try { BarTenderFacade Printer = new BarTenderFacade(); Printer.OpenTemplate(selectPrinter.Key, templatePath); Printer.SetNamedSubStringValue(this.SelectPrinter.Key); } catch (Exception ex) { MessageInvoker.ShowError(ex.Message); return false; } return true; } #endregion #region 跨库存调拨单条码号 private string req_Header_Id; public string Req_Header_Id { get { return req_Header_Id; } set { if (req_Header_Id != value) { req_Header_Id = value; NotifyPropertyChanged("Req_Header_Id"); } } } #endregion #region 查询单据明细 private RelayCommand queryReceiptsCommand; public RelayCommand QueryReceiptsCommand { get { return queryReceiptsCommand ?? (queryReceiptsCommand = new RelayCommand(ExcuteQueryReceiptsCommand)); } } void ExcuteQueryReceiptsCommand() { QureyReceiptsDtl(); } #endregion #region 单据明细 private ObservableCollection<Models.ReceiptsModel> receiptsDtl; public ObservableCollection<Models.ReceiptsModel> ReceiptsDtl { get { if (receiptsDtl == null) { receiptsDtl = new ObservableCollection<ReceiptsModel>(); } return receiptsDtl; } set { if (receiptsDtl != value) { receiptsDtl = value; NotifyPropertyChanged("ReceiptsDtl"); } } } private void QureyReceiptsDtl() { try { //增加调拨单号防呆,限定数字 bool IsNumber=System.Text.RegularExpressions.Regex.IsMatch(this.Req_Header_Id,@"^[0-9]\d*$"); if (!IsNumber) { MessageInvoker.ShowError("单据号只能为数字!"); return; } this.ReceiptsDtl.Clear(); var contract = new MessageContract(); contract.InvokeMethod = "Inv_Receipts_Detail"; contract.MessageToken = Assembly.GetExecutingAssembly().GetName().Name; contract.Context["InvOrgId"] = this.Framework.FrameworkContext[FrameworkSymbol.SYS_INFO_KEY_INV_ORG_ID]; contract.Context["Req_Header_Id"] = this.Req_Header_Id; contract.Context["Receipts_Source"] = this.CurrentReceiptsSource.Key; var msgContract = this.Framework.DataService.DoRequest(contract); if (msgContract.IsSucess) { var result = msgContract.GetMessageDataModel<DataTable>(); if (result != null) { if (result.Rows.Count < 1) { MessageInvoker.ShowError(" 单据明细查询无数据"); } else { MessageInvoker.ShowSuccess("单据明细查询成功"); } } else { MessageInvoker.ShowError("按单据来源条码号查询单据明细失败"); } for (int i = 0; i < result.Rows.Count; i++) { DataRow row = result.Rows[i]; this.ReceiptsDtl.Add(new Models.ReceiptsModel() { ITEM_ID = row["ITEM_ID"].ToString(), SUPPLIER_ID = row["SUPPLIER_ID"].ToString(), SUPPLIER_SHORT_CODE = row["SUPPLIER_SHORT_CODE"].ToString(), INV_ID = row["INV_ID"].ToString(), DISTRICT_ID = row["DISTRICT_ID"].ToString(), LOC_ID = row["LOC_ID"].ToString(), ERP_REQUIRE_ITEM_NUM = row["ERP_REQUIRE_ITEM_NUM"].ToString(), ERP_REQUIRE_ITEM_DESC = row["ERP_REQUIRE_ITEM_DESC"].ToString(), REQUEST_QTY = row["REQUEST_QTY"].ToString() == "" ? 0 : Convert.ToInt32(row["REQUEST_QTY"]), RCV_QTY = row["REQUEST_QTY"].ToString() == "" ? 0 : Convert.ToInt32(row["REQUEST_QTY"]), UOM = row["UOM"].ToString(), INV_NAME = row["INV_NAME"].ToString(), DISTRICT_NAME = row["DISTRICT_NAME"].ToString(), LOC_NAME = row["LOC_NAME"].ToString(), BATCH_NO = Req_Header_Id, PRINTTOTAL = row["RCV_QTY"].ToString() == "" ? 0 : Convert.ToInt32(row["RCV_QTY"]), QUANTITY = row["QUANTITY"].ToString(), PRINTNUM = row["QUANTITY"].ToString() == "" ? "" : (Math.Ceiling((double)(Convert.ToInt32(row["REQUEST_QTY"]) / (double)Convert.ToInt32(row["QUANTITY"])))).ToString() //QUANTITY = row["QUANTITY"] == null ? 0 : Convert.ToInt32(row["QUANTITY"]), //PRINTNUM = Convert.ToInt32(Math.Ceiling((double)(Convert.ToInt32(row["REQUEST_QTY"]) / (double)Convert.ToInt32(row["QUANTITY"])))) }); } } else { MessageInvoker.ShowError(string.Format("查询单据明细失败:{0}", msgContract.ErrorMessage)); } } catch (Exception ex) { MessageInvoker.ShowError(ex.Message); TraceHelper.TraceException(ex); } } #endregion #region 设置全屏显示 private void openBorrowMachine() { Type autoScanInterface = Type.GetType("Midea.MES.Plugin.MitemLabelsRePrintByDeliveryNo.MainWindow,Midea.MES.Plugin.MitemLabelsRePrintByDeliveryNo"); MControlBase borrowMachineCtl = Activator.CreateInstance(autoScanInterface, false) as MControlBase; borrowMachineCtl.Framework = this.Framework; var vm = borrowMachineCtl.DataContext as ViewModelPlugin; vm.Framework = this.Framework; var borrowMachineWin = new Window(); // 设置全屏 borrowMachineWin.WindowState = System.Windows.WindowState.Normal; borrowMachineWin.WindowStyle = System.Windows.WindowStyle.ToolWindow; borrowMachineWin.ResizeMode = System.Windows.ResizeMode.NoResize; //borrowMachineWin.Topmost = true; borrowMachineWin.Left = 0.0; borrowMachineWin.Top = 0.0; borrowMachineWin.Width = System.Windows.SystemParameters.PrimaryScreenWidth; borrowMachineWin.Height = System.Windows.SystemParameters.PrimaryScreenHeight; var grid = new Grid(); grid.Children.Add(borrowMachineCtl); borrowMachineWin.Content = grid; vm.OnLoad(this.Framework); borrowMachineWin.ShowDialog(); } #endregion #region 标题 private string title; public string Title { get { return title; } set { if (title != value) { title = value; NotifyPropertyChanged("Title"); } } } #endregion protected override void OnLoaded() { base.OnLoaded(); dynamic Header_Id = "",Title= ""; if (this.Framework.FrameworkContext.TryGetValue("1EC1B8EA72C301C4E0530A100C35CDD5", out Header_Id)) { Req_Header_Id = this.Framework.FrameworkContext["1EC1B8EA72C301C4E0530A100C35CDD5"]; } if (this.Framework.FrameworkContext.TryGetValue("1EC1B8EA72C201C4E0530A100C35CDD5",out Title)) { Title = this.Framework.FrameworkContext["1EC1B8EA72C201C4E0530A100C35CDD5"]; } } } }