using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms; 
// ref https://www.c-sharpcorner.com/article/read-excel-file-in-c-sharp-winform/
using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;
using System.IO;

namespace solarApp
{
    public partial class fmExcel : Form
    {
        System.Data.DataTable dt_cap1 = new System.Data.DataTable();

        public fmExcel()
        {
            InitializeComponent();
        }

        private void bt_inv_hour_hj_Click(object sender, EventArgs e)
        {
            string fname = "";
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Title = "Excel File Dialog";
            fdlg.InitialDirectory = @"c:\";
            fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
            fdlg.FilterIndex = 2;
            fdlg.RestoreDirectory = true;
            if (fdlg.ShowDialog() == DialogResult.OK)
            {
                fname = fdlg.FileName;
            }
            else return;
            //取得選取檔案的路徑
            string dir = Path.GetDirectoryName(fname);
            // 取得路徑下所有檔案
            string[] fileEntries = System.IO.Directory.GetFiles(dir); 

            Service.operateCSV csvSvc = new Service.operateCSV(); // readCsvTxt
            System.Data.DataTable dt = new System.Data.DataTable();
            bool isFirst = true;
            foreach (string fileName in fileEntries)
            {
                #region  取得 filename 中的 InvID 
                string fName = Path.GetFileName(fileName);
                string[] ss = fName.Split("_");
                string InvID = ss[0];
                #endregion

                if (isFirst)
                {
                    csvSvc.clear_inv("hour");
                    csvSvc.createColumnHour(ref dt, fileName);
                    csvSvc.readCsvFile(ref dt, fileName, InvID, dt.Columns.Count, isFirst);
                    isFirst = false;
                }
                else
                    csvSvc.readCsvFile(ref dt, fileName, InvID, dt.Columns.Count, isFirst);
            }
            MessageBox.Show(" 共 "+ dt.Rows.Count.ToString());

            //System.Data.DataTable dt = solarApp.Service.csvHelper.OpenCSV(fname); 
            dataGridView1.DataSource = csvSvc.insertHour2DB(ref dt);
            MessageBox.Show("OK");
        }
        protected void ImporExcel(string site_name)
        {         
            string fname = "";
            //OpenFileDialog fdlg = new OpenFileDialog();
            //fdlg.Title = "Excel File Dialog";
            //fdlg.InitialDirectory = @"d:\";
            //fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
            //fdlg.FilterIndex = 2;
            //fdlg.RestoreDirectory = true;
            string[] fileEntries = new string[0];
            Array.Clear(fileEntries, 0, fileEntries.Length);
            //取得選取檔案的路徑
            string dir;//= Path.GetDirectoryName(fname);

            using (var fbd = new FolderBrowserDialog())
            { 
                DialogResult result = fbd.ShowDialog();
                if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
                {
                    //dir = Path.GetDirectoryName(fname);
                    //fileEntries = Directory.GetFiles(fbd.SelectedPath);
                    fileEntries = Directory.GetFiles(fbd.SelectedPath, "*.*", SearchOption.AllDirectories);
                    MessageBox.Show("Files found: " + fileEntries.Length.ToString(), "Message");
                }
            }            

            // 取得路徑下所有檔案
            //string[] fileEntries = System.IO.Directory.GetFiles(dir);   //D:\temp\AUO\台中太平\台中太平\inverter
            //string[] fileEntries = Directory.GetFiles(@"D:\AUO\台中太平\inverter", "*.*", SearchOption.AllDirectories);

            // dt.Column = colCount;  
            solarApp.Service.excelHelper xlsSvc = new Service.excelHelper();
            System.Data.DataTable dt = new System.Data.DataTable();
            DataColumn mydc;
            bool isFirst = true; bool isFirstData = true;
            int x = 0;

            #region save file list
            xlsSvc.insertFile2DB(fileEntries, site_name);
            #endregion

            foreach (string fullfileName in fileEntries)
            {
                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
                if (fullfileName.Contains("~$")) { rt1.AppendText("\n -- contain ~$ in filename: " + fullfileName.ToString()); continue; }
                Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fullfileName);
                Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
                Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange;
                //dataGridView1.ColumnCount = colCount;
                //dataGridView1.RowCount = rowCount;
                string[] ff = fullfileName.Split("\\");
                string filename = string.Empty;
                filename += ff[ff.Length-1]; //只抓最後的檔名
                rt1.AppendText(filename.ToString() + "  ");
                rt1.SelectionStart = rt1.Text.Length;
                rt1.ScrollToCaret();
                int rowCount = xlRange.Rows.Count;
                int colCount = xlRange.Columns.Count;
                for (int i = 1; i <= rowCount; i++)
                {
                    #region dt add column 
                    if (isFirst)
                    {
                        for (int j = 1; j <= colCount; j++)
                        {
                            int col = 0;
                            col = j;
                            mydc = new DataColumn(col.ToString());
                            dt.Columns.Add(mydc);
                            isFirst = false;
                        } 
                    }
                    #endregion
                    DataRow row = dt.NewRow();
                    //只需要 10個欄位的版本 ---------------------------------
                    if (colCount != 10) {
                        rt1.AppendText("\n -- unable read file: " + fullfileName.ToString());
                        break; 
                    }

                    for (int j = 0; j <= colCount-1; j++)
                    {
                        if (isFirstData) // 第一筆資料為 欄位名稱
                        {
                            Microsoft.Office.Interop.Excel.Range range = xlRange.Cells[i, j+1] as Microsoft.Office.Interop.Excel.Range;
                            row[j] = range.Value.ToString();
                            if (j == 9) isFirstData = false;
                        }
                       // else if (i == 1) continue;// 第二個檔案之後的 firstRow 不需要, start from 1
                        else //從第二個檔案 開始都從第二個 row 開始
                        {
                            Microsoft.Office.Interop.Excel.Range range = xlRange.Cells[i, j+1] as Microsoft.Office.Interop.Excel.Range;
                            if (string.IsNullOrEmpty(range.Value) || string.IsNullOrWhiteSpace(range.Value)) 
                                MessageBox.Show("got it!");
                            //string ss = range.Value.ToString();
                            //ss = ss.Replace("[", "").Replace("]", "");
                            row[j] = range.Value.ToString();
                        }
                        if (j == colCount)
                        {
                            if (string.IsNullOrEmpty(row[j].ToString()) || string.IsNullOrWhiteSpace(row[j].ToString()))
                                MessageBox.Show("empty!");
                        }
                    }
                    if (string.IsNullOrEmpty(row[5].ToString()) || string.IsNullOrWhiteSpace(row[5].ToString()))
                    {
                        MessageBox.Show("empty!");
                    }
                    else
                    {
                        if (i == 1) continue;// 第二個檔案之後的 firstRow 不需要, start from 1
                        dt.Rows.Add(row);
                    }
                }
                //release com objects to fully kill excel process from running in the background  
                Marshal.ReleaseComObject(xlRange);
                Marshal.ReleaseComObject(xlWorksheet);

                //close and release  
                xlWorkbook.Close();
                Marshal.ReleaseComObject(xlWorkbook);

                //quit and release  
                xlApp.Quit();
                Marshal.ReleaseComObject(xlApp);

                //if (x ==3) break;
                string[] str = filename.Split("_"); 
                string inverterID = str[str.Length - 3] + "_" + str[str.Length - 2];
                str = inverterID.Split(" ");
                inverterID = str[str.Length - 1];

                xlsSvc.insertDay2DB(dt, filename, inverterID);
                dt.Rows.Clear();
                x++;
            } 

