using AR;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UniMarc
{
    public partial class Commodity_registration : Form
    {
        Skill_Grid skill_Grid = new Skill_Grid();
        Main main;
        Helper_DB db = new Helper_DB();
        public string comp_idx;
        public int EditNumber = 0;
        public int[] MorgeNum = { 0, 0 };
        public string User_Data_temp;
        bool cltchk = false;
        
        public Commodity_registration(Main _main)
        {
            InitializeComponent();
            main = _main;
        }
        private void Commodity_registration_Load(object sender, EventArgs e)
        {
            for(int a = 0; a < 9; a++)
            {
                dataGridView2.Columns[a].ReadOnly = true;
            }
            dataGridView1.CurrentCell = null;
            db.DBcon();
            // dataGridView1.Rows.Add(10000);
            string[] combo = { "진행", "완료" };
            comboBox1.Items.AddRange(combo);
            comboBox1.SelectedIndex = 0;
            if (comboBox1.Text == combo[0])
            {
                btn_Complet.Enabled = true;
                btn_ing.Enabled = false;
            }
            else if (comboBox1.Text == combo[1])
            {
                btn_Complet.Enabled = false;
                btn_ing.Enabled = true;
            }
            User_Data_temp = main.DB_User_Data;
            string[] User_Data = User_Data_temp.Split('|');
            comp_idx = PUB.user.CompanyIdx;

            tb_UserName.Text = User_Data[3];
            Add_Grid("진행");
        }

        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Shift && e.KeyCode == Keys.Insert) || (e.Control && e.KeyCode == Keys.V)) {
                skill_Grid.Excel_to_DataGridView(sender, e);
            }
            else if(e.KeyCode == Keys.Delete) {
                skill_Grid.DataGrid_to_Delete(sender, e);
            }
        }

        private void btn_FileOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();

            openFileDialog1.Filter = "텍스트 파일 (*.txt)|*.txt|모든 파일(*.*)|*.*";
            String file_path = null;
            openFileDialog1.InitialDirectory = "C:\\Users\\Administrator\\Desktop";  // 시작위치 "바탕화면"
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                // 선택된 파일의 풀 경로를 불러와 저장
                file_path = openFileDialog1.FileName;
                // 경로를 텍스트박스에 출력
                tb_FilePath.Text = file_path.Split('\\')[file_path.Split('\\').Length-1];
            }
            if (File.Exists(file_path))
            {
                using (StreamReader sr = new StreamReader(file_path, Encoding.UTF8))
                {
                    // 불러온 파일의 내용을 표에 적용
                    string file_con = sr.ReadToEnd();
                    string[] Cell_result = file_con.Split('\n');
                    for(int a = 0; a < Cell_result.Length; a++)
                    {
                        Cell_result[a] = Cell_result[a].Replace("\r", "");
                        string[] collumn_result = Cell_result[a].Split('\t');
                        for(int b = 0; b < collumn_result.Length; b++)
                        {
                            // dataGridView1.Rows[a].Cells[b].Value = collumn_result[b];
                        }
                        dataGridView1.Rows.Add(collumn_result);
                    }
                }
            }
            else
            {
                UTIL.MsgE("읽을 파일이 없습니다.");
            }
        }
        /// <summary>
        /// 라디오박스 체크. 납품:0 / 마크:1 / 양쪽 다:2 / 선택x:-1
        /// </summary>
        /// <returns></returns>
        private int chk_Save_DB()
        {
            if (rbtn_div.Checked == true) { return 0; }
            if (rbtn_marc.Checked == true) { return 1; }
            if (rbtn_all.Checked == true) { return 2; }
            return -1;
        }
        /// <summary>
        /// 표 내용 저장전 검수가 들어감
        /// 검수 내용
        /// 수량 * 단가 = 합계
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Save_Click(object sender, EventArgs e)
        {
            if(cltchk == false || tb_clt1.Text=="") { UTIL.MsgE("거래처를 확인해주세요."); return; }
            if (chk_Save_DB() == -1) { UTIL.MsgE("작업 대상을 선택해 주세요."); return; }
            string cmd = db.DB_Select_Search("name", "User_Data", "name", tb_UserName.Text);
            if (db.DB_Send_CMD_Search(cmd) == "")
            { UTIL.MsgE("담당자를 확인해주세요."); return; }

            // TODO: 목록명, 목록일자로 구분
            cmd = db.DB_Search("Obj_List", "list_name", "[" + tb_dvy1.Text + "]" + tb_clt1.Text, "comp_num", comp_idx);
            if (db.DB_Send_CMD_Search(cmd) != "") 
            { UTIL.MsgE("DB의 납품목록과 중복됩니다."); return; }

            bool MsgOk = false;
            int Marc_ton = chk_Save_DB();
            int vol, price, total, resVol = 0, resTotal = 0;  // 5, 6, 7
            string Strmsg = "";
            string[] data = { "", "", "", "", "", "", "", "", "", "", "", "ISBN조회", "" };
                           //  0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ,10 , 11   ,     12
            string[] add_grid_data = { "", "", "", "", "", "", "", "", "ISBN조회", "" }; // 0-9
            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["count"].Value == null ||
                    dataGridView1.Rows[a].Cells["count"].Value.ToString() == "") {
                    dataGridView1.Rows[a].Cells["count"].Value = "0";
                }
                if (dataGridView1.Rows[a].Cells["unit"].Value == null ||
                    dataGridView1.Rows[a].Cells["unit"].Value.ToString() == "") {
                    dataGridView1.Rows[a].Cells["unit"].Value = "0";
                }
                string Strvol = dataGridView1.Rows[a].Cells["count"].Value.ToString();
                string Strprice = dataGridView1.Rows[a].Cells["unit"].Value.ToString().Replace(",", "");
                string Strtotal;

                if (dataGridView1.Rows[a].Cells["total"].Value == null || 
                    dataGridView1.Rows[a].Cells["total"].Value.ToString() == "") {
                    int vol_tmp = Convert.ToInt32(Regex.Replace(Strvol, @"[^0-9]", ""));
                    int price_tmp = Convert.ToInt32(Regex.Replace(Strprice, @"[^0-9]", ""));
                    int total_tmp = vol_tmp + price_tmp;
                    Strtotal = total_tmp.ToString();
                }
                else {
                    Strtotal = dataGridView1.Rows[a].Cells["total"].Value.ToString();
                }

                Strvol = Regex.Replace(Strvol, @"[^0-9]", "");
                Strprice = Regex.Replace(Strprice, @"[^0-9]", "");
                Strtotal = Regex.Replace(Strtotal, @"[^0-9]", "");

                vol = Convert.ToInt32(Strvol);
                price = Convert.ToInt32(Strprice);
                total = Convert.ToInt32(Strtotal);
                resVol += vol;
                resTotal += total;
                if (vol * price != total) {
                    dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.Orange;
                    Strmsg += a.ToString() + ", ";
                    MsgOk = true;
                }
            }
            if (MsgOk) {
                UTIL.MsgE(Strmsg + "번째 행의 단가/수량/합계를 확인해 주세요.");
                return;
            }
            data[0] = start_date.Value.ToString().Substring(0,10);
            if (end_date.Checked == true) { data[1] = end_date.Value.ToString().Substring(0, 10); }
            data[2] = "[" + tb_dvy1.Text + "]" + tb_clt1.Text;
            data[3] = tb_clt1.Text;
            data[4] = tb_dvy1.Text;
            data[5] = tb_UserName.Text;
            data[6] = tb_ListNum.Text;
            data[7] = resVol.ToString();
            data[8] = resTotal.ToString();
            data[9] = "진행";
            data[12] = Marc_ton.ToString();
            add_grid_data[0] = data[0];
            add_grid_data[1] = data[3];
            add_grid_data[2] = data[4];
            add_grid_data[3] = data[5];
            add_grid_data[4] = data[6];
            add_grid_data[5] = data[7];
            add_grid_data[6] = data[8];
            add_grid_data[7] = data[9];
            add_grid_data[9] = data[12];
            string[] col_name = { "date", "date_res", "list_name", "clt", "dly",
                                  "charge", "list_num", "vol", "total", "state",
                                  "chk_marc", "comp_num", "unstock" };
            string[] setData = { data[0], data[1], data[2], data[3], data[4],
                                 data[5], data[6], data[7], data[8], data[9],
                                 data[12], PUB.user.CompanyIdx, data[7] };

            string Incmd = db.DB_INSERT("Obj_List", col_name, setData);
            Helper_DB.ExcuteNonQuery(Incmd);

            UTIL.MsgI("저장되었습니다.");

            Grid1_total();
            dataGridView2.Rows.Add(add_grid_data);
            GridColorChange();
            Save_Reset();
        }
        private void Save_Reset()
        {
            tb_FilePath.Text = "";
            tb_dvy1.Text = "";
            tb_clt1.Text = "";
            tb_UserName.Text = "";
            tb_ListNum.Text = "";
            tb_Work_method.Text = "";
            tb_dvy_method.Text = "";
            dataGridView1.Rows.Clear();
        }
        private void btn_Exit_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void tb_clt1_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
            {
                Commodity_Search sub = new Commodity_Search(this);
                sub.Clinet_name = tb_clt1.Text;
                cltchk = true;
                sub.Show();
            }
        }
        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBox1.Text == "진행")
            {
                btn_Complet.Enabled = true;
                btn_ing.Enabled = false;
            }
            else if (comboBox1.Text == "완료")
            {
                btn_Complet.Enabled = false;
                btn_ing.Enabled = true;
            }
        }
        private void btn_Del_Click(object sender, EventArgs e)
        {
            int cout = 0;
            int delcout = 0;
            if (UTIL.MsgQ("정말 삭제하시겠습니까?\n삭제는 1개씩입니다.") == DialogResult.Yes) 
            {
                for (int a = 0; a < dataGridView2.Rows.Count; a++)
                {
                    bool isChecked = Convert.ToBoolean(dataGridView2.Rows[a].Cells["Grid_Check"].Value);
                    if (isChecked)
                    {
                        if (cout == 0) { delcout = a; cout++; }
                        else { UTIL.MsgE("체크가 2개이상 되어있습니다!"); cout++; break; }
                    }
                }
                if (cout == 0) { UTIL.MsgE("체크된 사항이 없습니다."); return; }
                else if (cout == 1)
                {
                    string[] del_target = { dataGridView2.Rows[delcout].Cells["list_date"].Value.ToString(),
                                            dataGridView2.Rows[delcout].Cells["list_name"].Value.ToString() };
                    string[] del_table = { "date", "list_name" };

                    string cmd = db.DB_Delete_More_term("Obj_List", "comp_num", PUB.user.CompanyIdx, del_table, del_target);
                    Helper_DB.ExcuteNonQuery(cmd);
                    cmd = db.DB_Delete_No_Limit("Obj_List_Book", "compidx", comp_idx, del_table, del_target);
                    Helper_DB.ExcuteNonQuery(cmd);

                    dataGridView2.Rows.Remove(dataGridView2.Rows[delcout]);
                }
            }
        }
        private void btn_Edit_Click(object sender, EventArgs e)
        {
            int cout = 0;
            for (int a = 0; a < dataGridView2.Rows.Count; a++)
            {
                bool isChecked = Convert.ToBoolean(dataGridView2.Rows[a].Cells["Grid_Check"].Value);
                if (isChecked)
                {
                    if (cout == 0) { EditNumber = a; cout++; }
                    else if (cout != 0) { UTIL.MsgE("체크가 2개이상 되어있습니다!"); cout++; break; }
                }
            }
            if (cout == 0) { UTIL.MsgE("체크된 사항이 없습니다."); return; }
            if (cout == 1)
            {
                Commodity_Edit edit = new Commodity_Edit(this);
                edit.Show();
            }
        }
        /// <summary>
        /// 데이터 그리드뷰2에 값을 추가해주는 함수.
        /// </summary>
        /// <param name="code"></param>
        private void Add_Grid(string code)
        {
            dataGridView2.Rows.Clear();
            string getdata = "`date`, `clt`, `dly`, `charge`, `list_name`, " +
                             "`vol`, `total`, `state`, `chk_marc`";
            string[] othertable = { "comp_num", "state" };
            string[] othercol = { PUB.user.CompanyIdx, code };
            string cmd = db.More_DB_Search("Obj_List", othertable, othercol, getdata);
            string db_res = db.DB_Send_CMD_Search(cmd);

            string[] obj_list = db_res.Split('|');
            string[] add_data = { "", "", "", "", "", 
                                  "", "", "", "ISBN 조회", "" };

            for (int a = 0; a < obj_list.Length; a++)
            {
                if (a % 9 == 0) { add_data[0] = obj_list[a]; }
                if (a % 9 == 1) { add_data[1] = obj_list[a]; }
                if (a % 9 == 2) { add_data[2] = obj_list[a]; }
                if (a % 9 == 3) { add_data[3] = obj_list[a]; }
                if (a % 9 == 4) { add_data[4] = obj_list[a]; }
                if (a % 9 == 5) { add_data[5] = obj_list[a]; }
                if (a % 9 == 6) { add_data[6] = obj_list[a]; }
                if (a % 9 == 7) { add_data[7] = obj_list[a]; }
                if (a % 9 == 8) { add_data[9] = obj_list[a]; dataGridView2.Rows.Add(add_data); }
            }
            GridColorChange();
        }
        /// <summary>
        /// 데이터그리드뷰 색상변경
        /// </summary>
        public void GridColorChange()
        {
            for (int a = 0; a < dataGridView2.Rows.Count; a++)
            {
                dataGridView2.Rows[a].DefaultCellStyle.BackColor = Color.Empty;
                string marc_tmp = dataGridView2.Rows[a].Cells["chk_marc"].Value.ToString();
                int marc = Convert.ToInt32(marc_tmp);
                if (marc >= 1) {
                    dataGridView2.Rows[a].DefaultCellStyle.BackColor = Color.Yellow;
                }
            }
        }
        private void Grid1_total()
        {
            string[] DB_col_name = { "compidx", "list_name", "header", "num", "book_name", 
                                     "author", "book_comp", "count", "pay", "total", 
                                     "etc", "isbn", "order", "date" };
            string[] setData = { comp_idx, "[" + tb_dvy1.Text + "]" + tb_clt1.Text, "", "", "", 
                                 "", "", "", "", "", 
                                 "", "", "", start_date.Value.ToString().Substring(0,10) };

            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells[2].Value == null ||
                    dataGridView1.Rows[a].Cells[2].Value.ToString() == "") { break; }
                for (int ea = 0; ea < 12; ea++)
                {
                    if (ea == 11) { break; }
                    if (dataGridView1.Rows[a].Cells[ea].Value == null)
                    {
                        dataGridView1.Rows[a].Cells[ea].Value = "";
                    }
                    if (dataGridView1.Columns[ea].Name == "unit" || dataGridView1.Columns[ea].Name == "total")
                    {
                        setData[ea + 2] = dataGridView1.Rows[a].Cells[ea].Value.ToString().Replace(",", "");
                    }
                    else
                    {
                        setData[ea + 2] = dataGridView1.Rows[a].Cells[ea].Value.ToString();
                    }
                }
                string Incmd = db.DB_INSERT("Obj_List_Book", DB_col_name, setData);
                Helper_DB.ExcuteNonQuery(Incmd);
            }
        }
        private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView2.Columns[e.ColumnIndex].Name == "Grid_btn_ISBN")     // ISBN 조회 (버튼 클릭시 ISBN검수 창으로 넘어가야함)
            {
                Check_ISBN isbn = new Check_ISBN(this);
                isbn.list_name = dataGridView2.Rows[e.RowIndex].Cells["list_name"].Value.ToString();
                isbn.DataLoad();
                isbn.Show();
            }
        }
        private void btn_morge_Click(object sender, EventArgs e)
        {
            int cout = 0;
            for (int a = 0; a < dataGridView2.Rows.Count; a++)
            {
                bool isChecked = Convert.ToBoolean(dataGridView2.Rows[a].Cells["Grid_Check"].Value);
                if (isChecked)
                {
                    if (cout == 0) { MorgeNum[0] = a; cout++; }
                    else if (cout != 0) { MorgeNum[1] = a; cout++; break; }
                }
            }
            if (cout == 0) { UTIL.MsgE("체크된 사항이 없습니다."); return; }
            else if (cout == 1)
            {
                UTIL.MsgE("체크가 1개밖에 되어있지않습니다.");
            }
            else if (cout == 2) { 
                Commodity_Morge morge = new Commodity_Morge(this);
                morge.Show();
            }
            else if (cout > 2)
            {
                UTIL.MsgE("체크된 사항이 너무 많습니다!");
            }
        }
        private void btn_ing_Click(object sender, EventArgs e)
        {
            if(UTIL.MsgQ("진행처리 하시겠습니까?") == DialogResult.Yes)
            {
                for(int a = 0; a < dataGridView2.Rows.Count; a++)
                {
                    bool isChecked = Convert.ToBoolean(dataGridView2.Rows[a].Cells["Grid_Check"].Value);
                    if (isChecked)
                    {
                        string[] edit_col = { "state" };
                        string[] edit_name = { "진행" };
                        string[] seer_col = { "date", "list_name" };
                        string[] sear_name = { dataGridView2.Rows[a].Cells["list_date"].Value.ToString(),
                                               dataGridView2.Rows[a].Cells["list_name"].Value.ToString() };
                        string U_cmd = db.More_Update("Obj_List", edit_col, edit_name, seer_col, sear_name);
                        Helper_DB.ExcuteNonQuery(U_cmd);
                        dataGridView2.Rows[a].Cells["stat2"].Value = "진행";
                    }
                }
                Add_Grid("완료");
            }
        }
        private void btn_Complet_Click(object sender, EventArgs e)
        {
            if (UTIL.MsgQ("완료처리 하시겠습니까?") == DialogResult.Yes)
            {
                for (int a = 0; a < dataGridView2.Rows.Count; a++)
                {
                    bool isChecked = Convert.ToBoolean(dataGridView2.Rows[a].Cells["Grid_Check"].Value);
                    if (isChecked)
                    {
                        string[] edit_col = { "state" };
                        string[] edit_name = { "완료" };
                        string[] seer_col = { "date", "list_name" };
                        string[] sear_name = { dataGridView2.Rows[a].Cells["list_date"].Value.ToString(),
                                               dataGridView2.Rows[a].Cells["list_name"].Value.ToString() };
                        string U_cmd = db.More_Update("Obj_List", edit_col, edit_name, seer_col, sear_name);
                        Helper_DB.ExcuteNonQuery(U_cmd);
                        dataGridView2.Rows[a].Cells["stat2"].Value = "완료";
                    }
                }
                Add_Grid("진행");
            }
        }
        private void btn_lockup_Click(object sender, EventArgs e)
        {
            string cmd = "SELECT " +
                         "`date`,`clt`,`dly`,`charge`,`list_name`," +
                         "`vol`,`total`,`state`,`chk_marc`" +
                         " from Obj_List WHERE " +
                         "`comp_num` = '" + comp_idx + "' ";
            if(comboBox1.Text == "진행") { cmd += "AND `state` LIKE '%진행%'"; }
            else if (comboBox1.Text == "완료") { cmd += "AND `state` LIKE '%완료%'"; }
            if (tb_dvy2.Text != "")  { cmd += " AND `dly` LIKE '%" + tb_dvy2.Text + "%'"; }
            if (tb_clt2.Text != "")  { cmd += " AND `clt` LIKE '%" + tb_clt2.Text + "%'"; }
            if (tb_user2.Text != "") { cmd += " AND `charge` LIKE '%" + tb_user2.Text + "%'"; }
            cmd += ";";
            string res_temp = db.self_Made_Cmd(cmd);
            string[] result = { "", "", "", "", "", "", "", "", "ISBN 조회", "" }; // 0-9
            string[] tmp = res_temp.Split('|');
            dataGridView2.Rows.Clear();
            for (int a = 0; a < tmp.Length; a++)
            {
                if (a % 9 == 0) { result[0] = tmp[a]; }
                if (a % 9 == 1) { result[1] = tmp[a]; }
                if (a % 9 == 2) { result[2] = tmp[a]; }
                if (a % 9 == 3) { result[3] = tmp[a]; }
                if (a % 9 == 4) { result[4] = tmp[a]; }
                if (a % 9 == 5) { result[5] = tmp[a]; }
                if (a % 9 == 6) { result[6] = tmp[a]; }
                if (a % 9 == 7) { result[7] = tmp[a]; }
                if (a % 9 == 8) { result[9] = tmp[a]; dataGridView2.Rows.Add(result); }
            }
            GridColorChange();
        }
        private void button2_Click(object sender, EventArgs e)
        {
            // if (tb_ListNum.Text == "") { MessageBox.Show("목록번호가 비어있습니다!"); return; }
            int count = 1;

            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["book_name"].Value == null ||
                    dataGridView1.Rows[a].Cells["book_name"].Value.ToString() == "") { return; }
                if (dataGridView1.Rows[a].Cells["header"].Value == null ||
                    dataGridView1.Rows[a].Cells["header"].Value.ToString() == "") { 
                    dataGridView1.Rows[a].Cells["header"].Value = tb_ListNum.Text; 
                }

                
                dataGridView1.Rows[a].Cells["num"].Value = count.ToString();

                if(dataGridView1.Rows[a+1].Cells["header"].Value == null) {
                    return;
                }
                if (dataGridView1.Rows[a].Cells["header"].Value.ToString() != dataGridView1.Rows[a + 1].Cells["header"].Value.ToString()) 
                    count = 1;
                else 
                    count++;
            }
        }

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

        private void btn_Total_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["book_name"].Value == null || 
                    dataGridView1.Rows[a].Cells["book_name"].Value.ToString() == "") {
                    break;
                }
                if (dataGridView1.Rows[a].Cells["unit"].Value == null || 
                    dataGridView1.Rows[a].Cells["unit"].Value.ToString() == "") {
                    dataGridView1.Rows[a].Cells["unit"].Value = "0";
                }

                string StrCount = Regex.Replace(dataGridView1.Rows[a].Cells["count"].Value.ToString(), @"[^0-9]", "");
                string StrPrice = Regex.Replace(dataGridView1.Rows[a].Cells["unit"].Value.ToString(), @"[^0-9]", "");

                if (!StrPrice.All(char.IsDigit))
                    StrPrice = "0";

                int Count = Convert.ToInt32(StrCount);
                int Price = Convert.ToInt32(StrPrice);

                int Total = Count * Price;
                dataGridView1.Rows[a].Cells["total"].Value = Total.ToString();
            }
        }
    }
}