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 UniMarc.마크;
using WindowsFormsApp1.마크;

namespace WindowsFormsApp1.Mac
{
    public partial class Mac_List : Form
    {
        Helper_DB db = new Helper_DB();
        Main main;
        public string compidx;
        public string user_name;
        public Mac_List(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = main.com_idx;
            user_name = main.botUserLabel.Text;
        }
        private void Mac_List_Load(object sender, EventArgs e)
        {
            db.DBcon();

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

            // 마감일 등급 비고 제외한 나머지 수정불가.
            for (int a = 0; a < dataGridView1.Columns.Count; a++)
            {
                dataGridView1.Columns[a].ReadOnly = true;
            }
            dataGridView1.Columns["end_date"].ReadOnly = false;
            dataGridView1.Columns["work_name"].ReadOnly = false;
            dataGridView1.Columns["etc"].ReadOnly = false;
        }
        private void tb_Search_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                btn_Lookup_Click(null, null);
            }
        }

        public void btn_Lookup_Click(object sender, EventArgs e)
        {
            string table = "Obj_List";
            /* idx / 목록일자 / 완료일자 / 목록명 / 작업명
             * 전체수량 / 입고 / 미입고 / 상태 / 비고
             * 마크담당자 */
            string Area = "`idx`, `date`, `date_res`, `list_name`, `work_name`, " +
                          "`vol`, `stock`, `unstock`, `state`, `m_etc`, " +
                          "`m_charge`";
            string search = tb_Search.Text;
            string state = cb_state.Text;

            string cmd = string.Format(
                "SELECT {0} " +
                "FROM `{1}` " +
                "WHERE `comp_num` = {2} " +
                "AND `list_name` LIKE \"%{3}%\" " +
                "AND `state` = \"{4}\" " +
                "AND `chk_marc` > 0;",
                Area, table, compidx, search, state);
            string db_res = db.DB_Send_CMD_Search(cmd);
            string[] data = db_res.Split('|');

            input_Grid(data);
        }

        #region 목록조회 서브함수

        /// <summary>
        /// Grid에 데이터를 집어넣는 함수.
        /// </summary>
        /// <param name="data"></param>
        private void input_Grid(string[] data)
        {
            /* idx / 목록일자 / 완료일자 / 목록명 / 작업명
             * 전체수량 / 입고 / 미입고 / 상태 / 비고
             * 마크담당자 */

            string[] grid = { "", "", "", "", "",
                              "", "", "", "", "",
                              "", "" };
            int area_count = 11;
            dataGridView1.Rows.Clear();
            for (int a = 0; a < data.Length; a++)
            {
                if (a % area_count == 0) { grid[0] = data[a]; }
                if (a % area_count == 1) { grid[1] = data[a]; }
                if (a % area_count == 2) { grid[2] = data[a]; }
                if (a % area_count == 3) { grid[3] = data[a]; }
                if (a % area_count == 4) { grid[4] = data[a]; }
                if (a % area_count == 5) { grid[5] = data[a]; }
                if (a % area_count == 6) { grid[6] = data[a]; }
                if (a % area_count == 7) { grid[7] = data[a]; }
                if (a % area_count == 8) { grid[8] = data[a]; }
                if (a % area_count == 9) { grid[9] = data[a]; }
                if (a % area_count == 10) { grid[10] = data[a];
                    dataGridView1.Rows.Add(grid); 
                }
            }
        }
        #endregion

        private void btn_AddList_Click(object sender, EventArgs e)
        {
            Mac_List_Add listAdd = new Mac_List_Add(this);

            listAdd.Show();
        }

        private void btn_Save_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("선택사항을 저장하시겠습니까?", "저장", MessageBoxButtons.YesNo) == DialogResult.No)
                return;
            
            string table = "Obj_List";
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["check"].Value.ToString() == "V") {
                    string[] edit_col = {
                        "date", "date_res", "list_name", "work_name", "vol", 
                        "stock", "unstock", "state", "m_etc", "m_charge"
                    };
                    string[] edit_tbl = {
                        dataGridView1.Rows[a].Cells["start_date"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["end_date"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["list_name"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["work_name"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["count"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["stock"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["unstock"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["state"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["etc"].Value.ToString(),
                        dataGridView1.Rows[a].Cells["charge"].Value.ToString()
                    };
                    string[] sear_col = { "idx", "comp_num" };
                    string[] sear_tbl = { dataGridView1.Rows[a].Cells["idx"].Value.ToString(), compidx };

                    string U_cmd = db.More_Update(table, edit_col, edit_tbl, sear_col, sear_tbl);
                    db.DB_Send_CMD_reVoid(U_cmd);

                    dataGridView1.Rows[a].Cells["check"].Value = "";
                }
            }
            MessageBox.Show("저장되었습니다!");
        }

        private void btn_Excel_Click(object sender, EventArgs e)
        {
            Excel_text et = new Excel_text();
            string[] Excel_title = {
                "NO", "목록일자", "완료일자", "목록명", "마크담당자",
                //"작업명", "수량", "입고", "미입고", "상태", "비고" };
                "작업명", "수량", "상태", "비고" };
            int rowCount = dataGridView1.RowCount;
            // string[,] inputExcel = new string[rowCount, 11];
            string[,] inputExcel = new string[rowCount, 9];

            for (int a = 0; a < rowCount; a++)
            {
                int row_idx = dataGridView1.Rows[a].HeaderCell.RowIndex + 1;
                inputExcel[a, 0] = row_idx.ToString();
                inputExcel[a, 1] = dataGridView1.Rows[a].Cells["start_date"].Value.ToString();
                inputExcel[a, 2] = dataGridView1.Rows[a].Cells["end_date"].Value.ToString();
                inputExcel[a, 3] = dataGridView1.Rows[a].Cells["list_name"].Value.ToString();
                inputExcel[a, 4] = dataGridView1.Rows[a].Cells["charge"].Value.ToString();
                inputExcel[a, 5] = dataGridView1.Rows[a].Cells["work_name"].Value.ToString();
                inputExcel[a, 6] = dataGridView1.Rows[a].Cells["count"].Value.ToString();

                inputExcel[a, 7] = dataGridView1.Rows[a].Cells["state"].Value.ToString();
                inputExcel[a, 8] = dataGridView1.Rows[a].Cells["etc"].Value.ToString();

                // inputExcel[a, 7] = dataGridView1.Rows[a].Cells["stock"].Value.ToString();
                // inputExcel[a, 8] = dataGridView1.Rows[a].Cells["unstock"].Value.ToString();
                // inputExcel[a, 9] = dataGridView1.Rows[a].Cells["state"].Value.ToString();
                // inputExcel[a, 10] =dataGridView1.Rows[a].Cells["etc"].Value.ToString();
            }
            et.Mk_Excel(Excel_title, inputExcel);
        }

        private void btn_Merge_Click(object sender, EventArgs e)
        {
            Mac_List_Merge merge = new Mac_List_Merge(this);
            merge.ListState = cb_state.Text;
            merge.UserName = main.User;
            merge.Show();
        }

        private void btn_Progress_Click(object sender, EventArgs e)
        {
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["check"].Value.ToString() == "V") {
                    if (dataGridView1.Rows[a].Cells["state"].Value.ToString() == "진행") {
                        MessageBox.Show("체크된 목록이 현재 진행중입니다.");
                        return;
                    }
                }
            }
            for(int a= 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["check"].Value.ToString() == "V") {
                    if (dataGridView1.Rows[a].Cells["state"].Value.ToString() == "완료") {
                        dataGridView1.Rows[a].Cells["state"].Value = "진행";
                        state_Save(a);
                    }
                }
            }

            MessageBox.Show("진행처리되었습니다.", "목록진행");
            btn_Lookup_Click(null, null);
        }

        private void btn_Completion_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["check"].Value.ToString() == "V") {
                    if (dataGridView1.Rows[a].Cells["state"].Value.ToString() == "완료") {
                        MessageBox.Show("체크된 목록은 현재 완료되어있습니다.");
                        return;
                    }
                }
            }
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["check"].Value.ToString() == "V") {
                    if (dataGridView1.Rows[a].Cells["state"].Value.ToString() == "진행") {
                        dataGridView1.Rows[a].Cells["state"].Value = "완료";
                        state_Save(a);
                    }
                }
            }

            MessageBox.Show("완료처리되었습니다.", "목록완료");
            btn_Lookup_Click(null, null);
        }

        #region 진행/완료처리 서브함수

        /// <summary>
        /// 목록의 상태를 바꾸기 위한 함수.
        /// DB내 적용됨.
        /// </summary>
        /// <param name="count"></param>
        void state_Save(int row)
        {
            string[] edit_col = { "state" };
            string[] edit_tbl = { dataGridView1.Rows[row].Cells["state"].Value.ToString() };
            string[] sear_col = { "idx", "comp_num" };
            string[] sear_tbl = { dataGridView1.Rows[row].Cells["idx"].Value.ToString(), compidx };
            string U_cmd = db.More_Update("Obj_List", edit_col, edit_tbl, sear_col, sear_tbl);
            db.DB_Send_CMD_reVoid(U_cmd);
        }
        #endregion

        private void btn_Delete_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["check"].Value.ToString() == "V") {
                    string l_idx = dataGridView1.Rows[a].Cells["idx"].Value.ToString();
                    string D_cmd = db.DB_Delete("Obj_List", "comp_num", compidx, 
                        "idx", l_idx);
                    db.DB_Send_CMD_reVoid(D_cmd);

                    string[] delete_tbl = { "l_idx" };
                    string[] deleteData = { l_idx };
                    D_cmd = db.DB_Delete_No_Limit("Obj_List_Book", "compidx", compidx, delete_tbl, deleteData);
                    db.DB_Send_CMD_reVoid(D_cmd);
                }
            }

            MessageBox.Show("삭제되었습니다.");
            btn_Lookup_Click(null, null);
        }

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

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int idx_row = e.RowIndex;
            int idx_col = e.ColumnIndex;
            if (3 <= idx_col && idx_col <= 8) {
                ExcelTest.Marc marc = new ExcelTest.Marc(this);
                marc.MdiParent = main;
                marc.WindowState = FormWindowState.Maximized;
                marc.Show();
                marc.input_list(
                    dataGridView1.Rows[idx_row].Cells["idx"].Value.ToString(),
                    dataGridView1.Rows[idx_row].Cells["list_name"].Value.ToString(), compidx);
                /// marc.input_list(
                ///     dataGridView1.Rows[idx_row].Cells["idx"].Value.ToString(),
                ///     dataGridView1.Rows[idx_row].Cells["list_name"].Value.ToString());
            }
            if (((DataGridView)sender).Columns[idx_col].Name == "check")
            {
                if (((DataGridView)sender).Rows[idx_row].Cells[idx_col].Value.ToString() == "V")
                    ((DataGridView)sender).Rows[idx_row].Cells[idx_col].Value = "";

                else
                    ((DataGridView)sender).Rows[idx_row].Cells[idx_col].Value = "V";
            }
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            int row = dataGridView1.CurrentCell.RowIndex;
            int col = dataGridView1.CurrentCell.ColumnIndex;

            if (dataGridView1.Columns[col].Name == "check")
            {
                if (e.KeyCode == Keys.Space)
                {
                    if (dataGridView1.Rows[row].Cells[col].Value.ToString() == "V")
                        dataGridView1.Rows[row].Cells[col].Value = "";

                    else
                        dataGridView1.Rows[row].Cells[col].Value = "V";
                }
            }

        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();
            sg.Print_Grid_Num(sender, e);
        }
        private Check_ISBN mMac_check_ISBN;
        private void btnSearchISBN_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows[0].Index < 0) return;
            string tSearchText = dataGridView1.SelectedRows[0].Cells["list_name"].Value.ToString();
            string tSearchIDX = dataGridView1.SelectedRows[0].Cells["idx"].Value.ToString();
            if (mMac_check_ISBN != null)
            {
                mMac_check_ISBN.Focus();
            }
            else
            {
                mMac_check_ISBN = new Check_ISBN(main, tSearchText, tSearchIDX);
                mMac_check_ISBN.MdiParent = main;
                mMac_check_ISBN.WindowState = FormWindowState.Maximized;
                mMac_check_ISBN.FormClosed += (o, ea) => mMac_check_ISBN = null;
                mMac_check_ISBN.tb_list_name.Enabled = true;
                mMac_check_ISBN.Show();
            }
        }
    }
}
