using AR;
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.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UniMarc
{
    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;
        bool chk_V = false;
        public Order_input(Main _main)
        {
            InitializeComponent();
            main = _main;
        }
        private void Order_input_Load(object sender, EventArgs e)
        {
            db.DBcon();
            compidx = PUB.user.CompanyIdx;

            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 != 7 && a != 12 && a != 16) { 
                    dataGridView1.Columns[a].ReadOnly = true;
                }
            }

            // 사용자 구분
            cb_user.Items.Add("전체");
            string compName = main.lbCompanyName.Text;
            string cmd = db.self_Made_Cmd("SELECT `name` FROM `User_Data` WHERE `affil` = '" + compName + "';");
            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.SelectedItem = main.botUserLabel.Text;

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

            // 주문서 조건
            string[] order_Stat = { "ISBN 인쇄", "납품처 인쇄", "납품처 ISBN" };
            cb_OrderStat.Items.AddRange(order_Stat);
            cb_OrderStat.SelectedIndex = 0;

            // 주문서 구분
            string[] order_send = { "팩스", "메일" };
            cb_ordersend.Items.AddRange(order_send);
            cb_ordersend.SelectedIndex = 0;
        }

        private void btn_lookup_Click(object sender, EventArgs e)
        {
            string Area = "`order`, `order_stat`, `isbn`, `book_name`, `author`, " +
                              "`book_comp`, `order_count`, `count`, `pay`, `total`, " +
                              "`etc`, `list_name`, `order_date`, `send_date`, `header`, " +
                              "`num`, `idx`";
            string Table = "Obj_List_Book";

            string cmd = string.Format("SELECT {0} FROM `{1}` WHERE `compidx` = \"{2}\"", Area, Table, compidx);

            string tmpData = "";

            if (tb_search_book_name.Text != "")
                tmpData += string.Format(" AND `book_name` LIKE \"%{0}%\"", tb_search_book_name.Text);

            if (tb_search_book_comp.Text != "")
                tmpData += string.Format(" AND `book_comp` LIKE \"%{0}%\"", tb_search_book_comp.Text);

            if (cb_state.Text != "전체")
                tmpData += string.Format(" AND `import` = \"{0}\"", cb_state.Text);

            if (cb_order.Text == "주문중") {
                tmpData += string.Format(" AND `order_date` >= \"{0}\" AND `order_date` <= \"{1}\"", dtp_orderBegin.Text, dtp_orderEnd.Text);
            }
            else if (cb_order.Text == "미주문")
                tmpData += string.Format(" AND `order_date` =\"\"");

            cmd += tmpData + ";";

            // string cmd = db.More_DB_Search("Obj_List_Book", tmp_col, tmp_data, takedata);

            // SELECT {0}
            // FROM `Obj_List_Book`
            // WHERE `compidx` = \"{1}\"
            //   AND `list_name` = \"{2}\"
            //   AND `date` >= \"{3}\" AND `date` <= \"{4}\"
            //   AND `book_name` LIKE \"%{3}%\"
            //   AND `book_comp` LIKE \"%{4}%\"
            //   AND `import` = \"{5}\"
            //   AND `order_date` >= \"{6}\"
            //   AND `order_date` <= \"{7}\"
            // 
            //   ;

            string db_res = db.DB_Send_CMD_Search(cmd);
            made_grid(db_res, true);
            date_Substring();
        }
        #region lookup_Click_Sub
        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 % 17 == 0) { mkgrid[1] = data[a]; }    // 주문처
                if (a % 17 == 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 % 17 == 2) { mkgrid[3] = data[a]; }   // ISBN
                if (a % 17 == 3) { mkgrid[4] = data[a]; }   // 도서명
                if (a % 17 == 4) { mkgrid[5] = data[a]; }   // 저자
                if (a % 17 == 5) { mkgrid[6] = data[a]; }   // 출판사
                if (a % 17 == 6) {  }   // 주문수 => 원래 수량과 동일하게 됨.
                if (a % 17 == 7) { mkgrid[7] = data[a]; mkgrid[8] = data[a]; }   // 원주문
                if (a % 17 == 8) { mkgrid[9] = data[a]; }   // 정가
                if (a % 17 == 9) { mkgrid[10] = data[a]; }   // 합계
                if (a % 17 == 10) { mkgrid[11] = data[a]; }   // 비고
                if (a % 17 == 11) { mkgrid[12] = data[a]; }   // 납품처
                if (a % 17 == 12) { mkgrid[13] = data[a]; }   // 주문일자
                if (a % 17 == 13) { mkgrid[14] = data[a]; }   // 송금일자
                if (a % 17 == 14) { mkgrid[15] = data[a]; }   // 번호
                if (a % 17 == 15) { mkgrid[15] += " " + data[a]; }         // 번호
                if (a % 17 == 16) {
                    mkgrid[16] = data[a];
                    if (!chk)
                        dataGridView1.Rows.Add(mkgrid);
                    else
                        dataGridView1.Rows.Add(mkgrid);

                }
            }
            // 색입히는 함수 기입
            PrintColor_Grid();
        }
        /// <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("(주)", "");
                }
            }
        }
        /// <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;
        }
        #endregion
        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)
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                string[] sear_col = { "idx", "compidx" };
                string[] sear_data = { dataGridView1.Rows[a].Cells["idx"].Value.ToString(), compidx };
                string[] edit_col = 
                { 
                    "order", "order_stat", "isbn", "book_name", "author", 
                    "book_comp", "order_count", "count", "pay", "total",
                    "etc", "list_name", "order_date", "send_date"
                };
                string[] edit_data =
                {
                    dataGridView1.Rows[a].Cells["order"].Value.ToString(),
                    "",
                    dataGridView1.Rows[a].Cells["isbn"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["book_name"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["author"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["book_comp"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["order_count"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["count"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["pay"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["total"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["etc"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["list_name"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["order_date"].Value.ToString(),
                    dataGridView1.Rows[a].Cells["send_date"].Value.ToString()
                };
                if (edit_data[1] == "") { edit_data[1] = "0"; }
                else if (edit_data[1] == "V") { edit_data[1] = "1"; }
                string U_cmd = db.More_Update("Obj_List_Book", edit_col, edit_data, sear_col, sear_data);
                Helper_DB.ExcuteNonQuery(U_cmd);
            }
            UTIL.MsgI("저장되었습니다!");
        }
        private void btn_close_Click(object sender, EventArgs e)
        {
            Close();
        }
        private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = dataGridView1.CurrentCell.RowIndex;
            int col = dataGridView1.CurrentCell.ColumnIndex;

            if (row >= 0 && col == 0)
            {
                grididx = row;
                ColumnIndex = col;
            }
            if (dataGridView1.Rows[row].Cells[col].Selected == dataGridView1.Rows[row].Cells["chk"].Selected)
            {
                if (dataGridView1.Rows[row].Cells["chk"].Value.ToString() == "true")
                {
                    dataGridView1.Rows[row].Cells["chk"].Value = "false";
                }
                else if (dataGridView1.Rows[row].Cells["chk"].Value.ToString() == "false")
                {
                    dataGridView1.Rows[row].Cells["chk"].Value = "true";
                }
            }
        }
        private void dataGridView1_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = dataGridView1.CurrentCell.RowIndex;
            int col = dataGridView1.CurrentCell.ColumnIndex;

            grididx = dataGridView1.CurrentCell.RowIndex;
            ColumnIndex = dataGridView1.CurrentCell.ColumnIndex;

            if (col == 0 || col == 1 || col == 14 ||
                col == 6 || col == 15 || col == 16)
            { return; }
            if(col == 3 || col == 4 || col == 5)
            {
                Book_Lookup bl = new Book_Lookup(this);
                bl.TopMost = true;
                string book_name = ((DataGridView)sender).Rows[row].Cells["Book_name"].Value.ToString();
                string author = ((DataGridView)sender).Rows[row].Cells["author"].Value.ToString();
                string book_comp = ((DataGridView)sender).Rows[row].Cells["Book_comp"].Value.ToString();
                string list_name = ((DataGridView)sender).Rows[row].Cells["list_name"].Value.ToString();
                bl.Lookup_Load(book_name, author, book_comp, list_name);
                bl.Show();
                return;
            }
            if (col == 2 && !chk_V)
            {
                dataGridView1.Rows[row].Cells[col].Value = "V";
                chk_V = true;
            }
            else if (col == 2 && chk_V)
            {
                dataGridView1.Rows[row].Cells[col].Value = "";
                chk_V = false;
            }
            if (col == 13 && dataGridView1.Rows[grididx].Cells[ColumnIndex].Value.ToString() != "")
            {
                dataGridView1.Rows[row].Cells["order_date"].Value = "";
            }
            else if (col == 13 && dataGridView1.Rows[grididx].Cells[ColumnIndex].Value.ToString() == "")
            {
                dataGridView1.Rows[row].Cells["order_date"].Value = DateTime.Now.ToString("d");
            }
        }
        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.Delete) {
                if (dataGridView1.Columns[col].HeaderText == "비   고") {
                    Skill_Grid sg = new Skill_Grid();
                    sg.DataGrid_to_Delete(sender, e);
                }
            }
        }
        private void btn_Excel_Click(object sender, EventArgs e)
        {
            string same = same_order();
            if (same == "false") { return; }

            string temp = Excel_sub();
            if (temp == "false") { return; }

            if (sender != null && e != null) { Process.Start(Application.StartupPath + "/Excel"); }
        }
        private string Excel_sub()
        {
            List<int> chkIdx = new List<int>();
            int[] total = { 0, 0 };
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["chk"].Value.ToString() == "true")
                {
                    chkIdx.Add(a);
                    total[0] += Convert.ToInt32(dataGridView1.Rows[a].Cells["order_count"].Value.ToString());
                    total[1] += Convert.ToInt32(dataGridView1.Rows[a].Cells["pay"].Value.ToString());
                }
            }
            if (chkIdx.Count < 1) { UTIL.MsgE("선택된 도서가 없습니다!"); return "false"; }
            string[,] inputExcel = new string[chkIdx.Count, 7];
            string pur = dataGridView1.Rows[chkIdx[0]].Cells["order"].Value.ToString();

            int isCondition = cb_OrderStat.SelectedIndex;
            for (int a = 0; a < chkIdx.Count; a++)
            {
                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();

                if (isCondition == 0)       // ISBN만
                    inputExcel[a, 6] = dataGridView1.Rows[chkIdx[a]].Cells["isbn"].Value.ToString();
                else if (isCondition == 1)  // 납품처만
                    inputExcel[a, 6] = div;
                else                        // 납품처 + ISBN
                    inputExcel[a, 6] = div + "\n" +
                                   dataGridView1.Rows[chkIdx[a]].Cells["isbn"].Value.ToString();
            }
            Excel_text ex = new Excel_text();
            string filename = ex.mk_Excel_Order(inputExcel, total, compidx, pur, tb_PS.Text);
            UTIL.MsgI("엑셀 반출 완료");

            return filename;
        }
        /// <summary>
        /// 주문처가 동일한지 조건을 따져보는 함수
        /// </summary>
        private string same_order()
        {
            string over_lab = "";
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["chk"].Value.ToString() == "true" && over_lab == "")
                {
                    over_lab = dataGridView1.Rows[a].Cells["order"].Value.ToString();
                }
                else if (dataGridView1.Rows[a].Cells["chk"].Value.ToString() == "true")
                {
                    if (dataGridView1.Rows[a].Cells["order"].Value.ToString() != over_lab)
                    {
                        UTIL.MsgE("주문처가 동일하지 않습니다!");
                        return "false";
                    }
                }
            }
            return over_lab;
        }
        private void btn_order_send_Click(object sender, EventArgs e)
        {
            // 주문처 따옴
            string pur = same_order();
            if (pur == "false") { return; }

            // 보낼 경로가 메일인지 팩스인지 확인.
            string emchk = Email_Fax_chk(pur);

            // 엑셀파일 생성
            string filename = Excel_sub();
            string filePath = Application.StartupPath + "\\Excel\\";

            Upload_File(filename, filePath);

            bool isSend = false;
            switch (emchk)
            {
                case "0":
                    lbl_OrderStat.Text = "팩스전송중입니다.";
                    isSend = Send_FAX(pur, filename, filePath);
                    break;
                case "1":
                    lbl_OrderStat.Text = "메일전송중입니다.";
                    isSend = Send_Email(pur, filename, filePath);
                    break;
            }

            if (isSend)
            {
                InputOrderDate();
            }
        }
        #region Order_Send_Sub

        private void InputOrderDate()
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                if (dataGridView1.Rows[a].Cells["chk"].Value.ToString() == "true")
                {
                    dataGridView1.Rows[a].Cells["order_date"].Value = DateTime.Now.ToString("d");
                    dataGridView1.Rows[a].Cells["chk"].Value = false;
                }
            }
        }

        private void Upload_File(string file_name, string path)
        {
            FTP ftp = new FTP();
            bool result = ftp.ConnectToServer("1.215.250.130", "21", "ftpgloria", "admin@!@#$");
            
            DirectoryInfo dirInfo = new DirectoryInfo(path);
            FileInfo[] infos = dirInfo.GetFiles();

            if (result)
            {
                lbl_OrderStat.Text = "FTP 접속 성공";
                foreach (FileInfo info in dirInfo.GetFiles())
                {
                    if (Path.GetFileName(info.Name) == file_name)
                    {
                        path = path.Replace(Application.StartupPath, "");

                        if (!ftp.UpLoad(path, info.FullName))
                            lbl_OrderStat.Text = "FTP UpLoad 실패";

                        else
                            lbl_OrderStat.Text = "FTP UpLoad 성공";
                    }
                }
            }
            else
                lbl_OrderStat.Text = "FTP 접속 실패";
        }
        /// <summary>
        /// 보낼 경로가 메일인지 팩스인지 확인
        /// </summary>
        /// <param name="pur">주문처</param>
        /// <returns></returns>
        private string Email_Fax_chk(string pur)
        {
            string cmd = db.DB_Select_Search("`emchk`", "Purchase", "sangho", pur, "comparyidx", compidx);
            string db_res = db.DB_Send_CMD_Search(cmd);
            return db_res.Replace("|", "");
        }
        /// <summary>
        /// 팩스를 보내는 함수
        /// </summary>
        /// <param name="pur">거래처명</param>
        /// <param name="filename">파일명</param>
        /// <param name="FilePath">파일경로 (파일명 포함)</param>
        /// <returns>True / False 결과</returns>
        private bool Send_FAX(string pur, string filename, string FilePath)
        {
            List<string> data_list = new List<string>();

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

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

            cmd = db.DB_Select_Search("`fax`, `boss`, `emchk`", "Purchase", "sangho", pur, "comparyidx", compidx);
            db_res = db.DB_Send_CMD_Search(cmd);
            string[] db_pur = db_res.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 == 1)
                    {
                        if (db_pur[a] != "")
                        {
                            pur_data[2] = db_pur[a];
                        }
                    }
                }
            }

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

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

            string[] fax_param = data_list.ToArray();

            FTP ftp = new FTP();

            bool result = ftp.ConnectToServer("testftp.barobill.co.kr", "9031", "gloriabook", "gloria7300");
            string path = @"";
            DirectoryInfo dirInfo = new DirectoryInfo(FilePath);
            FileInfo[] infos = dirInfo.GetFiles();

            if (result)
            {
                foreach (FileInfo info in dirInfo.GetFiles())
                {
                    if (Path.GetFileName(info.Name) == filename)
                    {
                        if (ftp.UpLoad(path, info.FullName))
                            lbl_OrderStat.Text = "팩스 FTP UPload 성공";

                        else {
                            lbl_OrderStat.Text = "팩스 FTP UPload 실패";
                            return false;
                        }

                    }
                }
            }
            else {
                lbl_OrderStat.Text = "팩스 서버 접속 실패";
                return false;
            }

            // 날짜 시간 구해오기
            string Date = DateTime.Now.ToString("yyyy-MM-dd");
            string Time = DateTime.Now.ToString("HH:mm");

            // 바로빌 FAX API연동
            string Fax_Key = fax.Send_BaroFax(filename, fax_param);

            string U_cmd = db.DB_Update("Comp", "fax_Key", Fax_Key, "idx", compidx);
            Helper_DB.ExcuteNonQuery(U_cmd);

            string[] col_Name = { "compidx", "구분", "팩스전송키", "날짜", "시간", "전송파일명" };
            string[] set_Data = { compidx, "팩스", Fax_Key, Date, Time, filename };
            string Incmd = db.DB_INSERT("Send_Order", col_Name, set_Data);
            Helper_DB.ExcuteNonQuery(Incmd);

            return true;
        }
        /// <summary>
        /// 메일 보내는 함수
        /// </summary>
        /// <param name="pur">거래처명</param>
        /// <param name="filename">파일명</param>
        /// <param name="FilePath">파일경로 (파일명 포함)</param>
        private bool Send_Email(string pur, string filename, string filePath)
        {
            String_Text st = new String_Text();

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

            string[] arr_db = db_res.Split('|');
            string sender = arr_db[0];

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

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

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

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

            // 날짜 시간 구해오기
            string Date = DateTime.Now.ToString("yyyy-MM-dd");
            string Time = DateTime.Now.ToString("HH:mm");

            filePath += string.Format("\\{0}", filename);

            Email email = new Email();
            if (email.cross_mail(compidx, filePath, m_send))
            {
                string[] col_Name = { "compidx", "구분", "거래처명", "날짜", "시간", "보낸이", "받는이", "전송파일명", "전송결과" };
                string[] set_Data = { compidx, "메일", pur, Date, Time, arr_db[0], m_send, filename, "성공" };
                string Incmd = db.DB_INSERT("Send_Order", col_Name, set_Data);
                Helper_DB.ExcuteNonQuery(Incmd);
                lbl_OrderStat.Text = "메일 전송 성공!";
                return true;
            }
            else
            {
                lbl_OrderStat.Text = "메일 전송 실패!";
                return false;
            }
        }
        #endregion
        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)
        {
            for(int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                dataGridView1.Rows[a].Cells["chk"].Value = true;
            }
        }

        private void btn_All_unchk_Click(object sender, EventArgs e)
        {
            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                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.Columns[e.ColumnIndex].HeaderText == "주문처")
            {
                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; }
            }
        }

        private void btn_AutoOrder_Click(object sender, EventArgs e)
        {
            // SELECT `sangho`
            // FROM `Purchase` 
            // WHERE idx = (SELECT `puridx` FROM `IndexWord` WHERE `word` = "특별한서재");

            for (int a = 0; a < dataGridView1.Rows.Count; a++)
            {
                string book_comp = dataGridView1.Rows[a].Cells["book_comp"].Value.ToString();

                string cmdSub = string.Format(
                    "SELECT `puridx` FROM `IndexWord` WHERE `word` = \"{0}\" AND `compidx` = \"{1}\"", book_comp, compidx);

                string cmd = string.Format(
                    "SELECT `sangho` " +
                    "FROM `Purchase` " +
                    "WHERE `idx` = ({0});", cmdSub);

                string res = db.DB_Send_CMD_Search(cmd);
                string[] pur = res.Split('|');

                dataGridView1.Rows[a].Cells["order"].Value = pur[0];
            }
        }
    }
}