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

namespace garment_factory
{
    public partial class fManager : Form
    {
        public fManager()
        {
            InitializeComponent();
        }

        public string IdZakazchik = "";
        string IdTkan = "", IdFur = "";
        public struct Tkani
        {
            public string IdTkan, NameTkan, ColorTkan, Width, Length, Description;
            public Image PhotoTkan;
        }

        List<Tkani> LstTkani = new List<Tkani>();

        void GetTkaniFromDB()
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.Fabrika2024ConnectionString);
            con.Open();
            SqlCommand Query = new SqlCommand("select * from Tkani t join Cveta c on t.id_cvet=c.id_cvet where Dlina > 0", con);
            SqlDataReader Data = Query.ExecuteReader();
            while (Data.Read())
            {
                Tkani Tk = new Tkani();
                Tk.IdTkan = Data["id_Tkani"].ToString();
                Tk.NameTkan = Data["Nazvanie"].ToString();
                Tk.ColorTkan = Data["Name_cvet"].ToString();
                Tk.Width = Data["Shirina"].ToString();
                Tk.Length = Data["Dlina"].ToString();
                Tk.Description = Data["Primechanie"].ToString();
                try
                {
                    byte[] PhotoByte = (byte[])Data["Photo"];
                    ImageConverter ImConverter = new ImageConverter();
                    Tk.PhotoTkan = (Bitmap)ImConverter.ConvertFrom(PhotoByte);
                }
                catch
                {
                    Tk.PhotoTkan = Properties.Resources.picture;
                }
                LstTkani.Add(Tk);  
            }
            con.Close();
        }

        void FillLVTkani()
        {
            LVTkani.Items.Clear();
            ImageListTkani.Images.Clear();
            foreach (Tkani Tk in LstTkani)
            {
                ListViewItem LV = new ListViewItem(Tk.NameTkan);
                ImageListTkani.Images.Add(Tk.PhotoTkan);
                LV.ImageIndex = ImageListTkani.Images.Count - 1;
                LVTkani.Items.Add(LV);  
            }
        }

        public struct Furnitura
        {
            public string IdFur, NameFur, CountFur;
            public Image PhotoFur;
        }

        List<Furnitura> LstFurnitura = new List<Furnitura>();

        void GetFurnituraFromDB()
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.Fabrika2024ConnectionString);
            con.Open();
            SqlCommand Query = new SqlCommand("select * from Furnitura where countfur > 0", con);
            SqlDataReader Data = Query.ExecuteReader();
            while (Data.Read())
            {
                Furnitura Fr = new Furnitura();
                Fr.IdFur = Data["idfur"].ToString();
                Fr.NameFur = Data["namefur"].ToString();
                Fr.CountFur = Data["countfur"].ToString();
                try
                {
                    byte[] PhotoByte = (byte[])Data["photo"];
                    ImageConverter ImConverter = new ImageConverter();
                    Fr.PhotoFur = (Bitmap)ImConverter.ConvertFrom(PhotoByte);
                }
                catch
                {
                    Fr.PhotoFur = Properties.Resources.picture;
                }
                LstFurnitura.Add(Fr);  
            }
            con.Close();
        }

        void FillLVFurnitura()
        {
            LVFurnitura.Items.Clear();
            ImageListFur.Images.Clear();
            foreach (Furnitura Fr in LstFurnitura)
            {
                ListViewItem LV = new ListViewItem(Fr.NameFur);
                ImageListFur.Images.Add(Fr.PhotoFur);
                LV.ImageIndex = ImageListFur.Images.Count - 1;
                LVFurnitura.Items.Add(LV);  
            }
        }

        private void fManager_Load(object sender, EventArgs e)
        {
            // TODO: данная строка кода позволяет загрузить данные в таблицу "fabrika2024DataSet.Izdelie". При необходимости она может быть перемещена или удалена.
            this.izdelieTableAdapter.Fill(this.fabrika2024DataSet.Izdelie);
            // TODO: данная строка кода позволяет загрузить данные в таблицу "fabrika2024DataSet.Users". При необходимости она может быть перемещена или удалена.
            this.usersTableAdapter.Fill(this.fabrika2024DataSet.Users);
            string id = id_userLabel2.Text;
            SqlConnection con = new SqlConnection(Properties.Settings.Default.Fabrika2024ConnectionString);
            con.Open();
            string t1 = string.Format($@"select * from Users where id_user = {id}");
            SqlCommand query = new SqlCommand(t1, con);
            // выполнить запрос
            SqlDataReader rdr = query.ExecuteReader();
            while (rdr.Read())
            {
                FIO.Text = rdr["Surname"].ToString() + " " + rdr["Name"].ToString() + " " + rdr["Otch"].ToString();
            }
            con.Close();
            FillListZakaz();

            GetTkaniFromDB();
            FillLVTkani();
            GetFurnituraFromDB();
            FillLVFurnitura();
        }
        void FillListZakaz()
        {
            SqlConnection con = new SqlConnection(Properties.Settings.Default.Fabrika2024ConnectionString);
            DgvZakaz.Rows.Clear();
            string Query = $@"select Izdelie.name_izd, 
    Orders.CountIzdel, 
    Tkani.Nazvanie , 
    Furnitura.namefur , 
    Orders.CountFurnit , 
    Users.Surname 
from Orders, Users, Tkani, Furnitura, Izdelie
where Users.id_User = Orders.id_zakaz 
    and Tkani.Id_Tkani = Orders.id_tkani 
    and Furnitura.idfur = Orders.id_furnitur 
    and Izdelie.id_izdelie = Orders.id_izdelie
    and Orders.id_manager = " + id_userLabel2.Text;
            con.Open();
            SqlCommand cmd = new SqlCommand(Query, con);
            SqlDataReader Rez = cmd.ExecuteReader();
            if (DgvZakaz.Rows.Count > 0)
            {
                DgvZakaz.Rows.Clear();
            }
            while (Rez.Read())
            {
                DgvZakaz.Rows.Add(Rez["name_izd"], Rez["Nazvanie"], Rez["namefur"], Rez["CountFurnit"], Rez["CountIzdel"], Rez["Surname"]);
            }
            con.Close();
        }

        private void LVFurnitura_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (LVFurnitura.SelectedItems.Count > 0)  // есть выделенные элементы
            {
                int num = LVFurnitura.SelectedIndices[0];  // номер выделенного элемента
                TbxCountFurSklad.Text = LstFurnitura[num].CountFur;
                TbxNameFur.Text = LstFurnitura[num].NameFur;

            }
            else  // нет выделенных элементов
            {

                TbxCountFurSklad.Text = "";
                TbxNameFur.Text = "";
            }
        }

        private void BtnProfile_Click(object sender, EventArgs e)
        {
            fProfil frm = new fProfil();
            frm.BsUsers.Filter = this.usersBindingSource.Filter;
            if (frm.ShowDialog() == DialogResult.OK)
            {
                this.usersTableAdapter.Fill(this.fabrika2024DataSet.Users);
            }
        }

        private void BtnAdd_Click(object sender, EventArgs e)
        {
            izdelieBindingSource.AddNew();
            BtnSave.Enabled = true;
            BtnAdd.Enabled = false;
            BtnEdit.Enabled = false;
            izdelka.Enabled = false;
            TbxNameIzd.Enabled = true;
            TbxLengthIzd.Enabled = true;
            TbxWidthIzd.Enabled = true;
        }

        private void BtnEdit_Click(object sender, EventArgs e)
        {
            BtnSave.Enabled = true;
            BtnAdd.Enabled = false;
            BtnEdit.Enabled = false;
            izdelka.Enabled = false;
            TbxNameIzd.Enabled = true;
            TbxLengthIzd.Enabled = true;
            TbxWidthIzd.Enabled = true;
        }

        private void BtnSave_Click(object sender, EventArgs e)
        {
            izdelieBindingSource.EndEdit();
            this.izdelieTableAdapter.Update(this.fabrika2024DataSet.Izdelie);
            BtnSave.Enabled = false;
            BtnAdd.Enabled = true;
            BtnEdit.Enabled = true;
            izdelka.Enabled = true;
            TbxNameIzd.Enabled = false;
            TbxLengthIzd.Enabled = false;
            TbxWidthIzd.Enabled = false;
        }

        private void BtnAll_Click(object sender, EventArgs e)
        {
            if (RbtWord.Checked)
            {
                MessageBox.Show("Заказ экспартирован");
            }
            else
            {
                MessageBox.Show("Заказ экспартирован");
            }
        }

        private void BtnSelect_Click(object sender, EventArgs e)
        {
            if (RbtWord.Checked)
            {
                MessageBox.Show("Заказ экспартирован");
            }
            else
            {
                MessageBox.Show("Заказ экспартирован");
            }
        }

        private void LVTkani_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (LVTkani.SelectedItems.Count > 0)  // есть выделенные элементы
            {
                int num = LVTkani.SelectedIndices[0];  // номер выделенного элемента
                NametkanTextBox.Text = LstTkani[num].NameTkan;
                ColorTextBox.Text = LstTkani[num].ColorTkan;
                WidthTextBox.Text = LstTkani[num].Width;
                LengthTextBox.Text = LstTkani[num].Length;
                DescriptionTextBox.Text = LstTkani[num].Description;
            }
            else  // нет выделенных элементов
            {
                NametkanTextBox.Text = "";
                ColorTextBox.Text = "";
                WidthTextBox.Text = "";
                LengthTextBox.Text = "";
                DescriptionTextBox.Text = "";
            }
        }
    }
}
