using MySqlX.XDevAPI.Relational;
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;
using WindowsFormsApp1.Mac;
namespace WindowsFormsApp1.Delivery
{
    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 = main.com_idx;
            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;
            string file_con = 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[] Cell_result = null;
                    string[] collumn_result;
                    file_con = sr.ReadToEnd();
                    Cell_result = file_con.Split('\n');
                    for(int a = 0; a < Cell_result.Length; a++)
                    {
                        collumn_result = Cell_result[a].Split('\t');
                        richTextBox1.Text += Cell_result[a] + "\n";
                        for(int b = 0; b < collumn_result.Length; b++)
                        {
                            dataGridView1.Rows[a].Cells[b].Value = collumn_result[b];
                        }
                    }
                }
            }
            else
            {
                MessageBox.Show("읽을 파일이 없습니다.", "에러", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// 
        /// 라디오박스 체크. 납품:0 / 마크:1 / 양쪽 다:2 / 선택x:-1
        /// 
        /// 
        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;
        }
        /// 
        /// 표 내용 저장전 검수가 들어감
        /// 검수 내용
        /// 수량 * 단가 = 합계
        /// 
        /// 
        /// 
        private void btn_Save_Click(object sender, EventArgs e)
        {
            if(cltchk == false || tb_clt1.Text=="") { MessageBox.Show("거래처를 확인해주세요."); return; }
            if (chk_Save_DB() == -1) { MessageBox.Show("작업 대상을 선택해 주세요."); return; }
            if (db.DB_Select_Search("name", "User_Data", "name", tb_UserName.Text) == "") 
            { MessageBox.Show("담당자를 확인해주세요."); return; }
            if (db.DB_Search("Obj_List", "list_name", "[" + tb_clt1.Text + "]" + tb_dvy1.Text, "comp_num", comp_idx) != "") 
            { MessageBox.Show("DB의 납품목록과 중복됩니다."); return; }
            bool MsgOk = true;
            int Marc_ton = chk_Save_DB();
            int vol, price, total, resVol=0, resTotal=0;  // 5, 6, 7
            string Strvol = "";
            string Strprice = "";
            string Strtotal = "";
            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) { break; }
                Strvol = dataGridView1.Rows[a].Cells["count"].Value.ToString();
                Strprice = dataGridView1.Rows[a].Cells["unit"].Value.ToString().Replace(",", "");
                if(dataGridView1.Rows[a].Cells["total"].Value == null) {
                    int vol_tmp = Convert.ToInt32(Strvol);
                    int price_tmp = Convert.ToInt32(Strprice);
                    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 += dataGridView1.Rows[a].Cells[1].Value.ToString()+", ";
                    MsgOk = false;
                }
            }
            if (MsgOk == false) {
                MessageBox.Show(Strmsg + "번째 행의 단가/수량/합계를 확인해 주세요.");
            }
            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_clt1.Text + "]" + tb_dvy1.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], main.com_idx, data[7] };
            db.DB_INSERT("Obj_List", col_name, setData);
            if (chk_Save_DB() > 0) { Marc_list_input(data); }
            Grid1_total();
            dataGridView2.Rows.Add(add_grid_data);
            GridColorChange();
        }
        private void Marc_list_input(string[] data)
        {
            string table = "Obj_List_Marc";
            /* 목록일자, 완료일자, 마크목록명, 목록명, 목록담당자, 
               전체, 미편목 */
            string[] col_name = { "date", "date_res", "connect_data", "list_name", "charge", 
                                  "total", "unflatter", "compidx", "state" };
            string[] setData = { data[0], data[1], data[2], data[2], data[5], 
                                 data[8], data[8], main.com_idx, data[9] };
            db.DB_INSERT(table, col_name, setData);
        }
        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 (MessageBox.Show("정말 삭제하시겠습니까?\n삭제는 1개씩입니다.", "Danger!!!", MessageBoxButtons.YesNo) == 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 { MessageBox.Show("체크가 2개이상 되어있습니다!"); cout++; break; }
                    }
                }
                richTextBox1.Text = delcout.ToString();
                if (cout == 0) { MessageBox.Show("체크된 사항이 없습니다."); 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" };
                    db.DB_Delete_More_term("Obj_List", "comp_num", main.com_idx, del_table, del_target);
                    db.DB_Delete_No_Limit("Obj_List_Book", "compidx", comp_idx, del_table, del_target);
                    del_table[1] = "connect_data";
                    db.DB_Delete_More_term("Obj_List_Marc", "compidx", main.com_idx, del_table, del_target);
                    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) { MessageBox.Show("체크가 2개이상 되어있습니다!"); cout++; break; }
                }
            }
            if (cout == 0) { MessageBox.Show("체크된 사항이 없습니다."); return; }
            if (cout == 1)
            {
                Commodity_Edit edit = new Commodity_Edit(this);
                edit.Show();
            }
        }
        /// 
        /// 데이터 그리드뷰2에 값을 추가해주는 함수.
        /// 
        /// 
        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 = { main.com_idx, code };
            string dblist = db.More_DB_Search("Obj_List", othertable, othercol, getdata);
            string[] obj_list = dblist.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();
        }
        /// 
        /// 데이터그리드뷰 색상변경
        /// 
        public void GridColorChange()
        {
            for (int a = 0; a < dataGridView2.Rows.Count; a++)
            {
                dataGridView2.Rows[a].DefaultCellStyle.BackColor = Color.Empty;
            }
            for (int a = 0; a < dataGridView2.Rows.Count; a++)
            {
                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_clt1.Text + "]" + tb_dvy1.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();
                    }
                }
                db.DB_INSERT("Obj_List_Book", DB_col_name, setData);
            }
        }
        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.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) { MessageBox.Show("체크된 사항이 없습니다."); return; }
            else if (cout == 1)
            {
                MessageBox.Show("체크가 1개밖에 되어있지않습니다.");
            }
            else if (cout == 2) { 
                Commodity_Morge morge = new Commodity_Morge(this);
                morge.Show();
                richTextBox1.Text = EditNumber.ToString() + "\n";
            }
            else if (cout > 2)
            {
                MessageBox.Show("체크된 사항이 너무 많습니다!");
            }
        }
        private void btn_ing_Click(object sender, EventArgs e)
        {
            if(MessageBox.Show("진행처리 하시겠습니까?", "진행", MessageBoxButtons.YesNo) == 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() };
                        db.More_Update("Obj_List", edit_col, edit_name, seer_col, sear_name);
                        dataGridView2.Rows[a].Cells["stat2"].Value = "진행";
                    }
                }
                Add_Grid("완료");
            }
        }
        private void btn_Complet_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("완료처리 하시겠습니까?", "완료", MessageBoxButtons.YesNo) == 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() };
                        db.More_Update("Obj_List", edit_col, edit_name, seer_col, sear_name);
                        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; }
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                int num = a + 1;
                if (dataGridView1.Rows[a].Cells["book_name"].Value == null ||
                    dataGridView1.Rows[a].Cells["book_name"].Value.ToString() == "") {
                    return;
                }
                dataGridView1.Rows[a].Cells["header"].Value = tb_ListNum.Text;
                dataGridView1.Rows[a].Cells["num"].Value = num.ToString();
            }
        }
    }
}