using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using WindowsFormsApp1.납품관리;

namespace WindowsFormsApp1.Delivery
{
    public partial class Order_input : Form
    {
        Helper_DB db = new Helper_DB();
        Barobill_FAX fax = new Barobill_FAX();
        Main main;
        public string compidx = "";
        public int grididx;
        int ColumnIndex;
        string chk_mkdate = "";
        bool chk_V = false;
        public Order_input(Main _main)
        {
            InitializeComponent();
            main = _main;
        }
        private void Order_input_Load(object sender, EventArgs e)
        {
            db.DBcon();
            compidx = main.com_idx;

            dataGridView1.Columns["book_name"].DefaultCellStyle.Font = new Font("굴림", 8, FontStyle.Regular);
            dataGridView1.Columns["author"].DefaultCellStyle.Font = new Font("굴림", 8, FontStyle.Regular);
            dataGridView1.Columns["list_name"].DefaultCellStyle.Font = new Font("굴림", 8, FontStyle.Regular);

            // 데이터 그리드 뷰 수정
            for(int a = 0; a < dataGridView1.Columns.Count; a++)
            {
                if (a != 1 && a != 6 && a != 13 && a != 16) { 
                    dataGridView1.Columns[a].ReadOnly = true;
                }
            }

            // 사용자 구분
            cb_user.Items.Add("전체");
            string[] user_tmp = main.DB_User_Data.Split('|');
            string cmd = db.self_Made_Cmd("SELECT `name` FROM `User_Data` WHERE `affil` = '" + user_tmp[5] + "';");
            string[] user_name = cmd.Split('|');
            for (int a = 0; a < user_name.Length; a++)
            {
                if (a == user_name.Length - 1) { break; }
                cb_user.Items.Add(user_name[a]);
            }
            cb_user.SelectedIndex = 0;

            // 상태 구분
            string[] state = { "미입고", "입고", "전체" };
            cb_state.Items.AddRange(state);
            cb_state.SelectedIndex = 0;
            
            // 보기 구분
            string[] order = { "주문중", "미주문", "전체" };
            cb_order.Items.AddRange(order);
            cb_order.SelectedIndex = 1;

            // 주문서 구분
            string[] order_send = { "팩스", "메일" };
            cb_ordersend.Items.AddRange(order_send);
            cb_ordersend.SelectedIndex = 0;
        }
        private void btn_lookup_Click(object sender, EventArgs e)
        {
            string[] tmp_col = { "compidx" };
            string[] tmp_data = { compidx };
            string takedata = "`order`, `order_stat`, `isbn`, `book_name`, `author`, " +
                              "`book_comp`, `order_count`, `count`, `pay`, `total`, " +
                              "`etc`, `list_name`, `order_date`, `send_date`, `header`, " +
                              "`num`";
            string cmd = db.More_DB_Search("Obj_List_Book", tmp_col, tmp_data, takedata);
            made_grid(cmd, true);
            date_Substring();
        }
        /// <summary>
        /// Grid내의 주문일자와 송금일자를 날짜까지만 표시하게 해주는 함수.
        /// </summary>
        private void date_Substring()
        {
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["order_date"].Value.ToString() != "") {
                    dataGridView1.Rows[a].Cells["order_date"].Value = 
                        dataGridView1.Rows[a].Cells["order_date"].Value.ToString().Substring(0, 10);
                }
                if (dataGridView1.Rows[a].Cells["send_date"].Value.ToString() != "") {
                    dataGridView1.Rows[a].Cells["send_date"].Value = 
                        dataGridView1.Rows[a].Cells["send_date"].Value.ToString().Substring(0, 10);
                }
                if (dataGridView1.Rows[a].Cells["book_comp"].Value.ToString().Contains("(주)") == true) {
                    dataGridView1.Rows[a].Cells["book_comp"].Value =
                        dataGridView1.Rows[a].Cells["book_comp"].Value.ToString().Replace("(주)", "");
                }
            }
        }
        public void made_grid(string strValue, bool chk = false)
        {
            dataGridView1.Rows.Clear();
            string[] data = strValue.Split('|');
            string[] mkgrid = { "false", "", "", "", "",
                                "", "", "", "", "",
                                "", "", "", "", "",
                                "" };
            /* 선택 / o주문처 / oM / o도서명 / o저자 / 
             * o출판사 / o주문수 / o원주문 / o정가 / o합계 / 
             * o비고 / o납품처 / o주문일자 / o송금일자 / oo번호 / 
             * 목록번호
             */
            for (int a = 0; a < data.Length; a++)
            {
                if (a % 16 == 0) { mkgrid[1] = data[a]; }    // 주문처
                if (a % 16 == 1) {                           // M
                    if (data[a] == "0") { data[a] = data[a].Replace("0", ""); }
                    if (data[a] == "1") { data[a] = data[a].Replace("1", "V"); }
                    mkgrid[2] = data[a];
                }
                if (a % 16 == 2)  { mkgrid[3]  = data[a]; }   // ISBN
                if (a % 16 == 3)  { mkgrid[4]  = data[a]; }   // 도서명
                if (a % 16 == 4)  { mkgrid[5]  = data[a]; }   // 저자
                if (a % 16 == 5)  { mkgrid[6]  = data[a]; }   // 출판사
                if (a % 16 == 6)  { mkgrid[7]  = data[a]; }   // 주문수
                if (a % 16 == 7)  { mkgrid[8]  = data[a]; }   // 원주문
                if (a % 16 == 8)  { mkgrid[9]  = data[a]; }   // 정가
                if (a % 16 == 9)  { mkgrid[10] = data[a]; }   // 합계
                if (a % 16 == 10) { mkgrid[11] = data[a]; }   // 비고
                if (a % 16 == 11) { mkgrid[12] = data[a]; }   // 납품처
                if (a % 16 == 12) { mkgrid[13] = data[a]; }   // 주문일자
                if (a % 16 == 13) { mkgrid[14] = data[a]; }   // 송금일자
                if (a % 16 == 14) { mkgrid[15] = data[a]; }   // 번호
                if (a % 16 == 15) {                           // 번호
                    mkgrid[15] += " " + data[a];
                    if (chk == false) { dataGridView1.Rows.Add(mkgrid); }
                    else { 
                        if(Array_Inspection(mkgrid) == true)
                        {
                            dataGridView1.Rows.Add(mkgrid);
                        } 
                    }
                }
            }
            // 색입히는 함수 기입
            PrintColor_Grid();
        }
        /// <summary>
        /// 작업명단 검색중 상위 텍스트박스 및 콤보박스의 값에 따라 출력할지 안할지 분류.
        /// </summary>
        /// <param name="strValues"></param>
        /// <returns>false일 경우 필터에 걸러진 경우임.</returns>
        private bool Array_Inspection(string[] strValues)
        {
            if (tb_search_order.Text != "") {
                if (!strValues[1].Contains(tb_search_order.Text)) {
                    return false;
                }
            }
            if (tb_search_book_name.Text != "") {
                if (!strValues[3].Contains(tb_search_book_name.Text)) {
                    return false;
                }
            }
            if (tb_search_book_comp.Text != "") {
                if (!strValues[5].Contains(tb_search_book_comp.Text)) {
                    return false;
                }
            }
            if (cb_state.SelectedIndex == 0) {
                // TODO: 입고 상태 체크해야함. (방법 찾아볼것)
            }
            if (cb_order.SelectedIndex == 0) {
                if(strValues[13] == "") {
                    return false;
                }
            }
            else if(cb_order.SelectedIndex == 1) {
                if (strValues[13] != "") {
                    return false;
                }
            }
            return true;
        }
        private void PrintColor_Grid()
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["order_date"].Value.ToString() != "") {
                    dataGridView1.Rows[a].DefaultCellStyle.BackColor = Color.FromArgb(223, 223, 240);
                }
            }
        }
        private void tb_search_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                btn_lookup_Click(null, null);
            }
        }
        private void btn_Save_Click(object sender, EventArgs e)
        {

        }
        private void btn_close_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0 && e.ColumnIndex == 0)
            {
                grididx = e.RowIndex;
                ColumnIndex = e.ColumnIndex;
            }
            if( dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected == dataGridView1.Rows[e.RowIndex].Cells["chk"].Selected)
            {
                if (dataGridView1.Rows[e.RowIndex].Cells["chk"].Value.ToString() == "true") {
                    dataGridView1.Rows[e.RowIndex].Cells["chk"].Value = "false";
                }
                else if (dataGridView1.Rows[e.RowIndex].Cells["chk"].Value.ToString() == "false") {
                    dataGridView1.Rows[e.RowIndex].Cells["chk"].Value = "true";
                }
            }
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            grididx = e.RowIndex;
            ColumnIndex = e.ColumnIndex;
            if (e.ColumnIndex == 1 || e.ColumnIndex == 14 || e.ColumnIndex == 13 || 
                e.ColumnIndex == 6 || e.ColumnIndex == 15 || e.ColumnIndex == 16)
            { return; }
            if(e.ColumnIndex == 3 || e.ColumnIndex == 4 || e.ColumnIndex == 5)
            {
                Book_Lookup bl = new Book_Lookup(this);
                bl.TopMost = true;
                string book_name = ((DataGridView)sender).Rows[e.RowIndex].Cells["Book_name"].Value.ToString();
                string author = ((DataGridView)sender).Rows[e.RowIndex].Cells["author"].Value.ToString();
                string book_comp = ((DataGridView)sender).Rows[e.RowIndex].Cells["Book_comp"].Value.ToString();
                string list_name = ((DataGridView)sender).Rows[e.RowIndex].Cells["list_name"].Value.ToString();
                bl.Lookup_Load(book_name, author, book_comp, list_name);
                bl.Show();
                return;
            }
            if (e.ColumnIndex == 0)
            {
            }
            else if (e.ColumnIndex == 2 && chk_V == false)
            {
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "V";
                chk_V = true;
            }
            else if (e.ColumnIndex == 2 && chk_V == true)
            {
                dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = "";
                chk_V = false;
            }
            else if (chk_mkdate.Contains("." + e.RowIndex + ", ") == true)
            {
                dataGridView1.Rows[e.RowIndex].Cells[13].Value = "";
                chk_mkdate = chk_mkdate.Replace("." + e.RowIndex + ", ", "");
            }
            else if (chk_mkdate.Contains("." + e.RowIndex + " , ") == false)
            {
                dataGridView1.Rows[e.RowIndex].Cells[13].Value = DateTime.Now.ToString("d");
                chk_mkdate += "." + e.RowIndex + ", ";
            }
        }
        private void tb_search_book_list_KeyDown(object sender, KeyEventArgs e)
        {
            if(e.KeyCode == Keys.Enter)
            {
                Order_input_Search search = new Order_input_Search(this);
                search.Where_Open = "book_list";
                search.searchText = tb_search_book_list.Text;
                search.TopMost = true;
                search.Show();
            }
        }
        private void tb_orderText_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter) {
                Order_input_Search search = new Order_input_Search(this);
                search.Where_Open = "Order";
                search.searchText = tb_orderText.Text;
                search.TopMost = true;
                search.Show();
            }
        }
        private void dataGridView1_KeyDown(object sender, KeyEventArgs e)
        {
            int row = dataGridView1.CurrentCell.RowIndex;
            int col = dataGridView1.CurrentCell.ColumnIndex;
            if (e.KeyCode == Keys.Enter)
            {
                if (col == 1) {
                    MessageBox.Show(row.ToString() + " " + col.ToString());
                }
            }
            if (e.KeyCode == Keys.Delete) {
                Skill_Grid sg = new Skill_Grid();
                sg.DataGrid_to_Delete(sender, e);
            }

            //tb_orderText_KeyDown(sender, e);
        }
        private void btn_Excel_Click(object sender, EventArgs e)
        {
            List<int> chkIdx = new List<int>();
            int total = 0;
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["chk"].Value.ToString() == "true")
                {
                    chkIdx.Add(a);
                    total += Convert.ToInt32(dataGridView1.Rows[a].Cells["order_count"].Value.ToString());
                }
            }
            if (chkIdx.Count < 1) { MessageBox.Show("선택된 도서가 없습니다!"); return; }
            string[,] inputExcel = new string[chkIdx.Count,7];
            string pur = dataGridView1.Rows[chkIdx[0]].Cells["order"].Value.ToString();
            for(int a = 0; a < chkIdx.Count; a++)
            {
                if (dataGridView1.Rows[chkIdx[a]].Cells["order"].Value.ToString() != pur) {
                    MessageBox.Show("주문처가 동일하지 않습니다!", "Error");
                    return;
                }
                string list = dataGridView1.Rows[chkIdx[a]].Cells["list_name"].Value.ToString();
                string div = list.Substring(list.IndexOf(']')+1);
                int num = a + 1;
                inputExcel[a, 0] = num.ToString();
                inputExcel[a, 1] = dataGridView1.Rows[chkIdx[a]].Cells["book_comp"].Value.ToString();
                inputExcel[a, 2] = dataGridView1.Rows[chkIdx[a]].Cells["book_name"].Value.ToString();
                inputExcel[a, 3] = dataGridView1.Rows[chkIdx[a]].Cells["author"].Value.ToString();
                inputExcel[a, 4] = dataGridView1.Rows[chkIdx[a]].Cells["order_count"].Value.ToString();
                inputExcel[a, 5] = dataGridView1.Rows[chkIdx[a]].Cells["pay"].Value.ToString();
                inputExcel[a, 6] = div + "\n" +
                                   dataGridView1.Rows[chkIdx[a]].Cells["isbn"].Value.ToString();
            }                      
            Excel_text ex = new Excel_text();
            ex.mk_Excel_Order(inputExcel, total, compidx, pur);
        }
        private void btn_order_send_Click(object sender, EventArgs e)
        {
            /*
            List<int> chkIdx = new List<int>();
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["chk"].Value.ToString() == "O") {
                    chkIdx.Add(a);
                }
            }
            
            string pur = dataGridView1.Rows[chkIdx[0]].Cells["order"].Value.ToString();

            for (int a = 0; a < chkIdx.Count; a++)
            {
                if (dataGridView1.Rows[chkIdx[a]].Cells["order"].Value.ToString() != pur) {
                    MessageBox.Show("주문처가 동일하지 않습니다!", "Error");
                    return;
                }
            }
            */
            string Date = DateTime.Now.ToString("yyyy-MM-dd");
            string Time = DateTime.Now.ToString("HH-mm-ss");
            String_Text st = new String_Text();
            string pur = "dasd";
            string FilePath = string.Empty;
            string filename = string.Empty;

            OpenFileDialog Odig = openFileDialog1;
            Odig.Filter = "Excel Files(*.xls)|*.xls|Excel Files(*.xlsx)|*.xlsx|All FIles(*.*)|*.*";
            Odig.Title = "파일을 선택해주세요.";

            if (Odig.ShowDialog() == DialogResult.OK)
            {
                FilePath = Odig.FileName;
                filename = Path.GetFileName(FilePath);
                FilePath = Path.GetDirectoryName(FilePath);
            }
            else return;

            if (cb_ordersend.SelectedItem.ToString() == "팩스") {

                List<string> data_list = new List<string>();

                string Area = "`fax`";
                string tmp = db.DB_Select_Search(Area, "Comp", "idx", compidx);

                string[] tmp_data = tmp.Split('|');
                string[] fax_num = tmp_data[0].Split(',');

                string pur_area = "`fax`, `boss`";
                string tmp_pur = db.DB_Select_Search(pur_area, "Purchase", "sangho", pur);

                string[] db_pur = tmp_pur.Split('|');

                string[] pur_data = { "", pur, "" };
                if (db_pur.Length > 3)
                {
                    for(int a = 0; a < db_pur.Length; a++)
                    {
                        if (a % 3 == 0) {
                            if (db_pur[a] != "") {
                                pur_data[0] = db_pur[a];
                            }
                        }
                        if (a % 3 == 2) {
                            if (db_pur[a] != "") {
                                pur_data[2] = db_pur[a];
                            }
                        }
                    }
                }

                if (pur_data[1] == "") {
                    MessageBox.Show("주문처의 팩스 번호가 비어있습니다!", "Error");
                    return;
                }

                data_list.Add(fax_num[0]);
                data_list.AddRange(pur_data);

                string[] fax_param = data_list.ToArray();

                FTP ftp = new FTP();

                // TODO: openFileDialog 사용. 파일경로 가져와야함.

                bool result = ftp.ConnectToServer();
                string path = @"";
                DirectoryInfo dirInfo = new DirectoryInfo(FilePath);
                FileInfo[] infos = dirInfo.GetFiles();

                if (result == true) {
                    foreach (FileInfo info in dirInfo.GetFiles())
                    {
                        if (Path.GetFileName(info.Name) == filename) {
                            if (ftp.UpLoad(path, info.FullName) == false)
                                MessageBox.Show("FTP Upload 실패");

                            else
                                MessageBox.Show("FTP Upload 성공");
                        
                        }
                    }
                }
                else MessageBox.Show("접속 실패");

                // 바로빌 FAX API연동
                db.DB_Update("Comp", "fax_Key", fax.Send_BaroFax(filename, fax_param), "idx", compidx);
                string Fax_Key = fax.Send_BaroFax(filename, fax_param);
                string[] col_Name = { "compidx", "구분", "팩스전송키", "날짜", "시간" };
                string[] set_Data = { compidx, "팩스", Fax_Key, Date, Time };

                db.DB_INSERT("Send_Order", col_Name, set_Data);
            }
            if (cb_ordersend.SelectedItem.ToString() == "메일") {

                // 보내는 이 : 메일ID
                string sender_Area = "`email_ID`";
                string tmp_db = db.DB_Select_Search(sender_Area, "Comp", "idx", compidx);

                string[] arr_db = tmp_db.Split('|');

                // 받는 이 : 메일
                string taker_Area = "`email`";
                tmp_db = db.DB_Select_Search(taker_Area, "Purchase", "sangho", pur);

                string[] arr_pur = tmp_db.Split('|');
                string m_send = arr_pur[0];

                if (st.isContainHangul(m_send) == true)
                {
                    MessageBox.Show("DB내 저장된 이메일이 사양과 다릅니다. 직접 입력해주세요.");

                    Skill_Search_Text sst = new Skill_Search_Text();
                    string value = "";
                    if (sst.InputBox("보내실 이메일을 적어주세요.", "보내실 이메일을 적어주세요.", ref value) == DialogResult.OK) {
                        if (value == "") { return; }
                    }
                    else {
                        m_send = value;
                    }
                }

                Email email = new Email();
                if (email.Send_mail(compidx, pur, Odig.FileName, m_send)) {

                    string[] col_Name = { "compidx", "구분", "거래처명", "날짜", "시간", "보낸이", "받는이", "전송파일명", "전송결과" };
                    string[] set_Data = { compidx, "메일", pur, Date, Time, arr_db[0], m_send, filename, "성공" };
                    db.DB_INSERT("Send_Order", col_Name, set_Data);
                    MessageBox.Show("전송 성공!");
                }
                else { MessageBox.Show("전송 실패!"); }
            }
        }
        private void btn_send_chk_Click(object sender, EventArgs e)
        {
            Order_Send_Chk orc = new Order_Send_Chk(this);
            orc.Show();

        }
        private void btn_order_list_change_Click(object sender, EventArgs e)
        {
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                dataGridView1.Rows[a].Cells["order"].Value = tb_orderText.Text;
            }
        }
        private void btn_Reset_Order_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                dataGridView1.Rows[a].Cells["order"].Value = "";
            }
        }
        private void btn_order_chk_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["chk"].Value.ToString() == "true")
                    dataGridView1.Rows[a].Cells["order"].Value = tb_orderText.Text;
            }
        }
        private void btn_order_empty_Click(object sender, EventArgs e)
        {
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["order"].Value.ToString() == "")
                    dataGridView1.Rows[a].Cells["order"].Value = tb_orderText.Text;
            }
        }
        private void btn_All_chk_Click(object sender, EventArgs e)
        {
            string name = ((Button)sender).Name;
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (name == "btn_All_chk")
                    dataGridView1.Rows[a].Cells["chk"].Value = "true";

                else if (name == "btn_All_unchk")
                    dataGridView1.Rows[a].Cells["chk"].Value = "false";
            }
        }
        private void dataGridView1_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            
        }
        private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Selected == dataGridView1.Rows[e.RowIndex].Cells["order"].Selected)
            {
                if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString() != "" ||
                    dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
                {
                    Order_input_Search search = new Order_input_Search(this);
                    search.Where_Open = "Order_Grid";
                    search.searchText = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
                    search.oin_grid_idx[0] = e.RowIndex;
                    search.oin_grid_idx[1] = e.ColumnIndex;
                    search.TopMost = true;
                    search.Show();
                }
                else { return; }
            }
        }
    }
}