WPF印刷ソース記録

25985 ワード

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"];
            }
           
          
        }
    }
}