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

namespace WindowsFormsApp1.Delivery
{
    public partial class List_Chk_Work : Form
    {
        Helper_DB db = new Helper_DB();
        List_aggregation list_a;
        public string[] data = { "", "" };
        int grididx = 0;
        public List_Chk_Work(List_aggregation list_)
        {
            InitializeComponent();
            list_a = list_;
        }
        public List_Chk_Work()
        {
            InitializeComponent();
        }
        private void List_Chk_Work_Load(object sender, EventArgs e)
        {
            string[] combodata = { "전체", "미검수", "검수" };
            cb_chk_stat.Items.AddRange(combodata);
            cb_chk_stat.SelectedIndex = 0;

            string[] readtable = { "list_name", "comp_num" };
            string[] searchtable = { "list_name", "compidx" };
            string[] searchdata = { data[0], data[1] };
            string readdata = "`clt`,`dly`,`date`";
            string getdata = "`header`, `num`, `isbn`, `book_name`, `author`, " +
                             "`book_comp`, `count`, `pay`, `total`, `stat`, " +
                             "`etc`, `chk_date`";
            db.DBcon();
            string tmpdata = db.More_DB_Search("Obj_List",readtable,searchdata,readdata);
            string[] load = tmpdata.Split('|');
            tb_clt.Text = load[0];
            tb_dlv.Text = load[1];
            tb_date.Text = load[2];
            richTextBox1.Text = tmpdata;
            string dbdata = db.DB_Select_Search(getdata, "Obj_List_Book", 
                searchtable[0], searchdata[0], searchtable[1], searchdata[1]);
            Made_Grid(dbdata);
        }
        public int gridcout = 0;
        public int stack = 1;
        private void btn_chk_Click(object sender, EventArgs e)      // 이미지 따오는거 자료조사 및 수정필요
        {
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["stat"].Value.ToString() == "미검수")
                {
                    gridcout = a;
                    break;
                }
            }
            if(tb_ISBN.Text == dataGridView1.Rows[gridcout].Cells["isbn"].Value.ToString())
            {
                string tmpcount = dataGridView1.Rows[gridcout].Cells["vol"].Value.ToString();
                int count = Convert.ToInt32(tmpcount);
                if(count != stack)
                {
                    MessageBox.Show(stack.ToString() + "/" + tmpcount + " 검수");
                    stack++;
                }
                else
                {
                    dataGridView1.Rows[gridcout].Cells["date"].Value = DateTime.Now.ToString("G");
                    dataGridView1.Rows[gridcout].Cells["stat"].Value = "검수";

                    string[] edit_col = { "chk_date", "stat" };
                    string[] edit_data = {dataGridView1.Rows[gridcout].Cells["date"].Value.ToString(),
                                            dataGridView1.Rows[gridcout].Cells["stat"].Value.ToString()};
                    string[] search_col = { "list_name", "compidx", "header", "num", "book_name" };
                    string[] search_data = { data[0], data[1],
                                            dataGridView1.Rows[gridcout].Cells["header"].Value.ToString(),
                                            dataGridView1.Rows[gridcout].Cells["num"].Value.ToString(),
                                            dataGridView1.Rows[gridcout].Cells["book_name"].Value.ToString() };
                    stack = 1;
                    tb_ISBN.Text = "";
                    db.More_Update("Obj_List_Book", edit_col, edit_data, search_col, search_data);
                    GridColorChange();
                    MessageBox.Show("검수완료");
                }
            }
            /*
            string text = textBox5.Text.Replace("\n", "");
            pictureBox1.Image = WebImageView("http://image.aladin.co.kr/product/24077/64/letslook/K232639138_f.jpg");
            textBox5.Text = "";
            */
        }
        /// <summary>
        /// 데이터그리드뷰 색상변경
        /// </summary>
        public void GridColorChange()
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Empty;
            }
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["stat"].Value.ToString() == "검수")
                {
                    dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Yellow;
                }
            }
        }
        private void btn_Lookup_Click(object sender, EventArgs e)       // 조회버튼
        {
            string comboValue = cb_chk_stat.Text;
            string[] searchtable = { "list_name", "compidx", "stat" };
            string[] searchdata = { data[0], data[1], comboValue };
            string getdata = "`header`, `num`, `isbn`, `book_name`, `author`, " +
                             "`book_comp`, `count`, `pay`, `total`, `stat`, " +
                             "`etc`, `chk_date`";
            string dbdata = "";
            if(comboValue == "전체") {
                dbdata = db.DB_Select_Search(getdata, "Obj_List_Book",
                    searchtable[0], searchdata[0], searchtable[1], searchdata[1]);
            }
            else {
                dbdata = db.More_DB_Search("Obj_List_Book",
                    searchtable, searchdata, getdata);
            }
            Made_Grid(dbdata);
        }
        /// <summary>
        /// 받은 URL을 이미지값으로 변환해주는 함수.
        /// </summary>
        /// <param name="URL"></param>
        /// <returns></returns>
        private Bitmap WebImageView(string URL)
        {
            try
            {
                WebClient Downloader = new WebClient();
                Stream ImageStream = Downloader.OpenRead(URL);
                Bitmap DownloadImage = Bitmap.FromStream(ImageStream) as Bitmap;
                return DownloadImage;
            }
            catch (Exception)
            {
                return null;
            }
        }
        private void Made_Grid(String Value)
        {
            dataGridView1.Rows.Clear();
            string[] db_data = Value.Split('|');
            string[] grid = { "", "", "", "", "",
                              "", "", "", "", "", 
                              "", ""};
            /*
             * 번호, 도서명, ISBN, 도서명, 저자
             * 출판사, 수량, 단가, 합계, 상태
             * 비고, 검수시간
            */
            int ea = 0;
            for(int a = 0; a < db_data.Length; a++)
            {
                if (ea == 11) { grid[ea] = db_data[a]; dataGridView1.Rows.Add(grid); ea = 0; }
                if (a%12==ea) { grid[ea] = db_data[a]; ea++; }
            }
            GridColorChange();
        }
        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Skill_Grid skill = new Skill_Grid();
            skill.Print_Grid_Num(sender, e);
        }

        private void btn_Close_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void textBox5_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
            {
                btn_chk_Click(null, null);
            }
        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            grididx = e.RowIndex;
        }
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Up)
            {
                grididx--;
            }
            if (e.KeyCode == Keys.Down)
            {
                grididx++;
            }
        }
    }
}
