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

namespace UniMarc
{
    public partial class List_Lookup : Form
    {
        Helper_DB db = new Helper_DB();
        List_aggregation list_a;
        Main main;
        public string call_base;
        public int grididx;
        public string compidx;
        string list_Date;
        public List_Lookup()
        {
            InitializeComponent();
        }
        public List_Lookup(List_aggregation list_ag)
        {
            InitializeComponent();
            list_a = list_ag;
            compidx = list_a.compidx;
        }
        public List_Lookup(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = PUB.user.CompanyIdx;
        }
        private void List_Lookup_Load(object sender, EventArgs e)
        {
            db.DBcon();

            string[] combo_list = { "진행", "완료" };
            cb_stat.Items.AddRange(combo_list);
            cb_stat.SelectedIndex = 0;

            string[] combo_search = { "도서명", "출판사" };
            cb_search.Items.AddRange(combo_search);
            cb_search.SelectedIndex = 0;

            string[] combo_import = { "전체", "미입고", "입고" };
            cb_import.Items.AddRange(combo_import);
            cb_import.SelectedIndex = 0;

            string[] combo_export = { "전체", "미출고", "출고" };
            cb_export.Items.AddRange(combo_export);
            cb_export.SelectedIndex = 0;

            Init();
        }

        public void Init()
        {
            mk_combo_list_name();
            mk_charge();
        }
        #region Load_Sub
        /// <summary>
        /// 담당자 콤보박스(cb_charge)에 작성
        /// </summary>
        private void mk_charge()
        {
            cb_charge.Items.Clear();
            string cmd = db.DB_Select_Search("comp_name",
                "Comp", "idx", compidx);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] tmp_db = db_res.Split('|');
            cmd = db.DB_Select_Search("name", "User_Data", "affil", tmp_db[0]);
            db_res = db.DB_Send_CMD_Search(cmd);
            string[] data = db_res.Split('|');
            cb_charge.Items.Add("전체");
            for (int a = 0; a < data.Length - 1; a++)
            {
                cb_charge.Items.Add(data[a]);
            }
            cb_charge.SelectedIndex = 0;
        }
        #endregion
        int cnt = 0, pageNo = 1;
        private void btn_print_Click(object sender, EventArgs e)    // 인쇄 기능
        {
            if (dataGridView1.Rows.Count < 1) {
                UTIL.MsgE("인쇄할 목록이 없습니다!");
                return;
            }
            // 여백 설정
            printDocument1.DefaultPageSettings.Margins.Top = 10;
            printDocument1.DefaultPageSettings.Margins.Left = 10;
            printDocument1.DefaultPageSettings.Margins.Right = 10;
            printDocument1.DefaultPageSettings.Margins.Bottom = 10;

            // 용지 방향    가로(true), 세로(false)
            printDocument1.DefaultPageSettings.Landscape = false;

            // 용지 크기
            printDocument1.DefaultPageSettings.PaperSize = 
                new PaperSize("A4", 210 * 4, 297 * 4);

            // 프린터 설정 창의 페이지 지정
            printDialog1.AllowSomePages = true;
            
            printPreviewDialog1.Document = printDocument1;
            if (printPreviewDialog1.ShowDialog() == DialogResult.Cancel)
            {
                cnt = 0;
                pageNo = 1;
            }
        }

        private void printDocument1_BeginPrint(object sender, PrintEventArgs e)
        {
            cnt = 0;
            pageNo = 1;
        }

        private void printDocument1_tempPage(object sender, PrintPageEventArgs e)
        {
            PrintGrid(dataGridView1, e);
        }