            //cleanup  
            GC.Collect();
            GC.WaitForPendingFinalizers();
            dataGridView1.DataSource = dt;
            //MessageBox.Show(" dt.Rows.Count = " + dt.Rows.Count.ToString()); 
           
            MessageBox.Show(" ok  ");
            //rule of thumb for releasing com objects:  
            //  never use two dots, all COM objects must be referenced and released individually  
            //  ex: [somthing].[something].[something] is bad   
        }

        private void bt_inv_day_hj_Click(object sender, EventArgs e)
        {
            string fname = "";
            OpenFileDialog fdlg = new OpenFileDialog();
            fdlg.Title = "Excel File Dialog";
            fdlg.InitialDirectory = @"c:\";
            fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
            fdlg.FilterIndex = 2;
            fdlg.RestoreDirectory = true;
            if (fdlg.ShowDialog() == DialogResult.OK)
            {
                fname = fdlg.FileName;
            }
            else return;
            //取得選取檔案的路徑
            string dir = Path.GetDirectoryName(fname);
            // 取得路徑下所有檔案
            string[] fileEntries = System.IO.Directory.GetFiles(dir);

            Service.operateCSV csvSvc = new Service.operateCSV(); // readCsvTxt
            System.Data.DataTable dt = new System.Data.DataTable();
            bool isFirst = true;
            foreach (string fileName in fileEntries)
            {
                #region  取得 filename 中的 InvID 
                string fName = Path.GetFileName(fileName);
                string[] ss = fName.Split("_");
                string InvID = ss[0];
                #endregion

                if (isFirst)
                {
                    csvSvc.clear_inv("day");
                    csvSvc.createColumnDay(ref dt, fileName);
                    csvSvc.readCsvFile(ref dt, fileName, "", dt.Columns.Count, isFirst);
                    isFirst = false;
                }
                else
                    csvSvc.readCsvFile(ref dt, fileName, "", dt.Columns.Count, isFirst);
            }
            MessageBox.Show(" 共 " + dt.Rows.Count.ToString());

            //System.Data.DataTable dt = solarApp.Service.csvHelper.OpenCSV(fname);
            dataGridView1.DataSource = dt;
            csvSvc.insertDay2DB(ref dt);
            MessageBox.Show("OK");
        }

