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;
namespace WindowsFormsApp1.Delivery
{
    public partial class List_Lookup : Form
    {
        Helper_DB db = new Helper_DB();
        List_aggregation list_a;
        Main main;
        string form_call;
        public string call_base;
        public string compidx;
        public List_Lookup()
        {
            InitializeComponent();
        }
        public List_Lookup(List_aggregation list_ag)
        {
            InitializeComponent();
            list_a = list_ag;
            form_call = "list_a";
            compidx = list_a.compidx;
        }
        public List_Lookup(Main _main)
        {
            InitializeComponent();
            main = _main;
            form_call = "main";
            compidx = main.com_idx;
        }
        private void List_Lookup_Load(object sender, EventArgs e)
        {
            db.DBcon();
            string[] combo_list = { "진행", "완료" };
            cb_list.Items.AddRange(combo_list);
            cb_list.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;
            mk_combo_list_name();
            mk_charge();
        }
        int cnt = 0, pageNo = 1;
        private void btn_print_Click(object sender, EventArgs e)    // 인쇄 기능
        {
            PrinterSettings ps = new PrinterSettings();
            ps.FromPage = 12;
            ps.PrintRange = PrintRange.CurrentPage;
            ps.ToPage = 13;
            // 여백 설정
            printDocument1.DefaultPageSettings.Margins.Left = 10;
            printDocument1.DefaultPageSettings.Margins.Right = 10;
            printDocument1.DefaultPageSettings.Margins.Top = 10;
            printDocument1.DefaultPageSettings.Margins.Bottom = 10;
            // 용지 방향
            printDocument1.DefaultPageSettings.Landscape = true;    // 가로(true), 세로(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_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 (a == 0) {
                    width = 0;
                    width1 = dataGridView1.Columns[a].Width + 15;
                }
                else if (a >= 1 && a <= dataGridView1.ColumnCount - 2) {
                    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 (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();
        }
        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);
        }
        private void btn_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void cb_list_SelectedIndexChanged(object sender, EventArgs e)
        {
            mk_combo_list_name();
        }
        /// 
        /// 담당자 콤보박스(cb_charge)에 작성
        /// 
        private void mk_charge()
        {
            cb_charge.Items.Clear();
            string tmp_data = db.DB_Select_Search("comp_name",
                "Comp", "idx", compidx);
            string[] tmp_db = tmp_data.Split('|');
            tmp_data = db.DB_Select_Search("name", "User_Data", "affil", tmp_db[0]);
            string[] data = tmp_data.Split('|');
            cb_charge.Items.Add("전체");
            for (int a = 0; a < data.Length - 1; a++) {
                cb_charge.Items.Add(data[a]);
            }
            cb_charge.SelectedIndex = 0;
        }
        /// 
        /// 검색 필터 콤보박스(cb_list_name)에 작성
        /// 
        private void mk_combo_list_name()
        {
            cb_list_name.Items.Clear();
            // 진행과 완료를 구분지어 명단목록 작성
            string state = cb_list.Text;
            string charge = cb_charge.Text;
            string search_table = "list_name";
            string tmp_data;
            if (cb_charge.SelectedIndex != 0) {
                string[] table = { "comp_num", "state" };
                string[] search = { compidx, state };
                tmp_data = db.More_DB_Search("Obj_List", table, search, search_table);
            }
            else {
                string[] table = { "comp_num", "state", "charge" };
                string[] search = { compidx, state, charge };
                tmp_data = db.More_DB_Search("Obj_List", table, search, search_table);
            }
            string[] data = tmp_data.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; }
            }
        }
        /// 
        /// 그리드 내에 데이터 삽입
        /// TODO: 09.10 수정필요!
        /// 
        private void mk_grid()
        {
            dataGridView1.Rows.Clear();
            string list = cb_list_name.Text;
            string area = "`header`, `num`, `book_name`, `author`, `book_comp`, " +
                          "`count`, `pay`, `total`, `stat`, `etc`, " +
                          "`list_name`, `order`, `import`, `export`";
            string tmp_data = db.DB_Select_Search(area, "Obj_List_Book", "compidx", compidx);
            string[] data = tmp_data.Split('|');
            string[] mkgrid = { "", "", "", "", "",
                                "", "", "", "", "",
                                "", "", "", "" };
            int num = 14;
            for(int a = 0; a < data.Length; a++) {
                if (a % num == 0) { mkgrid[1] = data[a] + " "; }
                if (a % num == 1) { mkgrid[1] += 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 (filter(mkgrid) == true) {
                        dataGridView1.Rows.Add(mkgrid);
                    }
                }
            }
        }
        private bool filter(string[] array)
        {
            /* 주 | 번호 | 도서명 | 저자 | 출판사
             * 수량 | 단가 | 합계 | 상태 | 비고
             * 구분 | 주문처 | 입고상태 | 출고상태 */
            if (tb_search.Text != "") {
                if (cb_search.SelectedIndex == 0) {
                    if (array[2].Contains(tb_search.Text) == false) {
                        return false;
                    }
                }
                else if (cb_search.SelectedIndex == 1) {
                    if (array[4].Contains(tb_search.Text) == false) {
                        return false;
                    }
                }
            }
            if (tb_order.Text != "") {
                if (array[11].Contains(tb_order.Text) == false) {
                    return false;
                }
            }
            if (cb_list_name.SelectedIndex != 0) {
                if (array[10].Contains(cb_list_name.Text) == false){
                    return false;
                }
            }
            if (cb_import.SelectedIndex != 0) {
                if (array[12].Contains(cb_import.Text) == false) {
                    return false;
                }
            }
            if (cb_export.SelectedIndex != 0) {
                if (array[13].Contains(cb_export.Text) == false) {
                    return false;
                }
            }
            return true;
        }
    }
}