        private void PrintGrid(DataGridView gridView, PrintPageEventArgs e)
        {
            Graphics g = e.Graphics;

            // 페이지 전체넓이 printPreviewDialog.Width
            int dialogWidth = 528;

            // 컬럼 안에 있는 값들 가운데로 정렬하기 위해 선언
            StringFormat sf = new StringFormat();
            sf.Alignment = StringAlignment.Center;

            // 시작점 위치, datagrid 1개의 컬럼 가로길이
            int width, width1;

            // 시작점 x좌표
            int startWidth = 10;
            // 시작점 y좌표
            int startHeight = 80;

            // datagrid 1개의 컬럼 하나의 높이
            // int avgHeight = gridView.Rows[0].Height;
            int avgHeight = 25;

            int temp = 0;   // row개수 세어줄 것. cnt역할.

            string Title = cb_list_name.Text;

            g.DrawString(Title, new Font("Arial", 20, FontStyle.Bold), Brushes.Black, 10, 10);
            g.DrawString("목록일자: " + list_Date, new Font("Arial", 13), Brushes.Black, dialogWidth - 20, 45);
            g.DrawString("페이지번호: " + pageNo, new Font("Arial", 13), Brushes.Black, dialogWidth - 20, 1150);

            for (int a = 0; a < gridView.ColumnCount; a++)      // columnCount는 일정
            {
                if (!gridView.Columns[a].Visible)
                    continue;
                if (gridView.Columns[a].Name == "Column1" || gridView.Columns[a].Name == "stat" ||
                    gridView.Columns[a].Name == "gubun" || gridView.Columns[a].Name == "order")
                    continue;

                if (a == 2)
                {
                    width = 0;
                    width1 = gridView.Columns[a].Width + 15;
                }
                else if (gridView.Columns[a].Name == "etc")
                {
                    int etcWidth = 250;
                    width = gridView.Columns[a - 1].Width - 5;
                    width1 = etcWidth - 5;
                }
                else if (a < gridView.ColumnCount - 1)
                {
                    width = gridView.Columns[a - 1].Width + 15;
                    width1 = gridView.Columns[a].Width + 15;
                }
                else
                {
                    width = gridView.Columns[a - 1].Width + 15;
                    width1 = gridView.Columns[a].Width + 40;
                }
                RectangleF drawRect = new RectangleF((float)(startWidth + width) / 4 * 3,
                    (float)startHeight, (float)width1 / 4 * 3, avgHeight);
                g.DrawRectangle(Pens.Black, (float)(startWidth + width) / 4 * 3,
                    (float)startHeight, (float)width1 / 4 * 3, avgHeight);
                g.DrawString(gridView.Columns[a].HeaderText,
                    new Font("Arial", 12, FontStyle.Bold), Brushes.Black, drawRect, sf);
                startWidth += width;
            }
            startHeight += avgHeight;

            for (int a = cnt; a < gridView.RowCount; a++)
            {
                startWidth = 10;
                for (int b = 0; b < gridView.ColumnCount; b++)
                {
                    if (!gridView.Columns[b].Visible) 
                        continue;
                    if (gridView.Columns[b].Name == "Column1" || gridView.Columns[b].Name == "stat" ||
                        gridView.Columns[b].Name == "gubun" || gridView.Columns[b].Name == "order")
                        continue;

                    if (b == 2)
                    {
                        width = 0;
                        width1 = gridView.Columns[b].Width + 15;
                    }
                    else if (gridView.Columns[b].Name == "etc")
                    {
                        int etcWidth = 250;
                        width = gridView.Columns[b - 1].Width - 5;
                        width1 = etcWidth - 5;
                    }
                    else if (b <= gridView.ColumnCount - 2)
                    {
                        width = gridView.Columns[b - 1].Width + 15;
                        width1 = gridView.Columns[b].Width + 15;
                    }
                    else
                    {
                        width = gridView.Columns[b - 1].Width + 15;
                        width1 = gridView.Columns[b].Width + 40;
                    }
                    if (b == 2) { sf.LineAlignment = StringAlignment.Near; }
                    else { sf.LineAlignment = StringAlignment.Center; }
                    RectangleF drawRect = new RectangleF((float)(startWidth + width) / 4 * 3,
                        (float)startHeight, (float)width1 / 4 * 3, avgHeight);
                    g.DrawRectangle(Pens.Black, (float)(startWidth + width) / 4 * 3,
                        (float)startHeight, (float)width1 / 4 * 3, avgHeight);
                    g.DrawString(gridView.Rows[a].Cells[b].FormattedValue.ToString(),
                        new Font("Arial", 7), Brushes.Black, drawRect, sf);
                    startWidth += width;
                }
                startHeight += avgHeight;
                temp++;
                cnt++;

                if (temp % 40 == 0)
                {
                    e.HasMorePages = true;
                    pageNo++;
                    return;
                }
            }
        }
        private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            int dialogWidth = 528;      // 페이지 전체 넓이

