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

namespace WindowsFormsApp1.Mac
{
    public partial class Mac_List : Form
    {
        Helper_DB db = new Helper_DB();
        Main main;
        public string compidx;
        public Mac_List(Main _main)
        {
            InitializeComponent();
            main = _main;
            compidx = main.com_idx;
        }
        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["grade"].ReadOnly = false;
            dataGridView1.Columns["etc"].ReadOnly = false;
            dataGridView1.Columns["charge"].ReadOnly = false;
        }
        private void tb_Search_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                btn_Lookup_Click(null, null);
            }
        }
        private void btn_Lookup_Click(object sender, EventArgs e)
        {
            string table = "Obj_List_Marc";
                        /* 목록일자 / 완료일자 / 마크목록명 / Obj_List목록명 / KDC분류
                         * 전체 / 편목 / 미편목 / 상태 / 등급
                         * 비고 / 마크담당자 */
            string Area = "`idx`, `date`, `date_res`, `list_name`, `connect_data`, " +
                          "`KDC`, `total`, `flatter`, `unflatter`, `state`, " +
                          "`grade`, `etc`, `m_charge`";
            string search = tb_Search.Text;
            string state = cb_state.Text;

            string db_data = db.DB_Contains(table, compidx, "list_name", search, Area, "state", state);
            string[] data = db_data.Split('|');

            input_Grid(data);
        }
        /// <summary>
        /// Grid에 데이터를 집어넣는 함수.
        /// </summary>
        /// <param name="data"></param>
        private void input_Grid(string[] data)
        {
            /* 등록일 / 마감일 / 작업목록명 / 연동목록명(H) / 분류
             * 전체 / 편목 / 미편목 / 상태 / 등급
             * 비고 / 담당자 / V */
            string[] grid = { "", "", "", "", "",
                              "", "", "", "", "",
                              "", "", "", "" };
            int area_count = 13;
            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]; }
                if (a % area_count == 11) { grid[11] = data[a];
                    dataGridView1.Rows.Add(grid); 
                }
            }
        }
        private void btn_Save_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("선택사항을 저장하시겠습니까?", "저장", MessageBoxButtons.YesNo) == DialogResult.No) {
                return;
            }
            string table = "Obj_List_Marc";
            for (int a = 0; a < dataGridView1.Rows.Count - 1; a++)
            {
                if (dataGridView1.Rows[a].Cells["chk_V"].Value.ToString() == "V") {
                    string[] edit_col = { "date", "date_res", "list_name", "KDC", "total", 
                                          "flatter", "unflatter", "state", "grade", "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_marc"].Value.ToString(),
                                          dataGridView1.Rows[a].Cells["KDC"].Value.ToString(),
                                          dataGridView1.Rows[a].Cells["total"].Value.ToString(),

                                          dataGridView1.Rows[a].Cells["flatter"].Value.ToString(),
                                          dataGridView1.Rows[a].Cells["unflatter"].Value.ToString(),
                                          dataGridView1.Rows[a].Cells["state"].Value.ToString(),
                                          dataGridView1.Rows[a].Cells["grade"].Value.ToString(),
                                          dataGridView1.Rows[a].Cells["etc"].Value.ToString(),

                                          dataGridView1.Rows[a].Cells["charge"].Value.ToString() };
                    string[] sear_col = { "idx", "compidx" };
                    string[] sear_tbl = { dataGridView1.Rows[a].Cells["idx"].Value.ToString(), compidx };

                    db.More_Update(table, edit_col, edit_tbl, sear_col, sear_tbl);
                }
            }
            MessageBox.Show("저장되었습니다!");
        }
        private void btn_Excel_Click(object sender, EventArgs e)
        {
            // TODO: 현재 권한 설정때문에 테스트불가.
            /*
            Skill_Grid sg = new Skill_Grid();
            sg.ExcelCreate(dataGridView1, saveFileDialog1);
            MessageBox.Show("엑셀로 저장되었습니다!");
            */
        }
        private void btn_Merge_Click(object sender, EventArgs e)
        {
            Mac_List_Merge merge = new Mac_List_Merge(this);
            merge.Show();
        }
        private void btn_Progress_Click(object sender, EventArgs e)
        {
            for(int a = 0; a < dataGridView1.Rows.Count - 1; a++)
            {
                if (dataGridView1.Rows[a].Cells["chk_V"].Value.ToString() == "V") {
                    if (dataGridView1.Rows[a].Cells["state"].Value.ToString() == "진행") {
                        MessageBox.Show("체크된 목록이 현재 진행중입니다.");
                        return;
                    }
                }
            }
            for(int a= 0; a < dataGridView1.Rows.Count - 1; a++)
            {
                if (dataGridView1.Rows[a].Cells["chk_V"].Value.ToString() == "V") {
                    if (dataGridView1.Rows[a].Cells["state"].Value.ToString() == "완료") {
                        dataGridView1.Rows[a].Cells["state"].Value = "진행";
                        state_Save(a);
                    }
                }
            }
            MessageBox.Show("진행처리되었습니다.", "목록진행");
        }
        /// <summary>
        /// 목록의 상태를 바꾸기 위한 함수.
        /// DB내 적용됨.
        /// </summary>
        /// <param name="count"></param>
        void state_Save(int count)
        {
            string[] edit_col = { "state" };
            string[] edit_tbl = { dataGridView1.Rows[count].Cells["state"].Value.ToString() };
            string[] sear_col = { "idx", "compidx" };
            string[] sear_tbl = { dataGridView1.Rows[count].Cells["idx"].Value.ToString(), compidx };
            db.More_Update("Obj_List_Marc", edit_col, edit_tbl, sear_col, sear_tbl);
        }
        private void btn_Completion_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count - 1; a++)
            {
                if (dataGridView1.Rows[a].Cells["chk_V"].Value.ToString() == "V") {
                    if (dataGridView1.Rows[a].Cells["state"].Value.ToString() == "완료") {
                        MessageBox.Show("체크된 목록은 현재 완료되었습니다.");
                        return;
                    }
                }
            }
            for (int a = 0; a < dataGridView1.Rows.Count - 1; a++)
            {
                if (dataGridView1.Rows[a].Cells["chk_V"].Value.ToString() == "V") {
                    if (dataGridView1.Rows[a].Cells["state"].Value.ToString() == "진행") {
                        dataGridView1.Rows[a].Cells["state"].Value = "완료";
                        state_Save(a);
                    }
                }
            }
            MessageBox.Show("완료처리되었습니다.", "목록완료");
        }
        private void btn_Delete_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count - 1; a++)
            {
                if (dataGridView1.Rows[a].Cells["chk_V"].Value.ToString() == "V") {
                    db.DB_Delete("Obj_List_Marc", "compidx", compidx, 
                        "idx", dataGridView1.Rows[a].Cells["idx"].Value.ToString());
                }
            }
        }
        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int idx_col = e.ColumnIndex;
            if(idx_col == 13)
            {
                if (((DataGridView)sender).SelectedCells[idx_col].Value.ToString() == "V") {
                    ((DataGridView)sender).SelectedCells[idx_col].Value = "";
                }
                else {
                    ((DataGridView)sender).SelectedCells[idx_col].Value = "V";
                }
            }
        }
        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();
                marc.WindowState = FormWindowState.Maximized;
                marc.Show();
                marc.input_list(dataGridView1.Rows[idx_row].Cells[1].Value.ToString(), 
                    dataGridView1.Rows[idx_row].Cells[4].Value.ToString());
                
            }
        }
    }
}