        private void bt_day_archive_hj_Click(object sender, EventArgs e)
        {
            Service.operateCSV csvSvc = new Service.operateCSV(); // readCsvTxt
            csvSvc.archive_data("day");
            MessageBox.Show("ok");
        }

        private void bt_hour_archive_hj_Click(object sender, EventArgs e)
        {
            Service.operateCSV csvSvc = new Service.operateCSV(); // readCsvTxt
            csvSvc.archive_data("hour");
            MessageBox.Show("ok");
        }

        private void bt_clear_station_Click(object sender, EventArgs e)
        {
            ImporExcel("auo_taiping");
        }

        private void bt_archive_Click(object sender, EventArgs e)
        {

        }

        private void bt_AUO_Insert_Click(object sender, EventArgs e)
        {
            ImporExcel("auo_aimai");
        }

        /// <summary>
        /// 台中工34
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_gong34_Click(object sender, EventArgs e)
        {
            string fname = "";
            //OpenFileDialog fdlg = new OpenFileDialog();
            //fdlg.Title = "Excel File Dialog";
            //fdlg.InitialDirectory = @"d:\";
            //fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
            //fdlg.FilterIndex = 2;
            //fdlg.RestoreDirectory = true;
            string[] fileEntries = new string[0];
            Array.Clear(fileEntries, 0, fileEntries.Length);
            //取得選取檔案的路徑
            string dir;//= Path.GetDirectoryName(fname);

            using (var fbd = new FolderBrowserDialog())
            {
                DialogResult result = fbd.ShowDialog();
                if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
                {
                    //dir = Path.GetDirectoryName(fname);
                    //fileEntries = Directory.GetFiles(fbd.SelectedPath);
                    fileEntries = Directory.GetFiles(fbd.SelectedPath, "*.*", SearchOption.AllDirectories);
                    MessageBox.Show("Files found: " + fileEntries.Length.ToString(), "Message");
                }
            }

            // 取得路徑下所有檔案
            //string[] fileEntries = System.IO.Directory.GetFiles(dir);   //D:\temp\AUO\台中太平\台中太平\inverter
            //string[] fileEntries = Directory.GetFiles(@"D:\AUO\台中太平\inverter", "*.*", SearchOption.AllDirectories);

            // dt.Column = colCount;  
            solarApp.Service.excelHelper xlsSvc = new Service.excelHelper();
            System.Data.DataTable dt = new System.Data.DataTable();
            DataColumn mydc;
            bool isFirst = true; bool isFirstData = true;
            int x = 0;

            #region save file list
            xlsSvc.insertFile2DB__enlux_gong34(fileEntries, "gong34");
            #endregion

            foreach (string fullfileName in fileEntries)
            {
                Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
                if (fullfileName.Contains("~$")) { rt1.AppendText("\n -- contain ~$ in filename: " + fullfileName.ToString()); continue; }
                Microsoft.Office.Interop.Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(fullfileName);
                //Microsoft.Office.Interop.Excel._Worksheet xlWorksheet = xlWorkbook.Sheets[1];
                //xl.Worksheet ws = (xl.Worksheet)wb.Sheets[1];
                //foreach (xl.Worksheet ws1 in wb.Sheets)
                //{
                //    MessageBox.Show(ws1.Name);
                //    // or whatever you want to do with the worksheet	
                //}
                string[] ff = fullfileName.Split("\\");
                string filename = string.Empty;
                filename += ff[ff.Length - 1]; //只抓最後的檔名
                rt1.AppendText(filename.ToString() + "  ");
                rt1.SelectionStart = rt1.Text.Length;
                rt1.ScrollToCaret();

                foreach (Microsoft.Office.Interop.Excel._Worksheet xlWorksheet in  xlWorkbook.Sheets)
                {
                   // MessageBox.Show(xlWorksheet.Name);
                    Microsoft.Office.Interop.Excel.Range xlRange = xlWorksheet.UsedRange;
                    //dataGridView1.ColumnCount = colCount;
                    //dataGridView1.RowCount = rowCount;
                    rt1.AppendText(" - " + xlWorksheet.Name);
                    rt1.SelectionStart = rt1.Text.Length;
                    rt1.ScrollToCaret();
                    int rowCount = xlRange.Rows.Count;
                    int colCount = xlRange.Columns.Count;
                    for (int i = 1; i <= rowCount; i++)
                    {
                        #region dt add column 
                        if (isFirst)
                        {
                            for (int j = 1; j <= colCount; j++)
                            {
                                int col = 0;
                                col = j;
                                mydc = new DataColumn(col.ToString());
                                dt.Columns.Add(mydc);
                                isFirst = false;
                            }
                        }
                        #endregion
                        DataRow row = dt.NewRow();
                        //只需要 11個欄位的版本 ---------------------------------
                        if (colCount != 11)
                        {
                            rt1.AppendText("\n -- unable read file: " + fullfileName.ToString());
                            break;
                        }

                        for (int j = 0; j <= colCount - 1; j++)
                        {
                            if (isFirstData) // 第一筆資料為 欄位名稱
                            {
                                Microsoft.Office.Interop.Excel.Range range = xlRange.Cells[i, j + 1] as Microsoft.Office.Interop.Excel.Range;
                                row[j] = range.Value.ToString();
                                if (j == 11) isFirstData = false;
                            }
                            // else if (i == 1) continue;// 第二個檔案之後的 firstRow 不需要, start from 1
                            else //從第二個檔案 開始都從第二個 row 開始
                            {
                                Microsoft.Office.Interop.Excel.Range range = xlRange.Cells[i, j + 1] as Microsoft.Office.Interop.Excel.Range;
                                if (string.IsNullOrEmpty(range.Value) || string.IsNullOrWhiteSpace(range.Value))
                                    MessageBox.Show("got it!");
                                //string ss = range.Value.ToString();
                                //ss = ss.Replace("[", "").Replace("]", "");
                                row[j] = range.Value.ToString();
                            }
                            if (j == colCount)
                            {
                                if (string.IsNullOrEmpty(row[j].ToString()) || string.IsNullOrWhiteSpace(row[j].ToString()))
                                    MessageBox.Show("empty!");
                            }
                        }
                        if (string.IsNullOrEmpty(row[5].ToString()) || string.IsNullOrWhiteSpace(row[5].ToString()))
                        {
                            MessageBox.Show("empty!");
                        }
                        else
                        {
                            if (i == 1) continue;// 第二個檔案之後的 firstRow 不需要, start from 1
                            dt.Rows.Add(row);
                        }
                    }
                    //release com objects to fully kill excel process from running in the background  
                    Marshal.ReleaseComObject(xlRange);
                    Marshal.ReleaseComObject(xlWorksheet);

                    xlsSvc.insertDay2DB_enlux_gong34(dt, filename);
                    dt.Rows.Clear();

                } //foreach excel.sheet 

                //close and release  
                xlWorkbook.Close();
                Marshal.ReleaseComObject(xlWorkbook);

                //quit and release  
                xlApp.Quit();
                Marshal.ReleaseComObject(xlApp); 

                x++;
            }// foreach files

            //cleanup  
            GC.Collect();
            GC.WaitForPendingFinalizers();
            dataGridView1.DataSource = dt;
            //MessageBox.Show(" dt.Rows.Count = " + dt.Rows.Count.ToString()); 

            MessageBox.Show(" ok  ");
            //rule of thumb for releasing com objects:  
            //  never use two dots, all COM objects must be referenced and released individually  
            //  ex: [somthing].[something].[something] is bad   
        }

