using AR;
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;

namespace UniMarc
{
    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 = PUB.user.CompanyIdx;
            user_name = PUB.user.UserName;

            dataGridView1.AutoGenerateColumns = false;
            dataGridView1.DataSource = bs1;
        }
        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;
            dataGridView1.Columns["check"].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`,GetClientName({compidx},customer) as custname, `list_name`, `work_name`, " +
                          "`vol`, `stock`, `unstock`, `state`, `m_etc`,`m_charge`,`customer` ";
            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);
            
            DataTable dt = Helper_DB.ExecuteDataTable(cmd);
            List<MacListItem> items = new List<MacListItem>();

            if (dt == null || dt.Rows.Count == 0)
            {
                bs1.DataSource = items;
                return;
            }

            foreach (DataRow row in dt.Rows)
            {
                items.Add(new MacListItem
                {
                    idx = row["idx"].ToString(),
                    start_date = row["date"].ToString(),
                    end_date = row["date_res"].ToString(),
                    customer_name = row["custname"]?.ToString() ?? string.Empty,
                    list_name = row["list_name"].ToString(),
                    work_name = row["work_name"].ToString(),
                    count = row["vol"].ToString(),
                    stock = row["stock"].ToString(),
                    unstock = row["unstock"].ToString(),
                    state = row["state"].ToString(),
                    etc = row["m_etc"].ToString(),
                    charge = row["m_charge"].ToString(),
                    customer = row["customer"]?.ToString() ?? string.Empty,
                    check = ""
                });
            }
            bs1.DataSource = items;
        }

      
       
        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 (UTIL.MsgQ("선택사항을 저장하시겠습니까?") == DialogResult.No)
                return;

            string table = "Obj_List";
            string[] edit_col = { "date_res", "work_name", "m_etc" };

            List<MacListItem> items = bs1.List.Cast<MacListItem>().ToList();

            foreach (var item in items)
            {
                if (item.check == "V")
                {
                    string[] edit_tbl = { item.end_date, item.work_name, item.etc };
                    string[] sear_col = { "idx", "comp_num" };
                    string[] sear_tbl = { item.idx, compidx };

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

                    item.check = "";
                }
            }
            bs1.ResetBindings(false);
            UTIL.MsgI("저장되었습니다!");
        }

        private void btn_Excel_Click(object sender, EventArgs e)
        {
            Excel_text et = new Excel_text();
            string[] Excel_title = {
                "NO", "목록일자", "완료일자", "납품처","목록명", "마크담당자",
                "작업명", "수량", "상태", "비고" };

            List<MacListItem> items = bs1.List.Cast<MacListItem>().ToList();
            int rowCount = items.Count;
            string[,] inputExcel = new string[rowCount, 10];

            for (int a = 0; a < rowCount; a++)
            {
                var item = items[a];
                var seq = 0;
                inputExcel[a, seq++] = (a + 1).ToString();
                inputExcel[a, seq++] = item.start_date;
                inputExcel[a, seq++] = item.end_date;
                inputExcel[a, seq++] = item.customer_name ?? "";
                inputExcel[a, seq++] = item.list_name;
                inputExcel[a, seq++] = item.charge;
                inputExcel[a, seq++] = item.work_name;
                inputExcel[a, seq++] = item.count;
                inputExcel[a, seq++] = item.state;
                inputExcel[a, seq++] = item.etc;
            }
            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.Show();
        }

        private void btn_Progress_Click(object sender, EventArgs e)
        {
            List<MacListItem> items = bs1.List.Cast<MacListItem>().ToList();
            bool hasProgress = items.Any(i => i.check == "V" && i.state == "진행");
            if (hasProgress)
            {
                UTIL.MsgE("체크된 목록이 현재 진행중입니다.");
                return;
            }

            foreach (var item in items.Where(i => i.check == "V" && i.state == "완료"))
            {
                item.state = "진행";
                state_Save_Object(item);
            }

            UTIL.MsgI("진행처리되었습니다.");
            btn_Lookup_Click(null, null);
        }

        private void btn_Completion_Click(object sender, EventArgs e)
        {
            List<MacListItem> items = bs1.List.Cast<MacListItem>().ToList();
            bool hasCompletion = items.Any(i => i.check == "V" && i.state == "완료");
            if (hasCompletion)
            {
                UTIL.MsgE("체크된 목록은 현재 완료되어있습니다.");
                return;
            }

            foreach (var item in items.Where(i => i.check == "V" && i.state == "진행"))
            {
                item.state = "완료";
                state_Save_Object(item);
            }

            UTIL.MsgI("완료처리되었습니다.");
            btn_Lookup_Click(null, null);
        }

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

        void state_Save_Object(MacListItem item)
        {
            string[] edit_col = { "state" };
            string[] edit_tbl = { item.state };
            string[] sear_col = { "idx", "comp_num" };
            string[] sear_tbl = { item.idx, compidx };
            string U_cmd = db.More_Update("Obj_List", edit_col, edit_tbl, sear_col, sear_tbl);
            Helper_DB.ExcuteNonQuery(U_cmd);
        }

        void state_Save(int row)
        {
            // Deprecated
        }
        #endregion

        private void btn_Delete_Click(object sender, EventArgs e)
        {
            if (UTIL.MsgQ("정말로 삭제하시겠습니까?") == DialogResult.No) { return; }

            List<MacListItem> items = bs1.List.Cast<MacListItem>().ToList();
            foreach (var item in items.Where(i => i.check == "V"))
            {
                string l_idx = item.idx;
                string D_cmd = db.DB_Delete("Obj_List", "comp_num", compidx, "idx", l_idx);
                Helper_DB.ExcuteNonQuery(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);
                Helper_DB.ExcuteNonQuery(D_cmd);
            }

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

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

        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex < 0) return;

            var item = bs1[e.RowIndex] as MacListItem;
            if (item == null) return;

            int idx_col = e.ColumnIndex;
            if (3 <= idx_col && idx_col <= 8)
            {
                if (chkEditorTest.Checked == false)
                {
                    var marc = this.main.OpenFormInTab(() => new Marc2(item), allowMultiple: true);
                }
                else
                {
                    var marc = this.main.OpenFormInTab(() => new Marc(this), allowMultiple: true);
                    marc.input_list(
                        item.idx,
                        item.list_name,
                        compidx,
                        item.customer,
                        item.customer_name
                        );
                }
            }
            if (dataGridView1.Columns[idx_col].Name == "check")
            {
                item.check = (item.check == "V") ? "" : "V";
                bs1.ResetItem(e.RowIndex);
            }
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Space)
            {
                var item = bs1.Current as MacListItem;
                if (item != null)
                {
                    item.check = (item.check == "V") ? "" : "V";
                    bs1.ResetCurrentItem();
                }
            }
        }

        private void dataGridView1_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Skill_Grid sg = new Skill_Grid();
            sg.Print_Grid_Num(sender, e);
        }

        private void btnSearchISBN_Click(object sender, EventArgs e)
        {
            var item = bs1.Current as MacListItem;
            if (item == null) return;
            string tSearchText = item.list_name;
            string tSearchIDX = item.idx;
            var isbn = main.OpenFormInTab(() => new Check_ISBN(main, tSearchText, tSearchIDX));
            isbn.tb_list_name.Enabled = true;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var listAdd = new Mac_List_Add2(this);

            listAdd.Show();
        }

        private void btEdit_Click(object sender, EventArgs e)
        {
            var item = bs1.Current as MacListItem;
            if (item == null)
            {
                UTIL.MsgE("대상을 먼저 선택하세요.");
                return;
            }

            using (var edit = new Mac_List_Edit(this, item))
            {
                if (edit.ShowDialog() == DialogResult.OK)
                {
                    btn_Lookup_Click(null, null);
                }
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            var item = bs1.Current as MacListItem;
            if (item == null) return;
            string tSearchText = item.list_name;
            string tSearchIDX = item.idx;
            var isbn = main.OpenFormInTab(() => new Check_ISBN2( tSearchText, tSearchIDX));
            isbn.tb_list_name.Enabled = true;
        }
    }
}