            StringFormat sf = new StringFormat();
            // 컬럼 안에 있는 값들 가운데로 정렬
            sf.Alignment = StringAlignment.Center;
            sf.LineAlignment = StringAlignment.Center;

            int width, width1;                  // 시작점 위치, datagrid 1개의 컬럼
            int startWidth = 10;                    // 시작 x좌표
            int startHeight = 140;                      // 시작 y좌표
            int avgHeight = dataGridView1.Rows[0].Height;   // girdview 컬럼 하나의 높이
            int temp = 0;                                       // row 개수 세어줄 것. cnt의 역할
            avgHeight = avgHeight / 3 * 4;

            e.Graphics.DrawString("목록 조회", new Font("Arial", 20, FontStyle.Bold), Brushes.Black, dialogWidth / 2, 40);
            e.Graphics.DrawString("인쇄일: " + DateTime.Now.ToString("yyyy/MM/dd"), new Font("Arial", 13), Brushes.Black, dialogWidth - 20, 80);
            e.Graphics.DrawString("페이지번호: " + pageNo, new Font("Arial", 13), Brushes.Black, dialogWidth - 20, 100);

            for(int a = 0; a < dataGridView1.ColumnCount; a++)      // columnCount는 일정
            {
                if (!dataGridView1.Columns[a].Visible) { continue; }
                if (a == 0) {
                    width = 0;
                    width1 = dataGridView1.Columns[a].Width + 15;
                }
                else if (a >= 1 && a < dataGridView1.ColumnCount - 1) {
                    width = dataGridView1.Columns[a - 1].Width + 15;
                    width1 = dataGridView1.Columns[a].Width + 15;
                }
                else {
                    width = dataGridView1.Columns[a - 1].Width + 15;
                    width1 = dataGridView1.Columns[a].Width + 40;
                }
                RectangleF drawRect = new RectangleF((float)(startWidth + width) / 4 * 3, 
                    (float)startHeight, (float)width1 / 4 * 3, avgHeight);
                e.Graphics.DrawRectangle(Pens.Black, (float)(startWidth + width) / 4 * 3, 
                    (float)startHeight, (float)width1 / 4 * 3, avgHeight);
                e.Graphics.DrawString(dataGridView1.Columns[a].HeaderText, 
                    new Font("Arial", 12, FontStyle.Bold), Brushes.Black, drawRect, sf);
                startWidth += width;
            }
            startHeight += avgHeight;

