博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C# POS 小票打印

Posted on 2013-07-26 16:53  love楠  阅读(3884)  评论(0编辑  收藏  举报

网上查了好多资料终于让我捣鼓出来了!

public partial class Models_JXC_Sale_actNewSalePage : WebPartBase
{

    public string saild_id_ = System.DateTime.Now.ToString("yyyyMMddhhmmss");
    public string date_ = DateTime.Now.ToString();
    public DataTable datas_ = new DataTable();

    public double discount_ = 0;   //优惠金额
    public double amount_ = 0; // 应收金额
    public double recv_cash_ = 0;  // 收款金额

    public string card_no_ = ""; // 会员卡号
    public double mark_in_ = 0; // 本次积分

    private System.Windows.Forms.PrintPreviewDialog printv_pos = null;
    private System.Drawing.Printing.PrintDocument printd_pos = null;

    public string SVIDS = "";
    public string WHIDS = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsFirstLoad)
        {
            btnPrinter.Enabled = false;
            Session["mdp"] = "";
            Session["mdSLID"] = "0";
            IsFirstLoad = false;
            SVIDS = SVID.ToString();
            WHIDS = WHID.ToString();
        }
        else
        {
            btnPrinter.Enabled = true;
            if (Session["mdp"].ToString() == Session["mdSLID"].ToString())
            {
                CreateBlendListReport(Session["mdSLID"].ToString());
            }
        }
        if (cSaleDate.Text == "")
        {
            cSaleDate.Value = DateTime.Now;
        }


        this.printv_pos = new System.Windows.Forms.PrintPreviewDialog();
        this.printd_pos = new System.Drawing.Printing.PrintDocument();


        this.printv_pos.AutoScrollMargin = new System.Drawing.Size(0, 0);
        this.printv_pos.AutoScrollMinSize = new System.Drawing.Size(0, 0);
        this.printv_pos.ClientSize = new System.Drawing.Size(400, 300);
        this.printv_pos.Document = this.printd_pos;
        this.printv_pos.Enabled = true;
        this.printv_pos.Name = "printPreviewDialog1";
        this.printv_pos.Visible = false;
        // 
        // printd_pos
        // 
        this.printd_pos.DocumentName = "京华茶叶店POS小票";
        this.printd_pos.OriginAtMargins = true;
        this.printd_pos.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(this.printd_pos_PrintPage);


        datas_.Clear();
    }

    private int getYc(double cm)
    {
        return (int)(cm / 25.4) * 100;
    }

    public string GetPrintStr()
    {
        StringBuilder sb = new StringBuilder();

        sb.Append("*********" + "京华茶叶连锁店" + "***********\n");

        sb.Append("  流水号:" + this.saild_id_ + "\n");
        sb.Append("  日  期:" + date_ + "\n");

        sb.Append("  商品编号" + "\t" + "数量" + "\t" + "单价" + "\t" + "金额" + "\n");
        for (int i = 0; i < this.datas_.Rows.Count; i++)
        {
            sb.Append("  " + datas_.Rows[i][16] + "\t" + datas_.Rows[i][5] + "\t" + datas_.Rows[i][4] + "\t" + datas_.Rows[i][8] + "\n");
            sb.Append("  " + datas_.Rows[i][17]);
            sb.Append("\n");
        }

        sb.Append("\n");


        sb.Append("  优惠金额:" + discount_ + "\n");
        sb.Append("  应收金额:" + amount_ + "\n");
        sb.Append("  实收金额:" + recv_cash_ + "\n");
        sb.Append("                         \n");
        sb.Append("  会员卡号:" + card_no_ + "\n");
        sb.Append("  本次积分:" + mark_in_ + "\n");
        sb.Append("***************************************\n");
        string myfoot = string.Format("  {0}\n", "欢迎下次光临!");
        sb.Append(myfoot);
        return sb.ToString();
    }

    /// <summary>
    /// POS打印
    /// </summary>
    public void print()
    {
        this.printd_pos.PrintController = new System.Drawing.Printing.StandardPrintController();
        this.printd_pos.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printd_pos_PrintPage);

        //设置边距
        System.Drawing.Printing.Margins margins = new System.Drawing.Printing.Margins(5, 5, 5, 5);
        this.printd_pos.DefaultPageSettings.Margins = margins;

        this.printd_pos.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("First custom size", getYc(58), 600);
        //this.printDocument1.PrinterSettings.PrinterName = "";
        //Margins margins = new Margins(

        //this.printv_pos.Document = this.printd_pos;

        printv_pos.PrintPreviewControl.AutoZoom = false;
        printv_pos.PrintPreviewControl.Zoom = 1;

        // this.printv_pos.ShowDialog(win);

        try
        {
            printd_pos.Print();
        }
        catch (Exception ex)
        {
            MessageBox(ex.Message);
            printd_pos.PrintController.OnEndPrint(printd_pos, new PrintEventArgs());
        }

    }

    private void printd_pos_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
    {
        Graphics g = e.Graphics;
        string strFile = GetPrintStr();
        Font ft = new Font("宋体", 8.5F, FontStyle.Regular);
        Point pt = new Point(0, 0);
        g.DrawString(strFile, ft, new SolidBrush(Color.Black), pt);
    }

    #region 商品种类的无刷新事件
    protected void ASPxCBProductType_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        string ParentID = e.Parameter.ToString().Split(';')[0].ToString();
        Session["ParentID"] = ParentID;
        pc2.InnerHtml = createdivstr(ParentID);
    }

    #region 二级产品信息查询一系列实现步骤
    private string createdivstr(string ParentID)  //根据一级产品大类ID查询对应的二级产品类型
    {
        string divstr = "";
        divstr += "<table>";
        JXCProductService.ProductServiceClient ProductS = new JXCProductService.ProductServiceClient();
        DataTable dt = ProductS.GetProductCategorystrdt(" AND ProductCategoryCode<>'0'  AND IsSale=1   AND ParentCategoryID=" + ParentID);
        ProductS.Close();
        int icount = 1;
        divstr += "<tr>";
        divstr += "<td>";
        foreach (DataRow dr in dt.Rows) //循环显示二级产品信息并格式化操作
        {
            divstr += "<input type=\"radio\" name=\"b\" onclick=\"javascript:ProductView.PerformCallback('" + dr["PCID"].ToString() + "')\">" + dr["ProductCategoryCode"].ToString() + "-" + dr["ProductCategoryName"].ToString() + "</input>";
            if (icount % 5 == 0)
            {
                divstr += "</td>";
                divstr += "</tr>";
                divstr += "<tr>";
                divstr += "<td>";
            }
            icount++;
        }
        if (icount % 5 == 1)
        {
            divstr = divstr.Substring(0, divstr.Length - 8);
        }
        else
        {
            divstr += "</td>";
            divstr += "</tr>";
        }
        divstr += "</table>";
        return divstr;
    }
    #endregion


    protected void Product_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        JXCSaleService.SaleServiceClient SaleS = new JXCSaleService.SaleServiceClient();


        string salestrbp = e.Parameter.Split('&')[0];
        string salestrremark = e.Parameter.Split('&')[1];
        string[] str = salestrremark.Split(';');
        #region 保存单头
        JXCSaleService.JXCSaleBills sbs = new JXCSaleService.JXCSaleBills();
        sbs.SVID = SVID;  //门店的ID
        sbs.GUID = Guid.NewGuid();
        sbs.Isable = 0;

        double unionpayCard = 0; // cUnionpayCard.Text.Trim();
        double coolCard = 0;// cCoolCard.Text.Trim();
        double checks = 0;// cCheck.Text.Trim();
        double alipay = 0;// cAlipay.Text.Trim();
        string entryPeople = cEntryPeople.Text.Trim();


        //银联卡手续费
        double unionpayCommission = 0.00;
        //雅酷卡手续费
        double coolCommission = 0.00;
        //实收金额
        double paidAmount = 0.00;
        //应收金额
        double amountReceivable = 0.00;
        //现金金额
        double cashs = 0.00;
        if (str != null)
        {
            //备注
            sbs.SaleRemark = str[0];
            //实收金额
            paidAmount = double.Parse(str[1]);
            //应收金额
            amountReceivable = double.Parse(str[2]);
            //现金金额
            if (str[3] != "")
            {
                cashs = double.Parse(str[3]);
            }
            if (str[4] != "")
            {
                unionpayCard = double.Parse(str[4]);
            }

            if (str[5] != "")
            {
                coolCard = double.Parse(str[5]);
            }
            if (str[6] != "")
            {
                checks = double.Parse(str[6]);
            }
            if (str[7] != "")
            {
                alipay = double.Parse(str[7]);
            }
        }
        //现金
        sbs.Cash = cashs;
        //银联卡金额

        sbs.UnionpayCard = unionpayCard;
        //银联卡支付的1%,20000以上20封顶

        if (unionpayCard < 20000)
        {
            JXC.JXCBase.RefreshBasedt();
            DataRow[] drs = JXC.JXCBase.BaseDT.Select(" InfoName='银联支付手续费'");
            unionpayCommission = unionpayCard * double.Parse(drs[0]["InfoCode"].ToString());
        }
        else
        {
            JXC.JXCBase.RefreshBasedt();
            DataRow[] drs = JXC.JXCBase.BaseDT.Select(" InfoName='银联支付手续费封顶'");
            unionpayCommission = double.Parse(drs[0]["InfoCode"].ToString());
        }


        //雅酷卡金额

        sbs.CoolCard = coolCard;
        //雅酷卡支付的10%。
        DataRow[] drs1 = JXC.JXCBase.BaseDT.Select(" InfoName='雅酷卡支付手续费'");
        coolCommission = coolCard * double.Parse(drs1[0]["InfoCode"].ToString());

        //银联手续费
        sbs.UnionpayCommission = unionpayCommission;
        //雅酷卡手续费
        sbs.CoolCommission = coolCommission;
        //手续费=银联卡手续费+雅酷卡手续费
        sbs.Commission = unionpayCommission + coolCommission;
        //销售金额=实收金额-手续费
        sbs.SalesAmount = paidAmount - unionpayCommission - coolCommission;
        //让利金额=应收金额-实收金额
        sbs.ConcessionsAmount = amountReceivable - paidAmount;
        //支票

        sbs.Checkes = checks;


        //支付宝

        sbs.Alipay = alipay;
        if (paidAmount <= 0)
        {
            pc4.InnerText = "请输入销售商品的数量!";
            btnPrinter.Enabled = false;
            return;

        }

        if (paidAmount != (cashs + unionpayCard + coolCard + checks + alipay))
        {
            pc4.InnerText = "实收金额与现金,银联卡,雅酷卡,支票,支付宝之和不相等!";
            btnPrinter.Enabled = false;
            return;

        }

        //客户类型
        sbs.BuyerType = BuyerType.Text.Trim();
        if (BuyerType.Text.Trim() == "会员")
        {
            //会员卡号
            if (str[8].ToString() == "")
            {
                pc4.InnerText = "请填写会员卡号";
                btnPrinter.Enabled = false;
                return;
            }
            else
            {
                sbs.CardNo = str[8].ToString();

                JXCQCService.QCServiceClient qc = new JXCQCService.QCServiceClient();
                DataTable dtqc = new DataTable();

                dtqc = qc.GetBuyerMember(" and MemberCardNO=" + str[8].ToString());
                if (dtqc != null)
                {
                    if (dtqc.Rows.Count > 0)
                    {
                        double jifen = 0.0;
                        double sumJiFen = 0.0;
                        jifen = double.Parse(dtqc.Rows[0][6].ToString()) + paidAmount;
                        sumJiFen = double.Parse(dtqc.Rows[0][11].ToString()) + paidAmount;
                        bool count1 = qc.UpdateBM2(jifen, sumJiFen, str[8].ToString());
                        sbs.BMID = int.Parse(dtqc.Rows[0][0].ToString());
                    }
                    else
                    {
                        JXCQCService.JXC_S_BuyerMember bm = new JXCQCService.JXC_S_BuyerMember();
                        JXCSelfService.SelfServiceClient self = new JXCSelfService.SelfServiceClient();
                        DataTable dtMD = self.BindMD(" and SVID=" + SVID);

                        bm.MemberName = str[8].ToString();
                        bm.MemberCardNO = str[8].ToString();
                        bm.MemberCategory = UserName;
                        bm.PhoneNumber = "";
                        bm.MemberType = "个人";
                        bm.MemberPoints = decimal.Parse(paidAmount.ToString());
                        bm.DiscountRate = "九折";
                        bm.CreateTime = DateTime.Now.ToString("yyyy-MM-dd");
                        bm.IntergralCounts = 0;
                        bm.IntergralSumCounts = decimal.Parse(paidAmount.ToString());
                        bm.SVID = SVID;
                        if (dtMD != null)
                        {
                            if (dtMD.Rows.Count > 0)
                            {
                                bm.SalesName = dtMD.Rows[0][1].ToString();
                            }
                        }

                        bool reslut = qc.InsertBM(bm);
                        DataTable dtbm = new DataTable();

                        dtbm = qc.GetBuyerMember(" and MemberCardNO=" + str[8].ToString());
                        if (dtbm.Rows.Count > 0)
                        {
                            sbs.BMID = int.Parse(dtbm.Rows[0][0].ToString());
                        }
                    }
                }

            }

        }
        else
        {
            sbs.CardNo = str[8].ToString();
        }

        if (cSaleDate.Text != "")
        {
            //销售日期
            sbs.SaleTime = DateTime.Parse(cSaleDate.Text.ToString());
        }
        else
        {
            sbs.SaleTime = DateTime.Now;
        }

        JXCSelfService.SelfServiceClient selfService = new JXCSelfService.SelfServiceClient();

        DataTable dt = selfService.GetDayAndDate(SVID);
        if (dt.Rows[0][0].ToString() != "" & dt.Rows[0][0].ToString() != null)
        {
            if (DateTime.Parse(sbs.SaleTime.ToString("yyyy-MM-dd")) <= DateTime.Parse(dt.Rows[0][0].ToString()))
            {
                pc3.InnerText = "您选择的销售日期已经日结,请先删除该日期的日结报表!";
                btnPrinter.Enabled = false;
                return;
            }
        }

        //录入人
        if (entryPeople != "")
        {
            sbs.Payee = entryPeople;
        }
        else
        {
            sbs.Payee = UserName;
        }


        int result = SaleS.InsertSaleBills(sbs);
        #endregion
        bool Condition = true;
        if (result > 0)
        {
            #region 保存明细
            string bpstr = salestrbp.ToString().Substring(0, salestrbp.Length - 2);
            string bpssss = bpstr.Split('*')[1];
            string[] bpids = bpssss.Split('$');
            foreach (string bps in bpids)
            {
                JXCSaleService.JXCSaleBillDetail sbd = new JXCSaleService.JXCSaleBillDetail();
                string[] orderpid = bps.Split(';');
                sbd.BPID = int.Parse(orderpid[0]);
                sbd.SaleCounts = double.Parse(orderpid[1]);
                sbd.PredictSaleAmount = double.Parse(orderpid[2]);
                sbd.SLID = result;
                Condition = SaleS.InsertSaleBillDetail(sbd);
            }
            #endregion
        }
        if (result > 0 && Condition)
        {
            int isable = int.Parse(salestrbp.ToString().Substring(salestrbp.Length - 1, 1));
            Dictionary<object, object> ht = new Dictionary<object, object>();
            ht.Add("isable", isable);
            ht.Add("SLID", result);
            if (SaleS.UpdateByht(ht, "JXC_S_SaleBill"))
            {
                pc3.InnerText = "保存成功!";
                btnPrinter.Enabled = true;
                Session["mdSLID"] = result; //获得销售单ID


                datas_ = SaleS.GetSaleBillItemsBySlid(Convert.ToInt32(Session["mdSLID"]));

                discount_ = amountReceivable - paidAmount;   //优惠金额
                amount_ = amountReceivable; // 应收金额
                recv_cash_ = paidAmount;  // 收款金额

                card_no_ = str[8].ToString(); // 会员卡号
                if (card_no_ != "")
                {
                    mark_in_ = paidAmount; // 本次积分
                }
                print();

            } //调用销售信息方法   
            else
            {
                pc3.InnerText = "保存失败!请联系管理员!";
            }
        }
        else
        {
            pc3.InnerText = "保存失败!请联系管理员!";
        }
        SaleS.Close();
        cEntryPeople.Text = "";


    }



    protected void ProductView_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
        if (e.Parameter != "")
        {
            Session["getpcID"] = e.Parameter.ToString();
            GetDataViewBind();
        }

    }
    #endregion
    protected void btnNew_Click(object sender, EventArgs e)
    {
        Session["SaleGUID"] = GetGuid();
    }
    #region 绑定DataView
    protected void GetDataViewBind()
    {
        JXCProductService.ProductServiceClient psProdData = new JXCProductService.ProductServiceClient();
        DataTable dt = new DataTable();
        if (!JXC.fun.IsNull(this, "getpcID"))
        {
            if (!JXC.fun.IsNull(this, "ParentID"))
            {
                dt = psProdData.GetProDataViewInformation2(Convert.ToInt32(Session["getpcID"]), SVID, WHID);
            }
        }
        ASPxDataView1.DataSource = dt;
        ASPxDataView1.DataBind();
        psProdData.Close();
    }
    #endregion

    /// <summary>
    /// 打印门店订单方法
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnPrinter_Click(object sender, EventArgs e)
    {
        //CreateBlendListReport(Session["mdSLID"].ToString());
        //Session["mdp"] = Session["mdSLID"].ToString();

        print();
    }

    #region 报表打印的代码
    protected void CreateBlendListReport(string slid)
    {
        if (slid != null || slid != "")
        {
            JXCSelfService.SelfServiceClient saleItem = new JXCSelfService.SelfServiceClient();
            XtraReport xpst = null;
            DataTable dt = new DataTable();
            hidFidMDSale.Value = Session["mdSLID"].ToString();
            ASPxPCmdSalePrint.Top = 100;
            ASPxPCmdSalePrint.Left = 200;
            ASPxPCmdSalePrint.ShowOnPageLoad = true;
            xpst = XtraReport.FromFile(Server.MapPath("~") + "\\Models\\JXC\\Reports\\SaleList.repx", true);
            if (Session["mdSLID"] != null)
            {
                xpst.DataSource = saleItem.GetSaleBillItemsBySlid(Convert.ToInt32(Session["mdSLID"]));
            }
            xpst.Parameters["times"].Value = DateTime.Now.ToString("yyyy年MM月dd日");
            xpst.CreateDocument();
            RvmdPrint.Report = xpst;
            RvmdPrint.DataBind();
            saleItem.Close();
        }
        else
        {
            MessageBox("抱歉,暂无报表。");
        }
    }
    #endregion


}