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.Net;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace StekloMaster
{
    public partial class Form1 : Form
    {
        //печать клиентов и при другом товаре
        //база заказов, выдача заказа
        //копировать заказ из бд, временная база
        //сохранение


        public Form1()
        {
            InitializeComponent();
            this.KeyPreview = true;
            _rawinput = new RawInput_dll.RawInput(Handle, CaptureOnlyInForeground);
            _rawinput.KeyPressed += OnKeyPressed;
        }

        int versia = 29;

        /// <summary>
        /// данные о клиенте
        /// </summary>
        DataGridViewRow klient = null;
        /// <summary>
        /// Путь до атносительной базы
        /// </summary>
        public string putin = "";
        /// <summary>
        /// Массив товаров
        /// </summary>
        string[] tovar = new string[0];
        /// <summary>
        ///true - отключить обновление в списке товаров в корзине , false - включено обновление
        /// </summary>
        bool anti_obnovlenie_tovar = false;
        /// <summary>
        ///true - отключить обновление в списке товаров в корзине , false - включено обновление
        /// </summary>
        bool anti_obnovlenie_korzina = false;
        /// <summary>
        /// Переменная отвечающая за запрет сохранения при изменении полей true = запрет false = сохранение
        /// </summary>
        bool zagruzka = false;
        /// <summary>
        /// Переменная отвечающая за антисохранение при очищении
        /// </summary>
        bool cleaners = false;
        /// <summary>
        /// Содержит перфикс текущей точки
        /// </summary>
        string perfics = "";
        /// <summary>
        /// Содержит команду со сканера
        /// </summary>
        string komd = "";
        /// <summary>
        /// Объект сканера
        /// </summary>
        private readonly RawInput_dll.RawInput _rawinput;
        /// <summary>
        /// Флаг сканера
        /// </summary>
        const bool CaptureOnlyInForeground = true;
        /// <summary>
        /// содержит vid pid сканера
        /// </summary>
        string device = "";
        /// <summary>
        /// Находится ли программа в поисках сканера
        /// </summary>
        bool nastroyka = false;
        /// <summary>
        /// 
        bool statuszakaz = false;

        double tmpdublprice = 0;

        /// <summary>
        /// Точка входа в окно
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Shown(object sender, EventArgs e)
        {
            if (File.Exists(Application.StartupPath + "\\scaner.akv"))
            {
                this.Hide();
                if (File.Exists(Application.StartupPath + "\\device.txt"))
                {
                    StreamReader Sr = new StreamReader(Application.StartupPath + "\\device.txt", Encoding.UTF8);
                    device = Sr.ReadToEnd();
                    Sr.Close();
                }
                СТАТУСЫ_главная gs = new СТАТУСЫ_главная();
                gs.Show();
                statuszakaz = true;
                load_versia();
            }
            else
            {
                button29.Focus();
                default_file();
                load_config();
                load_versia();
                proverka_baz();
            }

            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);
        }


        /// <summary>
        /// Очищает строку от символов сканера
        /// </summary>
        /// <param name="tmp"></param>
        /// <returns></returns>
        string clean_skan(string tmp)
        {
            return tmp.Replace("D1", "1").Replace("D2", "2").Replace("D3", "3").Replace("D4", "4").Replace("D5", "5").Replace("D6", "6").Replace("D7", "7").Replace("D8", "8").Replace("D9", "9").Replace("D0", "0").Replace("LSHIFT", "").Replace("OEMMINUS", "-").Replace("OEMTILE", "#");
        }

        /// <summary>
        /// Событие со сканера
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void OnKeyPressed(object sender, RawInput_dll.RawInputEventArg e)
        {
            //&& this.Visible
            if (e.KeyPressEvent.KeyPressState == "MAKE" && (e.KeyPressEvent.DeviceName.IndexOf(device) != -1 || nastroyka))
            {
                label1.Focus();
                string s = e.KeyPressEvent.VKeyName;
                if (s == "ENTER")
                {
                    komd = clean_skan(komd);
                    if (statuszakaz)
                    {
                        foreach (Form f in Application.OpenForms)
                        {
                            if (f.GetType() == typeof(СТАТУСЫ_главная))
                            {
                                f.Activate();
                                СТАТУСЫ_главная gs = f as СТАТУСЫ_главная;
                                gs.scaner(komd);
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (nastroyka)
                        {
                            if (e.KeyPressEvent.DeviceName.IndexOf("HID") == -1)
                            {
                                new Thread(delegate () { MessageBox.Show("Устройство не в HID режиме"); }).Start();
                                //message_trey("Устройство не в HID режиме");

                            }
                            else
                            {
                                int s1 = e.KeyPressEvent.DeviceName.IndexOf("HID");
                                int s2 = e.KeyPressEvent.DeviceName.IndexOf("#", s1 + 4);
                                string s3 = e.KeyPressEvent.DeviceName.Substring(s1, s2 - s1);
                                File.WriteAllText(Application.StartupPath + "\\device.txt", s3, Encoding.UTF8);
                                device = s3;
                                new Thread(delegate () { MessageBox.Show("Устройство успешно подключено!"); }).Start();
                                button25_Click(null, null);
                            }
                        }
                        else
                        {
                            //скидочная карта
                            if (komd.Length == 13)
                            {
                                textBox8.Text = komd;
                            }
                            else if (komd.IndexOf("-") != -1)
                            {

                                textBox9.Text = komd;
                                button5_Click(null, null);
                            }
                            else
                            {
                                new Thread(delegate () { MessageBox.Show("Команда " + komd + " не распознана!"); }).Start();
                            }
                        }
                    }
                    //if (komd.Substring(0, 1) == "$")
                    //{
                    //}
                    //else if (komd.Substring(0, 1) == "#")
                    //{

                    //}
                    //else if (Int32.TryParse(komd.Substring(0, 1), out tmp))
                    //{
                    //    label33.Text = "Выдача заказа";
                    //    textBox6.Text = komd;
                    //    button23_Click(null, null);
                    //}
                    //else if (komd.Substring(0, 1) == "B")
                    //{

                    //}
                    //else if (komd.Substring(0, 1) == "P")
                    //{

                    //}
                    //else if (komd.Substring(0, 1) == "S")
                    //{

                    //}

                    // MessageBox.Show(komd);
                    komd = "";
                }
                else
                {
                    komd += s;
                }
            }

        }

        /// <summary>
        /// Выбор вида товара (кнопка новый)
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button29_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form2")
                {
                    MessageBox.Show("Выбор вида товара уже открыт!");
                    return;
                }
            }
            Form2 f1 = new Form2();
            f1.Owner = this;
            f1.Show();
        }

        /// <summary>
        /// Уведомление в трей
        /// </summary>
        /// <param name="message">Текст сообщения</param>
        public void message_trey(string message)
        {
            notifyIcon1.Visible = true;
            timer3.Start();
            notifyIcon1.ShowBalloonTip(1000, Application.ProductName, message, ToolTipIcon.Info);
        }

        /// <summary>
        /// Проверяет версию программы и сравнивает с серверной
        /// </summary>
        void load_versia(bool proverka = false)
        {
            Thread lod = new Thread(delegate ()
            {
                try
                {
                    HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create("https://lit-it.ru/programs/steklomaster/nomer");
                    HttpWebResponse r2 = (HttpWebResponse)request2.GetResponse();
                    string answer = new StreamReader(r2.GetResponseStream(), Encoding.UTF8).ReadToEnd();
                    if (answer != "" && answer != null)
                    {
                        int num = 0;
                        if (Int32.TryParse(answer, out num))
                        {
                            if (num > versia)
                            {
                                if (proverka)
                                {
                                    message_trey("Найдено обновление, пожалуйста перезапустите программу!");
                                }
                                else
                                {
                                    System.Diagnostics.Process p = System.Diagnostics.Process.Start("update", "https://lit-it.ru/programs/steklomaster/" + Application.ProductName + ".exe|" + Application.ProductName + ".exe");
                                    Application.Exit();
                                }
                            }
                        }
                        else
                        {
                            this.Invoke(new EventHandler(delegate
                            {
                                message_trey(answer);
                            }));
                        }
                    }
                }
                catch { }
            });
            lod.IsBackground = true;
            lod.Start();
        }

        /// <summary>
        /// Проверка актуальности баз
        /// </summary>
        /// <param name="backgaraund">Если true не вызовет события по получению даты и показа формы авторизации</param>
        public void proverka_baz(bool backgaraund = false)
        {
            Thread lod = new Thread(delegate ()
            {
                DirectoryInfo zFile = new DirectoryInfo(Application.StartupPath + "\\logs");
                if (!zFile.Exists)
                {
                    Directory.CreateDirectory(Application.StartupPath + "\\logs");
                }
                try
                {
                    HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create("https://lit-it.ru/programs/steklomaster/update/info.php");
                    HttpWebResponse r2 = (HttpWebResponse)request2.GetResponse();
                    string answer = new StreamReader(r2.GetResponseStream(), Encoding.UTF8).ReadToEnd();
                    if (answer != "" && answer != null)
                    {
                        string hash = Hash.MD5Hash(answer);
                        string hash2 = "";
                        if (File.Exists(Application.StartupPath + "\\md5.akv"))
                        {
                            StreamReader Sr = new StreamReader(Application.StartupPath + "\\md5.akv", Encoding.Default);
                            hash2 = Sr.ReadToEnd();
                            Sr.Close();
                        }
                        if (hash != hash2)
                        {
                            string logs = "";
                            message_trey("Обновляем файлы программы");
                            answer = answer.Replace("./", Application.StartupPath + "\\");
                            answer = answer.Replace("/", "\\");
                            string[] s = answer.Split('\n');
                            for (int i = 0; i < s.Length - 1; i++)
                            {
                                string[] tmp = s[i].Split('|');
                                if (tmp[1] == "folder")
                                {
                                    tmp[0] = tmp[0].Substring(0, tmp[0].Length - 1);
                                    try
                                    {
                                        DirectoryInfo aFile = new DirectoryInfo(tmp[0]);
                                        if (!aFile.Exists)
                                        {
                                            logs += DateTime.Now + " Создаем папку " + tmp[0] + "\n";
                                            Directory.CreateDirectory(tmp[0]);
                                        }
                                    }
                                    catch (Exception h)
                                    {
                                        logs += DateTime.Now + " Ошибка создания папки: " + h.Message + "\n";
                                        hash += "E";
                                    }
                                }
                                else
                                {
                                    try
                                    {
                                        FileInfo aFile = new FileInfo(tmp[0]);
                                        if (aFile.Exists)
                                        {
                                            if (Hash.Sh1(tmp[0]) != tmp[1].ToUpper())
                                            {
                                                WebClient wc = new WebClient();
                                                string url = tmp[0].Replace(Application.StartupPath, "");
                                                logs += DateTime.Now + " Обновляем " + url + "\n";
                                                url = url.Replace("\\", "/");
                                                wc.DownloadFile(new Uri("https://lit-it.ru/programs/steklomaster/update" + url), tmp[0]);
                                            }
                                        }
                                        else
                                        {
                                            WebClient wc = new WebClient();
                                            string url = tmp[0].Replace(Application.StartupPath, "");
                                            logs += DateTime.Now + " Создаем " + url + "\n";
                                            url = url.Replace("\\", "/");
                                            wc.DownloadFile(new Uri("https://lit-it.ru/programs/steklomaster/update" + url), tmp[0]);
                                        }
                                    }
                                    catch (Exception h)
                                    {
                                        logs += DateTime.Now + " Ошибка обновления файла: " + h.Message + "\n";
                                        hash += "E";
                                    }
                                }
                            }
                            File.WriteAllText(Application.StartupPath + "\\md5.akv", hash, Encoding.UTF8);
                            if (logs != "")
                                File.WriteAllText(Application.StartupPath + "\\logs\\log_" + (DateTime.Now).ToString().Replace(".", "_").Replace(":", "_") + ".txt", logs, Encoding.UTF8);
                        }
                    }
                }
                catch (Exception e)
                {
                    File.WriteAllText(Application.StartupPath + "\\logs\\log_" + (DateTime.Now).ToString().Replace(".", "_").Replace(":", "_") + ".txt", "Ошибка обновления файлов: " + e.Message, Encoding.UTF8);
                    message_trey(e.Message);
                }
                this.Invoke(new EventHandler(delegate
                {
                    if (!backgaraund)
                    {
                        poluchenie_daty();
                    }
                }));

            });
            lod.IsBackground = true;
            lod.Start();
        }

        /// <summary>
        /// Получение актуальной даты
        /// </summary>
        void poluchenie_daty()
        {
            Thread lod = new Thread(delegate ()
            {
                try
                {
                    HttpWebRequest request2 = (HttpWebRequest)WebRequest.Create("https://lit-it.ru/programs/steklomaster/scripts/time.php");
                    HttpWebResponse r2 = (HttpWebResponse)request2.GetResponse();
                    string answer = new StreamReader(r2.GetResponseStream(), Encoding.UTF8).ReadToEnd();
                    if (answer != "" && answer != null)
                    {
                        bool ret = true;
                        while (ret)
                        {
                            if (Convert.ToInt32(answer) - 60000 < (int)(DateTime.Now - new System.DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds && Convert.ToInt32(answer) + 60000 > (int)(DateTime.Now - new System.DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds)
                            {
                                ret = false;
                            }
                            else
                            {
                                if (MessageBox.Show("Время на вашем компьютере и сервере не совпадают!\nПожалуйста поменяйте время на компьютере!\n\nПовторить проверку времени?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.No)
                                {
                                    ret = false;
                                }
                            }
                        }
                    }
                }
                catch { }
            });
            lod.IsBackground = true;
            lod.Start();
        }


        //#новый
        /// <summary>
        /// Создает файлы необходимые для работы программы
        /// </summary>
        void default_file()
        {
            if (Application.StartupPath.IndexOf("comp") != -1)
            {
                putin = Application.StartupPath.Substring(0, Application.StartupPath.IndexOf("\\comp"));
            }
            else
            {
                putin = Application.StartupPath;
            }
            if (!File.Exists(putin + "\\users.akv"))
            {
                File.WriteAllText(putin + "\\users.akv", "", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\podem.akv"))
            {
                File.WriteAllText(putin + "\\podem.akv", "Стандарт|300\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\raone.akv"))
            {
                File.WriteAllText(putin + "\\raone.akv", "Московский|300\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\karta-users.akv"))
            {
                File.WriteAllText(putin + "\\karta-users.akv", "", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\rekvizit.txt"))
            {
                IniFile INI = new IniFile(putin + "\\rekvizit.txt");
                INI.Write("Print", "street", "603074, г. Нижний Новгород, ул. Шаляпина 2а оф. 2");
                INI.Write("Print", "site", "http://www.steklomaster-nn.ru");
                INI.Write("Print", "telephone", "8 (831) 217-60-18; 217-60-21 / Факс 8 (831) 217-60-23");
                INI.Write("Print", "mail", "stekmaster@list.ru");
                INI.Write("Print", "clock", "Пн. - Пт.: 9.00 - 18.00, Сб.: 9.00 - 15.00 только офис на прием заказов Вс. - Выходной\r\nВ общий счёт добавлено 5 руб. за упаковку и смс оповещение. Спасибо за понимание.");
                INI.Write("Print", "organization", "ООО \"СТЕКЛОМАСТЕР\", ОГРН 1165275015762, ИНН 5259124242, КПП 525901001");
                INI.Write("Print", "footer", "Срок хранения заказа 14 дней. По истечении срока компания ответственности не несет!\r\nВыдача заказа при предъявлении квитанции. Проверить готовность заказа можно на сайте в\r\nразделе \"Заказы\", или по телефону 410-79-42.");
                //File.WriteAllText(Application.StartupPath + "\\rekvizit.txt", "", Encoding.UTF8);
            }
            if (!File.Exists(Application.StartupPath + "\\manager.akv"))
            {
                File.WriteAllText(Application.StartupPath + "\\manager.akv", "Неизвестно|790000000000", Encoding.UTF8);
            }
            if (!File.Exists(Application.StartupPath + "\\baza.akv"))
            {
                File.WriteAllText(Application.StartupPath + "\\baza.akv", "", Encoding.UTF8);
            }
            if (!File.Exists(Application.StartupPath + "\\perfics.akv"))
            {
                File.WriteAllText(Application.StartupPath + "\\perfics.akv", "-??", Encoding.UTF8);
            }
            if (!File.Exists(Application.StartupPath + "\\device.txt"))
            {
                File.WriteAllText(Application.StartupPath + "\\device.txt", "HID#VID_08FF&PID_0009", Encoding.UTF8);
            }
            
            
            if (!Directory.Exists(putin + "\\data"))
            {
                Directory.CreateDirectory(putin + "\\data");
            }
            if (!Directory.Exists(putin + "\\baza"))
            {
                Directory.CreateDirectory(putin + "\\baza");
            }
            FileInfo aFile = new FileInfo(Application.StartupPath + "\\update.exe");
            if (aFile.Exists == false)
            {
                WebClient wc = new WebClient();
                wc.DownloadFile(new Uri("https://lit-it.ru/programs/steklomaster/update/update.exe"), Application.StartupPath + "\\update.exe");
            }
            aFile = new FileInfo(Application.StartupPath + "\\GenCode128.dll");
            if (aFile.Exists == false)
            {
                WebClient wc = new WebClient();
                wc.DownloadFile(new Uri("https://lit-it.ru/programs/steklomaster/update/GenCode128.dll"), Application.StartupPath + "\\GenCode128.dll");
            }
            if (File.Exists(Application.StartupPath + "\\device.txt"))
            {
                StreamReader Sr = new StreamReader(Application.StartupPath + "\\device.txt", Encoding.UTF8);
                device = Sr.ReadToEnd();
                Sr.Close();
            }
            //скинали
            if (!Directory.Exists(putin + "\\data\\skinali"))
            {
                Directory.CreateDirectory(putin + "\\data\\skinali");
            }
            if (!File.Exists(putin + "\\data\\skinali\\uslugi.akv"))
            {
                File.WriteAllText(putin + "\\data\\skinali\\uslugi.akv", "Монтаж скинали|500|Монтажи|c|\r\nОбработка экскиза (500 руб/час)|500|Работа с экскизом|c|\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\data\\skinali\\tovar.akv"))
            {
                File.WriteAllText(putin + "\\data\\skinali\\tovar.akv", "Крючёк|100|Крепление|p|\r\nРозетка двойная|200|Розетки|c|\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\data\\skinali\\material.akv"))
            {
                File.WriteAllText(putin + "\\data\\skinali\\material.akv", "Стекло полированное листовое|2 мм!150!200!250!150~4 мм!200!250!300!200~5 мм!500!550!600!500\r\nПланибель Бронза|2 мм!150!200!250!150~4 мм!200!250!300!200~5 мм!500!550!600!500~8 мм!700!800!900!700\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\data\\skinali\\dirkazak.akv"))
            {
                File.WriteAllText(putin + "\\data\\skinali\\dirkazak.akv", "3|0-16-40~16-30-60~30-50-70~50-70-200\r\n4|0-16-40~16-30-60~30-50-70~50-70-200\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\data\\skinali\\dirka.akv"))
            {
                File.WriteAllText(putin + "\\data\\skinali\\dirka.akv", "3|0-16-20~16-30-30~30-50-35~50-70-150\r\n4|0-16-20~16-30-30~30-50-35~50-70-150\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\data\\skinali\\obrabotka.akv"))
            {
                File.WriteAllText(putin + "\\data\\skinali\\obrabotka.akv", "Притупление|2!100~4!200\r\nТрапеция шлифованная|2!100~4!200\r\nТрапеция полированная|2!100~4!200\r\nФацет 10мм|2!100~4!200\r\nФацет 15 мм|2!100~4!200\r\nФацет 20мм|2!100~4!200\r\nФацет 25мм|2!100~4!200\r\nФацет 30 мм|2!100~4!200\r\nФацет 10мм без полировки|2!100~4!200\r\nФацет 15мм без полировки|2!100~4!200\r\nФацет 20мм без полировки|2!100~4!200\r\nФацет 25мм без полировки|2!100~4!200\r\nФацет 30мм без полировки|2!100~4!200\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\data\\skinali\\kosobrabotka.akv"))
            {
                File.WriteAllText(putin + "\\data\\skinali\\kosobrabotka.akv", "Притупление|2!100~4!200\r\nТрапеция шлифованная|2!100~4!200\r\nТрапеция полированная|2!100~4!200\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\data\\skinali\\variant.akv"))
            {
                File.WriteAllText(putin + "\\data\\skinali\\variant.akv", "Периметр\r\nПолупериметр\r\n1 сторона большего размера\r\n2 стороны большего размера\r\n1 сторона меньшего размера\r\n2 стороны меньшего размера\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\data\\skinali\\forma.akv"))
            {
                File.WriteAllText(putin + "\\data\\skinali\\forma.akv", "Прямоугольная\r\nФигурная\r\nОкружность\r\nСкругление углов минимальное, R5 мм\r\nРадиусные углы\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\data\\skinali\\dekor.akv"))
            {
                File.WriteAllText(putin + "\\data\\skinali\\dekor.akv", "Фотопечать|100\r\nПескоструйный рисунок|100\r\nМорозная искра|100\r\nАрт-тоннирование Oracal - 1 цвет|100\r\nАрт-тоннирование Oracal - 2 цвет|100\r\nАрт-тоннирование Oracal - 3 цвет|100\r\nАрт-тоннирование Oracal - 4 цвет|100\r\nАрт-тоннирование Oracal - 5 цвет|100\r\nАрт-тоннирование Oracal - 6 цвет|100\r\nАрт-тоннирование Oracal - 7 цвет|100\r\nБело-матовая пленка|100\r\nСплошное матирование|100\r\nАрхитектурная тоннирующая пленка|100\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\data\\skinali\\virez.akv"))
            {
                File.WriteAllText(putin + "\\data\\skinali\\virez.akv", "Внешний|100|\r\nВнутренний|100|\r\nОтверстие под розетку|100|\r\nОтверстие под петли|100|\r\nОтверстие|100|\r\n", Encoding.UTF8);
            }
            //модульные картины
            if (!Directory.Exists(putin + "\\data\\modulkart"))
            {
                Directory.CreateDirectory(putin + "\\data\\modulkart");
            }
            if (!File.Exists(putin + "\\data\\modulkart\\uslugi.akv"))
            {
                File.WriteAllText(putin + "\\data\\modulkart\\uslugi.akv", "Эскиз|500|Оформление|c|\r\n", Encoding.UTF8);
            }
            if (!File.Exists(putin + "\\data\\modulkart\\tovar.akv"))
            {
                File.WriteAllText(putin + "\\data\\modulkart\\tovar.akv", "Усиленный|100|Крепеж|c|\r\nПодвес (средний)|200|Крепеж|c|\r\nВеревочка|200|Крепеж|c|\r\nShutterstock|200|Фото|c|\r\n", Encoding.UTF8);
            }
        }

        /// <summary>
        /// Загружает текущие настройки
        /// </summary>
        void load_config()
        {
            //загрузка параметров печати
            IniFile INI = new IniFile(putin + "\\rekvizit.txt");
            if (INI.KeyExists("Print", "street"))
                Статика.Печать_Адрес = INI.ReadINI("Print", "street");
            if (INI.KeyExists("Print", "site"))
                Статика.Печать_Сайт = INI.ReadINI("Print", "site");
            if (INI.KeyExists("Print", "telephone"))
                Статика.Печать_Телефон = INI.ReadINI("Print", "telephone");
            if (INI.KeyExists("Print", "mail"))
                Статика.Печать_Почта = INI.ReadINI("Print", "mail");
            if (INI.KeyExists("Print", "clock"))
                Статика.Печать_График = INI.ReadINI("Print", "clock");
            if (INI.KeyExists("Print", "organization"))
                Статика.Печать_Организация = INI.ReadINI("Print", "organization");
            if (INI.KeyExists("Print", "footer"))
                Статика.Печать_футер = INI.ReadINI("Print", "footer");
            

            //Загрузка менеджера
            load_manager();
            //Загрузка перфикса
            load_perfics();
            //Загрузка интерфейса
            load_interfec();

        }

        //#новый + модуль
        /// <summary>
        /// Загружает интерфейс программы
        /// </summary>
        void load_interfec()
        {
            dateTimePicker1.Value = DateTime.Now.AddDays(-1);
            //скинали
            //товар|цена|группа|тип расчета|
            try
            {
                StreamReader sr = new StreamReader(putin + "\\data\\skinali\\tovar.akv");
                string k = sr.ReadToEnd();
                sr.Close();
                string postav = "";
                comboBox15.BeginUpdate();
                comboBox15.Items.Clear();
                comboBox15.Items.AddRange(new object[] { "Все" });

                string[] wordr = k.Split('\n');
                foreach (string word in wordr)
                {
                    if (word != "" && word != null)
                    {
                        string tmp = word.Replace("\r", "");
                        string[] a1 = tmp.Split('|');
                        if (postav.IndexOf("<" + a1[2] + ">") == -1)
                        {
                            comboBox15.Items.AddRange(new object[] { a1[2] });
                            postav += "<" + a1[2] + ">";
                        }
                    }
                }
                comboBox15.EndUpdate();
                comboBox15.SelectedIndex = 0;
            }
            catch
            {
                comboBox15.EndUpdate();
            }

            //услуга|цена|группа|тип расчета|
            try
            {
                StreamReader sr = new StreamReader(putin + "\\data\\skinali\\uslugi.akv");
                string k = sr.ReadToEnd();
                sr.Close();
                string postav = "";
                comboBox14.BeginUpdate();
                comboBox14.Items.Clear();
                comboBox14.Items.AddRange(new object[] { "Все" });

                string[] wordr = k.Split('\n');
                foreach (string word in wordr)
                {
                    if (word != "" && word != null)
                    {
                        string tmp = word.Replace("\r", "");
                        string[] a1 = tmp.Split('|');
                        if (postav.IndexOf("<" + a1[2] + ">") == -1)
                        {
                            comboBox14.Items.AddRange(new object[] { a1[2] });
                            postav += "<" + a1[2] + ">";
                        }
                    }
                }
                comboBox14.EndUpdate();
                comboBox14.SelectedIndex = 0;
            }
            catch
            {
                comboBox14.EndUpdate();
            }

            //модульные
            //товары
            try
            {
                StreamReader sr = new StreamReader(putin + "\\data\\modulkart\\tovar.akv");
                string k = sr.ReadToEnd();
                sr.Close();
                string postav = "";
                comboBox1.BeginUpdate();
                comboBox1.Items.Clear();
                comboBox1.Items.AddRange(new object[] { "Все" });

                string[] wordr = k.Split('\n');
                foreach (string word in wordr)
                {
                    if (word != "" && word != null)
                    {
                        string tmp = word.Replace("\r", "");
                        string[] a1 = tmp.Split('|');
                        if (postav.IndexOf("<" + a1[2] + ">") == -1)
                        {
                            comboBox1.Items.AddRange(new object[] { a1[2] });
                            postav += "<" + a1[2] + ">";
                        }
                    }
                }
                comboBox1.EndUpdate();
                comboBox1.SelectedIndex = 0;
            }
            catch
            {
                comboBox1.EndUpdate();
            }

            //услуга|цена|группа|тип расчета|
            try
            {
                StreamReader sr = new StreamReader(putin + "\\data\\modulkart\\uslugi.akv");
                string k = sr.ReadToEnd();
                sr.Close();
                string postav = "";
                comboBox2.BeginUpdate();
                comboBox2.Items.Clear();
                comboBox2.Items.AddRange(new object[] { "Все" });

                string[] wordr = k.Split('\n');
                foreach (string word in wordr)
                {
                    if (word != "" && word != null)
                    {
                        string tmp = word.Replace("\r", "");
                        string[] a1 = tmp.Split('|');
                        if (postav.IndexOf("<" + a1[2] + ">") == -1)
                        {
                            comboBox2.Items.AddRange(new object[] { a1[2] });
                            postav += "<" + a1[2] + ">";
                        }
                    }
                }
                comboBox2.EndUpdate();
                comboBox2.SelectedIndex = 0;
            }
            catch
            {
                comboBox2.EndUpdate();
            }
        }

        /// <summary>
        /// Загружает данные менеджера
        /// </summary>
        public void load_manager()
        {
            StreamReader Sr = new StreamReader(Application.StartupPath + "\\manager.akv", Encoding.UTF8);
            string f = Sr.ReadToEnd();
            Sr.Close();
            Sr = null;
            label31.Text = f.Split('|')[0];
            label32.Text = f.Split('|')[1];
            if (label31.Text == "Неизвестно")
            {
                button2_Click(null, null);
            }
        }

        /// <summary>
        /// Загружает перфикс
        /// </summary>
        public void load_perfics()
        {
            StreamReader Sr = new StreamReader(Application.StartupPath + "\\perfics.akv", Encoding.UTF8);
            perfics = Sr.ReadToEnd();
            Sr.Close();
            Sr = null;
            if (perfics == "-??")
            {
                button9_Click(null, null);
            }
            load_nomer();
        }

        /// <summary>
        /// Загружает текущий номер заказа
        /// </summary>
        void load_nomer()
        {
            try
            {
                StreamReader sr = new StreamReader(Application.StartupPath + "\\baza.akv");
                string temp = sr.ReadToEnd();
                sr.Close();
                if (temp.IndexOf("Дата :") != -1)
                {
                    int t = temp.IndexOf("Дата :");
                    int t2 = temp.IndexOf("№", t);
                    int t3 = temp.IndexOf("|", t2);
                    try
                    {
                        string t4 = temp.Substring(t2, t3 - t2).Replace("№", "");
                        try
                        {
                            t4 = t4.Replace(perfics, "");
                        }
                        catch { }
                        try
                        {
                            int t5 = Convert.ToInt32(t4);
                            label22.Text = (t5 + 1).ToString() + perfics;
                        }
                        catch { label22.Text = "1" + perfics; }
                    }
                    catch
                    {
                        label22.Text = "1" + perfics;
                    }
                }
                else
                {
                    label22.Text = "1" + perfics;
                }
            }
            catch
            {
                label22.Text = "1" + perfics;
            }

        }

        /// <summary>
        /// Вызов базы клиентов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button22_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form6")
                {
                    MessageBox.Show("База клиентов уже открыта!");
                    return;
                }
            }
            Form6 f1 = new Form6();
            f1.Owner = this;
            f1.Show();
            f1.load();
        }

        /// <summary>
        /// Загружает данные клиента из бд
        /// </summary>
        /// <param name="temp">Строка клиента</param>
        public void loadklient(DataGridViewRow temp)
        {
            klient = temp;
            label7.Text = klient.Cells[0].Value.ToString() + " " + klient.Cells[1].Value.ToString();
        }

        /// <summary>
        /// Вызов редактирования менеджера
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form7")
                {
                    MessageBox.Show("Редактор менеджера уже открыт!");
                    return;
                }
            }
            Form7 f1 = new Form7();
            f1.Owner = this;
            f1.Show();
            f1.Focus();
        }

        //#новый
        /// <summary>
        /// Создает новый товар
        /// </summary>
        public void tovar_new(int index)
        {
            Array.Resize(ref tovar, tovar.Length + 1);
            //название | цена общая | кол-во | комментарий мастеров | файлы | монтаж | цена за шт | резерв 1| резерв 2| резерв 3 | резерв 4 | резерв 5 |
            if (index == 0)
            {
                //+  Таблица панели|Таблица товары и услуги|
                tovar[tovar.Length - 1] = "Скинали|0|1|||0|0||||||||";
            }
            else if (index == 6)
            {
                tovar[tovar.Length - 1] = "Модульные картины|0|1|||0|0||||||";
            }
            else if (index == 9)
            {
                //+  Название|Цена|
                tovar[tovar.Length - 1] = "Другое|0|1|||0|0|||||||0";
            }
            else
                tovar[tovar.Length - 1] = "Неизвестно|0|1|||0|0||||||";
            pererisovka_korzina();
            listBox5.SelectedIndex = tovar.Length - 1;
        }

        /// <summary>
        /// Кнопка копировать товар
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button35_Click(object sender, EventArgs e)
        {
            Array.Resize(ref tovar, tovar.Length + 1);
            tovar[tovar.Length - 1] = tovar[listBox5.SelectedIndex];
            pererisovka_korzina();
            listBox5.SelectedIndex = tovar.Length - 1;
            obchechiy_schet();
        }

        /// <summary>
        /// Перерисовывает список из корзины
        /// </summary>
        public void pererisovka_korzina()
        {
            anti_obnovlenie_tovar = true;
            listBox5.BeginUpdate();
            try
            {
                listBox5.Items.Clear();
                for (int i = 0; i < tovar.Length; i++)
                {
                    string[] tmp = tovar[i].Split('|');
                    listBox5.Items.AddRange(new object[] { tmp[0] + " - " + tmp[1] + " руб." });
                }
            }
            catch { }
            listBox5.EndUpdate();
            anti_obnovlenie_tovar = false;
            obchechiy_schet();
        }

        /// <summary>
        /// Расчитывает общий счет
        /// </summary>
        private void obchechiy_schet()
        {
            double price = 0;
            for (int i = 0; i < tovar.Length; i++)
            {
                string[] tmp = tovar[i].Split('|');
                price += Convert.ToDouble(tmp[1]);
            }
            //смс на каждую 
            //if (price != 0)
            //{
            //    price += 5;
            //}
            double sum = 0;
            //доставка
            if (textBox1.Text != "" && textBox1.Text != "0")
            {
                sum += Convert.ToDouble(textBox1.Text);
            }
            //подъем на этаж
            if (textBox3.Text != "" && textBox3.Text != "0" && textBox10.Text != "")
            {
                if (textBox11.Text == "" || textBox11.Text == "1")
                    sum += Convert.ToDouble(textBox10.Text) * Convert.ToDouble(textBox3.Text);
                else
                    sum += Convert.ToDouble(textBox10.Text) * Convert.ToDouble(textBox3.Text) * Convert.ToDouble(textBox11.Text);
            }

            //срочность
            if (checkBox1.Checked)
            {
                int pro = (int)Math.Round(sum);
                pro = pro / 100 * 10;
                sum += pro;
            }
            //ндс
            if (numericUpDown1.Value != 0)
            {
                int pro = (int)Math.Round(sum);
                pro = pro / 100 * Convert.ToInt32(numericUpDown1.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);
            }
            price += sum;
            //срочность ндс скидка
            label10.Text = price.ToString() + " руб.";
        }

        /// <summary>
        /// Кнопка удалить товар из корзины
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button30_Click(object sender, EventArgs e)
        {
            if (listBox5.SelectedIndex == -1) return;
            int numToRemove = listBox5.SelectedIndex;
            button24_Click(null, null);
            if (tovar.Length != 1)
            {
                if (listBox5.SelectedIndex == 0)
                    listBox5.SelectedIndex += 1;
                else
                {
                    listBox5.SelectedIndex -= 1;
                }
            }
            else
            {
                listBox5.SelectedIndex = -1;

                label37.Text = "Товар";
                button24_Click(null, null);
                ochistka();
                scrit_panel();
            }
            listBox5.Items.RemoveAt(numToRemove);
            List<string> tmp = new List<string>(tovar);
            tmp.RemoveAt(numToRemove);
            tovar = tmp.ToArray();
            obchechiy_schet();
        }

        /// <summary>
        /// Кнопка очистить корзину
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button32_Click(object sender, EventArgs e)
        {
            cleaners = true;
            int j = tovar.Length;
            for (int i = 0; i < j; i++)
            {
                listBox5.SelectedIndex = 0;
                //listBox5.SelectedIndex = listBox5.Items.Count - 1;
                button30_Click(null, null);
            }
            //ochistka();
            cleaners = false;
        }

        private void ochistka()
        {
            textBox7.Text = "";
            label43.Text = "Остаток:";
            textBox8.Text = "";
            textBox3.Text = "";
            checkBox1.Checked = false;
            radioButton11.Checked = true;
            radioButton1.Checked = true;
            label7.Text = "не выбран";
            numericUpDown3.Value = 0;
            textBox12.Text = "0";
            if (textBox12.Visible)
                button40_Click(null, null);
            numericUpDown1.Value = 0;
            dateTimePicker1.Value = DateTime.Now.AddDays(-1);
            label10.Text = "0";
            textBox1.Text = "";
            textBox2.Text = "";
            textBox11.Text = "";
            textBox10.Text = "";
            klient = null;
        }

        //#новый
        /// <summary>
        /// Восстанавливает содержимое из памяти на экран
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox5_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (anti_obnovlenie_korzina) return;
            if (listBox5.SelectedIndex == -1) return;
            if (zagruzka) return;
            listBox5.Enabled = false;
            zagruzka = true;

            string[] sd = tovar[listBox5.SelectedIndex].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");
            listBox1.Items.Clear();
            string[] bd = sd[4].Split('~');
            foreach (string s in bd)
            {
                if (s != "" && s != null)
                    listBox1.Items.AddRange(new object[] { s });
            }
            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];
                        }

                    }
                }

                //+   Фотография из фотобанка |Работа с экскизом|Кол-во крепежей|Длина рейлинга|Монтаж скинали|Монтаж рейлинга|Монтаж  розеток|Монтаж плинтуса
                //comboBox5.SelectedIndex = Convert.ToInt32(sd[12]);
                //comboBox4.SelectedIndex = Convert.ToInt32(sd[13]);
                //textBox4.Text = sd[14];
                //comboBox3.SelectedIndex = Convert.ToInt32(sd[15]);
                //checkBox2.Checked = (sd[16] == "true");
                //checkBox5.Checked = (sd[17] == "true");
                //comboBox1.SelectedIndex = Convert.ToInt32(sd[18]);
                //comboBox2.SelectedIndex = Convert.ToInt32(sd[19]);
            }
            else if (sd[0] == "Модульные картины")
            {
                panel21.Visible = true;
            }
            else if (sd[0] == "Другое")
            {
                panel15.Visible = true;
                //+Название|Цена
                textBox4.Text = sd[12];
                textBox6.Text = sd[13];
            }
            zagruzka = false;
            listBox5.Enabled = true;
        }

        //#новый
        /// <summary>
        /// Скрывает все панели товаров
        /// </summary>
        private void scrit_panel()
        {
            panel10.Visible = false;
            panel21.Visible = false;
            panel15.Visible = false;
        }

        //#новый
        /// <summary>
        /// Обновляет информацию о товаре
        /// </summary>
        void tovar_obn()
        {
            if (listBox5.SelectedIndex == -1) return;
            if (zagruzka) return;
            //название | цена общая | кол-во | комментарий мастеров | файлы | монтаж | цена за шт |резерв 1| резерв 2| резерв 3 | резерв 4 | резерв 5 |
            string s = label37.Text + "|" + label19.Text + "|" + numericUpDown8.Value + "|" + richTextBox2.Text.Replace("|", "\\").Replace("\r", "<r>").Replace("\n", "<n>") + "|";
            for (int i = 0; i < listBox1.Items.Count; i++)
            {
                s += listBox1.Items[i].ToString() + "~";
            }
            s += "|" + label33.Text + "|" + label34.Text + "||||||";
            if (label37.Text == "Скинали")
            {
                //+  Таблица панели|Таблица товары и услуги|
                if (dataGridView1.Rows.Count != 0)
                {
                    for (int i = 0; i < dataGridView1.Rows.Count; i++)
                    {
                        for (int j = 0; j < 11; j++)
                            s += dataGridView1.Rows[i].Cells[j].Value + "!";
                        s += "~";
                    }
                }
                s += "|";
                if (dataGridView3.Rows.Count != 0)
                {
                    for (int i = 0; i < dataGridView3.Rows.Count; i++)
                    {
                        for (int j = 0; j < 4; j++)
                            s += dataGridView3.Rows[i].Cells[j].Value + "!";
                        s += "~";
                    }
                }
                s += "|";

                //+   Фотография из фотобанка |Работа с экскизом|Кол-во крепежей|Длина рейлинга|Монтаж скинали|Монтаж рейлинга|Монтаж  розеток|Монтаж плинтуса
                //s += comboBox5.SelectedIndex + "|" + comboBox4.SelectedIndex + "|" + textBox4.Text + "|" + comboBox3.SelectedIndex + "|";
                //if (checkBox2.Checked)
                //    s += "true";
                //else
                //    s += "false";
                //s += "|";
                //if (checkBox5.Checked)
                //    s += "true";
                //else
                //    s += "false";
                //s += "|"+comboBox1.SelectedIndex +"|"+comboBox2.SelectedIndex;
            }
            else if (label37.Text == "Другое")
            {
                //+Название|Цена
                s += textBox4.Text + "|" + textBox6.Text + "|";
            }
            tovar[listBox5.SelectedIndex] = s;
            pererisovka_schastnoe(listBox5.SelectedIndex);
        }

        /// <summary>
        /// Перерисовывает 1 элемент в списке
        /// </summary>
        /// <param name="index">Индекс в listBox</param>
        private void pererisovka_schastnoe(int index)
        {
            anti_obnovlenie_korzina = true;
            string[] tmp = tovar[index].Split('|');
            listBox5.Items[index] = tmp[0] + " - " + tmp[1] + " руб.";
            obchechiy_schet();
            anti_obnovlenie_korzina = false;
        }

        /// <summary>
        /// Добавление прикрепленного файла
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Filter = "Все файлы (*.*)|*.*";
            openFileDialog1.Title = "Выберите файл!";
            openFileDialog1.Multiselect = true;
            if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                foreach (String file in openFileDialog1.FileNames)
                {
                    bool fg = false;
                    for (int i = 0; i < listBox1.Items.Count; i++)
                    {
                        if (file == listBox1.Items[i].ToString())
                        {
                            MessageBox.Show("Файл " + file + " уже есть в списке!");
                            fg = true;
                            break;
                        }
                    }
                    if (fg)
                        continue;
                    listBox1.Items.AddRange(new object[] { file });
                    listBox1.SelectedIndex = listBox1.Items.Count - 1;
                }
                tovar_obn();
            }
        }

        /// <summary>
        /// Удаляет прикрепленный файл
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            if (listBox1.Items.Count == 0) return;
            int numToRemove = listBox1.SelectedIndex;
            if (listBox1.Items.Count != 1)
            {
                if (listBox1.SelectedIndex == 0)
                    listBox1.SelectedIndex += 1;
                else
                    listBox1.SelectedIndex -= 1;
            }
            else
            {
                listBox1.SelectedIndex = -1;
            }
            listBox1.Items.RemoveAt(numToRemove);
            tovar_obn();
        }

        /// <summary>
        /// Очищает все прикрепленные файлы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button8_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            tovar_obn();
        }

        /// <summary>
        /// Показывает полный путь файла
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void listBox1_DoubleClick(object sender, EventArgs e)
        {
            if (listBox1.SelectedIndex != -1)
                System.Diagnostics.Process.Start(listBox1.Items[listBox1.SelectedIndex].ToString());
        }

        /// <summary>
        /// Изменение текста примечание для мастеров
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {
            if (richTextBox2.Text == "" || richTextBox2.Text == null) return;
            InputLanguage myCurrentLanguage = InputLanguage.CurrentInputLanguage;
            if (myCurrentLanguage.Culture.Name != "ru-RU")
            {
                string s = RUSSIAN(richTextBox2.Text);
                if (s != richTextBox2.Text)
                {
                    richTextBox2.Text = s;
                    richTextBox2.SelectionStart = s.Length;

                }
            }
            InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new System.Globalization.CultureInfo("ru-RU"));
            tovar_obn();
        }

        /// <summary>
        /// Руссифицирует строку
        /// </summary>
        /// <param name="s">строка</param>
        /// <returns></returns>
        private string RUSSIAN(string s)
        {
            s = s.Replace('q', 'й');
            s = s.Replace('w', 'ц');
            s = s.Replace('e', 'у');
            s = s.Replace('r', 'к');
            s = s.Replace('t', 'е');
            s = s.Replace('y', 'н');
            s = s.Replace('u', 'г');
            s = s.Replace('i', 'ш');
            s = s.Replace('o', 'щ');
            s = s.Replace('p', 'з');
            s = s.Replace('a', 'ф');
            s = s.Replace('s', 'ы');
            s = s.Replace('d', 'в');
            s = s.Replace('f', 'а');
            s = s.Replace('g', 'п');
            s = s.Replace('h', 'р');
            s = s.Replace('j', 'о');
            s = s.Replace('k', 'л');
            s = s.Replace('l', 'д');
            s = s.Replace('z', 'я');
            s = s.Replace('x', 'ч');
            s = s.Replace('c', 'с');
            s = s.Replace('v', 'м');
            s = s.Replace('b', 'и');
            s = s.Replace('n', 'т');
            s = s.Replace('m', 'ь');


            if (Console.CapsLock)
            {
                s = s.Replace(';', 'Ж');
                s = s.Replace('"', 'Э');
                s = s.Replace('[', 'Х');
                s = s.Replace(']', 'Ъ');
                s = s.Replace(',', 'Б');
                s = s.Replace('.', 'Ю');
                s = s.Replace('\'', 'Э');
            }
            else
            {
                s = s.Replace('[', 'х');
                s = s.Replace(']', 'ъ');
                s = s.Replace(';', 'ж');
                s = s.Replace('"', 'э');
                s = s.Replace(',', 'б');
                s = s.Replace('.', 'ю');
                s = s.Replace('\'', 'э');
            }


            s = s.Replace('Q', 'Й');
            s = s.Replace('W', 'Ц');
            s = s.Replace('E', 'У');
            s = s.Replace('R', 'К');
            s = s.Replace('T', 'Е');
            s = s.Replace('Y', 'Н');
            s = s.Replace('U', 'Г');
            s = s.Replace('I', 'Ш');
            s = s.Replace('O', 'Щ');
            s = s.Replace('P', 'З');
            s = s.Replace('A', 'Ф');
            s = s.Replace('S', 'Ы');
            s = s.Replace('D', 'В');
            s = s.Replace('F', 'А');
            s = s.Replace('G', 'П');
            s = s.Replace('H', 'Р');
            s = s.Replace('J', 'О');
            s = s.Replace('K', 'Л');
            s = s.Replace('L', 'Д');
            s = s.Replace('Z', 'Я');
            s = s.Replace('X', 'Ч');
            s = s.Replace('C', 'С');
            s = s.Replace('V', 'М');
            s = s.Replace('B', 'И');
            s = s.Replace('N', 'Т');
            s = s.Replace('M', 'Ь');

            s = s.Replace("|", "/");
            s = s.Replace("\n", " ");
            s = s.Replace("\r", "");

            return s;
        }

        /// <summary>
        /// Изменение кол-ва товара
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void numericUpDown8_ValueChanged(object sender, EventArgs e)
        {
            if (zagruzka) return;
            sum();
        }

        //#новый
        /// <summary>
        /// Высчитывает частный счет товара
        /// </summary>
        public void sum()
        {
            if (zagruzka) return;
            if (cleaners == false)
            {
                try
                {
                    double sum = 0;
                    double skidsum = 0;
                    int sredneeskid = 0;
                    if (textBox12.Text != "")
                    {
                        skidsum = Convert.ToDouble(textBox12.Text);
                        sredneeskid = (int)skidsum / listBox5.Items.Count;
                    }
                    // double mont = 0;
                    //частный расчет
                    if (label37.Text == "Скинали")
                    {
                        for (int i = 0; i < dataGridView1.Rows.Count; i++)
                        {
                            sum += Convert.ToDouble(dataGridView1.Rows[i].Cells[9].Value.ToString());

                            string zna = "";
                            if (dataGridView1.Rows[i].Cells[10].Value != null && dataGridView1.Rows[i].Cells[10].Value.ToString() != "")
                                zna = dataGridView1.Rows[i].Cells[10].Value.ToString();
                            if (zna != "" && zna != null)
                            {
                                string[] bd2 = zna.Split('`');
                                foreach (string s in bd2)
                                {
                                    if (s != "")
                                    {
                                        string[] f = s.Split('@');
                                        if (f[4] != "" && f[4] != null)
                                            sum += Convert.ToDouble(f[4]) * Convert.ToDouble(f[3]);
                                    }

                                }
                            }
                            //цикл по отверстиям + при редактировании смена прайса
                        }
                        //определение цены отверстия

                        //for (int i = 0; i < dataGridView1.Rows.Count; i++)
                        //{
                        //    sum += Convert.ToDouble(dataGridView1.Rows[i].Cells[8].Value.ToString());
                        //    //цикл по отверстиям + при редактировании смена прайса
                        //}

                        for (int i = 0; i < dataGridView3.Rows.Count; i++)
                        {
                            sum += Convert.ToDouble(dataGridView3.Rows[i].Cells[1].Value.ToString().Replace(" м.кв.", "").Replace(" м.п.", "")) * Convert.ToInt32(dataGridView3.Rows[i].Cells[2].Value);
                            dataGridView3.Rows[i].Cells[3].Value = Convert.ToDouble(dataGridView3.Rows[i].Cells[1].Value.ToString().Replace(" м.кв.", "").Replace(" м.п.", "")) * Convert.ToInt32(dataGridView3.Rows[i].Cells[2].Value);
                        }
                    }
                    else if (label37.Text == "Модульные картины")
                    {
                        for (int i = 0; i < dataGridView4.Rows.Count; i++)
                        {
                            sum += Convert.ToDouble(dataGridView4.Rows[i].Cells[1].Value.ToString().Replace(" м.кв.", "").Replace(" м.п.", "")) * Convert.ToInt32(dataGridView4.Rows[i].Cells[2].Value);
                            dataGridView4.Rows[i].Cells[3].Value = Convert.ToDouble(dataGridView4.Rows[i].Cells[1].Value.ToString().Replace(" м.кв.", "").Replace(" м.п.", "")) * Convert.ToInt32(dataGridView4.Rows[i].Cells[2].Value);
                        }
                    }
                    else if (label37.Text == "Другое")
                    {
                        sum += Convert.ToDouble(textBox6.Text);
                    }
                    //
                    //срочность
                    if (checkBox1.Checked)
                    {
                        int pro = (int)Math.Round(sum);
                        pro = pro / 100 * 10;
                        sum += pro;
                    }
                    //ндс
                    if (numericUpDown1.Value != 0)
                    {
                        int pro = (int)Math.Round(sum);
                        pro = pro / 100 * Convert.ToInt32(numericUpDown1.Value);
                        sum = sum + pro;
                    }
                    //смска и упаковка
                    if (sum != 0)
                        sum += 5;
                    //сумма без скидки
                    label33.Text = ((int)Math.Round(sum)).ToString();

                    //скидка
                    if (numericUpDown3.Value != 0)
                    {
                        double pro = sum;
                        pro = pro / 100 * Convert.ToInt32(numericUpDown3.Value);
                        sum = sum - pro;
                        sum = Math.Round(sum);
                        label34.Text = sum.ToString();
                    }
                    else if (skidsum != 0)
                    {
                        //определение последнего элемента
                        if (listBox5.SelectedIndex != listBox5.Items.Count - 1)
                        {
                            sum -= sredneeskid;

                        }
                        else
                        {
                            double htmp = skidsum - ((listBox5.Items.Count - 1) * sredneeskid);
                            sum -= htmp;

                        }
                        sum = Math.Round(sum);
                        label34.Text = sum.ToString();
                    }
                    else
                    {
                        sum = Math.Round(sum);
                        label34.Text = sum.ToString();
                    }

                    //Прибавляем монтаж
                    // sum += mont;
                    //количество
                    sum = sum * Convert.ToInt32(numericUpDown8.Value);
                    //выводим общий счет
                    label19.Text = sum.ToString();
                    //Вызываем сохранение пересчета
                    tovar_obn();
                    obchechiy_schet();
                    //Вызываем пересчет остатка
                    textBox7_TextChanged(null, null);
                }
                catch { }
            }
        }

        //#новый
        /// <summary>
        /// Кнопка очистить товар
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button24_Click(object sender, EventArgs e)
        {
            if (listBox5.Items.Count == 0) return;
            cleaners = true;
            if (label37.Text == "Скинали")
            {
                dataGridView1.Rows.Clear();
                dataGridView2.Rows.Clear();
                dataGridView3.Rows.Clear();
                textBox5.Text = "";
                numericUpDown6.Value = 1;
                numericUpDown7.Value = 100;
                comboBox15.SelectedIndex = 0;
                comboBox14.SelectedIndex = 0;
                tovar[tovar.Length - 1] = "Скинали|0|1|||0|0||||||||";
            }
            else if (label37.Text == "Другое")
            {
                textBox4.Text = "";
                textBox6.Text = "0";
                tovar[tovar.Length - 1] = "Другое|0|1|||0|0|||||||0";
            }
            richTextBox2.Text = "";
            listBox1.Items.Clear();
            numericUpDown8.Value = 1;
            label33.Text = "0";
            dateTimePicker1.Value = DateTime.Now.AddDays(-1);
            label19.Text = "0";
            label34.Text = "0";
            cleaners = false;

            obnsp();
            obchechiy_schet();
        }

        /// <summary>
        /// Изменение поля оплачено
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox7_TextChanged(object sender, EventArgs e)
        {
            double vvd;
            if (textBox7.Text == "" || !Double.TryParse(textBox7.Text, out vvd)) return;
            double sum = Convert.ToDouble(label10.Text.Replace("руб.", "").Replace(" ", ""));
            label43.Text = "Остаток: " + (sum - vvd).ToString() + " руб.";
        }

        /// <summary>
        /// Изменение текста в оплачено
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox7_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsControl(e.KeyChar)) return;
            if (e.KeyChar < '0' || e.KeyChar > '9')
            {
                if (e.KeyChar != ',')
                    e.Handled = true;
            }
        }

        /// <summary>
        /// Изменение значения в ндс
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void numericUpDown1_ValueChanged(object sender, EventArgs e)
        {
            obnsp();
        }

        /// <summary>
        /// Изменение значения в поле скидка
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void numericUpDown3_ValueChanged(object sender, EventArgs e)
        {
            obnsp();
        }

        /// <summary>
        /// Общее обновление данных
        /// </summary>
        private void obnsp()
        {
            if (!cleaners)
            {
                int f = listBox5.SelectedIndex;
                for (int i = 0; i < listBox5.Items.Count; i++)
                {
                    listBox5.SelectedIndex = i;
                    sum();
                }
                listBox5.SelectedIndex = f;
            }

        }

        /// <summary>
        /// Выбран безналичиный метод оплаты
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void radioButton6_CheckedChanged(object sender, EventArgs e)
        {
            if (radioButton6.Checked)
                numericUpDown1.Value = 18;
            else
                numericUpDown1.Value = 0;

        }

        /// <summary>
        /// Открытие редактирования перфикса
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button9_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form3")
                {
                    MessageBox.Show("Редактор перфикса уже открыт!");
                    return;
                }
            }
            Form3 f1 = new Form3();
            f1.Owner = this;
            f1.Show();
            f1.Focus();
        }

        /// <summary>
        /// Изменение даты на панели
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            label9.Text = "Дата : " + DateTime.Now.ToString();
        }

        #region Скинали
        /// <summary>
        /// Изменение группы товаров
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox15_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox15.Text == "")
                return;
            int c = 0;
            string str33 = "";
            try
            {
                using (StreamReader sr = new StreamReader(putin + "\\data\\skinali\\tovar.akv"))
                {
                    listBox3.BeginUpdate();
                    listBox3.Items.Clear();
                    while ((str33 = sr.ReadLine()) != null)
                    {
                        if (str33 != "" && str33 != null)
                        {
                            c++;
                            string[] tmp = str33.Replace("\r", "").Split('|');
                            if (comboBox15.Text != "Все")
                            {
                                if (tmp[2] != comboBox15.Text)
                                    continue;
                            }
                            listBox3.Items.AddRange(new object[] { c.ToString() + ". " + tmp[0] + " - " + tmp[1] + " руб." });
                        }

                    }
                    if (listBox3.Items.Count != 0)
                        listBox3.SelectedIndex = 0;
                    listBox3.EndUpdate();
                }
            }
            catch { listBox3.EndUpdate(); }
        }

        /// <summary>
        /// Выделение позиции в списке товаров
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void listBox3_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox3.SelectedIndex == -1) return;
            int c = 0;
            string a = listBox3.SelectedItem.ToString();
            a = a.Substring(0, a.IndexOf("."));
            string str33 = "";
            try
            {
                using (StreamReader sr = new StreamReader(new FileStream(putin + "\\data\\skinali\\tovar.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    while ((str33 = sr.ReadLine()) != null)
                    {
                        if (c == Convert.ToInt32(a) - 1)
                        {
                            if (str33.Split('|')[3] == "p")
                            {
                                double p = 0.0;
                                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                                {
                                    p += (Convert.ToDouble(dataGridView1.Rows[i].Cells[1].Value) + Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value)) * 2 / 1000;
                                }
                                numericUpDown2.Value = Convert.ToDecimal(p);
                                label61.Text = " м.п.";
                                break;
                            }
                            if (str33.Split('|')[3] == "s")
                            {
                                double s = 0.0;
                                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                                {
                                    s += Convert.ToDouble(dataGridView1.Rows[i].Cells[1].Value) * Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value) / 1000000;
                                }
                                numericUpDown2.Value = Convert.ToDecimal(s);
                                label61.Text = " м.кв.";
                                break;
                            }
                            if (str33.Split('|')[3] == "c")
                            {
                                numericUpDown2.Value = 1;
                                label61.Text = "Кол-во";
                                break;
                            }

                        }
                        c++;
                    }
                }
            }
            catch { }
            c = 0;
            str33 = null;
        }

        /// <summary>
        /// Кнопка добавление товара
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button21_Click(object sender, EventArgs e)
        {
            int c = 0;
            string str33 = "";
            try
            {
                string nom = listBox3.SelectedItem.ToString().Substring(0, listBox3.SelectedItem.ToString().IndexOf("."));
                using (StreamReader sr = new StreamReader(new FileStream(putin + "\\data\\skinali\\tovar.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    while ((str33 = sr.ReadLine()) != null)
                    {
                        if ((c + 1).ToString() == nom)
                        {
                            try
                            {
                                string[] tmp = str33.Split('|');
                                int i = dataGridView3.Rows.Count;
                                // MessageBox.Show(dataGridView1.Rows.Count.ToString());
                                dataGridView3.Rows.Add();
                                dataGridView3.Rows[i].Cells[0].Value = tmp[2] + " - " + tmp[0];
                                string sd = "";
                                if (label61.Text != "Кол-во")
                                {
                                    sd = label61.Text;
                                }
                                dataGridView3.Rows[i].Cells[1].Value = numericUpDown2.Value + sd;
                                dataGridView3.Rows[i].Cells[2].Value = tmp[1];

                                dataGridView3.Rows[i].Selected = true;
                                dataGridView3.FirstDisplayedScrollingRowIndex = i;
                            }
                            catch { }
                            sum();
                            break;
                        }
                        c++;
                    }
                    sr.Close();
                }
            }
            catch { }
            c = 0;
            str33 = null;
        }

        /// <summary>
        /// Изменение типа услуги
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox14_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox14.Text == "")
                return;
            int c = 0;
            string str33 = "";
            try
            {
                using (StreamReader sr = new StreamReader(putin + "\\data\\skinali\\uslugi.akv"))
                {
                    listBox2.BeginUpdate();
                    listBox2.Items.Clear();
                    while ((str33 = sr.ReadLine()) != null)
                    {
                        if (str33 != "" && str33 != null)
                        {
                            c++;
                            string[] tmp = str33.Replace("\r", "").Split('|');
                            if (comboBox14.Text != "Все")
                            {
                                if (tmp[2] != comboBox14.Text)
                                    continue;
                            }
                            listBox2.Items.AddRange(new object[] { c.ToString() + ". " + tmp[0] + " - " + tmp[1] + " руб." });
                        }

                    }
                    if (listBox2.Items.Count != 0)
                        listBox2.SelectedIndex = 0;
                    listBox2.EndUpdate();
                }
            }
            catch { listBox2.EndUpdate(); }
        }

        /// <summary>
        /// Выделение позиции в списске услуг
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox2.SelectedIndex == -1) return;
            int c = 0;
            string a = listBox2.SelectedItem.ToString();
            a = a.Substring(0, a.IndexOf("."));
            string str33 = "";
            try
            {
                using (StreamReader sr = new StreamReader(new FileStream(putin + "\\data\\skinali\\uslugi.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    while ((str33 = sr.ReadLine()) != null)
                    {
                        if (c == Convert.ToInt32(a) - 1)
                        {
                            if (str33.Split('|')[3] == "p")
                            {
                                double p = 0.0;
                                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                                {
                                    p += (Convert.ToDouble(dataGridView1.Rows[i].Cells[1].Value) + Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value)) * 2 / 1000;
                                }
                                numericUpDown4.Value = Convert.ToDecimal(p);
                                label60.Text = " м.п.";
                                break;
                            }
                            if (str33.Split('|')[3] == "s")
                            {
                                double s = 0.0;
                                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                                {
                                    s += Convert.ToDouble(dataGridView1.Rows[i].Cells[1].Value) * Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value) / 1000000;
                                }
                                numericUpDown4.Value = Convert.ToDecimal(s);
                                label60.Text = " м.кв.";
                                break;
                            }
                            if (str33.Split('|')[3] == "c")
                            {
                                numericUpDown4.Value = 1;
                                label60.Text = "Кол-во";
                                break;
                            }
                            if (str33.Split('|')[3] == "m")
                            {
                                double s = 0.0;
                                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                                {
                                    s += Convert.ToDouble(dataGridView1.Rows[i].Cells[2].Value) / 1000;
                                }
                                numericUpDown4.Value = Convert.ToDecimal(s);
                                label60.Text = " м.п.";
                                break;
                            }

                        }
                        c++;
                    }
                }
            }
            catch { }
            c = 0;
            str33 = null;
        }

        /// <summary>
        /// Кнопка добавления услуги
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button19_Click(object sender, EventArgs e)
        {
            int c = 0;
            string str33 = "";
            try
            {
                string nom = listBox2.SelectedItem.ToString().Substring(0, listBox2.SelectedItem.ToString().IndexOf("."));
                using (StreamReader sr = new StreamReader(new FileStream(putin + "\\data\\skinali\\uslugi.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    while ((str33 = sr.ReadLine()) != null)
                    {
                        if ((c + 1).ToString() == nom)
                        {
                            try
                            {
                                string[] tmp = str33.Split('|');
                                int i = dataGridView3.Rows.Count;
                                // MessageBox.Show(dataGridView1.Rows.Count.ToString());
                                dataGridView3.Rows.Add();
                                dataGridView3.Rows[i].Cells[0].Value = tmp[2] + " - " + tmp[0];
                                string sd = "";
                                if (label60.Text != "Кол-во")
                                {
                                    sd = label60.Text;
                                }
                                dataGridView3.Rows[i].Cells[1].Value = numericUpDown4.Value + sd;
                                dataGridView3.Rows[i].Cells[2].Value = tmp[1];

                                dataGridView3.Rows[i].Selected = true;
                                dataGridView3.FirstDisplayedScrollingRowIndex = i;
                            }
                            catch { }
                            raschetdirok();
                            sum();
                            break;
                        }
                        c++;
                    }
                    sr.Close();
                }
            }
            catch { }
            c = 0;
            str33 = null;
        }

        /// <summary>
        /// Кнопка дополнительный товар добавить
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button31_Click(object sender, EventArgs e)
        {
            if (textBox5.Text != "")
            {
                try
                {
                    int i = dataGridView3.Rows.Count;
                    // MessageBox.Show(dataGridView1.Rows.Count.ToString());
                    dataGridView3.Rows.Add();
                    dataGridView3.Rows[i].Cells[0].Value = textBox5.Text.Replace("|", "/");
                    dataGridView3.Rows[i].Cells[1].Value = numericUpDown6.Value;
                    dataGridView3.Rows[i].Cells[2].Value = numericUpDown7.Value;
                    //  try { dataGridView1.Rows[i - 1].Selected = false; }
                    //catch { }

                    dataGridView3.Rows[i].Selected = true;
                    dataGridView3.FirstDisplayedScrollingRowIndex = i;
                    sum();
                }
                catch { }
            }
            else { MessageBox.Show("Не введено название!"); }
        }

        /// <summary>
        /// Кнопка удалить выбранный товар
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button27_Click(object sender, EventArgs e)
        {
            if (dataGridView3.CurrentRow == null) return;
            dataGridView3.Rows.RemoveAt(dataGridView3.CurrentRow.Index);
            raschetdirok();
            sum();
        }

        /// <summary>
        /// Кнопка редактировать товар или услугу
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button28_Click(object sender, EventArgs e)
        {
            try
            {
                int i = dataGridView3.CurrentRow.Index;
                textBox5.Text = dataGridView3.Rows[i].Cells[0].Value.ToString();
                if (dataGridView3.Rows[i].Cells[1].Value.ToString().IndexOf(" м.кв.") != -1)
                {
                    label63.Text = " м.кв.";
                }
                else
                {
                    if (dataGridView3.Rows[i].Cells[1].Value.ToString().IndexOf(" м.п.") != -1)
                    {
                        label63.Text = " м.п.";
                    }
                    else
                    {
                        label63.Text = "Кол-во";
                    }
                }
                numericUpDown6.Value = Convert.ToDecimal(dataGridView3.Rows[i].Cells[1].Value.ToString().Replace(" м.кв.", "").Replace(" м.п.", ""));
                numericUpDown7.Value = Convert.ToDecimal(dataGridView3.Rows[i].Cells[2].Value);

                //блокировка всего
                panel1.Enabled = false;
                panel13.Enabled = false;
                panel4.Enabled = false;
                panel9.Enabled = false;
                panel7.Enabled = false;
                panel8.Enabled = false;
                dataGridView1.Enabled = false;
                button12.Enabled = false;
                button13.Enabled = false;
                button14.Enabled = false;
                dataGridView2.Enabled = false;
                button16.Enabled = false;
                button36.Enabled = false;
                button17.Enabled = false;
                button18.Enabled = false;
                button27.Enabled = false;
                button34.Enabled = false;

                button23.Visible = true;
                button20.Visible = true;

            }
            catch { }
        }

        /// <summary>
        /// Отмена редактирования т или у
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button23_Click(object sender, EventArgs e)
        {
            textBox5.Text = "";
            label63.Text = "Кол-во";
            numericUpDown6.Value = 1;
            numericUpDown7.Value = 100;

            panel1.Enabled = true;
            panel13.Enabled = true;
            panel4.Enabled = true;
            panel9.Enabled = true;
            panel7.Enabled = true;
            panel8.Enabled = true;
            dataGridView1.Enabled = true;
            button12.Enabled = true;
            button13.Enabled = true;
            button14.Enabled = true;
            if (dataGridView1.Rows.Count != 0)
            {
                dataGridView2.Enabled = true;
                button16.Enabled = true;
                button36.Enabled = true;
                button17.Enabled = true;
                button18.Enabled = true;
            }
            button27.Enabled = true;

            button23.Visible = false;
            button20.Visible = false;
        }

        /// <summary>
        /// Кнопка изменить в редактировании т или у
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button20_Click(object sender, EventArgs e)
        {
            try
            {
                int ii = dataGridView3.CurrentRow.Index;
                dataGridView3.Rows[ii].Cells[0].Value = textBox5.Text.Replace("|", "/").Replace("!", "/").Replace("~", "/").Replace("\r", "").Replace("\n", " ");
                if (label63.Text != "Кол-во")
                {
                    dataGridView3.Rows[ii].Cells[1].Value = numericUpDown6.Value + label63.Text;
                }
                else
                {
                    dataGridView3.Rows[ii].Cells[1].Value = numericUpDown6.Value;
                }
                dataGridView3.Rows[ii].Cells[2].Value = numericUpDown7.Value;

                button23_Click(null, null);
                raschetdirok();
                sum();
            }
            catch { }
        }

        #endregion

        /// <summary>
        /// Изменение цены другого товара
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox6_TextChanged(object sender, EventArgs e)
        {
            sum();
        }

        /// <summary>
        /// Изменение названия другого товара
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox4_TextChanged(object sender, EventArgs e)
        {
            tovar_obn();
        }

        /// <summary>
        /// Новая панель - скинали
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button12_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form8")
                {
                    MessageBox.Show("Меню новой панели уже открыто!");
                    return;
                }
            }
            Form8 f1 = new Form8();
            f1.Owner = this;
            f1.Show();
        }

        /// <summary>
        /// Удаление панели - скинали
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button14_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null) return;
            dataGridView1.Rows.RemoveAt(dataGridView1.CurrentRow.Index);
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                dataGridView1.Rows[i].Cells[0].Value = i + 1;
            }
            sum();
        }

        /// <summary>
        /// Редактировать панель - скинали
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button13_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null) return;
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form8")
                {
                    MessageBox.Show("Меню панели уже открыто!");
                    return;
                }
            }
            Form8 f1 = new Form8();
            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();
            dataGridView1.Enabled = false;
            button12.Enabled = false;
            button13.Enabled = false;
            button14.Enabled = false;
        }

        /// <summary>
        /// Удаление отверстия
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button16_Click(object sender, EventArgs e)
        {
            if (dataGridView2.CurrentRow == null) return;
            dataGridView2.Rows.RemoveAt(dataGridView2.CurrentRow.Index);
            string s = "";
            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {
                for (int j = 0; j < 6; j++)
                    s += dataGridView2.Rows[i].Cells[j].Value + "@";
                s += "`";
            }
            dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[10].Value = s;
            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {
                dataGridView2.Rows[i].Cells[0].Value = i + 1;
            }
            sum();
        }

        /// <summary>
        /// Выделение панели
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void dataGridView1_CurrentCellChanged(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null)
            {
                dataGridView2.Enabled = false;
                button16.Enabled = false;
                button36.Enabled = false;
                button17.Enabled = false;
                button18.Enabled = false;
            }
            else
            {
                dataGridView2.Rows.Clear();
                dataGridView2.Enabled = true;
                button16.Enabled = true;
                button36.Enabled = true;
                button17.Enabled = true;
                button18.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];
                        }

                    }
                }
                listBox2_SelectedIndexChanged(null, null);
                listBox3_SelectedIndexChanged(null, null);
            }
        }

        /// <summary>
        /// Новое отверстие - скинали
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button18_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null) return;
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form9")
                {
                    MessageBox.Show("Меню новых отверстий уже открыто!");
                    return;
                }
            }
            Form9 f1 = new Form9();
            f1.Owner = this;
            f1.Show();
            dataGridView1.Enabled = false;
            button12.Enabled = false;
            button13.Enabled = false;
            button14.Enabled = false;
        }

        /// <summary>
        /// Расчитывает стоимость выреза
        /// </summary>
        public void raschetdirok()
        {
            try
            {
                string file = "";
                if (dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[7].Value.ToString() == "Да")
                    file = putin + "\\data\\skinali\\dirkazak.akv";
                else
                    file = putin + "\\data\\skinali\\dirka.akv";

                for (int h = 0; h < dataGridView2.Rows.Count; h++)
                {
                    dataGridView2.Rows[h].Cells[4].Value = "";
                }


                string str33 = "";
                int c = 0;
                try
                {
                    using (StreamReader sr = new StreamReader(file))
                    {
                        while ((str33 = sr.ReadLine()) != null)
                        {
                            if (str33 != "" && str33 != null)
                            {
                                c++;
                                string[] tmp = str33.Replace("\r", "").Split('|');
                                if (tmp[0] == dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[4].Value.ToString().Replace(" мм", ""))
                                {
                                    string[] nt = tmp[1].Split('~');
                                    foreach (string pt in nt)
                                    {
                                        if (pt == "" || pt == null) continue;
                                        string[] hd = pt.Split('-');
                                        for (int h = 0; h < dataGridView2.Rows.Count; h++)
                                        {
                                            if (Convert.ToDouble(hd[0]) < Convert.ToDouble(dataGridView2.Rows[h].Cells[2].Value.ToString()) && Convert.ToDouble(dataGridView2.Rows[h].Cells[2].Value.ToString()) <= Convert.ToDouble(hd[1]))
                                            {
                                                dataGridView2.Rows[h].Cells[4].Value = hd[2];
                                            }
                                        }
                                    }

                                    break;
                                }
                            }


                        }
                    }
                }
                catch { }
                string s = "";
                for (int i = 0; i < dataGridView2.Rows.Count; i++)
                {
                    if (dataGridView2.Rows[i].Cells[4].Value.ToString() != "")
                        dataGridView2.Rows[i].Cells[5].Value = Convert.ToDouble(dataGridView2.Rows[i].Cells[4].Value.ToString()) * Convert.ToDouble(dataGridView2.Rows[i].Cells[3].Value.ToString());
                    for (int j = 0; j < 6; j++)
                        s += dataGridView2.Rows[i].Cells[j].Value + "@";
                    s += "`";
                }
                dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[10].Value = s;

                for (int h = 0; h < dataGridView2.Rows.Count; h++)
                {
                    if (dataGridView2.Rows[h].Cells[4].Value.ToString() == "")
                        MessageBox.Show("Не удалось сформировать цену для " + dataGridView2.Rows[h].Cells[1].Value.ToString() + " - " + dataGridView2.Rows[h].Cells[2].Value + "\r\nВ прайс листе нет необходимого условия!");
                }
            }
            catch { }
        }

        /// <summary>
        /// Редактирование отверстия - скинали
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button17_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null || dataGridView2.RowCount == 0) return;

            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form9")
                {
                    MessageBox.Show("Меню отверстий уже открыто!");
                    return;
                }
            }
            Form9 f1 = new Form9();
            f1.Owner = this;
            f1.edit = dataGridView2.Rows[dataGridView2.CurrentRow.Index].Cells[0].Value + "|" + dataGridView2.Rows[dataGridView2.CurrentRow.Index].Cells[1].Value + "|" + dataGridView2.Rows[dataGridView2.CurrentRow.Index].Cells[2].Value + "|" + dataGridView2.Rows[dataGridView2.CurrentRow.Index].Cells[3].Value;
            f1.Show();
            dataGridView1.Enabled = false;
            button12.Enabled = false;
            button13.Enabled = false;
            button14.Enabled = false;
            dataGridView2.Enabled = false;
            button16.Enabled = false;
            button36.Enabled = false;
            button17.Enabled = false;
            button18.Enabled = false;
        }

        /// <summary>
        /// изменение срочности заказа
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            obnsp();
        }

        /// <summary>
        /// Нажатие клавиш на форме
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Insert)
            {
                if (label37.Text == "Скинали")
                    button12_Click(null, null);
            }
            else if (e.KeyCode == Keys.Oemplus)
            {
                if (label37.Text == "Скинали")
                    button18_Click(null, null);
            }
            else if (e.KeyValue == 107)
            {
                button29_Click(null, null);
            }
        }

        /// <summary>
        /// Кнопка настройка сканера
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button25_Click(object sender, EventArgs e)
        {
            if (button25.Text == "Отменить")
            {
                button25.Text = "Настройка сканера";
                nastroyka = false;
            }
            else
            {
                nastroyka = true;
                button25.Text = "Отменить";
                System.Threading.Tasks.Task.Factory.StartNew(() => MessageBox.Show("Отсканируйте любой штрихкод"));
            }
        }

        /// <summary>
        /// Изменения поля карта
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox8_TextChanged(object sender, EventArgs e)
        {
            if (textBox8.Text.Length == 13)
            {
                textBox8.ForeColor = Color.Red;
                label49.Text = "Минимальная скидка: " + textBox8.Text.Substring(0, 1) + "%";
                numericUpDown3.Minimum = Convert.ToDecimal(textBox8.Text.Substring(0, 1));
                if (klient == null)
                {
                    string str33 = "";
                    using (StreamReader sr = new StreamReader(new FileStream(putin + "\\karta-users.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                    {
                        while ((str33 = sr.ReadLine()) != null)
                        {
                            if (str33.IndexOf(textBox8.Text + "=") != -1)
                            {
                                string nomer = str33.Replace(textBox8.Text + "=", "");
                                Form6 f1 = new Form6();
                                f1.Owner = this;
                                f1.Show();
                                f1.load(nomer);
                                break;
                            }
                        }
                    }
                }
            }
            else
            {
                textBox8.ForeColor = Color.Black;
                label49.Text = "Минимальная скидка: 0%";
                numericUpDown3.Minimum = 0;
            }
        }

        /// <summary>
        /// Кнопка завершить заказ
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button15_Click(object sender, EventArgs e)
        {
            button15.Enabled = false;
            if (!cleaners)
            {
                if (textBox7.Text == "")
                {
                    MessageBox.Show("Не введено поле ОПЛАЧЕНО");
                    button15.Enabled = true;
                    return;
                }
                if (dateTimePicker1.Value.ToString().Substring(0, dateTimePicker1.Value.ToString().IndexOf(" ")).ToString() == DateTime.Now.AddDays(-1).ToString().Substring(0, dateTimePicker1.Value.ToString().IndexOf(" ")).ToString())
                {
                    MessageBox.Show("Не указана дата готовности");
                    button15.Enabled = true;
                    return;
                }
                //заполнение связи карта - пользователь
                if (textBox8.Text.Length == 13)
                {
                    if (klient != null && klient != null && klient.Cells[4].Value.ToString() != "")
                    {
                        string zapis = textBox8.Text + "=" + klient.Cells[4].Value.ToString();
                        string bd = "";
                        if (File.Exists(putin + "\\karta-users.akv"))
                        {
                            StreamReader Sr = new StreamReader(new FileStream(putin + "\\karta-users.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                            bd = Sr.ReadToEnd();
                            Sr.Close();
                            Sr = null;
                        }
                        if (bd.IndexOf(zapis) == -1)
                        {
                            bd = zapis + "\r\n" + bd;
                            File.WriteAllText(putin + "\\karta-users.akv", bd, Encoding.UTF8);
                        }
                    }
                }
                //переменные общего ввода баланса
                double ssum = Convert.ToDouble(label10.Text.Replace("руб.", "").Replace(" ", ""));
                double vvd = Convert.ToDouble(textBox7.Text);
                if (Convert.ToDouble(textBox7.Text) > ssum)
                    vvd = ssum;
                double ost = vvd;
                if (vvd >= ssum)
                {
                    ost = Double.MaxValue;
                }
                string nomgroup = "";
                for (int i = 0; i < listBox5.Items.Count; i++)
                {
                    nomgroup += "<" + (Convert.ToInt32(label22.Text.Replace(perfics, "")) + i) + perfics + ">";
                }


                //цикл по каждому заказу
                for (int i = 0; i < listBox5.Items.Count; i++)
                {
                    double prdostavka = 0;
                    double prpodem = 0;

                    listBox5.SelectedIndex = i;
                    //формирование номера
                    tmpnom = (Convert.ToInt32(label22.Text.Replace(perfics, "")) + i) + perfics;
                    //проверка существование в бд такого номера
                    if (Directory.Exists(putin + "\\baza\\" + tmpnom))
                    {
                        //папка существует
                        Directory.Move(putin + "\\baza\\" + tmpnom, putin + "\\baza\\" + tmpnom + "_old_" + DateTime.Now.ToString().Replace(":", "."));
                    }
                    //создаем папку
                    Directory.CreateDirectory(putin + "\\baza\\" + tmpnom);
                    //пишем текущий массив товаров
                    File.WriteAllText(putin + "\\baza\\" + tmpnom + "\\tovar.akv", tovar[i], Encoding.UTF8);
                    //пишем данные клиента
                    if (klient != null && klient.Cells != null)
                    {
                        string klients = "";
                        for (int ii = 0; ii < klient.Cells.Count; ii++)
                        {
                            klients += klient.Cells[ii].Value.ToString() + "|";

                        }
                        File.WriteAllText(putin + "\\baza\\" + tmpnom + "\\klient.akv", klients, Encoding.UTF8);
                    }
                    //пишем общие данные заказа
                    //дата|номер|срочный 1 - да | ндс | общая скидка |цена доставки|адрес доставки | подъем на этаж | кол-во единиц | цена | вид оплаты | 
                    string fg = label9.Text + "|№" + tmpnom + "|" + ((checkBox1.Checked) ? "1" : "0") + "|" + numericUpDown1.Value + "|";
                    if (numericUpDown3.Visible)
                    {
                        fg += numericUpDown3.Value;
                    }
                    else
                    {
                        fg += "raspred" + textBox12.Text;
                    }
                    fg += "|" + textBox1.Text + "|" + textBox2.Text.Replace("|", "/") + "|" + textBox3.Text + "|" + textBox11.Text + "|" + textBox10.Text + "|";
                    if (radioButton1.Checked) fg += "1";
                    else if (radioButton2.Checked) fg += "2";
                    else if (radioButton3.Checked) fg += "3";
                    else if (radioButton6.Checked) fg += "4";
                    fg += "|";
                    //сколько оплачено | остаток | объединеные заказы | общая сумма оплаты | общий оплачено |как слать смс (1 - на одну) | Дата готовности | Менеджер | Телефон
                    double ttmpprice = 0;
                    double pc = Convert.ToDouble(label19.Text.Replace(" руб.", ""));
                    if (i == 0)
                    {
                        //если 1 заказ , добавляем к цене доставку и подъем
                        if ((textBox1.Text != "" && textBox1.Text != "0") || (textBox10.Text != "" && textBox10.Text != "0"))
                        {
                            if (textBox1.Text != "" && textBox1.Text != "0")
                            {
                                double sum = Convert.ToDouble(textBox1.Text);
                                //срочность
                                if (checkBox1.Checked)
                                {
                                    int pro = (int)Math.Round(sum);
                                    pro = pro / 100 * 10;
                                    sum += pro;
                                }
                                //ндс
                                if (numericUpDown1.Value != 0)
                                {
                                    int pro = (int)Math.Round(sum);
                                    pro = pro / 100 * Convert.ToInt32(numericUpDown1.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);
                                }
                                prdostavka = sum;
                                pc += sum;
                            }
                            if (textBox10.Text != "" && textBox10.Text != "0")
                            {
                                double sum = 0;
                                if (textBox11.Text == "" || textBox11.Text == "1")
                                    sum = Convert.ToDouble(textBox10.Text) * Convert.ToDouble(textBox3.Text);
                                else
                                    sum = Convert.ToDouble(textBox10.Text) * Convert.ToDouble(textBox3.Text) * Convert.ToDouble(textBox11.Text);

                                //срочность
                                if (checkBox1.Checked)
                                {
                                    int pro = (int)Math.Round(sum);
                                    pro = pro / 100 * 10;
                                    sum += pro;
                                }
                                //ндс
                                if (numericUpDown1.Value != 0)
                                {
                                    int pro = (int)Math.Round(sum);
                                    pro = pro / 100 * Convert.ToInt32(numericUpDown1.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);
                                }
                                prpodem = sum;
                                pc += sum;


                            }
                        }
                    }
                    if (ost >= pc)
                    {
                        ost -= pc;
                        ttmpprice = pc;
                    }
                    else
                    {
                        ttmpprice = ost;
                        ost = 0;
                    }
                    fg += ttmpprice + "|" + (pc - ttmpprice) + "|" + nomgroup + "|" + label10.Text + "|";
                    if (Convert.ToDouble(textBox7.Text) > Convert.ToDouble(label10.Text.Replace("руб.", "").Replace(" ", "")))
                    {
                        fg += Convert.ToDouble(label10.Text.Replace("руб.", "").Replace(" ", "")) + "|";
                    }
                    else
                    {
                        fg += textBox7.Text + "|";
                    }
                    fg += ((radioButton11.Checked) ? "1" : "2") + "|" + dateTimePicker1.Text + "|" + label31.Text + "|" + label32.Text + "|";
                    //цена доставки | цена подъема | номер карты клиента
                    fg += prdostavka + "|" + prpodem + "|"+ textBox8.Text;
                    File.WriteAllText(putin + "\\baza\\" + tmpnom + "\\zakaz.akv", fg, Encoding.UTF8);
                    //копируем файлы
                    if (listBox1.Items.Count != 0)
                    {
                        //создаем директорию файлов
                        Directory.CreateDirectory(putin + "\\baza\\" + tmpnom + "\\files");
                        //копируем файлы
                        for (int ii = 0; ii < listBox1.Items.Count; ii++)
                        {
                            listBox1.SelectedIndex = ii;
                            string putfile = listBox1.SelectedItem.ToString();
                            string filename = putfile.Substring(putfile.LastIndexOf("\\") + 1);
                            int copie = 0;
                            while (File.Exists(putin + "\\baza\\" + tmpnom + "\\" + filename))
                            {
                                copie++;
                                filename = "(" + copie + ")" + filename;
                            }
                            File.Copy(putfile, putin + "\\baza\\" + tmpnom + "\\files\\" + filename);
                        }
                    }
                   // MessageBox.Show("7");
                    //пишем в локальную baza.akv дата номер зак
                    string f = "";
                    if (File.Exists(Application.StartupPath + "\\baza.akv"))
                    {
                        StreamReader Sr = new StreamReader(new FileStream(Application.StartupPath + "\\baza.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                        f = Sr.ReadToEnd();
                        Sr.Close();
                        Sr = null;
                    }
                 //   MessageBox.Show("7.5");
                    f = label9.Text + "|№" + tmpnom + "|\r\n" + f;
                   // MessageBox.Show(Application.StartupPath + "\\baza.akv");
                   // MessageBox.Show(f);
                    File.WriteAllText(Application.StartupPath + "\\baza.akv", f, Encoding.UTF8);
                   // MessageBox.Show("8");
                }
            }
            //очистка и подгрузка нового номера
            button32_Click(null, null);
            load_nomer();
            //разблокировка кнопки
            button15.Enabled = true;
        }


        /// <summary>
        /// Вызывает редактор
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button26_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form10")
                {
                    MessageBox.Show("Редактор уже открыт!");
                    return;
                }
            }
            Form10 f1 = new Form10();
            f1.Owner = this;
            f1.Show();
        }

        /// <summary>
        /// Изменение этажа
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox3_TextChanged(object sender, EventArgs e)
        {
            obchechiy_schet();
        }

        /// <summary>
        /// Изменение цены доставки
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            obchechiy_schet();
        }

        /// <summary>
        /// Открыть районы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form12")
                {
                    MessageBox.Show("Районы уже открыты!");
                    return;
                }
            }
            Form12 f1 = new Form12();
            f1.Owner = this;
            f1.Show();
        }

        /// <summary>
        /// Содержит информация нужно ли печатать общий блокс информацией
        /// </summary>
        bool infoblock = false;

        /// <summary>
        /// Содержит номера заказов в объединении
        /// </summary>
        string infoblock_nom = "";
        double tmpprice = 0;
        string tmpnom = "";


        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());
            }
        }

        /// <summary>
        /// Конопка печать
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            button4.Enabled = false;
            if (!cleaners)
            {
                if (textBox7.Text == "")
                {
                    MessageBox.Show("Не введено поле ОПЛАЧЕНО");
                    button4.Enabled = true;
                    return;
                }
                if (dateTimePicker1.Value.ToString().Substring(0, dateTimePicker1.Value.ToString().IndexOf(" ")).ToString() == DateTime.Now.AddDays(-1).ToString().Substring(0, dateTimePicker1.Value.ToString().IndexOf(" ")).ToString())
                {
                    MessageBox.Show("Не указана дата готовности");
                    button4.Enabled = true;
                    return;
                }
                double ssum = Convert.ToDouble(label10.Text.Replace("руб.", "").Replace(" ", ""));
                double vvd = Convert.ToDouble(textBox7.Text);
                // string[] price = new string[kartina.Length];

                double ost = vvd;
                if (vvd >= ssum)
                {
                    ost = Double.MaxValue;
                }

                int f = listBox5.SelectedIndex;

                for (int i = 0; i < listBox5.Items.Count; i++)
                {
                    if (listBox5.Items.Count != 1 && i == 0)
                    {
                        infoblock = true;
                        infoblock_nom = "c " + (Convert.ToInt32(label22.Text.Replace(perfics, "")) + i) + perfics + " по " + (Convert.ToInt32(label22.Text.Replace(perfics, "")) + (listBox5.Items.Count - 1)) + perfics;
                    }
                    else
                        infoblock = false;

                    tmpnom = (Convert.ToInt32(label22.Text.Replace(perfics, "")) + i) + perfics;
                    listBox5.SelectedIndex = i;
                    sum();
                    double pc = Convert.ToDouble(label19.Text.Replace(" руб.", ""));
                    if (ost >= pc)
                    {
                        ost -= pc;
                        tmpprice = pc;
                    }
                    else
                    {
                        tmpprice = ost;
                        ost = 0;
                    }
                    if (checkBox3.Checked)
                    {

                        printPreviewDialog1.Document = printDocument1;
                        //printDocument2.PrinterSettings.PrintToFile = ;
                        ((Form)printPreviewDialog1).WindowState = FormWindowState.Maximized;
                        ((Form)printPreviewDialog1).Icon = this.Icon;
                        printPreviewDialog1.ShowDialog();
                    }
                    if (checkBox4.Checked)
                    {
                        printPreviewDialog2.Document = printDocument2;
                        printDocument2.PrinterSettings.PrintToFile = false;
                        ((Form)printPreviewDialog2).WindowState = FormWindowState.Maximized;
                        ((Form)printPreviewDialog2).Icon = this.Icon;
                        printPreviewDialog2.ShowDialog();
                        //  printDocument1.Print();
                    }

                }
                if ((textBox1.Text != "" && textBox1.Text != "0") || (textBox10.Text != "" && textBox10.Text != "0"))
                {
                    if (textBox1.Text != "" && textBox1.Text != "0")
                    {
                        double sum = Convert.ToDouble(textBox1.Text);
                        //срочность
                        if (checkBox1.Checked)
                        {
                            int pro = (int)Math.Round(sum);
                            pro = pro / 100 * 10;
                            sum += pro;
                        }
                        //ндс
                        if (numericUpDown1.Value != 0)
                        {
                            int pro = (int)Math.Round(sum);
                            pro = pro / 100 * Convert.ToInt32(numericUpDown1.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;

                        if (ost >= pc)
                        {
                            ost -= pc;
                            tmpprice = pc;
                        }
                        else
                        {
                            tmpprice = ost;
                            ost = 0;
                        }
                    }
                    if (textBox10.Text != "" && textBox10.Text != "0")
                    {
                        double sum = 0;
                        if (textBox11.Text == "" || textBox11.Text == "1")
                            sum = Convert.ToDouble(textBox10.Text) * Convert.ToDouble(textBox3.Text);
                        else
                            sum = Convert.ToDouble(textBox10.Text) * Convert.ToDouble(textBox3.Text) * Convert.ToDouble(textBox11.Text);

                        //срочность
                        if (checkBox1.Checked)
                        {
                            int pro = (int)Math.Round(sum);
                            pro = pro / 100 * 10;
                            sum += pro;
                        }
                        //ндс
                        if (numericUpDown1.Value != 0)
                        {
                            int pro = (int)Math.Round(sum);
                            pro = pro / 100 * Convert.ToInt32(numericUpDown1.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;

                        if (ost >= pc)
                        {
                            ost -= pc;
                            tmpdublprice = pc;
                        }
                        else
                        {
                            tmpdublprice = ost;
                            ost = 0;
                        }
                    }


                    printPreviewDialog3.Document = printDocument3;
                    printDocument3.PrinterSettings.PrintToFile = false;
                    ((Form)printPreviewDialog3).WindowState = FormWindowState.Maximized;
                    ((Form)printPreviewDialog3).Icon = this.Icon;
                    printPreviewDialog3.ShowDialog();
                }
                listBox5.SelectedIndex = f;
            }
            button4.Enabled = true;

        }

        /// <summary>
        /// Изменение цены подъема
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox10_TextChanged(object sender, EventArgs e)
        {
            obchechiy_schet();
        }

        /// <summary>
        /// Открыть подъемы
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button33_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form15")
                {
                    MessageBox.Show("Подъемы уже открыты!");
                    return;
                }
            }
            Form15 f1 = new Form15();
            f1.Owner = this;
            f1.Show();
        }

        /// <summary>
        /// Копировать панель
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button34_Click(object sender, EventArgs e)
        {
            if (dataGridView1.CurrentRow == null) return;
            int i = dataGridView1.Rows.Count;
            dataGridView1.Rows.Add();
            for (int j = 0; j < dataGridView1.CurrentRow.Cells.Count; j++)
            {
                dataGridView1.Rows[i].Cells[j].Value = dataGridView1.CurrentRow.Cells[j].Value;
            }
            for (int ii = 0; ii < dataGridView1.Rows.Count; ii++)
            {
                dataGridView1.Rows[ii].Cells[0].Value = ii + 1;
            }
            sum();
        }

        //#новый
        /// <summary>
        /// Ресайз формы - красивое оформление
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Resize(object sender, EventArgs e)
        {
            if (!this.Visible) return;
            int baz = dataGridView1.Width;
            baz -= 30;
            int wid = (int)baz / 4;
            button55.Width = button54.Width = button53.Width = button42.Width =
                button16.Width = button17.Width = button18.Width = button36.Width = button12.Width = button13.Width = button14.Width = button34.Width = wid;

            button13.Location = new Point(button12.Width + 10 + button12.Location.X, button13.Location.Y);
            button54.Location = new Point(button55.Width + 10 + button12.Location.X, button54.Location.Y);

            button17.Location = new Point(button13.Location.X, button17.Location.Y);

            button34.Location = new Point(button13.Width + 10 + button13.Location.X, button34.Location.Y);
            button36.Location = new Point(button34.Location.X, button36.Location.Y);
            button42.Location = new Point(button54.Width + 10 + button54.Location.X, button42.Location.Y);

            button14.Location = new Point(button34.Width + 10 + button34.Location.X, button14.Location.Y);
            button16.Location = new Point(button14.Location.X, button16.Location.Y);
            button53.Location = new Point(button42.Width + 10 + button42.Location.X, button53.Location.Y);

            baz += 20;
            wid = (int)baz / 2;
            panel17.Width = panel16.Width = listBox3.Width = listBox2.Width = wid;
            panel23.Width = panel24.Width = listBox4.Width = listBox6.Width = wid;


            listBox2.Location = new Point(listBox3.Width + 10 + listBox3.Location.X, listBox2.Location.Y);
            listBox6.Location = new Point(listBox4.Width + 10 + listBox4.Location.X, listBox6.Location.Y);

            panel16.Location = new Point(listBox3.Width + 10 + listBox3.Location.X, panel16.Location.Y);
            panel24.Location = new Point(listBox4.Width + 10 + listBox4.Location.X, panel24.Location.Y);

            button19.Width = button21.Width = listBox3.Width - button21.Location.X + 12;
            button49.Width = button48.Width = listBox4.Width - button48.Location.X + 12;

            button19.Location = new Point(listBox2.Width + listBox2.Location.X - button19.Width, button19.Location.Y);
            button49.Location = new Point(listBox6.Width + listBox6.Location.X - button49.Width, button49.Location.Y);

            numericUpDown4.Location = new Point(button19.Location.X - 58, numericUpDown4.Location.Y);
            numericUpDown11.Location = new Point(button49.Location.X - 58, numericUpDown11.Location.Y);

            label60.Location = new Point(numericUpDown4.Location.X - 47, label60.Location.Y);
            label67.Location = new Point(numericUpDown11.Location.X - 47, label67.Location.Y);
        }

        /// <summary>
        /// Копировать отверстие
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button36_Click(object sender, EventArgs e)
        {
            if (dataGridView2.CurrentRow == null) return;

            int ii = dataGridView2.Rows.Count;
            dataGridView2.Rows.Add();
            for (int j = 0; j < dataGridView2.CurrentRow.Cells.Count; j++)
            {
                dataGridView2.Rows[ii].Cells[j].Value = dataGridView2.CurrentRow.Cells[j].Value;
            }

            string s = "";
            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {
                for (int j = 0; j < 6; j++)
                    s += dataGridView2.Rows[i].Cells[j].Value + "@";
                s += "`";
            }
            dataGridView1.Rows[dataGridView1.CurrentRow.Index].Cells[10].Value = s;
            for (int i = 0; i < dataGridView2.Rows.Count; i++)
            {
                dataGridView2.Rows[i].Cells[0].Value = i + 1;
            }
            sum();
        }




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

        //#новый
        /// <summary>
        /// Печать квитанции мастерской
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Image myimg = null;
            try
            {
                myimg = Code128Rendering.MakeBarcodeImage(tmpnom, 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 (checkBox3.Checked)
            {
                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 += "СРОЧНЫЙ заказ №" + tmpnom + "\r\nот " + DateTime.Now.ToString();
                    else
                        textToPrint += "Заказ №" + tmpnom + "\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);

                    double pc = Convert.ToDouble(label19.Text.Replace(" руб.", ""));
                    textToPrint = "Менеджер: " + label31.Text + "\r\nСумма заказа: " + ((int)pc).ToString() + " руб.       Оплачено: " + ((int)tmpprice).ToString() + " руб.";
                    if (tmpprice != 0)
                    {
                        if (radioButton1.Checked) textToPrint += " (нал.)";
                        else if (radioButton2.Checked) textToPrint += " (терм.)";
                        else if (radioButton3.Checked) textToPrint += " (карта)";
                        else if (radioButton6.Checked) textToPrint += " (безнал.)";
                    }
                    textToPrint += "       Остаток:" + ((int)pc - tmpprice).ToString() + " руб.";

                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b + 40);
                    if (klient != null && klient.Cells[4].Value.ToString() != "")
                    {
                        textToPrint = klient.Cells[4].Value.ToString();
                        g.DrawString(textToPrint, printFont, Brushes.Black, 420, b);
                    }
                    // b += 36;
                    b += 52;
                    if (klient != null && klient.Cells[0].Value.ToString() != "" && klient != null && klient.Cells[1].Value.ToString() != "" && klient != null && klient.Cells[2].Value.ToString() != "")
                    {
                        textToPrint = klient.Cells[0].Value.ToString().Substring(0, 1) + klient.Cells[0].Value.ToString().ToLower().Substring(1) + " " + klient.Cells[1].Value.ToString().Substring(0, 1) + klient.Cells[1].Value.ToString().ToLower().Substring(1) + " " + klient.Cells[2].Value.ToString().Substring(0, 1) + klient.Cells[2].Value.ToString().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;
                        
                        //prikin += (int)stringSize.Height;

                       
                        //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(tmpnom + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                                    numberlist++;
                                    e.HasMorePages = true;
                                    pageprint = i;
                                    komandpring = "skin";
                                    return;
                                }
                                //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;


                                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(tmpnom + " лист № " + 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(tmpnom + " лист № " + 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 (listBox1.Items.Count != 0)
                {
                    prik += 16;
                }
                if (textBox1.Text != "" && textBox1.Text != "0")
                {
                    prik += 16;
                }
                if (textBox10.Text != "" && textBox10.Text != "0")
                {
                    prik += 16;
                }
                /*if (richTextBox2.Text != "")
                {
                    prik += 16;
                }*/

                if (b + prik > e.MarginBounds.Bottom)
                {
                    g.DrawString(tmpnom + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                    numberlist++;
                    pageprint = 0;
                    e.HasMorePages = true;
                    return;
                }
                //общий футер
                a = 30;
                if (listBox1.Items.Count != 0)
                {
                    textToPrint = "К заказу прикреплено " + listBox1.Items.Count + " файлов. Для просмотра используйте ПК";
                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    b += 16;
                }
                if (textBox1.Text != "" && textBox1.Text != "0")
                {
                    textToPrint = "Доставка по адресу: " + textBox2.Text;
                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    b += 16;
                }
                if (textBox10.Text != "" && textBox10.Text != "0")
                {
                    textToPrint = "Подъем на: " + textBox3.Text + " этаж " + textBox11.Text + " единиц";
                    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    b += 16;
                }
                /* 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(tmpnom + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                }
                pageprint = 0;
                komandpring = "";
                numberlist = 1;
            }
            //if (flaginfile)
            //{
            //    Bitmap myBitmap = new Bitmap(800, b, g);
            //    myBitmap.Save("1.png");
            //}
            g.Dispose();
        }

        //#новый
        /// <summary>
        /// Печать квитанции клиента
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void printDocument2_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            Image myimg = null;
            try
            {
                if (tmpnom != "-")
                    myimg = Code128Rendering.MakeBarcodeImage(tmpnom, 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;
                if (checkBox4.Checked)
                {
                    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 += "СРОЧНЫЙ заказ №" + tmpnom + "\r\nот " + DateTime.Now.ToString();
                        else
                            textToPrint += "Заказ №" + tmpnom + "\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 = "Менеджер: " + label31.Text + " " + label32.Text;
                        g.DrawString(textToPrint, printFont, Brushes.Black, a, b + 40);
                        if (klient != null && klient.Cells[4].Value.ToString() != "")
                        {
                            textToPrint = klient.Cells[4].Value.ToString();
                            g.DrawString(textToPrint, printFont, Brushes.Black, 420, b);
                        }
                        b += 36;
                        if (klient != null && klient.Cells[0].Value.ToString() != "" && klient != null && klient.Cells[1].Value.ToString() != "" && klient != null && klient.Cells[2].Value.ToString() != "")
                        {
                            textToPrint = klient.Cells[0].Value.ToString().Substring(0, 1) + klient.Cells[0].Value.ToString().ToLower().Substring(1) + " " + klient.Cells[1].Value.ToString().Substring(0, 1) + klient.Cells[1].Value.ToString().ToLower().Substring(1) + " " + klient.Cells[2].Value.ToString().Substring(0, 1) + klient.Cells[2].Value.ToString().ToLower().Substring(1);
                            g.DrawString(textToPrint, printFont, Brushes.Black, 420, b - 18);
                        }
                        //b += 30;
                        b += 20;
                        //примечание
                        if (richTextBox2.Text != "")
                        {
                            /*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;*/
                            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;
                        }
                        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(tmpnom + " лист № " + 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;
                                    }
                                }
                                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(tmpnom + " лист № " + 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(tmpnom + " лист № " + 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 (listBox1.Items.Count != 0)
                    {
                        prik += 16;
                    }
                    //if (textBox1.Text != "" && textBox1.Text != "0")
                    //{
                    //    prik += 16;
                    //}
                    //if (textBox10.Text != "" && textBox10.Text != "0")
                    //{
                    //    prik += 16;
                    //}
                    /*if (richTextBox2.Text != "")
                    {
                        prik += 16;
                    }*/

                    if (b + prik > e.MarginBounds.Bottom)
                    {
                        g.DrawString(tmpnom + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                        numberlist++;
                        pageprint = 0;
                        e.HasMorePages = true;
                        return;
                    }
                    //общий футер
                    a = 30;
                    if (listBox1.Items.Count != 0)
                    {
                        textToPrint = "К заказу прикреплено " + listBox1.Items.Count + " файлов. Для просмотра используйте ПК";
                        g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                        b += 16;
                    }
                    //if (textBox1.Text != "" && textBox1.Text != "0")
                    //{
                    //    textToPrint = "Доставка по адресу: " + textBox2.Text;
                    //    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    //    b += 16;
                    //}
                    //if (textBox10.Text != "" && textBox10.Text != "0")
                    //{
                    //    textToPrint = "Подъем на: " + textBox3.Text + " этаж " + textBox11.Text + " единиц";
                    //    g.DrawString(textToPrint, printFont, Brushes.Black, a, b);
                    //    b += 16;
                    //}
                    /*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);
                    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 (textBox12.Visible)
                        if (textBox12.Text != "0" && textBox12.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 = "Оплачено:                  " + ((int)tmpprice).ToString() + " руб.";
                    if (tmpprice != 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("Остаток:                      " + ((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 (numberlist != 1)
                    {
                        g.DrawString(tmpnom + " лист № " + numberlist, printFont, Brushes.Black, 330, b + 15);
                    }
                }
                pageprint = 0;
                komandpring = "";
                numberlist = 1;
                g.Dispose();
            }
            catch (Exception g)
            {
                MessageBox.Show(g.Message);
            }
        }

        /// <summary>
        /// Кнопка служебный заказ
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button38_Click(object sender, EventArgs e)
        {
            Array.Resize(ref tovar, tovar.Length + 1);
            //название | цена общая | кол-во | комментарий мастеров | файлы | монтаж | цена за шт | резерв 1| резерв 2| резерв 3 | резерв 4 | резерв 5 |

            //+  Таблица панели|Таблица товары и услуги|
            tovar[tovar.Length - 1] = "Скинали|1842|1|тестовый заказ||1842|1842||||||1!600!600!Планибель Бронза!4!Притупление-Периметр-;!Прямоугольная!Нет!Фотопечать;!887!1@Внешний@100@1@200@200@`!~|Рейлинг - Рейлинг  до 600мм!1!555!555!~Монтажи - Установка одинарной розетки !1!200!200!~|";

            pererisovka_korzina();
            listBox5.SelectedIndex = tovar.Length - 1;
            sum();
            dateTimePicker1.Text = "2.01.2017";
            textBox7.Text = "700";
        }

        /// <summary>
        /// Сохранение в pdf файл
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button39_Click(object sender, EventArgs e)
        {
            if (!File.Exists(Application.StartupPath + "\\printpdf.akv"))
            {
                //файла не существует
                foreach (Form f in Application.OpenForms)
                {
                    if (f.Name == "Form16")
                    {
                        MessageBox.Show("Редактор pdf принтера уже открыт!");
                        return;
                    }
                }
                Form16 f1 = new Form16();
                f1.Owner = this;
                f1.Show();
                f1.Focus();
            }
            else
            {
                //открываем файл
                try
                {
                    StreamReader sr = new StreamReader(Application.StartupPath + "\\printpdf.akv");
                    string k = sr.ReadToEnd();
                    sr.Close();
                    string nameprint = printDocument2.PrinterSettings.PrinterName;
                    printDocument2.PrinterSettings.PrinterName = k;
                    tmpprice = 0;
                    tmpnom = "-";
                    for (int i = 0; i < listBox5.Items.Count; i++)
                    {
                        listBox5.SelectedIndex = i;
                        // printPreviewDialog2.ShowDialog();
                        printDocument2.Print();
                    }
                    printDocument2.PrinterSettings.PrinterName = nameprint;
                }
                catch (Exception f) { MessageBox.Show(f.Message); MessageBox.Show("Печать на pdf принтер не удалась!\r\nВозможно данного принтера не существует!\r\nДля вызова первоначальной настройки необходимо удалить файл printpdf.akv из директории программы!"); }
            }
        }

        /// <summary>
        /// Открытие базы заказов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form17")
                {
                    MessageBox.Show("База заказов уже открыта!");
                    return;
                }
            }
            Form17 f1 = new Form17();
            f1.Owner = this;
            f1.Show();
            f1.Focus();
        }

        /// <summary>
        /// Проверка версии программы каждые 10 мин
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer2_Tick(object sender, EventArgs e)
        {
            load_versia(true);
            proverka_baz(true);
        }

        /// <summary>
        /// скрывает уведомление в трей
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer3_Tick(object sender, EventArgs e)
        {
            timer3.Stop();
            notifyIcon1.Visible = false;
        }

        /// <summary>
        /// Кнопка о программе
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button37_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form20")
                {
                    MessageBox.Show("О программе уже открыто!");
                    return;
                }
            }
            Form20 f1 = new Form20();
            f1.Owner = this;
            f1.Show();
            f1.Focus();
        }

        /// <summary>
        /// Выдача заказов
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            if (textBox9.Text == "0000")
            {
                Form23 g = new Form23();
                g.Show();
                textBox9.Text = "";
                return;
            }
            if (Directory.Exists(putin + "\\baza\\" + textBox9.Text))
            {
                if (File.Exists(putin + "\\baza\\" + textBox9.Text + "\\zakaz.akv"))
                {
                    string h = "";
                    StreamReader Sr = new StreamReader(new FileStream(putin + "\\baza\\" + textBox9.Text + "\\zakaz.akv", FileMode.Open, FileAccess.Read, FileShare.Read));
                    h = Sr.ReadToEnd();
                    Sr.Close();
                    string[] tmp = h.Split('|');

                    double ostatok = 0;

                    if (File.Exists(putin + "\\baza\\" + textBox9.Text + "\\doplata.akv"))
                    {
                        string str33 = "";
                        // double opl = Convert.ToDouble(tmp[11]);
                        double opl = 0; //вычитаем из начального остатка
                        using (StreamReader sr = new StreamReader(new FileStream(putin + "\\baza\\" + textBox9.Text + "\\doplata.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                        {
                            while ((str33 = sr.ReadLine()) != null)
                            {
                                if (str33 == "") continue;
                                opl += Convert.ToDouble(str33.Split('|')[1]);
                            }
                        }
                        // textBox10.Text = opl.ToString();
                        ostatok = Convert.ToDouble(tmp[12]) - opl;
                    }
                    else
                    {
                        //textBox10.Text = tmp[11];
                        //ostatok = Convert.ToDouble(tmp[12]) - Convert.ToDouble(tmp[11]);
                        ostatok = Convert.ToDouble(tmp[12]);
                    }
                    if (ostatok <= 0)
                    {
                        //все заплачено
                        string fg = DateTime.Now + "|" + label31.Text + "|" + label32.Text;
                        File.WriteAllText(putin + "\\baza\\" + textBox9.Text + "\\zabran.akv", fg, Encoding.UTF8);
                        new Thread(delegate () { MessageBox.Show("Заказ помечан выданным,\r\nдоплата не требуется!"); }).Start();

                        textBox9.Text = "";
                    }
                    else
                    {
                        Form19 f1 = new Form19();
                        f1.Owner = this;
                        f1.zakaz = "<" + textBox9.Text + ">";
                        f1.ostatok = ostatok.ToString();
                        f1.flag = true;
                        f1.Show();
                        f1.Focus();
                    }
                }
                else
                {
                    new Thread(delegate () { MessageBox.Show("Заказа с номером " + textBox9.Text + " поврежден!"); }).Start();

                }
            }
            else
            {
                new Thread(delegate () { MessageBox.Show("Заказа с номером " + textBox9.Text + " не существует."); }).Start();

            }
        }

        public void pub_vidan()
        {
            //все заплачено
            string fg = DateTime.Now + "|" + label31.Text + "|" + label32.Text;
            File.WriteAllText(putin + "\\baza\\" + textBox9.Text + "\\zabran.akv", fg, Encoding.UTF8);
            textBox9.Text = "";
        }

        private void textBox9_TextChanged(object sender, EventArgs e)
        {
            textBox9.Text = textBox9.Text.ToUpper();
            textBox9.SelectionStart = textBox9.Text.Length;
        }

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

        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;

            //общий хеадер
            // 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;

            if (textBox1.Text != "" && textBox1.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 (listBox5.Items.Count == 1)
                {
                    textToPrint = "Доставка заказа : " + label22.Text;
                }
                else
                {
                    textToPrint = "Доставка заказов : " + "c " + (Convert.ToInt32(label22.Text.Replace(perfics, ""))) + perfics + " по " + (Convert.ToInt32(label22.Text.Replace(perfics, "")) + (listBox5.Items.Count - 1)) + perfics;
                }

                g.DrawString(textToPrint + "\r\nПо адресу : " + textBox2.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(textBox1.Text);
                //срочность
                if (checkBox1.Checked)
                {
                    int pro = (int)Math.Round(sum);
                    pro = pro / 100 * 10;
                    sum += pro;
                }
                //ндс
                if (numericUpDown1.Value != 0)
                {
                    int pro = (int)Math.Round(sum);
                    pro = pro / 100 * Convert.ToInt32(numericUpDown1.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 (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("Остаток:                      " + ((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 (textBox10.Text != "" && textBox10.Text != "0")
                {
                    b += 25;
                    g.DrawLine(new Pen(Color.Black, 2), new Point(a, b), new Point(785, b));
                    b += 30;
                }
            }

            if (textBox10.Text != "" && textBox10.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 (listBox5.Items.Count == 1)
                {
                    textToPrint = "Подъем заказа : " + label22.Text;
                }
                else
                {
                    textToPrint = "Подъем заказов : " + "c " + (Convert.ToInt32(label22.Text.Replace(perfics, ""))) + perfics + " по " + (Convert.ToInt32(label22.Text.Replace(perfics, "")) + (listBox5.Items.Count - 1)) + perfics;
                }
                textToPrint += "\r\nПодъем на этаж : " + textBox3.Text + "\r\nКоличество единиц:" + textBox11.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 (textBox11.Text == "" || textBox11.Text == "1")
                    sum = Convert.ToDouble(textBox10.Text) * Convert.ToDouble(textBox3.Text);
                else
                    sum = Convert.ToDouble(textBox10.Text) * Convert.ToDouble(textBox3.Text) * Convert.ToDouble(textBox11.Text);

                //срочность
                if (checkBox1.Checked)
                {
                    int pro = (int)Math.Round(sum);
                    pro = pro / 100 * 10;
                    sum += pro;
                }
                //ндс
                if (numericUpDown1.Value != 0)
                {
                    int pro = (int)Math.Round(sum);
                    pro = pro / 100 * Convert.ToInt32(numericUpDown1.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 (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("Остаток:                      " + ((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 button40_Click(object sender, EventArgs e)
        {
            if (numericUpDown3.Visible)
            {
                numericUpDown3.Value = 0;
                numericUpDown3.Visible = label13.Visible = false;
                textBox12.Visible = label57.Visible = true;
            }
            else
            {
                textBox12.Text = "0";
                numericUpDown3.Visible = label13.Visible = true;
                textBox12.Visible = label57.Visible = false;
            }
        }

        private void textBox12_TextChanged(object sender, EventArgs e)
        {
            obnsp();
        }

        private void textBox12_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (Char.IsControl(e.KeyChar)) return;
            if (e.KeyChar < '0' || e.KeyChar > '9')
            {
                if (e.KeyChar != ',')
                    e.Handled = true;
            }
        }

        /// <summary>
        /// изменение типа услуги
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox2.Text == "")
                return;
            int c = 0;
            string str33 = "";
            try
            {
                using (StreamReader sr = new StreamReader(putin + "\\data\\modulkart\\uslugi.akv"))
                {
                    listBox6.BeginUpdate();
                    listBox6.Items.Clear();
                    while ((str33 = sr.ReadLine()) != null)
                    {
                        if (str33 != "" && str33 != null)
                        {
                            c++;
                            string[] tmp = str33.Replace("\r", "").Split('|');
                            if (comboBox2.Text != "Все")
                            {
                                if (tmp[2] != comboBox2.Text)
                                    continue;
                            }
                            listBox6.Items.AddRange(new object[] { c.ToString() + ". " + tmp[0] + " - " + tmp[1] + " руб." });
                        }

                    }
                    if (listBox6.Items.Count != 0)
                        listBox6.SelectedIndex = 0;
                    listBox6.EndUpdate();
                }
            }
            catch { listBox6.EndUpdate(); }
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.Text == "")
                return;
            int c = 0;
            string str33 = "";
            try
            {
                using (StreamReader sr = new StreamReader(putin + "\\data\\modulkart\\tovar.akv"))
                {
                    listBox4.BeginUpdate();
                    listBox4.Items.Clear();
                    while ((str33 = sr.ReadLine()) != null)
                    {
                        if (str33 != "" && str33 != null)
                        {
                            c++;
                            string[] tmp = str33.Replace("\r", "").Split('|');
                            if (comboBox1.Text != "Все")
                            {
                                if (tmp[2] != comboBox1.Text)
                                    continue;
                            }
                            listBox4.Items.AddRange(new object[] { c.ToString() + ". " + tmp[0] + " - " + tmp[1] + " руб." });
                        }

                    }
                    if (listBox4.Items.Count != 0)
                        listBox4.SelectedIndex = 0;
                    listBox4.EndUpdate();
                }
            }
            catch { listBox4.EndUpdate(); }
        }

        private void listBox4_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox4.SelectedIndex == -1) return;
            int c = 0;
            string a = listBox4.SelectedItem.ToString();
            a = a.Substring(0, a.IndexOf("."));
            string str33 = "";
            try
            {
                using (StreamReader sr = new StreamReader(new FileStream(putin + "\\data\\modulkart\\tovar.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    while ((str33 = sr.ReadLine()) != null)
                    {
                        if (c == Convert.ToInt32(a) - 1)
                        {
                            if (str33.Split('|')[3] == "p")
                            {
                                double p = 0.0;
                                for (int i = 0; i < dataGridView6.Rows.Count; i++)
                                {
                                    p += (Convert.ToDouble(dataGridView6.Rows[i].Cells[1].Value) + Convert.ToDouble(dataGridView6.Rows[i].Cells[2].Value)) * 2 / 1000;
                                }
                                numericUpDown10.Value = Convert.ToDecimal(p);
                                label66.Text = " м.п.";
                                break;
                            }
                            if (str33.Split('|')[3] == "s")
                            {
                                double s = 0.0;
                                for (int i = 0; i < dataGridView6.Rows.Count; i++)
                                {
                                    s += Convert.ToDouble(dataGridView6.Rows[i].Cells[1].Value) * Convert.ToDouble(dataGridView6.Rows[i].Cells[2].Value) / 1000000;
                                }
                                numericUpDown10.Value = Convert.ToDecimal(s);
                                label66.Text = " м.кв.";
                                break;
                            }
                            if (str33.Split('|')[3] == "c")
                            {
                                numericUpDown10.Value = 1;
                                label66.Text = "Кол-во";
                                break;
                            }

                        }
                        c++;
                    }
                }
            }
            catch { }
            c = 0;
            str33 = null;
        }

        private void listBox6_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listBox6.SelectedIndex == -1) return;
            int c = 0;
            string a = listBox6.SelectedItem.ToString();
            a = a.Substring(0, a.IndexOf("."));
            string str33 = "";
            try
            {
                using (StreamReader sr = new StreamReader(new FileStream(putin + "\\data\\modulkart\\uslugi.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    while ((str33 = sr.ReadLine()) != null)
                    {
                        if (c == Convert.ToInt32(a) - 1)
                        {
                            if (str33.Split('|')[3] == "p")
                            {
                                double p = 0.0;
                                for (int i = 0; i < dataGridView6.Rows.Count; i++)
                                {
                                    p += (Convert.ToDouble(dataGridView6.Rows[i].Cells[1].Value) + Convert.ToDouble(dataGridView6.Rows[i].Cells[2].Value)) * 2 / 1000;
                                }
                                numericUpDown11.Value = Convert.ToDecimal(p);
                                label67.Text = " м.п.";
                                break;
                            }
                            if (str33.Split('|')[3] == "s")
                            {
                                double s = 0.0;
                                for (int i = 0; i < dataGridView6.Rows.Count; i++)
                                {
                                    s += Convert.ToDouble(dataGridView6.Rows[i].Cells[1].Value) * Convert.ToDouble(dataGridView6.Rows[i].Cells[2].Value) / 1000000;
                                }
                                numericUpDown11.Value = Convert.ToDecimal(s);
                                label67.Text = " м.кв.";
                                break;
                            }
                            if (str33.Split('|')[3] == "c")
                            {
                                numericUpDown11.Value = 1;
                                label67.Text = "Кол-во";
                                break;
                            }
                            if (str33.Split('|')[3] == "m")
                            {
                                double s = 0.0;
                                for (int i = 0; i < dataGridView6.Rows.Count; i++)
                                {
                                    s += Convert.ToDouble(dataGridView6.Rows[i].Cells[2].Value) / 1000;
                                }
                                numericUpDown11.Value = Convert.ToDecimal(s);
                                label67.Text = " м.п.";
                                break;
                            }

                        }
                        c++;
                    }
                }
            }
            catch { }
            c = 0;
            str33 = null;
        }

        private void button48_Click(object sender, EventArgs e)
        {
            int c = 0;
            string str33 = "";
            try
            {
                string nom = listBox4.SelectedItem.ToString().Substring(0, listBox4.SelectedItem.ToString().IndexOf("."));
                using (StreamReader sr = new StreamReader(new FileStream(putin + "\\data\\modulkart\\tovar.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    while ((str33 = sr.ReadLine()) != null)
                    {
                        if ((c + 1).ToString() == nom)
                        {
                            try
                            {
                                string[] tmp = str33.Split('|');
                                int i = dataGridView4.Rows.Count;
                                // MessageBox.Show(dataGridView1.Rows.Count.ToString());
                                dataGridView4.Rows.Add();
                                dataGridView4.Rows[i].Cells[0].Value = tmp[2] + " - " + tmp[0];
                                string sd = "";
                                if (label66.Text != "Кол-во")
                                {
                                    sd = label66.Text;
                                }
                                dataGridView4.Rows[i].Cells[1].Value = numericUpDown10.Value + sd;
                                dataGridView4.Rows[i].Cells[2].Value = tmp[1];

                                dataGridView4.Rows[i].Selected = true;
                                dataGridView4.FirstDisplayedScrollingRowIndex = i;
                            }
                            catch { }
                            sum();
                            break;
                        }
                        c++;
                    }
                    sr.Close();
                }
            }
            catch { }
            c = 0;
            str33 = null;
        }

        private void button49_Click(object sender, EventArgs e)
        {
            int c = 0;
            string str33 = "";
            try
            {
                string nom = listBox6.SelectedItem.ToString().Substring(0, listBox6.SelectedItem.ToString().IndexOf("."));
                using (StreamReader sr = new StreamReader(new FileStream(putin + "\\data\\modulkart\\uslugi.akv", FileMode.Open, FileAccess.Read, FileShare.Read)))
                {
                    while ((str33 = sr.ReadLine()) != null)
                    {
                        if ((c + 1).ToString() == nom)
                        {
                            try
                            {
                                string[] tmp = str33.Split('|');
                                int i = dataGridView4.Rows.Count;
                                // MessageBox.Show(dataGridView1.Rows.Count.ToString());
                                dataGridView4.Rows.Add();
                                dataGridView4.Rows[i].Cells[0].Value = tmp[2] + " - " + tmp[0];
                                string sd = "";
                                if (label67.Text != "Кол-во")
                                {
                                    sd = label67.Text;
                                }
                                dataGridView4.Rows[i].Cells[1].Value = numericUpDown11.Value + sd;
                                dataGridView4.Rows[i].Cells[2].Value = tmp[1];

                                dataGridView4.Rows[i].Selected = true;
                                dataGridView4.FirstDisplayedScrollingRowIndex = i;
                            }
                            catch { }
                            raschetdirok();
                            sum();
                            break;
                        }
                        c++;
                    }
                    sr.Close();
                }
            }
            catch { }
            c = 0;
            str33 = null;
        }

        private void button46_Click(object sender, EventArgs e)
        {
            if (dataGridView4.CurrentRow == null) return;
            dataGridView4.Rows.RemoveAt(dataGridView4.CurrentRow.Index);
            sum();
        }

        private void button44_Click(object sender, EventArgs e)
        {
            textBox13.Text = "";
            label59.Text = "Кол-во";
            numericUpDown9.Value = 1;
            numericUpDown5.Value = 100;

            panel1.Enabled = true;
            panel13.Enabled = true;
            panel4.Enabled = true;
            panel9.Enabled = true;
            panel7.Enabled = true;
            panel8.Enabled = true;

            dataGridView6.Enabled = true;
            button55.Enabled = true;
            button54.Enabled = true;
            button42.Enabled = true;
            button53.Enabled = true;

            button46.Enabled = true;

            button44.Visible = false;
            button43.Visible = false;


        }

        private void button47_Click(object sender, EventArgs e)
        {
            try
            {
                int i = dataGridView4.CurrentRow.Index;
                textBox13.Text = dataGridView4.Rows[i].Cells[0].Value.ToString();
                if (dataGridView4.Rows[i].Cells[1].Value.ToString().IndexOf(" м.кв.") != -1)
                {
                    label59.Text = " м.кв.";
                }
                else
                {
                    if (dataGridView4.Rows[i].Cells[1].Value.ToString().IndexOf(" м.п.") != -1)
                    {
                        label59.Text = " м.п.";
                    }
                    else
                    {
                        label59.Text = "Кол-во";
                    }
                }
                numericUpDown9.Value = Convert.ToDecimal(dataGridView4.Rows[i].Cells[1].Value.ToString().Replace(" м.кв.", "").Replace(" м.п.", ""));
                numericUpDown5.Value = Convert.ToDecimal(dataGridView4.Rows[i].Cells[2].Value);

                //блокировка всего
                panel1.Enabled = panel13.Enabled = panel4.Enabled = panel9.Enabled = panel7.Enabled = panel8.Enabled = false;

                dataGridView6.Enabled = button55.Enabled = button54.Enabled = button42.Enabled = button53.Enabled = button46.Enabled = false;

                button44.Visible = true;
                button43.Visible = true;

            }
            catch { }
        }

        private void button45_Click(object sender, EventArgs e)
        {
            if (textBox13.Text != "")
            {
                try
                {
                    int i = dataGridView4.Rows.Count;
                    // MessageBox.Show(dataGridView1.Rows.Count.ToString());
                    dataGridView4.Rows.Add();
                    dataGridView4.Rows[i].Cells[0].Value = textBox13.Text.Replace("|", "/");
                    dataGridView4.Rows[i].Cells[1].Value = numericUpDown9.Value;
                    dataGridView4.Rows[i].Cells[2].Value = numericUpDown5.Value;
                    //  try { dataGridView1.Rows[i - 1].Selected = false; }
                    //catch { }

                    dataGridView4.Rows[i].Selected = true;
                    dataGridView4.FirstDisplayedScrollingRowIndex = i;
                    sum();
                }
                catch { }
            }
            else { MessageBox.Show("Не введено название!"); }
        }

        private void button43_Click(object sender, EventArgs e)
        {
            try
            {
                int ii = dataGridView4.CurrentRow.Index;
                dataGridView4.Rows[ii].Cells[0].Value = textBox13.Text.Replace("|", "/").Replace("!", "/").Replace("~", "/").Replace("\r", "").Replace("\n", " ");
                if (label59.Text != "Кол-во")
                {
                    dataGridView4.Rows[ii].Cells[1].Value = numericUpDown9.Value + label59.Text;
                }
                else
                {
                    dataGridView4.Rows[ii].Cells[1].Value = numericUpDown9.Value;
                }
                dataGridView4.Rows[ii].Cells[2].Value = numericUpDown5.Value;

                button44_Click(null, null);
                sum();
            }
            catch { }
        }

        //удалить модуль
        private void button53_Click(object sender, EventArgs e)
        {
            if (dataGridView6.CurrentRow == null) return;
            dataGridView6.Rows.RemoveAt(dataGridView6.CurrentRow.Index);
            for (int i = 0; i < dataGridView6.Rows.Count; i++)
            {
                dataGridView6.Rows[i].Cells[0].Value = i + 1;
            }
            sum();
        }

        //копировать модуль
        private void button42_Click(object sender, EventArgs e)
        {
            if (dataGridView6.CurrentRow == null) return;
            int i = dataGridView6.Rows.Count;
            dataGridView6.Rows.Add();
            for (int j = 0; j < dataGridView6.CurrentRow.Cells.Count; j++)
            {
                dataGridView6.Rows[i].Cells[j].Value = dataGridView6.CurrentRow.Cells[j].Value;
            }
            for (int ii = 0; ii < dataGridView6.Rows.Count; ii++)
            {
                dataGridView6.Rows[ii].Cells[0].Value = ii + 1;
            }
            sum();
        }

        private void button55_Click(object sender, EventArgs e)
        {
            foreach (Form f in Application.OpenForms)
            {
                if (f.Name == "Form25")
                {
                    MessageBox.Show("Меню нового модуля уже открыто!");
                    return;
                }
            }
            Form25 f1 = new Form25();
            f1.Owner = this;
            f1.Show();
        }

        private void button41_Click(object sender, EventArgs e)
        {
            ИЗОБРАЖЕНИЯ_главная fs = new ИЗОБРАЖЕНИЯ_главная();
            fs.Show();
            fs.Focus();
        }

        public void load_in_bd(string tov, string prikrepfiles,string klients,string zakazobsh)
        {
            Array.Resize(ref tovar, tovar.Length + 1);
            //название | цена общая | кол-во | комментарий мастеров | файлы | монтаж | цена за шт | резерв 1| резерв 2| резерв 3 | резерв 4 | резерв 5 |

            //+  Таблица панели|Таблица товары и услуги|
            tovar[tovar.Length - 1] = tov;

            pererisovka_korzina();
            listBox5.SelectedIndex = tovar.Length - 1;
            sum();
            //прикрепленные файлы
            if (prikrepfiles != "")
            {
                listBox1.Items.Clear();
                var files = Directory.GetFiles(prikrepfiles);
                foreach (var item in files)
                {
                    listBox1.Items.AddRange(new object[] { item });
                }
            }
            //данные клиента
            if(klients != "")
            {
                string[] tmkl = klients.Split('|');
            
                Form6 f1 = new Form6();
                f1.Owner = this;
                f1.load();
                DataGridViewRow temp = (DataGridViewRow) f1.dataGridView1.Rows[0].Clone();

                for (int i=0;i<temp.Cells.Count;i++)
                {
                    temp.Cells[i].Value = tmkl[i];
                }
                klient = temp;
                label7.Text = klient.Cells[0].Value.ToString() + " " + klient.Cells[1].Value.ToString();
                f1.Close();
            }
            //общие данные
            if(zakazobsh != "")
            {
                /*
                    //цена доставки | цена подъема
                    fg += prdostavka + "|" + prpodem;
                 */



                string[] tmp = zakazobsh.Split('|');
                //дата|номер|срочный 1 - да | ндс | общая скидка |цена доставки|адрес доставки | подъем на этаж | кол-во единиц | цена | вид оплаты | 
                
                checkBox1.Checked = (tmp[2] == "1");
                numericUpDown1.Value = Convert.ToDecimal(tmp[3]);

                if (tmp[4].IndexOf("raspred") != -1)
                {
                    textBox12.Text = tmp[4].Replace("raspred", "");
                    if(numericUpDown3.Visible)
                    {
                        button40_Click(null, null);
                    }

                }
                else
                {
                    numericUpDown3.Value = Convert.ToDecimal(tmp[4]);
                    if (!numericUpDown3.Visible)
                    {
                        button40_Click(null, null);
                    }
                }
                   

                    textBox1.Text = tmp[5];
                textBox2.Text = tmp[6];
                textBox3.Text = tmp[7];
                textBox11.Text = tmp[8];
                textBox10.Text = tmp[9];

                radioButton1.Checked = (tmp[10] == "1");
                radioButton2.Checked = (tmp[10] == "2");
                radioButton3.Checked = (tmp[10] == "3");
                radioButton6.Checked = (tmp[10] == "4");


                //сколько оплачено | остаток | объединеные заказы | общая сумма оплаты | общий оплачено |как слать смс (1 - на одну) | Дата готовности
                
                textBox7.Text = tmp[15];

                //tmp[15]
                if (tmp[16] == "1")
                {
                    radioButton11.Checked = true;
                }
                else
                {
                    radioButton10.Checked = true;
                }
                dateTimePicker1.Text = tmp[17];
                try
                {
                    if(tmp.Length > 22)
                        textBox8.Text = tmp[22];
                }
                catch { }
              
            }
            sum();
            // dateTimePicker1.Text = "2.01.2017";
            //textBox7.Text = "700";
        }

        private void button50_Click(object sender, EventArgs e)
        {
            Form1_Resize(null, null);
        }
    }

    /// <summary>
    /// Класс хеширования
    /// </summary>
    static class Hash
    {

        /// <summary>
        /// Получает MD5 Hash приведенный к верхнему регистру
        /// </summary>
        /// <param name="instr">Строка для приведения</param>
        /// <returns>MD5</returns>
        public static string MD5Hash(string instr)
        {
            string strHash = string.Empty;

            foreach (byte b in new MD5CryptoServiceProvider().ComputeHash(Encoding.Default.GetBytes(instr)))
            {
                strHash += b.ToString("X2");
            }
            return strHash;
        }

        /// <summary>
        /// Получает SH1 Hash файла
        /// </summary>
        /// <param name="path">Путь до файла</param>
        /// <returns>SH1</returns>
        public static string Sh1(string path)
        {
            string strHash = string.Empty;
            using (FileStream fs = new FileStream(path, FileMode.Open))
            using (BufferedStream bs = new BufferedStream(fs))
            {
                using (SHA1Managed sha1 = new SHA1Managed())
                {
                    byte[] hash = sha1.ComputeHash(bs);
                    StringBuilder formatted = new StringBuilder(2 * hash.Length);
                    foreach (byte b in hash)
                    {
                        strHash = formatted.AppendFormat("{0:X2}", b).ToString();
                    }
                }
            }
            return strHash;
        }

    }
}
