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

namespace WindowsFormsApp1.Delivery
{
    public partial class List_aggregation : Form
    {
        Helper_DB db = new Helper_DB();
        string db_tmp;
        public int EditNumber;
        public string compidx;
        int row = 0;
        Main main;
        public List_aggregation(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = main.com_idx;
        }
        /////// TODO: 
        // 새로운 폼 작업 필요.
        // "목록집계등록"
        private void List_aggregation_Load(object sender, EventArgs e)
        {
            db.DBcon();
            // 작업명 - 배송방법까진 수정이 가능하여야함. 3,4,5,6 + 체크 추가
            for (int a = 0; a < 16; a++)
            {
                if(a==2 || a == 4 || a == 5 || a == 6 || a == 15) {
                    dataGridView1.Columns[a].ReadOnly = false;
                }
                else { dataGridView1.Columns[a].ReadOnly = true; }
            }
            string[] state = { "진행", "완료", "전체" };
            combo_state.Items.AddRange(state);
            combo_state.SelectedIndex = 0;

            string[] years = {"2009", "2010", "2011", "2012", "2013",
                              "2014", "2015", "2016", "2017", "2018",
                              "2019", "2020"};
            combo_year.Items.AddRange(years);
            combo_year.SelectedIndex = 11;
            combo_year.Visible = false;

            combo_user.Items.Add("전체");
            string[] user_tmp = main.DB_User_Data.Split('|');
            string cmd = db.self_Made_Cmd("SELECT `name` FROM `User_Data` WHERE `affil` = '" + user_tmp[5] + "';");
            string[] user_name = cmd.Split('|');
            for(int a = 0; a < user_name.Length; a++)
            {
                if (a == user_name.Length - 1) { break; }
                combo_user.Items.Add(user_name[a]);
            }
            combo_user.SelectedIndex = 0;
            /*
            string searchdb = "`list_name`, `date`, `date_res`, `charge`, `work_name`, " +
                              "`work_way`, `send_way`, `total`, `stock_money`, `vol`, " +
                              "`stock`, `unstock`, `list_num`, `chk_marc`";
            string[] searchdb1 = { "comp_num", "state" };
            string[] searchdb2 = { compidx, "진행" };
            db_tmp = db.More_DB_Search("Obj_List", searchdb1, searchdb2, searchdb);
            Made_Grid(db_tmp);
            dataGridView1.Focus();
            infor_Update(0);*/
        }
        /// <summary>
        /// 표에 값을 채우는 함수.
        /// </summary>
        /// <param name="tmp">분할을 하지않은 데이터베이스 값</param>
        private void Made_Grid(string tmp)
        {
            dataGridView1.Rows.Clear();
            string[] db_data = tmp.Split('|');
            string[] grid = {"", "", "", "", "",
                             "", "", "", "", "",
                             "", "", "", "", "", "" };
            for (int a = 0; a < db_data.Length; a++)
            {
                if (a % 14 == 0)  { grid[0] = db_data[a]; }
                if (a % 14 == 1)  {
                    if (db_data[a].Length < 3) {
                        grid[1] = db_data[a];
                    }
                    else { grid[1] = db_data[a].Substring(0, 10); }
                    grid[1] = db_data[a]; }
                if (a % 14 == 2) {
                    if (db_data[a].Length < 3) {
                        grid[2] = db_data[a];
                    }
                    else { grid[2] = db_data[a].Substring(0, 10); }
                }
                if (a % 14 == 3)  { grid[3] = db_data[a]; }
                if (a % 14 == 4)  { grid[4] = db_data[a]; }
                if (a % 14 == 5)  { grid[5] = db_data[a]; }
                if (a % 14 == 6)  { grid[6] = db_data[a]; }
                if (a % 14 == 7)  { grid[7] = db_data[a]; }
                if (a % 14 == 8)  { grid[8] = db_data[a]; }
                if (a % 14 == 9)  { grid[9] = db_data[a]; }
                if (a % 14 == 10) { grid[10] = db_data[a]; }
                if (a % 14 == 11) { grid[11] = db_data[a]; }
                if (a % 14 == 12) { grid[14] = db_data[a]; }
                if (a % 14 == 13) { 
                    grid[15] = db_data[a];
                    if (Grid_filter(grid)) {
                        dataGridView1.Rows.Add(grid);
                    }
                }
            }
            GridColorChange();
        }
        private bool Grid_filter(string[] arr)
        {
            String_Text st = new String_Text();
            string db_clt = st.GetMiddelString(arr[0], "[", "]");
            string cb_year = combo_year.SelectedItem.ToString();
            string db_year = arr[1].Substring(0, 4);
            if (combo_state.SelectedIndex == 1) {
                if (cb_year != db_year) {
                    MessageBox.Show("연도 컷");
                    return false;
                }
            }
            if (combo_user.SelectedIndex != 0) {
                if (combo_user.SelectedItem.ToString() != arr[3]) {
                    MessageBox.Show("사용자 컷");
                    return false;
                }
            }
            if (tb_clt.Text != "") {
                if(tb_clt.Text == db_clt) {
                    return true;
                }
                MessageBox.Show("거래처 컷");
                return false;
            }
            return true;
        }
        private void btn_lookup_Click(object sender, EventArgs e)   // 조회
        {
            /// 목록명 / 목록일자 / 완료일자 / 담당자 / 작업명
            /// 작업방법 / 배송방법 / 합계금액 / 입고금액 / 수량
            /// 입고 / 미입고 / 목록번호 / 마크여부
            string searchdb = "`list_name`, `date`, `date_res`, `charge`, `work_name`, " +
                              "`work_way`, `send_way`, `total`, `stock_money`, `vol`, " +
                              "`stock`, `unstock`, `list_num`, `chk_marc`";
            List<string> search_L_tbl = new List<string>();
            List<string> search_L_col = new List<string>();

            search_L_tbl.Add("comp_num");
            search_L_col.Add(compidx);

            if (combo_state.SelectedItem.ToString() != "전체") {
                search_L_tbl.Add("state");
                search_L_col.Add(combo_state.SelectedItem.ToString());
            }

            string[] searchdb1 = search_L_tbl.ToArray();
            string[] searchdb2 = search_L_col.ToArray();

            db_tmp = db.More_DB_Search("Obj_List", searchdb1, searchdb2, searchdb);
            Made_Grid(db_tmp);
            dataGridView1.Focus();
        }
        private void btn_save_Click(object sender, EventArgs e)     // 저장
        {
            string table = "Obj_List";
            string[] Edit_col = { "work_name", "work_way", "send_way" };
            string[] Search_col = { "list_name", "total" };
            string edit1, edit2, edit3;
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if(dataGridView1.Rows[a].Cells["work_name"].Value.ToString() == null) { edit1 = ""; }
                else { edit1 = dataGridView1.Rows[a].Cells["work_name"].Value.ToString(); }

                if(dataGridView1.Rows[a].Cells["work_way"].Value.ToString() == null) { edit2 = ""; }
                else { edit2 = dataGridView1.Rows[a].Cells["work_way"].Value.ToString(); }

                if(dataGridView1.Rows[a].Cells["send_way"].Value.ToString() == null) { edit3 = ""; }
                else { edit3 = dataGridView1.Rows[a].Cells["send_way"].Value.ToString(); }

                string[] Edit_Data = { edit1, edit2, edit3 };
                string[] Search_Data = {dataGridView1.Rows[a].Cells["list_name"].Value.ToString(),
                                        dataGridView1.Rows[a].Cells["total"].Value.ToString()};
                db.More_Update(table, Edit_col, Edit_Data, Search_col, Search_Data);
            }
        }
        private void btn_process_Click(object sender, EventArgs e)  // 완료처리
        {
            string table = "Obj_List";
            string[] Edit_col = { "state" };
            string[] Search_col = { "list_name", "total" };
            string[] Edit_Data = { "완료" };

            int cout = 0;
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                bool isChecked = Convert.ToBoolean(dataGridView1.Rows[a].Cells["Chk_Column"].Value);
                if (isChecked)
                {
                    if (cout == 0) { EditNumber = a; cout++; }
                    string[] Search_Data = { dataGridView1.Rows[a].Cells["list_name"].Value.ToString(),
                                             dataGridView1.Rows[a].Cells["total"].Value.ToString()};
                    db.More_Update(table, Edit_col, Edit_Data, Search_col, Search_Data);
                }
            }
            if (cout == 0) { MessageBox.Show("체크된 사항이 없습니다."); return; }
            else { btn_lookup_Click(null, null); }
        }
        int cnt = 0; int pageNo = 1;
        private void btn_print_Click(object sender, EventArgs e)    // 인쇄
        {
            // TODO: 별도의 인쇄폼이 만들어져야함. (미리보기 구현 수정해야함)
            // 08.18 TODO: 인쇄 보류.
            //MessageBox.Show("보류");
            //return;

            printPreviewDialog1.Document = printDocument1;
            printDocument1.DefaultPageSettings.Landscape = false;
            if (printPreviewDialog1.ShowDialog() == DialogResult.Cancel)
            {
                cnt = 0;
                pageNo = 1;
            }
        }
        private void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
        {
            int dialogWidth = 528;  // 페이지 전체넓이 printPreviewDialog.Width

            StringFormat sf = new StringFormat();   // 컬럼 안에 있는 값들 가운데 정렬
            sf.Alignment = StringAlignment.Center;
            int width, width1;      // 시작점위치, datagrid 1개의 컬럼 가로길이
            int startWidth = 10;    // 시작 x좌표
            int startHeight = 140;  // 시작 y좌표
            int avgHeight = dataGridView1.Rows[0].Height;   // gridview 컬럼 하나의 높이
            int temp = 0;

            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 i = 0; i < dataGridView1.ColumnCount; i++)
            {
                if (i == 0)
                {
                    width = 0;
                    width1 = this.dataGridView1.Columns[i].Width + 15;
                }
                else if (i >= 1 && i < dataGridView1.ColumnCount - 2)
                {
                    width = this.dataGridView1.Columns[i - 1].Width + 15;
                    width1 = this.dataGridView1.Columns[i].Width + 15;
                }
                else
                {
                    width = this.dataGridView1.Columns[i - 1].Width + 15;
                    width1 = this.dataGridView1.Columns[i].Width + 40;
                }
                RectangleF drawRect = new RectangleF((float)(startWidth + width), (float)startHeight, (float)width1, avgHeight);
                e.Graphics.DrawRectangle(Pens.Black, (float)(startWidth + width), (float)startHeight, (float)width1, avgHeight);
                e.Graphics.DrawString(dataGridView1.Columns[i].HeaderText, new Font("Arial", 12, FontStyle.Bold), Brushes.Black, drawRect, sf);

                startWidth += width;
            }
            startHeight += avgHeight;

            for (int i = cnt; i < dataGridView1.RowCount - 1; i++) {
                startWidth = 10;
                for(int j = 0; j < dataGridView1.ColumnCount; j++) {
                    if (j == 0) {
                        width = 0;
                        width1 = this.dataGridView1.Columns[j].Width + 15;
                    }
                    else if (j >= 1 && j <= dataGridView1.ColumnCount - 2)
                    {
                        width = this.dataGridView1.Columns[j - 1].Width + 15;
                        width1 = this.dataGridView1.Columns[j].Width + 15;
                    }
                    else
                    {
                        width = this.dataGridView1.Columns[j - 1].Width + 15;
                        width1 = this.dataGridView1.Columns[j].Width + 40;
                    }
                    RectangleF drawRect = new RectangleF((float)(startWidth + width), (float)startHeight, (float)width1, avgHeight);
                    e.Graphics.DrawRectangle(Pens.Black, (float)(startWidth + width), (float)startHeight, (float)width1, avgHeight);
                    e.Graphics.DrawString(dataGridView1.Rows[i].Cells[j].FormattedValue.ToString(), new Font("Arial", 9), Brushes.Black, drawRect, sf);
                    startWidth += width;
                }
                startHeight += avgHeight;
                temp++;
                cnt++;

                if (temp % 40 == 0)
                {
                    MessageBox.Show("40으로 나눠졌다.");
                    e.HasMorePages = true;
                    pageNo++;
                    return;
                }
            }
        }
        private void btn_apply_Click(object sender, EventArgs e)
        {
            dataGridView1.Rows[row].Cells["list_name"].Value = tb_list_name.Text;
            dataGridView1.Rows[row].Cells["list_date"].Value = tb_date.Text;
            dataGridView1.Rows[row].Cells["date_res"].Value = tb_date_res.Text;
            dataGridView1.Rows[row].Cells["charge"].Value = tb_charge.Text;
            dataGridView1.Rows[row].Cells["work_name"].Value = tb_work_name.Text;
            dataGridView1.Rows[row].Cells["work_way"].Value = tb_work_way.Text;
            dataGridView1.Rows[row].Cells["send_way"].Value = tb_send_way.Text;
            dataGridView1.Rows[row].Cells["total"].Value = tb_total.Text;
            dataGridView1.Rows[row].Cells["stock_money"].Value = tb_stock.Text;
            dataGridView1.Rows[row].Cells["count"].Value = tb_count.Text;
            dataGridView1.Rows[row].Cells["Column13"].Value = tb_stock_per.Text;
            dataGridView1.Rows[row].Cells["Column11"].Value = lbl_stock_count.Text;
            dataGridView1.Rows[row].Cells["Column12"].Value = lbl_unstock_count.Text;
            dataGridView1.Rows[row].Cells["Column20"].Value = tb_list_num.Text;
        }
        private void btn_checkup_Click(object sender, EventArgs e)  // 검수작업 (내부 작업필요)
        {
            List_Chk_Work chk_work = new List_Chk_Work(this);
            chk_work.TopMost = true;
            chk_work.data[0] = tb_list_name.Text;
            chk_work.data[1] = compidx;
            chk_work.Show();
        }
        private void btn_ISBN_Click(object sender, EventArgs e)     // ISBN조회
        {
            Check_ISBN isbn = new Check_ISBN(this);
            isbn.list_name = tb_list_name.Text;
            isbn.Show();
        }
        private void btn_date_Click(object sender, EventArgs e)     // 일정
        {
            // TODO: 별도의 일정폼이 만들어져야함.
        }

        //////////////////////////////////////////////////////////////////////////////////////

        private void tb_clt_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                Commodity_Search sea = new Commodity_Search(this);
                sea.Clinet_name = tb_clt.Text;
                sea.Show();
            }
        }
        private void combo_state_SelectedIndexChanged(object sender, EventArgs e)
        {
            if(combo_state.Text == "진행")
            {
                combo_year.Visible = false;
            }
            else if(combo_state.Text == "완료")
            {
                combo_year.Visible = true;
            }
        }
        /// <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["chk_label"].Value.ToString() == "라벨")
                {
                    dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Yellow;
                }
            }
        }
        private void btn_close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            Skill_Grid skill = new Skill_Grid();
            if(e.KeyCode == Keys.Delete)
            {
                skill.DataGrid_to_Delete(sender, e);
            }

            // gird 선택시 우측란에 해당 정보로 초기화 및 최신화
            if(e.KeyCode == Keys.Up)
            {
                if (row > 0) { row -= 1; }
                infor_Update(row);
            }
            if (e.KeyCode == Keys.Down)
            {
                if (row < dataGridView1.Rows.Count-1) { row += 1; }
                infor_Update(row);
            }
        }
        private void infor_reset()
        {
            tb_list_name.Text = "";
            tb_date.Text = "";
            tb_date_res.Text = "";
            tb_charge.Text = "";
            tb_work_name.Text = "";
            tb_work_way.Text = "";
            tb_send_way.Text = "";
            tb_total.Text = "";
            tb_stock.Text = "";
            tb_count.Text = "";
            tb_stock_per.Text = "";
            lbl_stock_count.Text = "";
            lbl_unstock_count.Text = "";
            tb_list_num.Text = "";
        }
        private void infor_Update(int rowidx)
        {
            if (rowidx < 0) { return; }
            row = rowidx;
            infor_reset();
            // 목록명
            tb_list_name.Text = dataGridView1.Rows[rowidx].Cells["list_name"].Value.ToString();
            // 목록일자
            tb_date.Text = dataGridView1.Rows[rowidx].Cells["list_date"].Value.ToString().Substring(0,10);
            // 완료일자
            if (dataGridView1.Rows[rowidx].Cells["date_res"].Value.ToString().Length < 3) {
                tb_date_res.Text = "";
            }
            else {
                tb_date_res.Text = dataGridView1.Rows[rowidx].Cells["date_res"].Value.ToString().Substring(0, 10);
            }
            // 담당자
            tb_charge.Text = dataGridView1.Rows[rowidx].Cells["charge"].Value.ToString();
            // 작업명
            tb_work_name.Text = dataGridView1.Rows[rowidx].Cells["work_name"].Value.ToString();
            // 작업방법
            tb_work_way.Text = dataGridView1.Rows[rowidx].Cells["work_way"].Value.ToString();
            // 배송방법
            tb_send_way.Text = dataGridView1.Rows[rowidx].Cells["send_way"].Value.ToString();
            // 합계금액
            tb_total.Text = dataGridView1.Rows[rowidx].Cells["total"].Value.ToString();
            // 입고금액
            tb_stock.Text = dataGridView1.Rows[rowidx].Cells["stock_money"].Value.ToString();
            // 수량
            tb_count.Text = dataGridView1.Rows[rowidx].Cells["count"].Value.ToString();
            // 입고 / 미입고
            lbl_stock_count.Text = dataGridView1.Rows[rowidx].Cells["Column11"].Value.ToString();
            lbl_unstock_count.Text = dataGridView1.Rows[rowidx].Cells["Column12"].Value.ToString();
            // 입고율
            tb_stock_per.Text = dataGridView1.Rows[rowidx].Cells["Column13"].Value.ToString();
            // 목록번호
            tb_list_num.Text = dataGridView1.Rows[rowidx].Cells["Column20"].Value.ToString();
            // 택배여부
            if(dataGridView1.Rows[rowidx].Cells["Column18"].Value.ToString() == "") {
                lbl_send_n.Font = new Font(this.Font, FontStyle.Bold);
                lbl_send_y.Font = new Font(this.Font, FontStyle.Regular);
            }
            else { lbl_send_y.Font = new Font(this.Font, FontStyle.Bold); 
                lbl_send_n.Font = new Font(this.Font, FontStyle.Regular);
            }
            // 라벨여부
            if (dataGridView1.Rows[rowidx].Cells["chk_label"].Value.ToString() == "라벨") {
                lbl_l_y.Font = new Font(this.Font, FontStyle.Bold);
                lbl_l_n.Font = new Font(this.Font, FontStyle.Regular);
            }
            else { lbl_l_n.Font = new Font(this.Font, FontStyle.Bold);
                lbl_l_y.Font = new Font(this.Font, FontStyle.Regular);
            }
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex != 2 || e.ColumnIndex != 4 || e.ColumnIndex != 5 || 
                e.ColumnIndex != 6 || e.ColumnIndex != 15)
            {
                List_Lookup list_l = new List_Lookup(this);
                list_l.call_base = dataGridView1.Rows[e.RowIndex].Cells["list_name"].Value.ToString();
                list_l.MdiParent = main;
                list_l.WindowState = FormWindowState.Maximized;
                list_l.Show();
            }
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            row = e.RowIndex;
            infor_Update(e.RowIndex);
        }

        private void lbl_l_y_Click(object sender, EventArgs e)
        {
            if(((Label)sender).Name == "lbl_l_y") {
                lbl_l_y.Font = new Font(this.Font, FontStyle.Bold);
                lbl_l_n.Font = new Font(this.Font, FontStyle.Regular);
            }
            if(((Label)sender).Name == "lbl_l_n") {
                lbl_l_y.Font = new Font(this.Font, FontStyle.Regular);
                lbl_l_n.Font = new Font(this.Font, FontStyle.Bold);
            }
            if(((Label)sender).Name == "lbl_send_y")
            {
                lbl_send_y.Font = new Font(this.Font, FontStyle.Bold);
                lbl_send_n.Font = new Font(this.Font, FontStyle.Regular);
            }
            if (((Label)sender).Name == "lbl_send_n")
            {
                lbl_send_y.Font = new Font(this.Font, FontStyle.Regular);
                lbl_send_n.Font = new Font(this.Font, FontStyle.Bold);
            }
        }

    }
}