        private void bt_sun_taoyuan_Click(object sender, EventArgs e)
        {
            string fname = "";
            string[] fileEntries = new string[0];
            Array.Clear(fileEntries, 0, fileEntries.Length);
            //取得選取檔案的路徑
            string dir;//= Path.GetDirectoryName(fname);

            using (var fbd = new FolderBrowserDialog())
            {
                DialogResult result = fbd.ShowDialog();
                if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
                {
                    //dir = Path.GetDirectoryName(fname);
                    //fileEntries = Directory.GetFiles(fbd.SelectedPath);
                    fileEntries = Directory.GetFiles(fbd.SelectedPath, "*.*", SearchOption.AllDirectories);
                    MessageBox.Show("Files found: " + fileEntries.Length.ToString(), "Message");
                }
            }

            Service.operateCSV csvSvc = new Service.operateCSV(); // readCsvTxt
            System.Data.DataTable dt = new System.Data.DataTable();
            bool isFirst = true;
            foreach (string fileName in fileEntries)
            {
                #region  取得 filename 中的 InvID 
                string fName = Path.GetFileName(fileName); 
                rt1.AppendText(fName + "  ");
                rt1.SelectionStart = rt1.Text.Length;
                rt1.ScrollToCaret();
                #endregion

                if (isFirst)
                {
                    //csvSvc.clear_inv("hour");
                    csvSvc.taoYuan_createColumnHour(ref dt, fileName);
                    csvSvc.taoYuan_readCsvFile(ref dt, fileName, dt.Columns.Count, isFirst);
                    isFirst = false;
                }
                else
                    csvSvc.taoYuan_readCsvFile(ref dt, fileName, dt.Columns.Count, isFirst);
            }
            MessageBox.Show(" 共 " + dt.Rows.Count.ToString());

            //System.Data.DataTable dt = solarApp.Service.csvHelper.OpenCSV(fname); 
            csvSvc.taoYuan_insertHour2DB(ref dt, "sun_taoyuan");
            MessageBox.Show("OK");
        }