            for(int a = cnt; a < dataGridView1.RowCount - 1; a++)
            {
                startWidth = 10;
                for(int b = 0; b < dataGridView1.ColumnCount; b++) {
                    if (!dataGridView1.Columns[b].Visible) { continue; }
                    if (b == 0) {
                        width = 0;
                        width1 = dataGridView1.Columns[b].Width + 15;
                    }
                    else if (b >= 1 && b <= dataGridView1.ColumnCount - 2) {
                        width = dataGridView1.Columns[b - 1].Width + 15;
                        width1 = dataGridView1.Columns[b].Width + 15;
                    }
                    else {
                        width = dataGridView1.Columns[b - 1].Width + 15;
                        width1 = dataGridView1.Columns[b].Width + 40;
                    }
                    if (b == 2) { sf.LineAlignment = StringAlignment.Near; }
                    else { sf.LineAlignment = StringAlignment.Center; }
                    RectangleF drawRect = new RectangleF((float)(startWidth + width) / 4 * 3,
                        (float)startHeight, (float)width1 / 4 * 3, avgHeight);
                    e.Graphics.DrawRectangle(Pens.Black, (float)(startWidth + width) / 4 * 3,
                        (float)startHeight, (float)width1 / 4 * 3, avgHeight);
                    e.Graphics.DrawString(dataGridView1.Rows[a].Cells[b].FormattedValue.ToString(), 
                        new Font("Arial", 7), Brushes.Black, drawRect, sf);
                    startWidth += width;
                }
                startHeight += avgHeight;
                temp++;
                cnt++;

                if (temp % 23 == 0) {
                    e.HasMorePages = true;
                    pageNo++;
                    return;
                }
            }
        }
        private void btn_lookup_Click(object sender, EventArgs e)
        {
            // 조회 기능
            mk_grid();
            res_total();
            Column_Text_Color();
        }
        #region Lookup_Sub
        /// <summary>
        /// 그리드 내에 데이터 삽입
        /// TODO: 09.10 수정필요!
        /// </summary>
        private void mk_grid()
        {
            dataGridView1.Rows.Clear();
            string db_res = db.DB_Send_CMD_Search(QueryFilter());
            string[] data = db_res.Split('|');
            string[] mkgrid = { "", "", "", "", "",
                                "", "", "", "", "",
                                "", "", "", "", "" };
            int num = 16;
            for (int a = 0; a < data.Length; a++)
            {
                if (a % num == 0) { mkgrid[0] = data[a]; }
                if (a % num == 1) { mkgrid[2] = data[a] + " "; }
                if (a % num == 2) { mkgrid[2] += data[a]; }
                if (a % num == 3) { mkgrid[3] = data[a]; }
                if (a % num == 4) { mkgrid[4] = data[a]; }
                if (a % num == 5) { mkgrid[5] = data[a]; }
                if (a % num == 6) { mkgrid[6] = data[a]; }
                if (a % num == 7) { mkgrid[7] = data[a]; }
                if (a % num == 8) { mkgrid[8] = data[a]; }
                if (a % num == 9) { mkgrid[9] = data[a]; }
                if (a % num == 10) { mkgrid[10] = data[a]; }
                if (a % num == 11) { mkgrid[11] = data[a]; }
                if (a % num == 12) { mkgrid[12] = data[a]; }
                if (a % num == 13) { mkgrid[13] = data[a]; }
                if (a % num == 14) { mkgrid[14] = data[a]; }
                if (a % num == 15)
                {
                    if (data[a] != "")      // 세트분할도서 미표시
                        continue;

                    dataGridView1.Rows.Add(mkgrid);
                }
            }
        }
        private string QueryFilter()
        {
            string[] ary_where = { "", "", "", "", "", "" };

            ary_where[0] = string.Format("`l_idx` IN (SELECT `idx` FROM `Obj_List` WHERE `state` = \"{0}\" AND `comp_num` = \"{1}\")", cb_stat.Text, compidx);
            if (tb_search.Text != "")
            {
                if (cb_search.SelectedIndex == 0)           // 도서명
                    ary_where[1] = string.Format("`book_name` like \"%{0}%\"", tb_search.Text);

                else if (cb_search.SelectedIndex == 1)      // 출판사
                    ary_where[1] = string.Format("`book_comp` like \"%{0}%\"", tb_search.Text);
            }
            if (tb_clt.Text != "")
            {
                ary_where[2] = string.Format("`order` like \"%{0}%\"", tb_clt.Text);
            }
            if (cb_list_name.SelectedItem.ToString() != "전체")
            {
                ary_where[3] = string.Format("`list_name` = \"{0}\"", cb_list_name.Text);
            }
            if (cb_import.SelectedIndex != 0)
            {
                ary_where[4] = string.Format("`import` = \"{0}\"", cb_import.Text);
            }
            if (cb_export.SelectedIndex != 0)
            {
                ary_where[5] = string.Format("`export` = \"{0}\"", cb_export.Text);
            }

            string where = "";
            for (int a = 0; a < ary_where.Length; a++)
            {
                if (ary_where[a] != "" && where != "")
                    where += " AND " + ary_where[a];

                else if (ary_where[a] != "")
                    where += ary_where[a];
            }

            string area = "`idx`, `header`, `num`, `book_name`, `author`, `book_comp`, " +
                          "`count`, `pay`, `total`, `stat`, `etc`, " +
                          "`list_name`, `order`, `import`, `export`, `set_book_name`";
            // string cmd = db.DB_Select_Search(area, "Obj_List_Book", "compidx", compidx);
            string cmd = string.Format("SELECT {0} FROM {1} WHERE {2};", area, "Obj_List_Book", where);
            return cmd;
        }

        private void res_total()
        {
            int itcount = 0;
            int itpay = 0;
            int ittotal = 0;
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                itcount += Convert.ToInt32(dataGridView1.Rows[a].Cells["count"].Value.ToString());
                itpay += Convert.ToInt32(dataGridView1.Rows[a].Cells["pay"].Value.ToString());
                ittotal += Convert.ToInt32(dataGridView1.Rows[a].Cells["total"].Value.ToString());
            }
            lbl_count.Text = "수량: " + String.Format("{0:#,0}", itcount);
            lbl_pay.Text   = "단가: " + String.Format("{0:#,0}", itpay);
            lbl_total.Text = "합계: " + String.Format("{0:#,0}", ittotal);
        }

        void Column_Text_Color()
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["Column2"].Value.ToString() == "입고")
                {
                    dataGridView1.Rows[a].DefaultCellStyle.ForeColor = Color.Blue;
                }
                else if (dataGridView1.Rows[a].Cells["Column2"].Value.ToString() == "미입고")
                {
                    dataGridView1.Rows[a].DefaultCellStyle.ForeColor = Color.Red;
                }
            }
        }
        #endregion
        private void btn_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void cb_list_SelectedIndexChanged(object sender, EventArgs e)
        {
            mk_combo_list_name();
        }
        /// <summary>
        /// 검색 필터 콤보박스(cb_list_name)에 작성
        /// </summary>
        private void mk_combo_list_name()
        {
            cb_list_name.Items.Clear();
            // 진행과 완료를 구분지어 명단목록 작성
            string state = cb_stat.Text;
            string charge = cb_charge.Text;
            string search_table = "list_name";
            string cmd;
            if (cb_charge.SelectedIndex != 0) {
                string[] table = { "comp_num", "state" };
                string[] search = { compidx, state };
                cmd = db.More_DB_Search("Obj_List", table, search, search_table);
            }
            else {
                string[] table = { "comp_num", "state", "charge" };
                string[] search = { compidx, state, charge };
                cmd = db.More_DB_Search("Obj_List", table, search, search_table);
            }
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] data = db_res.Split('|');
            cb_list_name.Items.Add("전체");
            for (int a = 0; a < data.Length - 1; a++) {
                cb_list_name.Items.Add(data[a]); 
            }
            for (int a = 0; a < cb_list_name.Items.Count; a++)
            {
                if (call_base == cb_list_name.Items[a].ToString())
                {
                    cb_list_name.SelectedIndex = a;
                    btn_lookup_Click(null, null);
                    break;
                }
                else { cb_list_name.SelectedIndex = 0; }
            }
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            Book_Lookup bl = new Book_Lookup(this);
            bl.TopMost = true;
            bl.Lookup_Load_tmp(dataGridView1.Rows[e.RowIndex].Cells["idx"].Value.ToString());
            bl.Show();
        }

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

        private void cb_list_name_SelectedIndexChanged(object sender, EventArgs e)
        {
            string cmd = string.Format("SELECT {0} FROM {1} WHERE `list_name` = \"{2}\";",
                "`date`", "Obj_List", cb_list_name.SelectedItem.ToString());
            string res = db.DB_Send_CMD_Search(cmd);
            list_Date = res.Replace("|", "");
        }

        private void tb_order_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Commodity_Search cs = new Commodity_Search(this);
                cs.Clinet_name = tb_clt.Text;
                cs.Show();
            }
        }

    }
}
