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_Send_Chk : Form
    {
        string compidx;
        Helper_DB db = new Helper_DB();
        Order_input oi;
        public Order_Send_Chk(Order_input _oi)
        {
            InitializeComponent();
            oi = _oi;
            compidx = oi.compidx;
        }
        private void Order_Send_Chk_Load(object sender, EventArgs e)
        {
            db.DBcon();

            #region 일자설정
            int Year = DateTime.Now.Year;
            int Month = DateTime.Now.Month;
            int Day = DateTime.Now.Day - 1;
            try
            {
                Start_DatePicker.Value = new DateTime(Year, Month, Day);
            }
            catch
            {
                Month -= 1;
                Day = DateTime.DaysInMonth(Year, Month);
                Start_DatePicker.Value = new DateTime(Year, Month, Day);
            }
            #endregion

            btn_Lookup_Click(null, null);
        }

        private void btn_Lookup_Click(object sender, EventArgs e)
        {
            dataGrid_Email.Rows.Clear();
            dataGrid_Fax.Rows.Clear();

            string start = Start_DatePicker.Value.ToString().Substring(0, 10);
            string end = End_DatePicker.Value.ToString().Substring(0, 10);
            string gu = oi.cb_ordersend.Text;

            #region Grid설정
            string Area = "`구분`, `팩스전송키`, `거래처명`, `날짜`, `시간`, `보낸이`, `받는이`, `전송파일명`, `전송결과`";
            string cmd = string.Format(
                "SELECT {0} FROM `Send_Order` WHERE `{1}` >= \"{2}\" AND `{1}` <= \"{3}\" AND `구분` = \"{4}\" AND `compidx` = \"{5}\";",
                Area, "날짜", start, end, gu, compidx );
            //string cmd = db.Search_Date("Send_Order", Area, "날짜", set_date[0], set_date[1], compidx);
            string Fax_Key_ary = db.DB_Send_CMD_Search(cmd);
            UTIL.MsgI(Fax_Key_ary);
            string[] Fax_Key = Fax_Key_ary.Split('|');
            input_Grid(Fax_Key);
            #endregion
        }
        #region LookUp 서브 함수
        private void input_Grid(string[] data)
        {
            switch(oi.cb_ordersend.SelectedIndex)
            {
                case 0:
                    this.Text = "팩스 전송현황";
                    dataGrid_Email.Enabled = false;
                    dataGrid_Email.Visible = false;
                    Fax_Grid(data);
                    break;

                case 1:
                    this.Text = "메일 전송현황";
                    dataGrid_Fax.Enabled = false;
                    dataGrid_Fax.Visible = false;
                    Email_Grid(data);
                    break;

                default:
                    break;
            }
        }
        private void Fax_Grid(string[] data)
        {
            string[] grid = { "", "", "", "", "", 
                              "", "", "", "" };
            bool isMail = true;
            int len = 9;
            for(int a = 0; a < data.Length; a++)
            {
                if (a % len == 0) {
                    if (data[a] != "팩스") isMail = false;
                    else isMail = true;
                }
                if (a % len == 1 && isMail) {
                    dataGrid_Fax.Rows.Add(Plus_Fax(data, grid, a));
                }
            }
        }
        private string[] Plus_Fax(string[] db_data, string[] grid, int a)
        {
            Barobill_FAX fax = new Barobill_FAX();

            // 수신자회사명, 수신번호, 전송일시, 전송상태, 전송페이지수, 성공페이지수, 전송파일명, 전송결과
            string[] data = fax.Send_chk_BaroFax(db_data[a]);
            grid[0] = db_data[a];
            grid[1] = data[0];
            grid[2] = data[1];
            grid[3] = db_data[3] + " " + db_data[4];
            grid[4] = data[3];
            grid[5] = data[4];
            grid[6] = data[5];
            grid[7] = db_data[7];
            grid[8] = data[3];

            return grid;
        }

        private void Email_Grid(string[] data)
        {
            string[] grid = { "", "", "", "", "",
                              "" };
            bool isMail = true;
            int len = 9;
            for(int a= 0; a < data.Length; a++)
            {
                if (a % len == 0) {
                    if (data[a] != "메일") isMail = false;
                    else { isMail = true; }
                }
                if (a % len == 2) { grid[0] = data[a]; }
                if (a % len == 3) { grid[1] = data[a]; }
                if (a % len == 4) { grid[2] = data[a]; }
                if (a % len == 5) { grid[3] = data[a]; }
                if (a % len == 6) { grid[4] = data[a]; }
                if (a % len == 7 && isMail) { 
                    grid[5] = data[a]; 
                    dataGrid_Email.Rows.Add(grid); 
                }
            }
        }
        #endregion

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

        private void dataGrid_Email_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            int row = e.RowIndex;
            int col = e.ColumnIndex;
            string name = ((DataGridView)sender).Name;
            string filename = "";
            switch (name)
            {
                // f_filename m_filename
                case "dataGrid_Email":
                    if (dataGrid_Email.Columns["m_filename"].Index != col) { return; }
                    filename = dataGrid_Email.Rows[row].Cells[col].Value.ToString();
                    break;
                case "dataGrid_Fax":
                    if (dataGrid_Fax.Columns["f_filename"].Index != col) { return; }
                    filename = dataGrid_Fax.Rows[row].Cells[col].Value.ToString();
                    break;
            }
            try
            {
                string localPath = Application.StartupPath + "\\Excel\\";
                // filename += ".xlsx";
                string strFile = localPath + filename;
                FileInfo fileInfo = new FileInfo(strFile);

                if (fileInfo.Exists)        // 로컬 경로에 파일이 존재 할 경우
                    Process.Start(strFile);
                else {
                    // 존재하지 않을 경우 FTP에 접속하여 로컬경로로 파일을 다운로드 함.
                    FTP_Down(filename);
                    Process.Start(strFile);
                }
            }
            catch { }
        }
        #region Sub
        private void FTP_Down(string file_name)
        {
            string ip = "1.215.250.130";
            string id = "ftpgloria";
            string pw = "admin@!@#$";

            WebClient clnt = new WebClient();

            clnt.Credentials = new NetworkCredential(id, pw);

            Uri uri = new Uri(string.Format("FTP://{0}@{1}/Excel/{2}", id, ip, file_name));

            clnt.DownloadFileAsync(uri, Application.StartupPath + "\\Excel\\" + file_name);

            clnt.DownloadFileCompleted += new AsyncCompletedEventHandler(DownloadFileCallBack);
        }
        private static void DownloadFileCallBack(object sender, AsyncCompletedEventArgs e)
        {
            if (e.Cancelled)
                UTIL.MsgE("File Download Cancelled");

            if (e.Error != null)
                UTIL.MsgE(e.Error.ToString());
        }
        #endregion
    }
}
