using GenCode128;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace StekloMaster
{
    public partial class Form17 : Form
    {
        public Form17()
        {
            InitializeComponent();
        }
        string putin = "";
        string fullzakaz = "";
        string manager = "";
        string telmanager = "";

        public void master()
        {
            button3.Visible = false;
            button10.Visible = false;
            button9.Visible = false;
            button2.Visible = false;
            button5.Visible = false;
            button6.Visible = false;
            button14.Visible = false;
            button15.Visible = false;
            textBox12.Visible = false;
            button7.Visible = button8.Visible = false;
            button13.Location = new Point(button13.Location.X, button4.Location.Y + button4.Height + 5); 
            panel9.Visible = true;
            button17.Visible = button18.Visible = true;
            textBox14.Visible = false;
            textBox11.Visible = false;
            label19.Visible = false;
            label33.Visible = false;
            label34.Visible = false;
            panel3.Visible = false;
            panel3.Width = button18.Width;
            panel3.Location = new Point(button18.Location.X, button18.Location.Y + 30);

        }
        private void Form17_Shown(object sender, EventArgs e)
        {
            if (Application.StartupPath.IndexOf("comp") != -1)
            {
                putin = Application.StartupPath.Substring(0, Application.StartupPath.IndexOf("\\comp"));
            }
            else
            {
                putin = Application.StartupPath;
            }
            if (Directory.Exists(putin + "\\baza"))
            {
                var files = Directory.GetDirectories(putin + "\\baza");
                var iter = files.OrderByDescending(f => Directory.GetCreationTime(f));
                listBox1.BeginUpdate();

                foreach (var item in iter)
                {
                    if (listBox1.Items.Count < 50)
                        listBox1.Items.AddRange(new object[] { item.Substring(item.LastIndexOf("\\") + 1) });
                    else
                        break;
                }
                listBox1.EndUpdate();
                if (listBox1.Items.Count != 0)
                {
                    listBox1.SelectedIndex = 0;
                }
            }
            else
            {
                MessageBox.Show("База пуста, просмотр не возможен!");
                this.Close();
            }
            comboBox1.SelectedIndex = 0;

            ToolStripButton b = new ToolStripButton();
            b.Image = Properties.Resources.settings_gears;
            b.DisplayStyle = ToolStripItemDisplayStyle.Image;
            b.Click += printPreview1_PrintClick;
            // ((ToolStrip)(printPreviewDialog1.Controls[1])).Items.RemoveAt(0);
            ((ToolStrip)(printPreviewDialog1.Controls[1])).Items.Insert(1, b);

            ToolStripButton b2 = new ToolStripButton();
            b2.Image = Properties.Resources.settings_gears;
            b2.DisplayStyle = ToolStripItemDisplayStyle.Image;
            b2.Click += printPreview2_PrintClick;
            ((ToolStrip)(printPreviewDialog2.Controls[1])).Items.Insert(1, b2);

            ToolStripButton b3 = new ToolStripButton();
            b3.Image = Properties.Resources.settings_gears;
            b3.DisplayStyle = ToolStripItemDisplayStyle.Image;
            b3.Click += printPreview3_PrintClick;
            ((ToolStrip)(printPreviewDialog3.Controls[1])).Items.Insert(1, b3);
        }


        private void printPreview1_PrintClick(object sender, EventArgs e)
        {
            try
            {
                printDialog1.Document = printDocument1;

                if (printDialog1.ShowDialog() == DialogResult.OK)
                {
                    printDocument1.PrinterSettings = printDialog1.PrinterSettings;

                    printDocument1.Print();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ToString());
            }
        }

        private void printPreview2_PrintClick(object sender, EventArgs e)
        {
            try
            {
                printDialog1.Document = printDocument2;

                if (printDialog1.ShowDialog() == DialogResult.OK)
                {
                    printDocument2.PrinterSettings = printDialog1.PrinterSettings;

                    printDocument2.Print();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ToString());
            }
        }

        private void printPreview3_PrintClick(object sender, EventArgs e)
        {
            try
            {
                printDialog1.Document = printDocument3;

                if (printDialog1.ShowDialog() == DialogResult.OK)
                {
                    printDocument3.PrinterSettings = printDialog1.PrinterSettings;

                    printDocument3.Print();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ToString());
            }
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex == -1) return;
            string fq = "";
            if (File.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\tovar.akv"))
            {
                StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\tovar.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                fq = Sr.ReadToEnd();
                Sr.Close();
                Sr = null;

                string[] sd = fq.Split('|');
                //название | цена общая | кол-во | комментарий мастеров | файлы | резерв | цена за шт |резерв 1| резерв 2| резерв 3 | резерв 4 | резерв 5 |
                label37.Text = sd[0];
                label19.Text = sd[1];
                numericUpDown8.Value = Convert.ToDecimal(sd[2]);
                richTextBox2.Text = sd[3].Replace("<r>", "\r").Replace("<n>", "\n");
                label33.Text = sd[5];
                label34.Text = sd[6];

                scrit_panel();

                if (sd[0] == "Скинали")
                {
                    panel10.Visible = true;
                //    //+  Таблица панели|Таблица товары и услуги|
                    dataGridView1.Rows.Clear();
                    if (sd[12] != "" && sd[12] != null)
                    {
                        string[] bd2 = sd[12].Split('~');
                        foreach (string s in bd2)
                        {
                            if (s != "")
                            {
                                string[] f = s.Split('!');
                                int i = dataGridView1.Rows.Count;
                                dataGridView1.Rows.Add();
                                for (int h = 0; h < 11; h++)
                                    dataGridView1.Rows[i].Cells[h].Value = f[h];
                            }

                        }
                    }
                    if (dataGridView1.Rows.Count != 0)
                    {
                        dataGridView1.Rows[0].Selected = true;
                        dataGridView1.FirstDisplayedScrollingRowIndex = 0;
                        dataGridView1.Rows[0].Cells[0].Selected = true;
                        dataGridView1_CurrentCellChanged(null, null);
                    }
                    else
                        dataGridView2.Rows.Clear();
                    //т и у
                    dataGridView3.Rows.Clear();
                    if (sd[13] != "" && sd[13] != null)
                    {
                        string[] bd2 = sd[13].Split('~');
                        foreach (string s in bd2)
                        {
                            if (s != "")
                            {
                                string[] f = s.Split('!');
                                int i = dataGridView3.Rows.Count;
                                dataGridView3.Rows.Add();
                                for (int h = 0; h < 4; h++)
                                    dataGridView3.Rows[i].Cells[h].Value = f[h];
                            }

                        }
                    }
                }
                else if (sd[0] == "Другое")
                {
                    panel15.Visible = true;
                    //+Название|Цена
                    textBox4.Text = sd[12];
                    textBox6.Text = sd[13];
                }
            }
            //чтение прикрепленных файлов
            listBox2.Items.Clear();
            if (Directory.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\files"))
            {
                var files = Directory.GetFiles(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\files");
                foreach (var item in files)
                {
                    listBox2.Items.AddRange(new object[] { item.Substring(item.LastIndexOf("\\") + 1) });
                }
            }
            //чтение данных клиента
            if (File.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\klient.akv"))
            {
                panel1.Visible = true;
                string h = "";
                StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\klient.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                h = Sr.ReadToEnd();
                Sr.Close();
                string[] tmp = h.Split('|');
                textBox8.Text = tmp[0];
                textBox7.Text = tmp[1];
                textBox3.Text = tmp[2];
                if (tmp[3] == "М")
                    radioButton2.Checked = true;
                else
                    radioButton1.Checked = true;
                textBox2.Text = tmp[4];
                numericUpDown1.Value = Convert.ToDecimal(tmp[5]);
                numericUpDown2.Value = Convert.ToDecimal(tmp[6]);
                textBox5.Text = tmp[7];
                textBox9.Text = tmp[8].Replace("\n","  ");
            }
            else
            {
                panel1.Visible = false;
            }
            //чтение общих данных
            if (File.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\zakaz.akv"))
            {
                string h = "";
                StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\zakaz.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                h = Sr.ReadToEnd();
                Sr.Close();
                string[] tmp = h.Split('|');
                //дата|номер|срочный 1 - да | ндс | общая скидка |цена доставки|адрес доставки | подъем на этаж | кол-во единиц | цена | вид оплаты | 
                label32.Text = tmp[0];
                label41.Text = tmp[1];
                checkBox1.Checked = (tmp[2] == "1");
                numericUpDown4.Value = Convert.ToDecimal(tmp[3]);
                if (tmp[4].IndexOf("raspred") != -1)
                {
                    label6.Text = "Общ.ск.:";
                    label57.Visible = textBox16.Visible = true;
                    label13.Visible = numericUpDown3.Visible = false;
                    textBox16.Text = tmp[4].Replace("raspred", "");
                }
                else
                {
                    label6.Text = "Скидка:";
                    label57.Visible = textBox16.Visible = false;
                    label13.Visible = numericUpDown3.Visible = true;
                    numericUpDown3.Value = Convert.ToDecimal(tmp[4]);
                }
                textBox11.Text = tmp[5];
                textBox12.Text = tmp[6];
                textBox15.Text = tmp[7];
                textBox13.Text = tmp[8];
                textBox14.Text = tmp[9];
                radioButton4.Checked = (tmp[10] == "1");
                radioButton5.Checked = (tmp[10] == "2");
                radioButton3.Checked = (tmp[10] == "3");
                radioButton6.Checked = (tmp[10] == "4");
                //сколько оплачено | остаток | объединеные заказы | общая сумма оплаты | общий оплачено |как слать смс (1 - на одну) | Дата готовности
                if (File.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\doplata.akv"))
                {
                    string str33 = "";
                    double opl = 0;
                    using (StreamReader sr = new StreamReader(new FileStream(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\doplata.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                    {
                        while ((str33 = sr.ReadLine()) != null)
                        {
                            if (str33 == "") continue;
                            if(str33.Split('|')[1]!="")
                                opl += Convert.ToDouble(str33.Split('|')[1]);
                        }
                    }
                    textBox10.Text = (opl+Convert.ToDouble(tmp[11])).ToString();
                    label10.Text = (Convert.ToDouble(tmp[12]) - opl).ToString();
                    radioButton7.Checked = true;
                }
                else
                {
                    textBox10.Text = tmp[11];
                    label10.Text = tmp[12];
                }
                fullzakaz = tmp[13];
                obshchet = tmp[14];
                //tmp[15]
                if(tmp[16]=="1")
                {
                    radioButton11.Checked = true;
                }
                else
                {
                    radioButton10.Checked = true;
                }
                dateTimePicker1.Text = tmp[17];
                label48.Visible = false;
                try
                {
                    manager = tmp[18];
                    telmanager = tmp[19];
                    if(tmp[20]!= "0")
                    {
                        label48.Visible = true;
                        label19.Text = (Convert.ToDouble(label19.Text) + Convert.ToDouble(tmp[20]) + Convert.ToDouble(tmp[21])).ToString();
                    }
                    prdostavka = tmp[20];
                    prpodem = tmp[21];
                }
                catch { }
            }
            label44.Visible = (File.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\zabran.akv"));
        }
        string prdostavka = "";
        string prpodem = "";
        string obshchet = "";

        public void reload_active()
        {
            if (listBox1.SelectedIndex != -1)
                listBox1_SelectedIndexChanged(null, null);
        }

        /// <summary>
        /// Скрывает все панели товаров
        /// </summary>
        private void scrit_panel()
        {
            panel10.Visible = false;
            panel15.Visible = false;
        }
        private void listBox2_DoubleClick(object sender, EventArgs e)
        {
            if (listBox2.SelectedIndex != -1)
                System.Diagnostics.Process.Start(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\files\\"+listBox2.Items[listBox2.SelectedIndex].ToString());
        }

        private void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null)
            {
                dataGridView2.Enabled = false;
            }
            else
            {
                dataGridView2.Rows.Clear();
                dataGridView2.Enabled = true;
                string zna = "";
                if (dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[10].Value != null && dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[10].Value.ToString() != "")
                    zna = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[10].Value.ToString();
                if (zna != "" && zna != null)
                {
                    string[] bd2 = zna.Split('`');
                    foreach (string s in bd2)
                    {
                        if (s != "")
                        {
                            string[] f = s.Split('@');
                            int i = dataGridView2.Rows.Count;
                            dataGridView2.Rows.Add();
                            for (int h = 0; h < 6; h++)
                                dataGridView2.Rows[i].Cells[h].Value = f[h];
                        }

                    }
                }
            }
        }

        private void dataGridView1_DoubleClick(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null) return;
            Form18 f1 = new Form18();
            f1.Owner = this;
            f1.edit = dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[0].Value + "|" + dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[1].Value + "|" + dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[2].Value + "|" + dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[3].Value + "|" + dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[4].Value + "|" + dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[5].Value + "|" + dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[6].Value + "|" + dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[7].Value + "|" + dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[8].Value + "|" + dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[9].Value + "|";
            f1.Show();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex == -1) return;
            if (MessageBox.Show("Вы действительно хотите удалить текущий заказ?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                Directory.Delete(putin + "\\baza\\" + listBox1.SelectedItem.ToString(),true);
                listBox1.Items.RemoveAt(listBox1.SelectedIndex);
            }

        }

        private void button4_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            string[] group = fullzakaz.Split('>');
            foreach (string tmp in group)
            {
                if (tmp == null || tmp == "") continue;
                string tmp2 = tmp.Replace("<", "");
                if (tmp2 != null && tmp2 != "")
                {
                    listBox1.Items.AddRange(new object[] { tmp2 });

                }
            }
        }

        private void button25_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            if (Directory.Exists(putin + "\\baza"))
            {
                var files = Directory.GetDirectories(putin + "\\baza");
                var iter = files.OrderByDescending(f => Directory.GetCreationTime(f));
                foreach (var item in iter)
                {
                    listBox1.Items.AddRange(new object[] { item.Substring(item.LastIndexOf("\\") + 1) });
                }
                if (listBox1.Items.Count != 0)
                {
                    listBox1.SelectedIndex = 0;
                }
            }
            else
            {
                MessageBox.Show("База пуста, просмотр не возможен!");
                this.Close();
            }
        }

        private void button9_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex == -1) return;
            if (MessageBox.Show("Вы действительно хотите удалить текущий заказ с привязанной группой?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes)
            {
                string[] group = fullzakaz.Split('>');
                foreach (string tmp in group)
                {
                    if (tmp == null||tmp=="") continue;
                    string tmp2 = tmp.Replace("<", "");
                    if (tmp2 != null && tmp2 != "")
                    {
                        Directory.Delete(putin + "\\baza\\" + tmp2, true);
                        for (int i = 0; i < listBox1.Items.Count;i++ )
                        {
                            if(listBox1.Items[i].ToString() == tmp2)
                            {
                                listBox1.Items.RemoveAt(i);
                            }
                        }
                            
                    }
                }
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            if(label10.Text == "0")
            {
                MessageBox.Show("Данный товар оплачен полностью!");
                return;
            }
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form19")
                {
                    MessageBox.Show("Меню оплаты уже открыто!");
                    return;
                }
            }
            Form19 f1 = new Form19();
            f1.Owner = this;
            f1.zakaz = "<" + label41.Text.Replace("№","") + ">";
            f1.ostatok = label10.Text;
            f1.Show();
            f1.Focus();
        }

        private void button11_Click(object sender, EventArgs e)
        {
            if(textBox10.Text == "0")
            {
                MessageBox.Show("Оплат нет!");
                return;
            }
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form21")
                {
                    MessageBox.Show("Доплаты уже открыты!");
                    return;
                }
            }
            Form21 f1 = new Form21();
            f1.Owner = this;
            f1.zakaz = label41.Text.Replace("№", "");
            f1.Show();
            f1.Focus();
        }

        private void button10_Click(object sender, EventArgs e)
        {
            button4_Click(null, null);
            double opl = 0;
            double ost = 0;
            for(int i =0; i <listBox1.Items.Count;i++)
            {
                listBox1.SelectedIndex = i;
                opl += Convert.ToDouble(textBox10.Text);
                ost += Convert.ToDouble(label10.Text);
            }
            if(ost == 0)
            {
                MessageBox.Show("Данная группа полностью оплачена!");
                return;
            }
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form19")
                {
                    MessageBox.Show("Меню оплаты уже открыто!");
                    return;
                }
            }
            Form19 f1 = new Form19();
            f1.Owner = this;
            f1.zakaz = fullzakaz;
            f1.ostatok = ost.ToString();
            f1.Show();
            f1.Focus();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form22")
                {
                    MessageBox.Show("Меню редактора уже открыто!");
                    return;
                }
            }

            Form22 f1 = new Form22();
            f1.Owner=this;
            f1.Show();
            f1.zak = "<" + label41.Text.Replace("№", "") + ">";
        }

        private void button6_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form22")
                {
                    MessageBox.Show("Меню редактора уже открыто!");
                    return;
                }
            }

            Form22 f1 = new Form22();
            f1.Owner = this;
            f1.Show();
            f1.zak = fullzakaz;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if(textBox1.Text == "")
            {
                MessageBox.Show("Не задан параметр поиска!");
                return;
            }
            listBox1.Items.Clear();
            ОЖИДАНИЕ hg = null;
            this.Enabled = false;
            hg = new ОЖИДАНИЕ();
            hg.opis = "Выполняем поиск...";
            hg.Show();
            int sct = comboBox1.SelectedIndex;
            Thread nom = new Thread(delegate ()
            {
                if (sct == 0)
                {
                    if (Directory.Exists(putin + "\\baza"))
                    {
                        var files = Directory.GetDirectories(putin + "\\baza");
                        var iter = files.OrderByDescending(f => Directory.GetCreationTime(f));
                        foreach (var item in iter)
                        {
                            if (item.IndexOf(textBox1.Text) != -1)
                            {
                                this.Invoke(new EventHandler(delegate
                                {
                                    listBox1.Items.AddRange(new object[] { item.Substring(item.LastIndexOf("\\") + 1) });
                                }));
                            }
                        }
                       
                    }
                    else
                    {
                        this.Invoke(new EventHandler(delegate
                        {
                            MessageBox.Show("База пуста, просмотр не возможен!");
                            this.Close();
                        }));
                       
                    }
                }
                else
                {
                    if (Directory.Exists(putin + "\\baza"))
                    {
                        var files = Directory.GetDirectories(putin + "\\baza");
                        var iter = files.OrderByDescending(f => Directory.GetCreationTime(f));
                        foreach (var item in iter)
                        {
                            string[] fisles = Directory.GetFiles(item);
                            foreach (var file in fisles)
                            {
                                //открываем смотрим файл
                                string h = "";
                                StreamReader Sr = new StreamReader(new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read));
                                h = Sr.ReadToEnd();
                                Sr.Close();
                                if(h.IndexOf(textBox1.Text)!= -1)
                                {
                                    this.Invoke(new EventHandler(delegate
                                    {
                                        listBox1.Items.AddRange(new object[] { item.Substring(item.LastIndexOf("\\") + 1) });
                                    }));
                                    break;
                                }
                            }
                        }

                    }
                    else
                    {
                        this.Invoke(new EventHandler(delegate
                        {
                            MessageBox.Show("База пуста, просмотр не возможен!");
                            this.Close();
                        }));

                    }
                }
                this.Invoke(new EventHandler(delegate
                {
                    hg.Close();
                    this.Enabled = true;
                    if (listBox1.Items.Count != 0)
                    {
                        listBox1.SelectedIndex = 0;
                    }
                }));
            });
            nom.IsBackground = true;
            nom.Start();
        }

        private void textBox1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button1_Click(null, null);
            }
        }

        private void button8_Click(object sender, EventArgs e)
        {
            printPreviewDialog1.Document = printDocument1;
            ((Form)printPreviewDialog1).WindowState = FormWindowState.Maximized;
            ((Form)printPreviewDialog1).Icon = this.Icon;
            printPreviewDialog1.ShowDialog();
        }

        string komandpring = "";
        int pageprint = 0;
        int numberlist = 1;

        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Image myimg = null;
            try
            {
                if (label41.Text.Replace("№", "") != "-")
                    myimg = Code128Rendering.MakeBarcodeImage(label41.Text.Replace("№", ""), 2, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, this.Text);
            }

            try
            {
                Graphics g = e.Graphics;
                String textToPrint = "";
                int a = 30;
                Font printFont = new Font("Arial", 12);
                Font printFont2 = new Font("Arial", 12, System.Drawing.FontStyle.Bold);
                int kol = dataGridView1.RowCount;
                int b = 15;
                    Font font = new Font("Tahoma", 9);
                    Image bs = Properties.Resources.logo;
                    if (komandpring == "")
                    {

                        g.DrawImage(bs, new Point(a, b));

                        b += 15;
                        bs = Properties.Resources.location;
                        g.DrawImage(bs, new Point(180, b));
                        g.DrawString(Статика.Печать_Адрес, font, Brushes.Black, 200, b);

                        bs = Properties.Resources.inet;
                        g.DrawImage(bs, new Point(550, b));
                        g.DrawString(Статика.Печать_Сайт, font, Brushes.Black, 570, b);

                        bs = Properties.Resources.phone;
                        g.DrawImage(bs, new Point(180, b + 20));
                        g.DrawString(Статика.Печать_Телефон, font, Brushes.Black, 200, b + 20);

                        bs = Properties.Resources.mail;
                        g.DrawImage(bs, new Point(550, b + 20));
                        g.DrawString(Статика.Печать_Почта, font, Brushes.Black, 570, b + 20);

                        bs = Properties.Resources.time;
                        g.DrawImage(bs, new Point(180, b + 40));
                        g.DrawString(Статика.Печать_График, font, Brushes.Black, 200, b + 40);
                        int multiline = (int)e.Graphics.MeasureString(Статика.Печать_График, font, 1000).Height;
                        if (multiline > 32)
                        {
                            b += multiline - 32;
                        }
                    b += 80;

                        //общий хеадер
                        g.DrawLine(new Pen(Color.Black, 2), new Point(a, b), new Point(785, b));
                        g.DrawLine(new Pen(Color.Black, 2), new Point(a, b + 40), new Point(785, b + 40));
                        b += 2;
                        //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 720, 35));
                        textToPrint = "";
                        if (checkBox1.Checked)
                            textToPrint += "СРОЧНЫЙ заказ №" + label41.Text.Replace("№", "") + "\r\nот " + label32.Text.Replace("Дата : ", "");
                        else
                            textToPrint += "Заказ №" + label41.Text.Replace("№", "") + "\r\nот " + label32.Text.Replace("Дата : ", "");
                        // textToPrint += "\r\nМенеджер: " + label31.Text;
                        g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                        g.DrawString("Дата готовности: ", printFont2, Brushes.Black, 240, b);
                        g.DrawString(dateTimePicker1.Text, printFont, Brushes.Black, 240, b + 18);
                        textToPrint = "Менеджер: " + manager + " "+ telmanager;
                        g.DrawString(textToPrint, printFont, Brushes.Black, a, b + 40);
                        if (textBox2.Text != "" && panel1.Visible && textBox2.Text != "79")
                        {
                            textToPrint = textBox2.Text;
                            g.DrawString(textToPrint, printFont, Brushes.Black, 420, b);
                        }
                        b += 36;
                        if (panel1.Visible && textBox8.Text != "" && textBox7.Text != "" && textBox3.Text != "")
                        {
                            textToPrint = textBox8.Text.Substring(0, 1) + textBox8.Text.ToLower().Substring(1) + " " + textBox7.Text.Substring(0, 1) + textBox7.Text.ToLower().Substring(1) + " " + textBox3.Text.Substring(0, 1) + textBox3.Text.ToLower().Substring(1);
                            g.DrawString(textToPrint, printFont, Brushes.Black, 420, b - 18);
                        }
                    //b += 30;
                        //b += 30;
                        b += 20;
                        //примечание
                        if (richTextBox2.Text != "")
                        {
                            g.DrawString("ПРИМЕЧАНИЕ: ", printFont2, Brushes.Black, a, b);
                            string measureString = "                            " + richTextBox2.Text.Replace("\r", "").Replace("\n", " ");
                            int stringWidth = 755;
                            SizeF stringSize = new SizeF();
                            stringSize = e.Graphics.MeasureString(measureString, printFont2, stringWidth);
                            Rectangle gs = new Rectangle(a, b, 755, (int)stringSize.Height);
                            g.DrawString(measureString, printFont, Brushes.Black, gs);
                            b += (int)stringSize.Height;

                       /* g.DrawString("ПРИМЕЧАНИЕ: ", printFont2, Brushes.Black, a, b);
                            textToPrint = richTextBox2.Text.Replace("\r", "").Replace("\n", " ");
                            g.DrawString(textToPrint, printFont, Brushes.Black, a + 130, b);
                            // b += 16;
                            b += 30; */
                        }
                        else
                        {
                            b += 7;
                        }
                }
                    //ожидаемый товар скинали
                    if (label37.Text == "Скинали")
                    {
                        if (komandpring == "" || komandpring == "skin")
                        {
                            if (dataGridView1.Rows.Count != 0)
                            {
                                if (komandpring == "")
                                    b -= 22;
                                int i = 0;
                                if (komandpring == "skin")
                                    i = pageprint;
                                for (; i < dataGridView1.Rows.Count; i++)
                                {
                                    a = 30;
                                    b += 16; int prikin = 86;
                                    if (dataGridView1[8, i].Value.ToString() != "")
                                    {
                                        string measureString = "Виды декорирования:   " + dataGridView1[8, i].Value.ToString();
                                        int stringWidth = 755;
                                        SizeF stringSize = new SizeF();
                                        stringSize = e.Graphics.MeasureString(measureString, printFont, stringWidth);
                                        Rectangle gs = new Rectangle(a, b, 755, (int)stringSize.Height);
                                        prikin += (int)stringSize.Height;
                                    }
                                    if (dataGridView1[5, i].Value.ToString() != "")
                                    {
                                        string[] bd2 = dataGridView1[5, i].Value.ToString().Split(';');
                                        foreach (string s in bd2)
                                        {
                                            if (s != "")
                                            {
                                                prikin += 16;
                                            }
                                        }
                                    }
                                    string zna = "";
                                    if (dataGridView1[10, i].Value != null && dataGridView1[10, i].Value.ToString() != "")
                                        zna = dataGridView1[10, i].Value.ToString();
                                    if (zna != "" && zna != null)
                                    {
                                        prikin -= 22;
                                        string[] bd2 = zna.Split('`');
                                        foreach (string s in bd2)
                                        {
                                            if (s != "")
                                            {
                                                string[] f = s.Split('@');
                                                prikin += 22;
                                            }

                                        }
                                        prikin += 16;
                                    }
                                    if (b + prikin > e.MarginBounds.Bottom)
                                    {
                                        g.DrawString(label41.Text.Replace("№", "") + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                                        numberlist++;
                                        e.HasMorePages = true;
                                        pageprint = i;
                                        komandpring = "skin";
                                        return;
                                    }
                                    g.DrawString("№ ", printFont2, Brushes.Black, a, b);
                                    g.DrawString(dataGridView1[0, i].Value.ToString(), printFont, Brushes.Black, a + 20, b);
                                    b += 16;
                                    g.DrawString("Материал: ", printFont2, Brushes.Black, a, b);
                                    g.DrawString(dataGridView1[3, i].Value.ToString(), printFont, Brushes.Black, a + 100, b);
                                    a += 450;
                                    g.DrawString("Толщина стекла: ", printFont2, Brushes.Black, a, b);
                                    g.DrawString(dataGridView1[4, i].Value.ToString(), printFont, Brushes.Black, a + 150, b);
                                    // a += 230;
                                    b += 16;
                                    a = 30;
                                    if (dataGridView1[8, i].Value.ToString() != "")
                                    {
                                        a = 30;
                                        string measureString = "Виды декорирования:   " + dataGridView1[8, i].Value.ToString();
                                        int stringWidth = 755;
                                        SizeF stringSize = new SizeF();
                                        stringSize = e.Graphics.MeasureString(measureString, printFont, stringWidth);
                                        Rectangle gs = new Rectangle(a, b, 755, (int)stringSize.Height);
                                        g.DrawString("Виды декорирования: ", printFont2, Brushes.Black, a, b);
                                        g.DrawString(measureString.Replace("Виды декорирования:   ", "                                         "), printFont, Brushes.Black, gs);
                                        b += (int)stringSize.Height;
                                    }
                                    a = 30;
                                    g.DrawString("В ", printFont2, Brushes.Black, a, b);
                                    g.DrawString(dataGridView1[1, i].Value.ToString(), printFont, Brushes.Black, a + 20, b);
                                    a += 60;
                                    g.DrawString("Ш ", printFont2, Brushes.Black, a, b);
                                    g.DrawString(dataGridView1[2, i].Value.ToString(), printFont, Brushes.Black, a + 20, b);
                                    b += 16;
                                    a = 30;
                                    g.DrawString("Форма: ", printFont2, Brushes.Black, a, b);
                                    g.DrawString(dataGridView1[6, i].Value.ToString(), printFont, Brushes.Black, a + 70, b);
                                    b += 16;
                                    a = 30;
                                    if (dataGridView1[5, i].Value.ToString() != "")
                                    {
                                        string[] bd2 = dataGridView1[5, i].Value.ToString().Split(';');
                                        foreach (string s in bd2)
                                        {
                                            if (s != "")
                                            {
                                                a = 30;
                                                g.DrawString("Вид обработки: ", printFont2, Brushes.Black, a, b);
                                                g.DrawString(s.Split('-')[0], printFont, Brushes.Black, a + 145, b);
                                                a += 450;
                                                g.DrawString(s.Split('-')[1], printFont, Brushes.Black, a, b);
                                                b += 16;
                                            }
                                        }
                                    }
                                    a = 30;
                                    g.DrawString("Закалка: ", printFont2, Brushes.Black, a, b);
                                    g.DrawString(dataGridView1[7, i].Value.ToString(), printFont, Brushes.Black, a + 80, b);
                                    b += 22;
                                    a = 30;


                                    zna = "";
                                    if (dataGridView1[10, i].Value != null && dataGridView1[10, i].Value.ToString() != "")
                                        zna = dataGridView1[10, i].Value.ToString();
                                    if (zna != "" && zna != null)
                                    {
                                        b -= 22;
                                        string[] bd2 = zna.Split('`');
                                        foreach (string s in bd2)
                                        {
                                            if (s != "")
                                            {
                                                string[] f = s.Split('@');
                                                a = 30;
                                                b += 22;
                                                g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 125, 22));
                                                g.DrawString("№ " + f[0], printFont, Brushes.Black, a + 2, b);
                                                a += 125;
                                                g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 295, 22));
                                                g.DrawString(f[1], printFont, Brushes.Black, a + 2, b);
                                                a += 295;
                                                g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));
                                                g.DrawString("Диаметр " + f[2], printFont, Brushes.Black, a + 2, b);
                                                a += 150;
                                                g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));
                                                g.DrawString("Количество " + f[3], printFont, Brushes.Black, a + 2, b);
                                                a += 150;
                                            }

                                        }
                                        b += 16;
                                    }
                                }
                                a = 30;
                                b += 16;
                                //не обнулять переменные зло
                                komandpring = "";
                                
                                if (dataGridView3.Rows.Count != 0)
                                {
                                    b += 30;
                                }
                            }
                        }
                    if (komandpring == "")
                    {
                        komandpring = "doptov";
                        pageprint = 0;
                    }
                        if (komandpring == "doptov")
                        {
                            if (dataGridView3.Rows.Count != 0)
                            {
                                if (dataGridView1.Rows.Count != 0 && komandpring != "doptov")
                                {
                                    b -= 30;
                                }
                                a = 30;
                                if (b > e.MarginBounds.Bottom)
                                {
                                    g.DrawString(label41.Text.Replace("№", "") + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                                    numberlist++;
                                    pageprint = 0;
                                    e.HasMorePages = true;
                                    return;
                                }
                                g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 605, 22));
                                g.DrawString("Доп. товары/услуги", printFont, Brushes.Black, a + 2, b);
                                a += 605;
                                g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 115, 22));
                                g.DrawString("Кол-во", printFont, Brushes.Black, a, b);
                                int i = 0;
                                if (pageprint != 0)
                                    i = pageprint;
                                for (; i < dataGridView3.Rows.Count; i++)
                                {
                                    if (b + 32 > e.MarginBounds.Bottom)
                                    {
                                        g.DrawString(label41.Text.Replace("№", "") + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 22);
                                        numberlist++;
                                        pageprint = i;
                                        e.HasMorePages = true;
                                        return;
                                    }
                                    a = 30;
                                    b += 22;
                                    g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 605, 22));
                                    g.DrawString(dataGridView3[0, i].Value.ToString(), printFont, Brushes.Black, a + 2, b);
                                    a += 605;
                                    g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 115, 22));
                                    g.DrawString(dataGridView3[1, i].Value.ToString(), printFont, Brushes.Black, a + 2, b);
                                }
                                a = 30;
                                b += 28;
                                komandpring = "";
                            }
                        }
                    }
                    else if (label37.Text == "Другое")
                    {
                        a = 30;
                        g.DrawString("Товар/Услуга: " + textBox4.Text + " цена за шт.: " + textBox6.Text + " руб.", printFont2, Brushes.Black, a, b);
                        b += 30;
                    }
                    if (komandpring == "")
                        komandpring = "footer";

                    //прикинуть фут
                    int prik = 192;
                    if (listBox2.Items.Count != 0)
                    {
                        prik += 16;
                    }
                    if (textBox11.Text != "" && textBox11.Text != "0")
                    {
                        //prik += 16;
                         if (label48.Visible)
                        {
                            if (prdostavka != "" && prdostavka != "0")
                            {
                                prik += 5;
                            }
                         }
                    }
                    if (textBox14.Text != "" && textBox14.Text != "0")
                    {
                       // prik += 16;
                        if (label48.Visible)
                        {
                            if (prpodem != "" && prpodem != "0")
                            {
                                prik += 5;
                            }
                        }
                    }
                    /*if (richTextBox2.Text != "")
                    {
                        prik += 16;
                    }*/

                    if (b + prik > e.MarginBounds.Bottom)
                    {
                        g.DrawString(label41.Text.Replace("№", "") + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                        numberlist++;
                        pageprint = 0;
                        e.HasMorePages = true;
                        return;
                    }

                    //общий футер
                    a = 30;
                    if (listBox2.Items.Count != 0)
                    {
                        textToPrint = "К заказу прикреплено " + listBox2.Items.Count + " файлов. Для просмотра используйте ПК";
                        g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                        b += 16;
                    }
                    int klsd = 0;
                    if (textBox11.Text != "" && textBox11.Text != "0")
                    {
                        textToPrint = "Доставка по адресу: " + textBox12.Text;
                        if (label48.Visible)
                        {
                            if (prdostavka != "" && prdostavka != "0")
                            {
                                textToPrint += " в цену заказа добавлено: " + prdostavka + " руб.";
                                g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                                klsd += 5;
                            }
                        }
                        
                        b += 16;
                    }
                    if (textBox14.Text != "" && textBox14.Text != "0")
                    {
                        textToPrint = "Подъем на: " + textBox15.Text + " этаж " + textBox13.Text + " единиц";
                        if (label48.Visible)
                        {
                            if (prpodem != "" && prpodem != "0")
                            {
                                textToPrint += " в цену заказа добавлено: " + prpodem + " руб.";
                                g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                                 klsd += 5;
                            }
                        }
                        
                        b += 16;
                    }
                    b += klsd;
                    /*if (richTextBox2.Text != "")
                    {
                        textToPrint = "Примечание: " + richTextBox2.Text.Replace("\r", "").Replace("\n", " ");
                        g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                        b += 16;
                    }*/

                    if (label37.Text == "Скинали")
                    {
                        if (numericUpDown8.Value != 1)
                        {
                            g.DrawString("Количество повторов всего заказа: " + numericUpDown8.Value + " раз(а)", printFont, Brushes.Black, a, b);
                        }
                    }
                    else
                    {
                        g.DrawString("Общее количество: " + numericUpDown8.Value + " шт.", printFont, Brushes.Black, a, b);
                    }

                    if (myimg != null)
                        g.DrawImage(myimg, new Point(770 - (myimg.Width * 72 / 96) - 200, b));
                    b += 40;
                    g.DrawLine(new Pen(Color.Black, 2), new Point(a, b), new Point(785, b));
                    b += 2;
                    g.DrawString(Статика.Печать_Организация, font, Brushes.Black, a + 165, b);
                    g.DrawLine(new Pen(Color.Black, 2), new Point(a, b + 15), new Point(785, b + 15));
                    b += 16;
                    g.DrawString(Статика.Печать_футер, new Font("Arial", 12), Brushes.Black, 30, b);
                    int multiline2 = (int)e.Graphics.MeasureString(Статика.Печать_футер, new Font("Arial", 12), 1000).Height;
                    if (multiline2 > 59)
                    {
                        b += multiline2 - 59;
                    }
                b += 60;


                    font = new Font("Tahoma", 10, FontStyle.Bold, GraphicsUnit.Point);
                    b += 10;

                    double pc = Convert.ToDouble(label19.Text.Replace(" руб.", ""));
                    g.DrawString("Сумма заказа:                         " + ((int)pc).ToString() + " руб.", font, Brushes.Black, 30, b);
                    Font gd = new Font("Tahoma", 9, FontStyle.Regular, GraphicsUnit.Point);
                    if (textBox16.Visible)
                        if (textBox16.Text != "0" && textBox16.Text != "")
                            g.DrawString("с учётом скидки", gd, Brushes.Black, 35, b + 12);
                    //надпись с учетом скидки
                    if (numericUpDown3.Visible)
                        if (numericUpDown3.Value != 0)
                            g.DrawString("с учётом скидки", gd, Brushes.Black, 35, b + 12);
                    string opl = "Оплачено:" ;
                    if (textBox10.Text != "0")
                    {
                    //понимаем по суммам 
                    string zakaz = label41.Text.Replace("№", "");
                    if (File.Exists(putin + "\\baza\\" + zakaz + "\\doplata.akv"))
                    {
                        opl += "     ";

                        //существует файл оплат
                        string str33 = "";
                        using (StreamReader sr = new StreamReader(new FileStream(putin + "\\baza\\" + zakaz + "\\doplata.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                        {
                            while ((str33 = sr.ReadLine()) != null)
                            {
                                if (str33 == "") continue;
                                string[] tm = str33.Split('|');

                                opl += tm[1];
                                if (tm[2] == "1")
                                    opl += " (нал.)+";
                                else if (tm[2] == "2")
                                    opl += " (терм.)+";
                                else if (tm[2] == "4")
                                    opl += " (карт.)+";
                                else if (tm[2] == "3")
                                    opl += " (безн.)+";
                            }


                        }

                        StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\zakaz.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                        string h = Sr.ReadToEnd();
                        Sr.Close();
                        string[] tmp = h.Split('|');

                        double tmp3 = Convert.ToDouble(tmp[11]);
                        if (tmp3 > 0)
                        {
                            opl += tmp[11];
                            if (radioButton1.Checked) opl += " (нал.)";
                            else if (radioButton2.Checked) opl += " (терм.)";
                            else if (radioButton3.Checked) opl += " (карт.)";
                            else if (radioButton6.Checked) opl += " (безн.)";

                            opl += "=" + textBox10.Text + " р.";
                                //45
                            if (opl.Length > 50)
                            {
                                opl = "Оплачено:                  " + textBox10.Text + " р. (смешанная)";
                            }
                        }
                        else
                        {
                            opl = opl.Substring(0, opl.Length - 1);
                            opl += "=" + textBox10.Text + " р.";

                            if (opl.Length > 50)
                            {
                                opl = "Оплачено:                  " + textBox10.Text + " р. (смешанная)";
                            }
                        }


                    }
                    else
                    {
                        //ток начальная оплата
                        opl += "                  " + textBox10.Text + " р.";
                        if (radioButton1.Checked) opl += " (нал.)";
                        else if (radioButton2.Checked) opl += " (терм.)";
                        else if (radioButton3.Checked) opl += " (карт.)";
                        else if (radioButton6.Checked) opl += " (безн.)";
                        else opl += " (смешанная)";
                    }
                }
                    g.DrawString(opl, font, Brushes.Black, 400, b);

                    b += 22;
                    g.DrawLine(new Pen(Color.Black), new Point(200, b), new Point(385, b));
                    g.DrawLine(new Pen(Color.Black), new Point(500, b), new Point(785, b));
                    b += 10;
                    g.DrawString("Подпись клиента:", font, Brushes.Black, 30, b);

                    g.DrawString("Остаток:                      " + label10.Text + " руб.", font, Brushes.Black, 400, b);
                    b += 22;
                    g.DrawLine(new Pen(Color.Black), new Point(200, b), new Point(385, b));
                    g.DrawLine(new Pen(Color.Black), new Point(500, b), new Point(785, b));
                    b += 10;

                    if (numberlist != 1)
                    {
                        g.DrawString(label41.Text.Replace("№", "") + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                    }
                pageprint = 0;
                komandpring = "";
                numberlist = 1;
                g.Dispose();
            }
            catch (Exception g)
            {
                MessageBox.Show(g.Message);
            }
            /*Image myimg = null;
            try
            {
                myimg = Code128Rendering.MakeBarcodeImage(label41.Text.Replace("№", ""), 2, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, this.Text);
            }


            Graphics g = e.Graphics;
            String textToPrint = "";
            int a = 30;
            Font printFont = new Font("Arial", 12);
            Font printFont2 = new Font("Arial", 12, System.Drawing.FontStyle.Bold);
            int kol = dataGridView1.RowCount;
            int b = 15;

                Font font = new Font("Tahoma", 9);
                //Font font = new Font("Tahoma", 10, FontStyle.Bold, GraphicsUnit.Point);
                Image bs = Properties.Resources.logo;
                g.DrawImage(bs, new Point(a, b));

                b += 15;
                bs = Properties.Resources.location;
                g.DrawImage(bs, new Point(180, b));
                g.DrawString("603074, г. Нижний Новгород, ул. Шаляпина 2а оф. 2", font, Brushes.Black, 200, b);

                bs = Properties.Resources.inet;
                g.DrawImage(bs, new Point(550, b));
                g.DrawString("http://www.steklomaster-nn.ru", font, Brushes.Black, 570, b);

                bs = Properties.Resources.phone;
                g.DrawImage(bs, new Point(180, b + 20));
                g.DrawString("8 (831) 217-60-18; 217-60-21 / Факс 8 (831) 217-60-23", font, Brushes.Black, 200, b + 20);

                bs = Properties.Resources.mail;
                g.DrawImage(bs, new Point(550, b + 20));
                g.DrawString("stekmaster@list.ru", font, Brushes.Black, 570, b + 20);

                bs = Properties.Resources.time;
                g.DrawImage(bs, new Point(180, b + 40));
                g.DrawString("Пн. - Пт.: 9.00 - 18.00, Сб.: 9.00 - 15.00 только офис на прием заказов Вс. - Выходной\r\nВ общий счёт добавлено 5 руб. за упаковку и смс оповещение. Спасибо за понимание.", font, Brushes.Black, 200, b + 40);

                b += 80;

                //общий хеадер
                g.DrawLine(new Pen(Color.Black, 2), new Point(a, b), new Point(785, b));
                g.DrawLine(new Pen(Color.Black, 2), new Point(a, b + 40), new Point(785, b + 40));
                b += 2;
                //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 720, 35));
                textToPrint = "";
                if (checkBox1.Checked)
                    textToPrint += "СРОЧНЫЙ заказ №" + label41.Text.Replace("№", "") + "\r\nот " + DateTime.Now.ToString();
                else
                    textToPrint += "Заказ №" + label41.Text.Replace("№", "") + "\r\nот " + DateTime.Now.ToString();
                // textToPrint += "\r\nМенеджер: " + label31.Text;
                g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                g.DrawString("Дата готовности: ", printFont2, Brushes.Black, 240, b);
                g.DrawString(dateTimePicker1.Text, printFont, Brushes.Black, 240, b + 18);
                    textToPrint = "Менеджер: " + manager + " (217-60-23)";
                g.DrawString(textToPrint, printFont, Brushes.Black, a, b + 40);
                if (textBox2.Text != "" && panel1.Visible && textBox2.Text != "79")
                {
                    textToPrint = textBox2.Text;
                    g.DrawString(textToPrint, printFont, Brushes.Black, 420, b);
                }
                b += 36;
                if (panel1.Visible && textBox8.Text != "" && textBox7.Text != "" && textBox3.Text != "")
                {
                    textToPrint = textBox8.Text.Substring(0, 1) + textBox8.Text.ToLower().Substring(1) + " " + textBox7.Text.Substring(0, 1) + textBox7.Text.ToLower().Substring(1) + " " + textBox3.Text.Substring(0, 1) + textBox3.Text.ToLower().Substring(1);
                    g.DrawString(textToPrint, printFont, Brushes.Black, 420, b - 18);
                }
                b += 30;
                //ожидаемый товар скинали
                if (label37.Text == "Скинали")
                {
                    if (dataGridView1.Rows.Count != 0)
                    {
                        b -= 22;
                        for (int i = 0; i < dataGridView1.Rows.Count; i++)
                        {
                            a = 30;
                            b += 16;
                            //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 80, 22));
                            g.DrawString("№ ", printFont2, Brushes.Black, a, b);
                            g.DrawString(dataGridView1[0, i].Value.ToString(), printFont, Brushes.Black, a + 20, b);
                            b += 16;
                            //a += 80;
                            //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 375, 22));
                            g.DrawString("Материал: ", printFont2, Brushes.Black, a, b);
                            g.DrawString(dataGridView1[3, i].Value.ToString(), printFont, Brushes.Black, a + 100, b);
                            a += 450;
                            // g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 230, 22));
                            g.DrawString("Толщина стекла: ", printFont2, Brushes.Black, a, b);
                            g.DrawString(dataGridView1[4, i].Value.ToString(), printFont, Brushes.Black, a + 150, b);
                            // a += 230;
                            b += 16;
                            a = 30;
                            if (dataGridView1[8, i].Value.ToString() != "")
                            {
                                a = 30;
                                string measureString = "Виды декорирования:   " + dataGridView1[8, i].Value.ToString();
                                int stringWidth = 755;
                                SizeF stringSize = new SizeF();
                                stringSize = e.Graphics.MeasureString(measureString, printFont, stringWidth);
                                Rectangle gs = new Rectangle(a, b, 755, (int)stringSize.Height);
                                // g.DrawRectangle(new Pen(Color.Black), gs);
                                g.DrawString("Виды декорирования: ", printFont2, Brushes.Black, a, b);
                                g.DrawString(measureString.Replace("Виды декорирования:   ", "                                         "), printFont, Brushes.Black, gs);
                                b += (int)stringSize.Height;
                            }
                            a = 30;
                            //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));\
                            g.DrawString("В ", printFont2, Brushes.Black, a, b);
                            g.DrawString(dataGridView1[1, i].Value.ToString(), printFont, Brushes.Black, a + 20, b);
                            a += 60;
                            //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));
                            g.DrawString("Ш ", printFont2, Brushes.Black, a, b);
                            g.DrawString(dataGridView1[2, i].Value.ToString(), printFont, Brushes.Black, a + 20, b);
                            b += 16;
                            a = 30;
                            //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 375, 22));
                            g.DrawString("Форма: ", printFont2, Brushes.Black, a, b);
                            g.DrawString(dataGridView1[6, i].Value.ToString(), printFont, Brushes.Black, a + 70, b);
                            b += 16;
                            a = 30;
                            if (dataGridView1[5, i].Value.ToString() != "")
                            {
                                string[] bd2 = dataGridView1[5, i].Value.ToString().Split(';');
                                foreach (string s in bd2)
                                {
                                    if (s != "")
                                    {
                                        a = 30;
                                        // g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 380, 22));
                                        g.DrawString("Вид обработки: ", printFont2, Brushes.Black, a, b);
                                        g.DrawString(s.Split('-')[0], printFont, Brushes.Black, a + 145, b);
                                        a += 450;
                                        // g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 375, 22));
                                        g.DrawString(s.Split('-')[1], printFont, Brushes.Black, a, b);
                                        b += 16;
                                    }
                                }
                            }
                            a = 30;
                            //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));
                            g.DrawString("Закалка: ", printFont2, Brushes.Black, a, b);
                            g.DrawString(dataGridView1[7, i].Value.ToString(), printFont, Brushes.Black, a + 80, b);
                            b += 22;
                            a = 30;


                            string zna = "";
                            if (dataGridView1[10, i].Value != null && dataGridView1[10, i].Value.ToString() != "")
                                zna = dataGridView1[10, i].Value.ToString();
                            if (zna != "" && zna != null)
                            {
                                b -= 22;
                                string[] bd2 = zna.Split('`');
                                foreach (string s in bd2)
                                {
                                    if (s != "")
                                    {
                                        string[] f = s.Split('@');
                                        a = 30;
                                        b += 22;
                                        g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 125, 22));
                                        g.DrawString("№ " + f[0], printFont, Brushes.Black, a + 2, b);
                                        a += 125;
                                        g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 295, 22));
                                        g.DrawString(f[1], printFont, Brushes.Black, a + 2, b);
                                        a += 295;
                                        g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));
                                        g.DrawString("Диаметр " + f[2], printFont, Brushes.Black, a + 2, b);
                                        a += 150;
                                        g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));
                                        g.DrawString("Количество " + f[3], printFont, Brushes.Black, a + 2, b);
                                        a += 150;
                                    }

                                }
                                b += 16;
                            }
                        }
                        a = 30;
                        b += 16;
                        if (dataGridView3.Rows.Count != 0)
                        {
                            b += 30;
                        }
                    }
                    if (dataGridView3.Rows.Count != 0)
                    {
                        if (dataGridView1.Rows.Count != 0)
                        {
                            b -= 30;
                        }
                        a = 30;
                        g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 605, 22));
                        g.DrawString("Доп. товары/услуги", printFont, Brushes.Black, a + 2, b);
                        a += 605;
                        g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 115, 22));
                        g.DrawString("Кол-во", printFont, Brushes.Black, a, b);
                        for (int i = 0; i < dataGridView3.Rows.Count; i++)
                        {
                            a = 30;
                            b += 22;
                            g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 605, 22));
                            g.DrawString(dataGridView3[0, i].Value.ToString(), printFont, Brushes.Black, a + 2, b);
                            a += 605;
                            g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 115, 22));
                            g.DrawString(dataGridView3[1, i].Value.ToString(), printFont, Brushes.Black, a + 2, b);
                        }
                        a = 30;
                        b += 28;
                    }
                }
                else if (label37.Text == "Другое")
                {
                    a = 30;
                    g.DrawString("Товар/Услуга: " + textBox4.Text + " цена за шт.: " + textBox6.Text + " руб.", printFont2, Brushes.Black, a, b);
                    b += 30;
                }
                //общий футер
                a = 30;
                if (listBox2.Items.Count != 0)
                {
                    textToPrint = "К заказу прикреплено " + listBox2.Items.Count + " файлов. Для просмотра используйте ПК";
                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    b += 16;
                }
                int klsd = 0;
                if (textBox11.Text != "" && textBox11.Text != "0")
                {
                    textToPrint = "Доставка по адресу: " + textBox12.Text;
                    if (label48.Visible)
                    {
                        if (prdostavka != "" && prdostavka != "0")
                        {
                            textToPrint += " в цену заказа добавлено: " + prdostavka + " руб.";
                            klsd += 5;
                        }
                    }
                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    b += 16;
                }
                if (textBox14.Text != "" && textBox14.Text != "0")
                {
                    textToPrint = "Подъем на: " + textBox15.Text + " этаж " + textBox13.Text + " единиц";
                    if (label48.Visible)
                    {
                        if (prpodem != "" && prpodem != "0")
                        {
                            textToPrint += " в цену заказа добавлено: " + prpodem + " руб.";
                            klsd += 5;
                        }
                    }
                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    b += 16;
                }
                b += klsd;
                if (richTextBox2.Text != "")
                {
                    textToPrint = "Примечание: " + richTextBox2.Text.Replace("\r", "").Replace("\n", " ");
                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    b += 16;
                }
                if (label37.Text == "Скинали")
                {
                    if (numericUpDown8.Value != 1)
                    {
                        g.DrawString("Количество повторов всего заказа: " + numericUpDown8.Value + " раз(а)", printFont, Brushes.Black, a, b);
                    }
                }
                else
                {
                    g.DrawString("Общее количество: " + numericUpDown8.Value + " шт.", printFont, Brushes.Black, a, b);
                }
               // g.DrawString("Общее количество: " + numericUpDown8.Value + " шт.", printFont, Brushes.Black, a, b);
                g.DrawImage(myimg, new Point(770 - (myimg.Width * 72 / 96) - 200, b));
                b += 40;
                // g.DrawLine(new Pen(Color.Black), new Point(a, b), new Point(785, b));
                g.DrawLine(new Pen(Color.Black, 2), new Point(a, b), new Point(785, b));
                b += 2;
                g.DrawString("ООО \"СТЕКЛОМАСТЕР\", ОГРН 1165275015762, ИНН 5259124242, КПП 525901001", font, Brushes.Black, a + 165, b);
                g.DrawLine(new Pen(Color.Black, 2), new Point(a, b + 15), new Point(785, b + 15));
                b += 16;
                g.DrawString("Срок хранения заказа 14 дней. По истечении срока компания ответственности не несет!\r\nВыдача заказа при предъявлении квитанции. Проверить готовность заказа можно на сайте в\r\nразделе \"Заказы\", или по телефону 410-79-42.", new Font("Arial", 12), Brushes.Black, 30, b);
                b += 60;


                font = new Font("Tahoma", 10, FontStyle.Bold, GraphicsUnit.Point);

                //b += 30;
                //g.DrawLine(new Pen(Color.Black), new Point(a, b), new Point(785, b));
                b += 10;
                // g.DrawString("Дата", font, Brushes.Black, 30, b);

                double pc = Convert.ToDouble(label19.Text.Replace(" руб.", ""));
                g.DrawString("Сумма заказа:                         " + ((int)pc).ToString() + " руб.", font, Brushes.Black, 30, b);

                string opl = "Оплачено:                  " + (textBox10.Text).ToString() + " руб.";
                if (textBox10.Text != "0")
                {
                    if (radioButton1.Checked) opl += " (нал.)";
                    else if (radioButton2.Checked) opl += " (терм.)";
                    else if (radioButton3.Checked) opl += " (карта)";
                    else if (radioButton6.Checked) opl += " (безнал.)";
                }
                g.DrawString(opl, font, Brushes.Black, 400, b);

                b += 22;
                g.DrawLine(new Pen(Color.Black), new Point(200, b), new Point(385, b));
                g.DrawLine(new Pen(Color.Black), new Point(500, b), new Point(785, b));
                b += 10;
                g.DrawString("Подпись клиента:", font, Brushes.Black, 30, b);

                g.DrawString("Остаток:                      " + label10.Text + " руб.", font, Brushes.Black, 400, b);
                b += 22;
                g.DrawLine(new Pen(Color.Black), new Point(200, b), new Point(385, b));
                g.DrawLine(new Pen(Color.Black), new Point(500, b), new Point(785, b));
                b += 10;
            //if(flaginfile)
            //{
            //    g.Save();
            //    Image myBitmap = new Bitmap(800, b, g.Im);
            //    myBitmap.Save("2.png");
            //}
            g.Dispose();*/
        }

        private void printDocument2_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Image myimg = null;
            try
            {
                myimg = Code128Rendering.MakeBarcodeImage(label41.Text.Replace("№", ""), 2, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, this.Text);
            }


            Graphics g = e.Graphics;
            String textToPrint = "";
            int a = 30;
            Font printFont = new Font("Arial", 12);
            Font printFont2 = new Font("Arial", 12, System.Drawing.FontStyle.Bold);
            int kol = dataGridView1.RowCount;
            int b = 20;
                if (komandpring == "")
                {
                    //общий хеадер
                    g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 720, 35));
                    Font font = new Font("Tahoma", 10, FontStyle.Bold, GraphicsUnit.Point);
                    textToPrint = "";
                    if (checkBox1.Checked)
                        textToPrint += "СРОЧНЫЙ заказ №" + label41.Text.Replace("№", "") + "\r\nот " + label32.Text.Replace("Дата : ", "");
                    else
                        textToPrint += "Заказ №" + label41.Text.Replace("№", "") + "\r\nот " + label32.Text.Replace("Дата : ", "");
                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    g.DrawString("Дата готовности: ", printFont2, Brushes.Black, 240, b);
                    g.DrawString(dateTimePicker1.Text, printFont, Brushes.Black, 240, b + 18);

                    textToPrint = "Менеджер: " + manager + "\r\nСумма заказа: " + label19.Text + " руб.       Оплачено: " + textBox10.Text + " руб.";
                    if (textBox10.Text != "0")
                    {
                        if (radioButton1.Checked) textToPrint += " (нал.)";
                        else if (radioButton2.Checked) textToPrint += " (терм.)";
                        else if (radioButton3.Checked) textToPrint += " (карта)";
                        else if (radioButton6.Checked) textToPrint += " (безнал.)";
                        else textToPrint += " (смешанная)";
                }
                    textToPrint += "       Остаток:" + label10.Text + " руб.";

                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b + 40);

                    if (textBox2.Text != "" && panel1.Visible && textBox2.Text != "79")
                    {
                        textToPrint = textBox2.Text;
                        g.DrawString(textToPrint, printFont, Brushes.Black, 420, b);
                    }
                    b += 52;
                    if (panel1.Visible && textBox8.Text != "" && textBox7.Text != "" && textBox3.Text != "")
                    {
                        textToPrint = textBox8.Text.Substring(0, 1) + textBox8.Text.ToLower().Substring(1) + " " + textBox7.Text.Substring(0, 1) + textBox7.Text.ToLower().Substring(1) + " " + textBox3.Text.Substring(0, 1) + textBox3.Text.ToLower().Substring(1);
                        g.DrawString(textToPrint, printFont, Brushes.Black, 420, b - 36);
                    }
                //b += 30;
                    b += 24;
                    //примечание
                    if (richTextBox2.Text != "")
                    {
                        g.DrawString("ПРИМЕЧАНИЕ: ", printFont2, Brushes.Black, a, b);
                        string measureString = "                            " + richTextBox2.Text.Replace("\r", "").Replace("\n", " ");
                        int stringWidth = 755;
                        SizeF stringSize = new SizeF();
                        stringSize = e.Graphics.MeasureString(measureString, printFont2, stringWidth);
                        Rectangle gs = new Rectangle(a, b, 755, (int)stringSize.Height);
                        g.DrawString(measureString, printFont, Brushes.Black, gs);
                        b += (int)stringSize.Height;
                    /*  g.DrawString("ПРИМЕЧАНИЕ: ", printFont2, Brushes.Black, a, b);
                      textToPrint = richTextBox2.Text.Replace("\r", "").Replace("\n", " ");
                      g.DrawString(textToPrint, printFont, Brushes.Black, a + 130, b);
                      // b += 16;
                      b += 26;*/
                }
                    else
                    {
                        b += 7;
                    }
            }
                //ожидаемый товар скинали
                if (label37.Text == "Скинали")
                {
                    if (komandpring == "" || komandpring == "skin")
                    {
                        if (dataGridView1.Rows.Count != 0)
                        {
                            if (komandpring == "")
                                b -= 22;
                            int i = 0;
                            if (komandpring == "skin")
                                i = pageprint;
                            for (; i < dataGridView1.Rows.Count; i++)
                            {
                                a = 30;
                                b += 16;

                                int prikin = 86;
                                if (dataGridView1[8, i].Value.ToString() != "")
                                {
                                    string measureString = "Виды декорирования:   " + dataGridView1[8, i].Value.ToString();
                                    int stringWidth = 755;
                                    SizeF stringSize = new SizeF();
                                    stringSize = e.Graphics.MeasureString(measureString, printFont, stringWidth);
                                    Rectangle gs = new Rectangle(a, b, 755, (int)stringSize.Height);
                                    prikin += (int)stringSize.Height;
                                }
                                if (dataGridView1[5, i].Value.ToString() != "")
                                {
                                    string[] bd2 = dataGridView1[5, i].Value.ToString().Split(';');
                                    foreach (string s in bd2)
                                    {
                                        if (s != "")
                                        {
                                            prikin += 16;
                                        }
                                    }
                                }
                                string zna = "";
                                if (dataGridView1[10, i].Value != null && dataGridView1[10, i].Value.ToString() != "")
                                    zna = dataGridView1[10, i].Value.ToString();
                                if (zna != "" && zna != null)
                                {
                                    prikin -= 22;
                                    string[] bd2 = zna.Split('`');
                                    foreach (string s in bd2)
                                    {
                                        if (s != "")
                                        {
                                            string[] f = s.Split('@');
                                            prikin += 22;
                                        }

                                    }
                                    prikin += 16;
                                }
                                if (b + prikin > e.MarginBounds.Bottom)
                                {
                                    g.DrawString(label41.Text.Replace("№", "") + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                                    numberlist++;
                                    e.HasMorePages = true;
                                    pageprint = i;
                                    komandpring = "skin";
                                    return;
                                }
                                g.DrawString("№ ", printFont2, Brushes.Black, a, b);
                                g.DrawString(dataGridView1[0, i].Value.ToString(), printFont, Brushes.Black, a + 20, b);
                                b += 16;
                                g.DrawString("Материал: ", printFont2, Brushes.Black, a, b);
                                g.DrawString(dataGridView1[3, i].Value.ToString(), printFont, Brushes.Black, a + 100, b);
                                a += 450;
                                g.DrawString("Толщина стекла: ", printFont2, Brushes.Black, a, b);
                                g.DrawString(dataGridView1[4, i].Value.ToString(), printFont, Brushes.Black, a + 150, b);
                                b += 16;
                                a = 30;
                                if (dataGridView1[8, i].Value.ToString() != "")
                                {
                                    a = 30;
                                    string measureString = "Виды декорирования:   " + dataGridView1[8, i].Value.ToString();
                                    int stringWidth = 755;
                                    SizeF stringSize = new SizeF();
                                    stringSize = e.Graphics.MeasureString(measureString, printFont, stringWidth);
                                    Rectangle gs = new Rectangle(a, b, 755, (int)stringSize.Height);
                                    g.DrawString("Виды декорирования: ", printFont2, Brushes.Black, a, b);
                                    g.DrawString(measureString.Replace("Виды декорирования:   ", "                                         "), printFont, Brushes.Black, gs);
                                    b += (int)stringSize.Height;
                                }
                                a = 30;
                                g.DrawString("В ", printFont2, Brushes.Black, a, b);
                                g.DrawString(dataGridView1[1, i].Value.ToString(), printFont, Brushes.Black, a + 20, b);
                                a += 60;
                                g.DrawString("Ш ", printFont2, Brushes.Black, a, b);
                                g.DrawString(dataGridView1[2, i].Value.ToString(), printFont, Brushes.Black, a + 20, b);
                                b += 16;
                                a = 30;
                                g.DrawString("Форма: ", printFont2, Brushes.Black, a, b);
                                g.DrawString(dataGridView1[6, i].Value.ToString(), printFont, Brushes.Black, a + 70, b);
                                b += 16;
                                a = 30;
                                if (dataGridView1[5, i].Value.ToString() != "")
                                {
                                    string[] bd2 = dataGridView1[5, i].Value.ToString().Split(';');
                                    foreach (string s in bd2)
                                    {
                                        if (s != "")
                                        {
                                            a = 30;
                                            g.DrawString("Вид обработки: ", printFont2, Brushes.Black, a, b);
                                            g.DrawString(s.Split('-')[0], printFont, Brushes.Black, a + 145, b);
                                            a += 450;
                                            g.DrawString(s.Split('-')[1], printFont, Brushes.Black, a, b);
                                            b += 16;
                                        }
                                    }
                                }
                                a = 30;
                                g.DrawString("Закалка: ", printFont2, Brushes.Black, a, b);
                                g.DrawString(dataGridView1[7, i].Value.ToString(), printFont, Brushes.Black, a + 80, b);
                                b += 22;
                                a = 30;


                                zna = "";
                                if (dataGridView1[10, i].Value != null && dataGridView1[10, i].Value.ToString() != "")
                                    zna = dataGridView1[10, i].Value.ToString();
                                if (zna != "" && zna != null)
                                {
                                    b -= 22;
                                    string[] bd2 = zna.Split('`');
                                    foreach (string s in bd2)
                                    {
                                        if (s != "")
                                        {
                                            string[] f = s.Split('@');
                                            a = 30;
                                            b += 22;
                                            g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 125, 22));
                                            g.DrawString("№ " + f[0], printFont, Brushes.Black, a + 2, b);
                                            a += 125;
                                            g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 295, 22));
                                            g.DrawString(f[1], printFont, Brushes.Black, a + 2, b);
                                            a += 295;
                                            g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));
                                            g.DrawString("Диаметр " + f[2], printFont, Brushes.Black, a + 2, b);
                                            a += 150;
                                            g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));
                                            g.DrawString("Количество " + f[3], printFont, Brushes.Black, a + 2, b);
                                            a += 150;
                                        }

                                    }
                                    b += 16;
                                }
                            }
                            komandpring = "";
                            a = 30;
                            b += 16;
                            if (dataGridView3.Rows.Count != 0)
                            {
                                b += 30;
                            }
                        }
                    }
                if (komandpring == "")
                {
                    komandpring = "doptov";
                    pageprint = 0;
                }
                    if (komandpring == "doptov")
                    {
                        if (dataGridView3.Rows.Count != 0)
                        {
                            if (dataGridView1.Rows.Count != 0 && komandpring != "doptov")
                            {
                                b -= 30;
                            }
                            a = 30;
                            if (b > e.MarginBounds.Bottom)
                            {
                                g.DrawString(label41.Text.Replace("№", "") + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                                numberlist++;
                                pageprint = 0;
                                e.HasMorePages = true;
                                return;
                            }
                            g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 605, 22));
                            g.DrawString("Доп. товары/услуги", printFont, Brushes.Black, a + 2, b);
                            a += 605;
                            g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 115, 22));
                            g.DrawString("Кол-во", printFont, Brushes.Black, a, b);
                            int i = 0;
                            if (pageprint != 0)
                                i = pageprint;
                            for (; i < dataGridView3.Rows.Count; i++)
                            {
                                if (b + 32 > e.MarginBounds.Bottom)
                                {
                                    g.DrawString(label41.Text.Replace("№", "") + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 22);
                                    numberlist++;
                                    pageprint = i;
                                    e.HasMorePages = true;
                                    return;
                                }
                                a = 30;
                                b += 22;
                                g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 605, 22));
                                g.DrawString(dataGridView3[0, i].Value.ToString(), printFont, Brushes.Black, a + 2, b);
                                a += 605;
                                g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 115, 22));
                                g.DrawString(dataGridView3[1, i].Value.ToString(), printFont, Brushes.Black, a + 2, b);
                            }
                            a = 30;
                            b += 28;
                            komandpring = "";
                        }
                    }
                }
                else if (label37.Text == "Другое")
                {
                    a = 30;
                    g.DrawString("Товар/Услуга: " + textBox4.Text + " цена за шт.: " + textBox6.Text + " руб.", printFont2, Brushes.Black, a, b);
                    b += 30;
                }
                if (komandpring == "")
                    komandpring = "footer";

                //прикинуть фут
                int prik = 40;
                if (listBox2.Items.Count != 0)
                {
                    prik += 16;
                }
                if (textBox11.Text != "" && textBox11.Text != "0")
                {
                    prik += 16;
                    if (label48.Visible)
                    {
                        if (prdostavka != "" && prdostavka != "0")
                        {
                            prik += 5;
                        }
                    }
                }
                if (textBox14.Text != "" && textBox14.Text != "0")
                {
                    prik += 16;
                    if (label48.Visible)
                    {
                        if (prpodem != "" && prpodem != "0")
                        {
                            prik += 5;
                        }
                    }
                }
               /* if (richTextBox2.Text != "")
                {
                    prik += 16;
                }*/

                if (b + prik > e.MarginBounds.Bottom)
                {
                    g.DrawString(label41.Text.Replace("№", "") + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                    numberlist++;
                    pageprint = 0;
                    e.HasMorePages = true;
                    return;
                }
                //общий футер
                a = 30;
                if (listBox2.Items.Count != 0)
                {
                    textToPrint = "К заказу прикреплено " + listBox2.Items.Count + " файлов. Для просмотра используйте ПК";
                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    b += 16;
                }
                int klsd = 0;
                if (textBox11.Text != "" && textBox11.Text != "0")
                {
                    textToPrint = "Доставка по адресу: " + textBox12.Text;
                    if (label48.Visible)
                    {
                        if (prdostavka != "" && prdostavka != "0")
                        {
                            textToPrint += " в цену заказа добавлено: " + prdostavka + " руб.";
                            klsd += 5;
                        }
                    }

                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    b += 16;
                }

                if (textBox14.Text != "" && textBox14.Text != "0")
                {
                    textToPrint = "Подъем на: " + textBox15.Text + " этаж " + textBox13.Text + " единиц";
                    if (label48.Visible)
                    {
                        if (prpodem != "" && prpodem != "0")
                        {
                            textToPrint += " в цену заказа добавлено: " + prpodem + " руб.";
                            klsd += 5;
                        }
                    }
                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    b += 16;
                }
                b += klsd;
                /*if (richTextBox2.Text != "")
                {
                    textToPrint = "Примечание: " + richTextBox2.Text.Replace("\r", "").Replace("\n", " ");
                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    b += 16;
                }*/
                if (label37.Text == "Скинали")
                {
                    if (numericUpDown8.Value != 1)
                    {
                        g.DrawString("Количество повторов всего заказа: " + numericUpDown8.Value + " раз(а)", printFont, Brushes.Black, a, b);
                    }
                }
                else
                {
                    g.DrawString("Общее количество: " + numericUpDown8.Value + " шт.", printFont, Brushes.Black, a, b);
                }
                
                g.DrawImage(myimg, new Point(770 - (myimg.Width * 72 / 96) - 200, b));
                b += 40;
                g.DrawLine(new Pen(Color.Black), new Point(a, b), new Point(785, b));
                if (numberlist != 1)
                {
                    g.DrawString(label41.Text.Replace("№", "") + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                }
                pageprint = 0;
                komandpring = "";
                numberlist = 1;
            g.Dispose();







          /*  Image myimg = null;
            try
            {
                myimg = Code128Rendering.MakeBarcodeImage(label41.Text.Replace("№",""), 2, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, this.Text);
            }


            Graphics g = e.Graphics;
            String textToPrint = "";
            int a = 30;
            Font printFont = new Font("Arial", 12);
            Font printFont2 = new Font("Arial", 12, System.Drawing.FontStyle.Bold);
            int kol = dataGridView1.RowCount;
            int b = 20;
            //общий хеадер
            g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 720, 35));
            Font font = new Font("Tahoma", 10, FontStyle.Bold, GraphicsUnit.Point);
            textToPrint = "";
            if (checkBox1.Checked)
                textToPrint += "СРОЧНЫЙ заказ №" + label41.Text.Replace("№", "") + "\r\nот " + DateTime.Now.ToString();
            else
                textToPrint += "Заказ №" + label41.Text.Replace("№", "") + "\r\nот " + DateTime.Now.ToString();
            // textToPrint += "\r\nМенеджер: " + label31.Text;
            g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
            g.DrawString("Дата готовности: ", printFont2, Brushes.Black, 240, b);
            g.DrawString(dateTimePicker1.Text, printFont, Brushes.Black, 240, b + 18);

            textToPrint = "Менеджер: " + manager + "\r\nСумма заказа: " + label19.Text + " руб.       Оплачено: " + textBox10.Text + " руб.";
            if (textBox10.Text != "0")
            {
                if (radioButton1.Checked) textToPrint += " (нал.)";
                else if (radioButton2.Checked) textToPrint += " (терм.)";
                else if (radioButton3.Checked) textToPrint += " (карта)";
                else if (radioButton6.Checked) textToPrint += " (безнал.)";
            }
            textToPrint += "       Остаток:" + label10.Text + " руб.";

            g.DrawString(textToPrint, printFont, Brushes.Black, a, b + 40);

            if (textBox2.Text != "" && panel1.Visible && textBox2.Text != "79")
            {
                textToPrint = textBox2.Text;
                g.DrawString(textToPrint, printFont, Brushes.Black, 420, b);
            }
            b += 52;
            if (panel1.Visible && textBox8.Text != "" && textBox7.Text != "" && textBox3.Text != "")
            {
                textToPrint = textBox8.Text.Substring(0, 1) + textBox8.Text.ToLower().Substring(1) + " " + textBox7.Text.Substring(0, 1) + textBox7.Text.ToLower().Substring(1) + " " + textBox3.Text.Substring(0, 1) + textBox3.Text.ToLower().Substring(1);
                g.DrawString(textToPrint, printFont, Brushes.Black, 420, b - 36);
            }
            b += 30;
            //ожидаемый товар скинали
            if (label37.Text == "Скинали")
            {
                if (dataGridView1.Rows.Count != 0)
                {
                    b -= 22;
                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        a = 30;
                        b += 16;
                        //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 80, 22));
                        g.DrawString("№ ", printFont2, Brushes.Black, a, b);
                        g.DrawString(dataGridView1[0, i].Value.ToString(), printFont, Brushes.Black, a + 20, b);
                        b += 16;
                        //a += 80;
                        //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 375, 22));
                        g.DrawString("Материал: ", printFont2, Brushes.Black, a, b);
                        g.DrawString(dataGridView1[3, i].Value.ToString(), printFont, Brushes.Black, a + 100, b);
                        a += 450;
                        // g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 230, 22));
                        g.DrawString("Толщина стекла: ", printFont2, Brushes.Black, a, b);
                        g.DrawString(dataGridView1[4, i].Value.ToString(), printFont, Brushes.Black, a + 150, b);
                        // a += 230;
                        b += 16;
                        a = 30;
                        if (dataGridView1[8, i].Value.ToString() != "")
                        {
                            a = 30;
                            string measureString = "Виды декорирования:   " + dataGridView1[8, i].Value.ToString();
                            int stringWidth = 755;
                            SizeF stringSize = new SizeF();
                            stringSize = e.Graphics.MeasureString(measureString, printFont, stringWidth);
                            Rectangle gs = new Rectangle(a, b, 755, (int)stringSize.Height);
                            // g.DrawRectangle(new Pen(Color.Black), gs);
                            g.DrawString("Виды декорирования: ", printFont2, Brushes.Black, a, b);
                            g.DrawString(measureString.Replace("Виды декорирования:   ", "                                         "), printFont, Brushes.Black, gs);
                            b += (int)stringSize.Height;
                        }
                        a = 30;
                        //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));\
                        g.DrawString("В ", printFont2, Brushes.Black, a, b);
                        g.DrawString(dataGridView1[1, i].Value.ToString(), printFont, Brushes.Black, a + 20, b);
                        a += 60;
                        //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));
                        g.DrawString("Ш ", printFont2, Brushes.Black, a, b);
                        g.DrawString(dataGridView1[2, i].Value.ToString(), printFont, Brushes.Black, a + 20, b);
                        b += 16;
                        a = 30;
                        //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 375, 22));
                        g.DrawString("Форма: ", printFont2, Brushes.Black, a, b);
                        g.DrawString(dataGridView1[6, i].Value.ToString(), printFont, Brushes.Black, a + 70, b);
                        b += 16;
                        a = 30;
                        if (dataGridView1[5, i].Value.ToString() != "")
                        {
                            string[] bd2 = dataGridView1[5, i].Value.ToString().Split(';');
                            foreach (string s in bd2)
                            {
                                if (s != "")
                                {
                                    a = 30;
                                    // g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 380, 22));
                                    g.DrawString("Вид обработки: ", printFont2, Brushes.Black, a, b);
                                    g.DrawString(s.Split('-')[0], printFont, Brushes.Black, a + 145, b);
                                    a += 450;
                                    // g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 375, 22));
                                    g.DrawString(s.Split('-')[1], printFont, Brushes.Black, a, b);
                                    b += 16;
                                }
                            }
                        }
                        a = 30;
                        //g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));
                        g.DrawString("Закалка: ", printFont2, Brushes.Black, a, b);
                        g.DrawString(dataGridView1[7, i].Value.ToString(), printFont, Brushes.Black, a + 80, b);
                        b += 22;
                        a = 30;


                        string zna = "";
                        if (dataGridView1[10, i].Value != null && dataGridView1[10, i].Value.ToString() != "")
                            zna = dataGridView1[10, i].Value.ToString();
                        if (zna != "" && zna != null)
                        {
                            b -= 22;
                            string[] bd2 = zna.Split('`');
                            foreach (string s in bd2)
                            {
                                if (s != "")
                                {
                                    string[] f = s.Split('@');
                                    a = 30;
                                    b += 22;
                                    g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 125, 22));
                                    g.DrawString("№ " + f[0], printFont, Brushes.Black, a + 2, b);
                                    a += 125;
                                    g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 295, 22));
                                    g.DrawString(f[1], printFont, Brushes.Black, a + 2, b);
                                    a += 295;
                                    g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));
                                    g.DrawString("Диаметр " + f[2], printFont, Brushes.Black, a + 2, b);
                                    a += 150;
                                    g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 150, 22));
                                    g.DrawString("Количество " + f[3], printFont, Brushes.Black, a + 2, b);
                                    a += 150;
                                }

                            }
                            b += 16;
                        }
                    }
                    a = 30;
                    b += 16;
                    if (dataGridView3.Rows.Count != 0)
                    {
                        b += 30;
                    }
                }
                if (dataGridView3.Rows.Count != 0)
                {
                    if (dataGridView1.Rows.Count != 0)
                    {
                        b -= 30;
                    }
                    a = 30;
                    g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 605, 22));
                    g.DrawString("Доп. товары/услуги", printFont, Brushes.Black, a + 2, b);
                    a += 605;
                    g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 115, 22));
                    g.DrawString("Кол-во", printFont, Brushes.Black, a, b);
                    for (int i = 0; i < dataGridView3.Rows.Count; i++)
                    {
                        a = 30;
                        b += 22;
                        g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 605, 22));
                        g.DrawString(dataGridView3[0, i].Value.ToString(), printFont, Brushes.Black, a + 2, b);
                        a += 605;
                        g.DrawRectangle(new Pen(Color.Black), new Rectangle(a, b, 115, 22));
                        g.DrawString(dataGridView3[1, i].Value.ToString(), printFont, Brushes.Black, a + 2, b);
                    }
                    a = 30;
                    b += 28;
                }
            }
            else if (label37.Text == "Другое")
            {
                a = 30;
                g.DrawString("Товар/Услуга: " + textBox4.Text + " цена за шт.: " + textBox6.Text + " руб.", printFont2, Brushes.Black, a, b);
                b += 30;
            }
            //общий футер
            a = 30;
            if (listBox2.Items.Count != 0)
            {
                textToPrint = "К заказу прикреплено " + listBox2.Items.Count + " файлов. Для просмотра используйте ПК";
                g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                b += 16;
            }
            int klsd = 0;
            if (textBox11.Text != "" && textBox11.Text != "0")
            {
                textToPrint = "Доставка по адресу: " + textBox12.Text;
                if(label48.Visible)
                {
                    if (prdostavka != "" && prdostavka != "0")
                    {
                        textToPrint += " в цену заказа добавлено: " + prdostavka + " руб.";
                        klsd += 5;
                    }
                }
               
                g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                b += 16;
            }
            if (textBox14.Text != "" && textBox14.Text != "0")
            {
                textToPrint = "Подъем на: " + textBox15.Text + " этаж " + textBox13.Text + " единиц";
                if (label48.Visible)
                {
                    if (prpodem != "" && prpodem != "0")
                    {
                        textToPrint += " в цену заказа добавлено: " + prpodem + " руб.";
                        klsd += 5;
                    }
                }
                g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                b += 16;
            }
            b += klsd;
            if (richTextBox2.Text != "")
            {
                textToPrint = "Примечание: " + richTextBox2.Text.Replace("\r", "").Replace("\n", " ");
                g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                b += 16;
            }
            if (label37.Text == "Скинали")
            {
                if (numericUpDown8.Value != 1)
                {
                    g.DrawString("Количество повторов всего заказа: " + numericUpDown8.Value + " раз(а)", printFont, Brushes.Black, a, b);
                }
            }
            else
            {
                g.DrawString("Общее количество: " + numericUpDown8.Value + " шт.", printFont, Brushes.Black, a, b);
            }
           // g.DrawString("Общее количество: " + numericUpDown8.Value + " шт.", printFont, Brushes.Black, a, b);
            g.DrawImage(myimg, new Point(770 - (myimg.Width * 72 / 96) - 200, b));
            b += 40;
            g.DrawLine(new Pen(Color.Black), new Point(a, b), new Point(785, b));
            g.Dispose();*/
        }

        private void button7_Click(object sender, EventArgs e)
        {
            printPreviewDialog2.Document = printDocument2;
            ((Form)printPreviewDialog2).WindowState = FormWindowState.Maximized;
            ((Form)printPreviewDialog2).Icon = this.Icon;
            printPreviewDialog2.ShowDialog();
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (comboBox1.SelectedIndex == 0)
            {
                textBox1.Text = textBox1.Text.ToUpper();
                textBox1.SelectionStart = textBox1.TextLength;
            }
        }

        double tmpprice = 0;
        double tmpdublprice = 0;

        private void button12_Click(object sender, EventArgs e)
        {
            if ((textBox11.Text != "" && textBox11.Text != "0") || (textBox14.Text != "" && textBox14.Text != "0"))
            {
                //алгоритм вычисления tmpprice 
                button4_Click(null, null);

                double ssum = Convert.ToDouble(obshchet.Replace("руб.", "").Replace(" ", ""));

                //double vvd = 0;
                //for

                printPreviewDialog3.Document = printDocument3;
                ((Form)printPreviewDialog3).WindowState = FormWindowState.Maximized;
                ((Form)printPreviewDialog3).Icon = this.Icon;
                printPreviewDialog3.ShowDialog();
            }
            else
            {
                MessageBox.Show("У клиента не заказана ни подъем, ни доставка!");
            }
        }

        private void printDocument3_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Graphics g = e.Graphics;
            String textToPrint = "";
            int a = 30;
            Font printFont = new Font("Arial", 12);
            Font printFont2 = new Font("Arial", 12, System.Drawing.FontStyle.Bold);
            int b = 15;
            Font font = new Font("Tahoma", 9);
            //Font font = new Font("Tahoma", 10, FontStyle.Bold, GraphicsUnit.Point);
            Image bs = Properties.Resources.logo;
            g.DrawImage(bs, new Point(a, b));

            b += 15;
            bs = Properties.Resources.location;
            g.DrawImage(bs, new Point(180, b));
            g.DrawString(Статика.Печать_Адрес, font, Brushes.Black, 200, b);

            bs = Properties.Resources.inet;
            g.DrawImage(bs, new Point(550, b));
            g.DrawString(Статика.Печать_Сайт, font, Brushes.Black, 570, b);

            bs = Properties.Resources.phone;
            g.DrawImage(bs, new Point(180, b + 20));
            g.DrawString(Статика.Печать_Телефон, font, Brushes.Black, 200, b + 20);

            bs = Properties.Resources.mail;
            g.DrawImage(bs, new Point(550, b + 20));
            g.DrawString(Статика.Печать_Почта, font, Brushes.Black, 570, b + 20);

            bs = Properties.Resources.time;
            g.DrawImage(bs, new Point(180, b + 40));
            g.DrawString(Статика.Печать_График, font, Brushes.Black, 200, b + 40);
            int multiline = (int)e.Graphics.MeasureString(Статика.Печать_График, font, 1000).Height;
            if (multiline > 32)
            {
                b += multiline - 32;
            }
            b += 80;

            b += 2;
             
                    if (textBox11.Text != "" && textBox11.Text != "0")
                    {
                        //заказана доставка
                        g.DrawLine(new Pen(Color.Black, 2), new Point(a, b), new Point(785, b));
                        b += 5;
                        font = new Font("Tahoma", 10, FontStyle.Bold, GraphicsUnit.Point);
                        
                        if(fullzakaz.IndexOf(">")==fullzakaz.Length -1)
                        {
                            textToPrint = "Доставка заказа : "+label41.Text;
                        }
                        else
                        {
                            string[] mg = fullzakaz.Replace("<","").Split('>');

                            textToPrint = "Доставка заказов : " + "c " + mg[0] + " по " + mg[mg.Length -2];
                        }

                        g.DrawString(textToPrint+"\r\nПо адресу : " + textBox12.Text, font, Brushes.Black, 30, b);

                        font = new Font("Tahoma", 9);
                        b += 44;
                        g.DrawLine(new Pen(Color.Black, 2), new Point(a, b), new Point(785, b));
                        b += 2;
                        g.DrawString(Статика.Печать_Организация, font, Brushes.Black, a + 165, b);
                        g.DrawLine(new Pen(Color.Black, 2), new Point(a, b + 15), new Point(785, b + 15));
                        b += 20;

                        font = new Font("Tahoma", 10, FontStyle.Bold, GraphicsUnit.Point);

                        //b += 30;
                        //g.DrawLine(new Pen(Color.Black), new Point(a, b), new Point(785, b));
                        b += 10;
                        // g.DrawString("Дата", font, Brushes.Black, 30, b);

                        double sum = Convert.ToDouble(textBox11.Text);
                        //срочность
                        if (checkBox1.Checked)
                        {
                            int pro = (int)Math.Round(sum);
                            pro = pro / 100 * 10;
                            sum += pro;
                        }
                        //ндс
                        if (numericUpDown4.Value != 0)
                        {
                            int pro = (int)Math.Round(sum);
                            pro = pro / 100 * Convert.ToInt32(numericUpDown4.Value);
                            sum = sum + pro;
                        }
                        //скидка
                        if (numericUpDown3.Value == 0)
                        {
                            sum = Math.Round(sum);
                        }
                        else
                        {
                            double pro = sum;
                            pro = pro / 100 * Convert.ToInt32(numericUpDown3.Value);
                            sum = sum - pro;
                            sum = Math.Round(sum);
                        }
                        double pc = sum;
                        g.DrawString("Сумма заказа:                         " + ((int)pc).ToString() + " руб.", font, Brushes.Black, 30, b);

                        string opl = "Оплачено:                  " + ((int)tmpprice).ToString() + " руб.";
                        if (tmpprice != 0)
                        {
                            if (radioButton4.Checked) opl += " (нал.)";
                            else if (radioButton5.Checked) opl += " (терм.)";
                            else if (radioButton3.Checked) opl += " (карта)";
                            else if (radioButton6.Checked) opl += " (безнал.)";
                            else opl += " (смешанная)";
                }
                        g.DrawString(opl, font, Brushes.Black, 400, b);

                        b += 22;
                        g.DrawLine(new Pen(Color.Black), new Point(200, b), new Point(385, b));
                        g.DrawLine(new Pen(Color.Black), new Point(500, b), new Point(785, b));
                        b += 10;
                        g.DrawString("Подпись клиента:", font, Brushes.Black, 30, b);

                        g.DrawString("Остаток:                      " + ((int)pc - tmpprice).ToString() + " руб.", font, Brushes.Black, 400, b);
                        b += 22;
                        g.DrawLine(new Pen(Color.Black), new Point(200, b), new Point(385, b));
                        g.DrawLine(new Pen(Color.Black), new Point(500, b), new Point(785, b));
                        b += 10;
                        if (textBox14.Text != "" && textBox14.Text != "0")
                        {
                            b += 25;
                            g.DrawLine(new Pen(Color.Black, 2), new Point(a, b), new Point(785, b));
                            b += 30;
                        }
                    }

                    if (textBox14.Text != "" && textBox14.Text != "0")
                    {
                        font = new Font("Tahoma", 9);
                        g.DrawLine(new Pen(Color.Black), new Point(a, b), new Point(785, b));
                        b += 5;
                        font = new Font("Tahoma", 10, FontStyle.Bold, GraphicsUnit.Point);
                        if (fullzakaz.IndexOf(">") == fullzakaz.Length - 1)
                        {
                            textToPrint = "Подъем заказа : " + label41.Text;
                        }
                        else
                        {
                            string[] mg = fullzakaz.Replace("<", "").Split('>');

                            textToPrint = "Подъем заказов : " + "c " + mg[0] + " по " + mg[mg.Length - 2];
                        }
                        textToPrint += "\r\nПодъем на этаж : " + textBox15.Text + "\r\nКоличество единиц:" + textBox13.Text;

                        g.DrawString(textToPrint, font, Brushes.Black, 30, b);
                        font = new Font("Tahoma", 9);
                        b += 64;
                        g.DrawLine(new Pen(Color.Black), new Point(a, b), new Point(785, b));
                        b += 2;
                        g.DrawString(Статика.Печать_Организация, font, Brushes.Black, a + 165, b);
                        g.DrawLine(new Pen(Color.Black), new Point(a, b + 15), new Point(785, b + 15));
                        b += 20;

                        font = new Font("Tahoma", 10, FontStyle.Bold, GraphicsUnit.Point);

                        //b += 30;
                        //g.DrawLine(new Pen(Color.Black), new Point(a, b), new Point(785, b));
                        b += 10;
                        // g.DrawString("Дата", font, Brushes.Black, 30, b);

                        double sum = 0;
                        if (textBox13.Text == "" || textBox13.Text == "1")
                            sum = Convert.ToDouble(textBox14.Text) * Convert.ToDouble(textBox15.Text);
                        else
                            sum = Convert.ToDouble(textBox14.Text) * Convert.ToDouble(textBox15.Text) * Convert.ToDouble(textBox13.Text);

                        //срочность
                        if (checkBox1.Checked)
                        {
                            int pro = (int)Math.Round(sum);
                            pro = pro / 100 * 10;
                            sum += pro;
                        }
                        //ндс
                        if (numericUpDown4.Value != 0)
                        {
                            int pro = (int)Math.Round(sum);
                            pro = pro / 100 * Convert.ToInt32(numericUpDown4.Value);
                            sum = sum + pro;
                        }
                        //скидка
                        if (numericUpDown3.Value == 0)
                        {
                            sum = Math.Round(sum);
                        }
                        else
                        {
                            double pro = sum;
                            pro = pro / 100 * Convert.ToInt32(numericUpDown3.Value);
                            sum = sum - pro;
                            sum = Math.Round(sum);
                        }
                        double pc = sum;

                        g.DrawString("Сумма заказа:                         " + ((int)pc).ToString() + " руб.", font, Brushes.Black, 30, b);

                        string opl = "Оплачено:                  " + ((int)tmpdublprice).ToString() + " руб.";
                        if (tmpprice != 0)
                        {
                            if (radioButton4.Checked) opl += " (нал.)";
                            else if (radioButton5.Checked) opl += " (терм.)";
                            else if (radioButton3.Checked) opl += " (карта)";
                            else if (radioButton6.Checked) opl += " (безнал.)";
                             else opl += " (смешанная)";
                }
                        g.DrawString(opl, font, Brushes.Black, 400, b);

                        b += 22;
                        g.DrawLine(new Pen(Color.Black), new Point(200, b), new Point(385, b));
                        g.DrawLine(new Pen(Color.Black), new Point(500, b), new Point(785, b));
                        b += 10;
                        g.DrawString("Подпись клиента:", font, Brushes.Black, 30, b);

                        g.DrawString("Остаток:                      " + ((int)pc - tmpprice).ToString() + " руб.", font, Brushes.Black, 400, b);
                        b += 22;
                        g.DrawLine(new Pen(Color.Black), new Point(200, b), new Point(385, b));
                        g.DrawLine(new Pen(Color.Black), new Point(500, b), new Point(785, b));
                        b += 10;
                    }
        }

        private void button13_Click(object sender, EventArgs e)
        {
            //чтение данных клиента
            string dannie = "Нет актуальных статусов!";
            if (File.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\status.akv"))
            {
                StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\status.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                string h = Sr.ReadToEnd();
                Sr.Close();
                h = h.Replace("|", "\t");
                dannie ="Дата\t\tКод\tТекст\r\n"+ h;
            }
            if (File.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\zabran.akv"))
            {
                StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\zabran.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                string h = Sr.ReadToEnd();
                Sr.Close();
                h = h.Replace("|", "\t");
                dannie = "Информация по выдаче\r\n" + h;
            }
            MessageBox.Show(dannie);
        }

        private void button14_Click(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex == -1) return;
            Form1 gl = this.Owner as Form1;
            string tovar = "";
            if (File.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\tovar.akv"))
            {
                StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\tovar.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                tovar = Sr.ReadToEnd();
                Sr.Close();
                Sr = null;
            }
            string prikrepfiles = "";
             //чтение прикрепленных файлов
             if (Directory.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\files"))
             {
                prikrepfiles = putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\files";
                MessageBox.Show("В заказе существуют прикрепленные файлы, сначало проведите заказ, потом удалите текущий (если требуется)");
             }
            string klient = "";
            //чтение данных клиента
            if (File.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\klient.akv"))
            {
                StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\klient.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                klient = Sr.ReadToEnd();
                Sr.Close();
            }
            //общие данные
            string zakazobsh = "";
            if (File.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\zakaz.akv"))
            {
                StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\zakaz.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                zakazobsh = Sr.ReadToEnd();
                Sr.Close();
            }
            if (File.Exists(putin + "\\baza\\" + listBox1.SelectedItem.ToString() + "\\doplata.akv"))
            {
                MessageBox.Show("Программа не может высчитать корректно сумму оплаты, т.к. были совершены доплаты! Учтите этот факт при пробитии!");
            }
            gl.load_in_bd(tovar,prikrepfiles,klient, zakazobsh);

        }

        private void button15_Click(object sender, EventArgs e)
        {
            button4_Click(null, null);
            for(int i =0; i<listBox1.Items.Count;i++)
            {
                listBox1.SelectedIndex = i;
                button14_Click(null, null);
            }
        }

        private void button16_Click(object sender, EventArgs e)
        {
            if(textBox17.Text == "14582")
            {
                panel9.Visible = false;
                textBox12.Visible = true;
                textBox14.Visible = true;
                textBox11.Visible = true;
                label19.Visible = true;
                label33.Visible = true;
                label34.Visible = true;
                panel3.Visible = true;

            }

            textBox17.Text = "";
        }

        private void textBox17_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                button16_Click(null, null);
            }
        }

        private void button17_Click(object sender, EventArgs e)
        {
            СТАТУСЫ_главная sg = this.Owner as СТАТУСЫ_главная;
            sg.maskedTextBox2.Text = listBox1.SelectedItem.ToString();
            sg.button2_Click(null, null);
            //this.Close();
        }

        private void button18_Click(object sender, EventArgs e)
        {
            СТАТУСЫ_главная sg = this.Owner as СТАТУСЫ_главная;
            sg.vidacha(listBox1.SelectedItem.ToString());
        }

        private void button24_Click(object sender, EventArgs e)
        {
            Button fs = sender as Button;
            textBox17.Text += fs.Text;
        }
    }
}