        private void bt_sun_yadong_Click(object sender, EventArgs e)
        {
            string fname = "";
            string[] fileEntries = new string[0];
            Array.Clear(fileEntries, 0, fileEntries.Length);
            //取得選取檔案的路徑
            string dir;//= Path.GetDirectoryName(fname);

            using (var fbd = new FolderBrowserDialog())
            {
                DialogResult result = fbd.ShowDialog();
                if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
                {
                    //dir = Path.GetDirectoryName(fname);
                    //fileEntries = Directory.GetFiles(fbd.SelectedPath);
                    fileEntries = Directory.GetFiles(fbd.SelectedPath, "*.*", SearchOption.AllDirectories);
                    MessageBox.Show("Files found: " + fileEntries.Length.ToString(), "Message");
                }
            }

            Service.operateCSV csvSvc = new Service.operateCSV(); // readCsvTxt
            System.Data.DataTable dt = new System.Data.DataTable();
            bool isFirst = true;
            foreach (string fileName in fileEntries)
            {
                #region  取得 filename 中的 InvID 
                string fName = Path.GetFileName(fileName);
                rt1.AppendText(fName + "  ");
                rt1.SelectionStart = rt1.Text.Length;
                rt1.ScrollToCaret();
                #endregion

                if (isFirst)
                {
                    //csvSvc.clear_inv("hour");
                    csvSvc.taoYuan_createColumnHour(ref dt, fileName);
                    csvSvc.taoYuan_readCsvFile(ref dt, fileName, dt.Columns.Count, isFirst);
                    isFirst = false;
                }
                else
                    csvSvc.taoYuan_readCsvFile(ref dt, fileName, dt.Columns.Count, isFirst);
            }
            //MessageBox.Show(" 共 " + dt.Rows.Count.ToString());
            lbSiteName_sensor.Text = " sun 亞東觀音 共：" + dt.Rows.Count.ToString();
            //System.Data.DataTable dt = solarApp.Service.csvHelper.OpenCSV(fname); 
            csvSvc.taoYuan_insertHour2DB(ref dt, "sun_yadong");
            MessageBox.Show("OK");
        }
    }
}
