using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Net.Mail;
using System.Text;
using System.Windows.Forms;
using solarApp.Service;
using solarApp.Model;
//using System.Text.RegularExpressions;

namespace solarApp
{
    public partial class fmArchive : Form
    {
        getStationSvc stationSvc = new getStationSvc();
        System.Timers.Timer _timer;
        bool autoTask = false; //測試自動跑 irrDayHour 累計日照小時差異
        procSyncError svc = new procSyncError(); // 異常資料同步
        DateTime doTimerTaskTime = DateTime.Now;
        TimeSpan doTaskDuratin;
        public fmArchive()
        {
            InitializeComponent();
        }

        private void bt_inv_proc_Click(object sender, EventArgs e)
        {

        }

        private void bt_Sensor_Click(object sender, EventArgs e)
        {
            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            //procSensorSvc sensorSvc = new procSensorSvc(lbSiteDB_sensor.Text, lbSiteID_sensor.Text, date1, date1);
            string date2 = dtSelect2.Value.ToString("yyyy-MM-dd");
            //procSensorSvc sensorSvc = new procSensorSvc(lbSiteDB_sensor.Text, lbSiteID_sensor.Text, date1, date1);
            procSensorSvc sensorSvc = new procSensorSvc();
            //invSvc._siteDB = lbSiteDB_sensor.Text;
            //invSvc._siteID = lbSiteID_sensor.Text.Substring(0, 9);
            //invSvc._siteID01 = lbSiteID_sensor.Text;
            //invSvc._date1 = date1;
            //invSvc._date2 = date1;
            sensorSvc.isFirst = true;
            foreach (DateTime day in EachDay(DateTime.Parse(date1), DateTime.Parse(date2)))
            {
                //string d1 = day.ToString("yyyy-MM-dd"); 
                sensorSvc.archiveData(lbSiteID_sensor.Text.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                sensorSvc.archiveSensorHistoryHourData(lbSiteID_sensor.Text.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                sensorSvc.isFirst = false;
            }
            //sensorSvc._siteDB = lbSiteDB_sensor.Text;
            //sensorSvc._siteID = lbSiteID_sensor.Text.Substring(0, 9);
            //sensorSvc._siteID01 = lbSiteID_sensor.Text;
            //sensorSvc._date1 = date1;
            //sensorSvc._date2 = date1;

            //sensorSvc.archiveData();
            //MessageBox.Show("OK");
            lbMsgTitle.Text = DateTime.Now.ToString() + " sensor OK";
        }

        private void fmArchive_Load(object sender, EventArgs e)
        {
           // MessageBox.Show(" loading ");
            #region 電站清單
            int i = 0;
            var site_list = stationSvc.get_station_list();
            foreach (var item in site_list)
            {
                RadioButton rb = new RadioButton();
                rb.Name = item.SiteID;
                rb.Text = item.SiteName;
                rb.Tag = item.SiteDB;
                rb.Font = new Font(Font.FontFamily, 12);
                rb.AutoSize = true;
                rb.CheckedChanged += new EventHandler(rb_site_CheckedChanged);
                fp_site.Controls.Add(rb);
                if (i == 0) rb.Checked = true;
                i++;
            }
            #endregion

            #region 自動執行
            _timer = new System.Timers.Timer();
            _timer.Interval = 10000;
            _timer.SynchronizingObject = this;
            _timer.Elapsed += _timer_Elapsed;
            _timer.Start();
            #endregion

            // dtselect_station1.Value = DateTime.Today.AddDays(-1);
            dtSelect1.Value = System.DateTime.Today.AddDays(-1);
            dtSelect2.Value = System.DateTime.Today.AddDays(-1);

            #region 載入 DB -> Niagara
            fmMain f2 = new fmMain();
            f2.TopLevel = false;
            f2.Parent = tabControl1.TabPages[1];
            f2.FormBorderStyle = FormBorderStyle.None;
            f2.Dock = DockStyle.Fill;
            f2.Show();
            #endregion
        }

        private void _timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            lbMsgStatus.Text = (autoTask) ? "autoTask = true" : "autoTask = false";
            lbMsgStatus.Text += " timespan = " + (DateTime.Now - doTimerTaskTime).TotalMinutes.ToString();

            if (DateTime.Now.Hour >= 2 && DateTime.Now.Minute == 0)
            {
                doTimerTaskTime = DateTime.Now;
                autoTask = false;
            }

            // 凌晨 2點後，如果間隔30分鐘 沒有跑異常同步 就啟動啟動
            doTaskDuratin = DateTime.Now - doTimerTaskTime;  // 
            if (DateTime.Now.Hour >= 2 && doTaskDuratin.TotalMinutes > 15 && (autoTask == true))
            {
                doTimerTaskTime = DateTime.Now;
                autoTask = false;
            }
            //每日歸檔
            if (DateTime.Now.Hour == 00 && DateTime.Now.Minute == 15 )
            {
                //MessageBox.Show("ok");
                autoTask = true;
                lbMsgTitle.Text = DateTime.Now.ToString() + " timer start";
                dtSelect1.Value = System.DateTime.Now.AddDays(-1);
                dtSelect2.Value = System.DateTime.Now.AddDays(-1);
                bt_archive.PerformClick();
                autoTask = false;
                //bt_archive_Click.PerformClick(); 
            }

            //異常處理 每 5分鐘跑一次
            if ((DateTime.Now.Minute % 5) == 0 && (DateTime.Now.Second) < 30 && (autoTask == false))
            {
                doTimerTaskTime = DateTime.Now;
                autoTask = true;
                lbMsgTitle.Text = "異常處理 " + DateTime.Now.ToString() + " timer start";                
                btSyncErr.PerformClick();
                lbMsgTitle.Text = "異常處理 done" + DateTime.Now.ToString() ;
                autoTask = false;
                //bt_archive_Click.PerformClick(); 
            }


            //臨時的 累計日照
            //if (DateTime.Now.Minute == 30 && (DateTime.Now.Second >= 0 && DateTime.Now.Second <= 10) && autoTask == false)
            //{
            //    //MessageBox.Show("ok");
            //    autoTask = true;
            //    lbMsgTitle.Text = DateTime.Now.ToString() + " 臨時的 累計日照 start";

            //    button2.PerformClick();
            //    //bt_archive_Click.PerformClick(); 
            //}


            //水位管理
            //if (System.DateTime.Now.Hour == 03 && DateTime.Now.Minute == 30 
            //    && (DateTime.Now.Second >= 0 && DateTime.Now.Second <= 10) 
            //    && autoTask == false)
            //{
            //    int i = 0;
            //    var site_list = stationSvc.get_station_list();

            //    archiveLowData archiveData = new archiveLowData();
            //    autoTask = true;
            //    foreach (var item in site_list)
            //    {
            //        archiveData.archiveData(item.SiteID.Substring(0, 9));

            //        i++;
            //    }
            //    autoTask = false;
            //    lbMsgTitle.Text = System.DateTime.Now.ToString() + "  水位管理 - 資料搬移完成！";
            //}
        }

        private void rb_site_CheckedChanged(object sender, EventArgs e)
        {
            RadioButton rb = sender as RadioButton;
            if (rb.Checked)
            { 
                lbSiteName_sensor.Text = rb.Text;
                lbSiteDB_sensor.Text = rb.Tag.ToString();
                lbSiteID_sensor.Text = rb.Name;

                //顯示 table name on label
                //lbSiteRaw.Text = lbSiteName_inv.Text + "  " + lbSiteDB_inv.Text + ".s" + lbSiteID_inv.Text + "_Station";
                //lbInvRaw.Text = lbSiteName_inv.Text + "  " + lbSiteDB_inv.Text + ".s" + lbSiteID_inv.Text + "_Inv";
                //lbSensorRaw.Text = lbSiteName_inv.Text + "  " + lbSiteDB_inv.Text + ".s" + lbSiteID_inv.Text + "_SensorAVG";

                //add_inv_list(lbSiteDB_inv.Text, lbSiteID_inv.Text.Substring(0, 9));
            }
        }

        private void btVerifyData_Click(object sender, EventArgs e)
        {
            fmMain fm = new fmMain();
            fm.Show();
        }

        public IEnumerable<DateTime> EachDay(DateTime from, DateTime thru)
        {
            for (var day = from.Date; day.Date <= thru.Date; day = day.AddDays(1))
                yield return day;
        }

        public IEnumerable<DateTime> EachHour(DateTime from, DateTime thru)
        {
            for (var time = from.Date; time.Date <= thru.Date; time = time.AddHours(1))
                yield return time;
        }

        private void bt_Inv_Click(object sender, EventArgs e)
        {
            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            string date2 = dtSelect2.Value.ToString("yyyy-MM-dd");
            //procSensorSvc sensorSvc = new procSensorSvc(lbSiteDB_sensor.Text, lbSiteID_sensor.Text, date1, date1);
            procInvSvc invSvc = new procInvSvc();
            //invSvc._siteDB = lbSiteDB_sensor.Text;
            //invSvc._siteID = lbSiteID_sensor.Text.Substring(0, 9);
            //invSvc._siteID01 = lbSiteID_sensor.Text;
            //invSvc._date1 = date1;
            //invSvc._date2 = date1;
            foreach (DateTime day in EachDay(DateTime.Parse(date1), DateTime.Parse(date2)))
            {
                //string d1 = day.ToString("yyyy-MM-dd");
                invSvc.archiveData(lbSiteID_sensor.Text.Substring(0, 9), day.ToString("yyyy-MM-dd"));
            }
            //sensorSvc.archiveData();
            //MessageBox.Show("OK");
            lbMsgTitle.Text = DateTime.Now.ToString() + " Inv OK";
        }

        private void dtSelect_ValueChanged(object sender, EventArgs e)
        {
            bt_clear_inv.Enabled = true;
            bt_clear_station.Enabled = true;
            bt_clear_sensor.Enabled = true;
            bt_clear_inv.Text = "clear " + dtSelect1.Value.ToString("MM-dd");
            bt_clear_station.Text = "clear " + dtSelect1.Value.ToString("MM-dd");
            bt_clear_sensor.Text = "clear " + dtSelect1.Value.ToString("MM-dd");
        }

        private void bt_clear_inv_Click(object sender, EventArgs e)
        {
            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            //procSensorSvc sensorSvc = new procSensorSvc(lbSiteDB_sensor.Text, lbSiteID_sensor.Text, date1, date1);
            procInvSvc invSvc = new procInvSvc();
            invSvc._siteDB = lbSiteDB_sensor.Text;
            invSvc._siteID = lbSiteID_sensor.Text.Substring(0, 9);
            invSvc._siteID01 = lbSiteID_sensor.Text;
            invSvc._date1 = date1;
            //invSvc._date2 = date1;
            invSvc.clearData();
            //sensorSvc.archiveData();
            //MessageBox.Show("OK");
            lbMsgTitle.Text = DateTime.Now.ToString() + " inv clear OK";
        }

        private void bt_clear_station_Click(object sender, EventArgs e)
        {
            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            //procSensorSvc sensorSvc = new procSensorSvc(lbSiteDB_sensor.Text, lbSiteID_sensor.Text, date1, date1);
            procStationSvc siteSvc = new procStationSvc();
            siteSvc._siteDB = lbSiteDB_sensor.Text;
            siteSvc._siteID = lbSiteID_sensor.Text.Substring(0, 9);
            siteSvc._siteID01 = lbSiteID_sensor.Text;
            siteSvc._date1 = date1;
            //siteSvc._date2 = date1;
            siteSvc.clearData();
            //sensorSvc.archiveData();
            //MessageBox.Show("OK");
            lbMsgTitle.Text = DateTime.Now.ToString() + " clear station OK";
        }

        private void bt_site_Click(object sender, EventArgs e)
        {
            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            string date2 = dtSelect2.Value.ToString("yyyy-MM-dd");
            //procSensorSvc sensorSvc = new procSensorSvc(lbSiteDB_sensor.Text, lbSiteID_sensor.Text, date1, date1);
            procStationSvc siteSvc = new procStationSvc();
            //invSvc._siteDB = lbSiteDB_sensor.Text;
            //invSvc._siteID = lbSiteID_sensor.Text.Substring(0, 9);
            //invSvc._siteID01 = lbSiteID_sensor.Text;
            //invSvc._date1 = date1;
            //invSvc._date2 = date1;
            foreach (DateTime day in EachDay(DateTime.Parse(date1), DateTime.Parse(date2)))
            {
                //string d1 = day.ToString("yyyy-MM-dd"); 
                siteSvc.archiveData(lbSiteID_sensor.Text.Substring(0, 9), day.ToString("yyyy-MM-dd"));
            }
            //sensorSvc.archiveData();
            //MessageBox.Show("OK");
            lbMsgTitle.Text = DateTime.Now.ToString() + " site OK";
        }

        private void bt_archive_Click(object sender, EventArgs e)
        {
            var site_list = stationSvc.get_station_list();
           
            //bt_Sensor.PerformClick();
            //bt_Inv.PerformClick();
            //bt_site.PerformClick(); 
            //bt_rpt_invDay.PerformClick();
            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd"); 
            string date2 = dtSelect2.Value.ToString("yyyy-MM-dd"); 
            procSensorSvc sensorSvc = new procSensorSvc();
            procInvSvc invSvc = new procInvSvc();
            procStationSvc siteSvc = new procStationSvc(); 
           
            foreach (var item in site_list)
            {
                //RadioButton rb = new RadioButton();
                //rb.Name = item.SiteID;
                //rb.Text = item.SiteName;
                //rb.Tag = item.SiteDB;
                foreach (DateTime day in EachDay(DateTime.Parse(date1), DateTime.Parse(date2)))
                { 
                    sensorSvc.archiveData(item.SiteID.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                    invSvc.archiveData(item.SiteID.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                    siteSvc.archiveData(item.SiteID.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                }
            }
            sensorSvc.isFirst = true;
            foreach (var item in site_list)
            {
                //for sensor_history_hour
                foreach (DateTime day in EachDay(DateTime.Parse(date1), DateTime.Parse(date2)))
                {
                    sensorSvc.archiveSensorHistoryHourData(item.SiteID.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                    sensorSvc.isFirst = false;
                    invSvc.report_invDay(item.SiteID.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                }
            }
           
            lbMsgTitle.Text = System.DateTime.Now.ToString() + " 完成！";
        }

        private void bt_clear_sensor_Click(object sender, EventArgs e)
        {
            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            //procSensorSvc sensorSvc = new procSensorSvc(lbSiteDB_sensor.Text, lbSiteID_sensor.Text, date1, date1);
            procSensorSvc sensorSvc = new procSensorSvc();
            sensorSvc._siteDB = lbSiteDB_sensor.Text;
            sensorSvc._siteID = lbSiteID_sensor.Text.Substring(0, 9);
            sensorSvc._siteID01 = lbSiteID_sensor.Text;
            sensorSvc._date1 = date1;
            //sensorSvc._date2 = date1;
            sensorSvc.clearData();
            //sensorSvc.archiveData();
            //MessageBox.Show("OK");
            lbMsgTitle.Text = DateTime.Now.ToString() + " clear_sensor OK";
        }

        private void lbSiteDB_sensor_Click(object sender, EventArgs e)
        {
            fmExcel fm = new fmExcel();
            fm.Show();

        }

        private void bt_meter_Click(object sender, EventArgs e)
        {
            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            procSensorSvc sensorSvc = new procSensorSvc();

            sensorSvc.archiveMeterData(lbSiteID_sensor.Text.Substring(0, 9), date1);
            //MessageBox.Show("OK");
            lbMsgTitle.Text = DateTime.Now.ToString() + " meter OK";
        }

        /// <summary>
        /// 日報表 - 每日歸檔
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void bt_rpt_invDay_Click(object sender, EventArgs e)
        {
            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            string date2 = dtSelect2.Value.ToString("yyyy-MM-dd"); 
            procInvSvc invSvc = new procInvSvc();
             
            foreach (DateTime day in EachDay(DateTime.Parse(date1), DateTime.Parse(date2)))
            { 
                invSvc.report_invDay(lbSiteID_sensor.Text.Substring(0, 9), day.ToString("yyyy-MM-dd"));
            }

            //MessageBox.Show("OK");
            lbMsgTitle.Text = DateTime.Now.ToString() + " 日報 OK";
        }

        private void bt_invDay_Click(object sender, EventArgs e)
        {
            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            string date2 = dtSelect2.Value.ToString("yyyy-MM-dd");
            get_inv_svc invSvc = new get_inv_svc();
            var ds =  invSvc.get_ck_invDay_list(date1, date2);
            gv_rpt_invDay.DataSource = ds;
            gv_rpt_invDay.Columns[0].Width = 60;            
            gv_rpt_invDay.Columns[1].Width = 80;
            gv_rpt_invDay.Columns[2].Width = 100;
            gv_rpt_invDay.Columns[3].Width = 90;
            gv_rpt_invDay.Columns[3].HeaderText = "資料量";
            gv_rpt_invDay.Columns[4].Width = 90;
            gv_rpt_invDay.Columns[4].HeaderText = "Inv建立";
            //gv_rpt_invDay.Columns[5].Width = 90;
            //gv_rpt_invDay.Columns[5].HeaderText = "日期間";
            gv_rpt_invDay.Columns[5].Visible = false;
            gv_rpt_invDay.Columns[6].Width = 80;
            gv_rpt_invDay.Columns[6].HeaderText = "日區間";
            gv_rpt_invDay.Columns[7].Width = 80;
            gv_rpt_invDay.Columns[7].HeaderText = "差異量";
            gv_rpt_invDay.Columns[8].Width = 80;
            gv_rpt_invDay.Columns[8].HeaderText = "日報";

        }

        private void gv_rpt_invDay_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (gv_rpt_invDay.Rows[e.RowIndex].Cells["CsubstrctionB"].Value != null && !string.IsNullOrWhiteSpace(gv_rpt_invDay.Rows[e.RowIndex].Cells["CsubstrctionB"].Value.ToString()))
            {
                if (gv_rpt_invDay.Rows[e.RowIndex].Cells["CsubstrctionB"].Value.ToString() != "0")
                {
                    gv_rpt_invDay.Rows[e.RowIndex].Cells["CsubstrctionB"].Style = new DataGridViewCellStyle { ForeColor = Color.Red, BackColor = Color.White };
                }
            }
        }

        private void gv_rpt_invDay_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.RowIndex > 0)
            {
                string powerStationID = gv_rpt_invDay.Rows[e.RowIndex].Cells[0].Value.ToString();
                string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
                string date2 = dtSelect2.Value.ToString("yyyy-MM-dd");
                get_inv_svc invSvc = new get_inv_svc();
                if (e.ColumnIndex != 8)
                { 
                    var ds = invSvc.get_ck_invDay_detail1(powerStationID, date1, date2);
                    gv_inv_detail.DataSource = ds;
                    gv_inv_detail.Columns[0].Width = 60;
                    gv_inv_detail.Columns[1].Width = 160; //invID
                    gv_inv_detail.Columns[2].Width = 80;
                    gv_inv_detail.Columns[3].Width = 90;
                } else
                { // 日報 
                   var ds = invSvc.get_reportDay(powerStationID, date1, date2);
                    gv_inv_detail.DataSource = ds;
                    gv_inv_detail.Columns[0].Width = 60;
                    gv_inv_detail.Columns[1].Width = 80; //report_date
                    gv_inv_detail.Columns[2].Width = 70;
                    gv_inv_detail.Columns[3].Width = 70;
                    gv_inv_detail.Columns[4].Width = 70;
                    gv_inv_detail.Columns[5].Width = 70;
                    gv_inv_detail.Columns[6].Width = 70;
                }                
            }
            //switch (e.ColumnIndex)
            //{
            //    case 0:
            //        MessageBox.Show("这是第零列得");
            //        break;
            //    default:
            //        break;
            //}
        }

        private void gv_inv_detail_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (gv_inv_detail.Columns.Count == 5 || e.RowIndex == -1) return; 

            string inverterID = gv_inv_detail.Rows[e.RowIndex].Cells[1].Value.ToString();
            //MessageBox.Show(inverterID);

            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            string date2 = dtSelect2.Value.ToString("yyyy-MM-dd");
            get_inv_svc invSvc = new get_inv_svc();
            var ds = invSvc.get_ck_invDay_detail2(inverterID, date1, date2);
            gv_inv_detail.DataSource = ds;
            gv_inv_detail.Columns[0].Width = 60;
            gv_inv_detail.Columns[1].Width = 150;
            gv_inv_detail.Columns[2].Width = 80;
            gv_inv_detail.Columns[3].Width = 100;
            gv_inv_detail.Columns[4].Width = 80;
            gv_inv_detail.Columns[5].Width = 80;
        } 

        private void bt_sensor_lackData_Click(object sender, EventArgs e)
        {
            //procSensorSvc sensorSvc = new procSensorSvc();
            //getSensorSvc GetSensor = new getSensorSvc();
            //var ds = GetSensor.get_lack_sensorData(dtSelect1.Value.ToString("yyyy-MM-dd"));
            ////foreach (DateTime day in EachDay(DateTime.Parse(date1), DateTime.Parse(date2)))
            //foreach (var item in ds) 
            //{ 
            //    sensorSvc.archiveData(item.SITEID, item.TIMESTAMP.ToString("yyyy-MM-dd"));
            //}

            var site_list = stationSvc.get_station_list();

            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            string date2 = dtSelect2.Value.ToString("yyyy-MM-dd");
            procSensorSvc sensorSvc = new procSensorSvc();
            procInvSvc invSvc = new procInvSvc();
            //procStationSvc siteSvc = new procStationSvc();
            int i = 0;
            foreach (var item in site_list)
            {

                foreach (DateTime day in EachDay(DateTime.Parse(date1), DateTime.Parse(date2)))
                {
                    sensorSvc.archiveData(item.SiteID.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                    //invSvc.archiveData(item.SiteID.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                    //siteSvc.archiveData(item.SiteID.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                    invSvc.report_invDay(item.SiteID.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                }
                i++;
            }

            sensorSvc.isFirst = true;
            foreach (var item in site_list)
            {
                //for sensor_history_hour
                foreach (DateTime day in EachDay(DateTime.Parse(date1), DateTime.Parse(date2)))
                {
                    sensorSvc.archiveSensorHistoryHourData(item.SiteID.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                    sensorSvc.isFirst = false;
                }
            }

            // MessageBox.Show("OK");
            lbMsgTitle.Text = DateTime.Now.ToString() + " sensor_lackData OK";
        }

        private void bt_lackStation_Click(object sender, EventArgs e)
        {
            procStationSvc stationSvc = new procStationSvc();
            getStationSvc GetStation = new getStationSvc();
            var ds = GetStation.get_lack_stationData(dtSelect1.Value.ToString("yyyy-MM-dd"));

            procInvSvc invSvc = new procInvSvc(); 
            //foreach (DateTime day in EachDay(DateTime.Parse(date1), DateTime.Parse(date2)))
            foreach (var item in ds)
            {
                stationSvc.archiveData(item.SITEID, item.TIMESTAMP.ToString("yyyy-MM-dd")); // 補 station
                invSvc.report_invDay(item.SITEID, item.TIMESTAMP.ToString("yyyy-MM-dd")); // 補日報表
            }

            //MessageBox.Show("OK"); lackStation
            lbMsgTitle.Text = DateTime.Now.ToString() + " lackStation OK";
        }


        private void bt_archive_One_Click(object sender, EventArgs e)
        {
            int i = 0;
            //var site_list = stationSvc.get_station_list();

            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            string date2 = dtSelect2.Value.ToString("yyyy-MM-dd");
            procSensorSvc sensorSvc = new procSensorSvc();
            procInvSvc invSvc = new procInvSvc();
            procStationSvc siteSvc = new procStationSvc();

            //foreach (var item in site_list)
            //{ 
            sensorSvc.isFirst = true;
            foreach (DateTime day in EachDay(DateTime.Parse(date1), DateTime.Parse(date2)))
            {
                sensorSvc.archiveData(lbSiteID_sensor.Text.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                sensorSvc.archiveSensorHistoryHourData(lbSiteID_sensor.Text.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                sensorSvc.isFirst = false;
                invSvc.archiveData(lbSiteID_sensor.Text.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                siteSvc.archiveData(lbSiteID_sensor.Text.Substring(0, 9), day.ToString("yyyy-MM-dd"));
                invSvc.report_invDay(lbSiteID_sensor.Text.Substring(0, 9), day.ToString("yyyy-MM-dd"));
            }
            i++;
            //}
            lbMsgTitle.Text = System.DateTime.Now.ToString() + " 完成！";
        }

        private void bt_updateInstantValue_Click(object sender, EventArgs e)
        {
            procArchiveHourly svc = new procArchiveHourly();
            var result = svc.proc_s1_site();
            gv_inv_detail.DataSource = result;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            List<string> user = new List<string>();
            user.Add(tbReceiver.Text.Trim());
            List<string> file = new List<string>();

            var result = Send(user, tbTitle.Text, tbContent.Text, file);

            if (result.CompareTo("成功") == 0)
            {
                MessageBox.Show("【SendEmailJob】 寄送成功! ");
            } 
        }
        private string Send(List<string> recipientEmails, string subject, string content, List<string> attachments)
        {
            var reason = string.Empty;
            var CanDoSend = true;
            MailMessage MyMail = new MailMessage();

            MyMail.SubjectEncoding = System.Text.Encoding.UTF8;//郵件標題編碼
            MyMail.BodyEncoding = System.Text.Encoding.UTF8; //郵件內容編碼
            MyMail.IsBodyHtml = true; //是否使用html格式
            var kkk = $"FIC 太陽能電站管理系統通知 <{tbUserName.Text.Trim()}>";
            MyMail.From = new System.Net.Mail.MailAddress(kkk); //寄件人
            foreach (var email in recipientEmails)
            {
                MyMail.To.Add(email); //設定收件者Email
            }

            MyMail.Subject = subject; //主題
            MyMail.Body = content; //設定信件內容

            foreach (var attachment in attachments)
            {
                var directoryBase = Directory.GetCurrentDirectory();
                var filePath = @$"{directoryBase}\wwwroot{attachment}";

                if (File.Exists(filePath))
                {
                    var data = new Attachment(filePath);
                    MyMail.Attachments.Add(data);
                }
                else
                {
                    CanDoSend = false;
                    reason = "失敗 - 檔案遺失";
                    break;
                }
            }
             
            //讀取 SMTP Config
            if (CanDoSend)
            {
                SMTPConfig smtp = new SMTPConfig(); ;
                smtp.Host = "smtp.gmail.com";
                //smtp.UserName = "ficgreen01@gmail.com";
                //smtp.Password = "qwe2015qwe";
                //smtp.UserName = "ficgreen02@gmail.com";
                //smtp.Password = "qwe20150504qwe";
                //smtp.UserName = "shanghohui@gmail.com";
                //smtp.Password = "wswgnluvoodfexrb"; 
                //smtp.EnableSsl = true;
                //smtp.Port = 587;
                smtp.UserName = tbUserName.Text;
                smtp.Password = tbPassword.Text;
                if (rbSSL.Checked)
                {
                    smtp.EnableSsl = true;
                    smtp.Port = 587;
                }
                else
                {
                    smtp.EnableSsl = false;
                    smtp.Port = 25;
                }

                SmtpClient MySMTP = new SmtpClient(smtp.Host, smtp.Port);
                MySMTP.EnableSsl = smtp.EnableSsl;

                MySMTP.Credentials = new System.Net.NetworkCredential(smtp.UserName, smtp.Password);
                try
                {
                    MySMTP.Send(MyMail);
                    MySMTP.Dispose();
                    MyMail.Dispose(); //釋放資源
                    //richTextBox1.Text.Insert(0, "成功");
                    return "成功";
                }
                catch (Exception ex)
                {
                    string json = System.Text.Json.JsonSerializer.Serialize(recipientEmails);
                    
                    //MessageBox.Show("【SendEmailJob】 " + "寄送信件失敗" + json + " Exception:" + ex.Message); 

                    return "失敗 - " + ex.Message;
                }
            }
            else
            {
                return reason;
            } 
        }
        public class SMTPConfig
        {
            public string Host { get; set; }
            public int Port { get; set; }
            public string UserName { get; set; }
            public string Password { get; set; }
            public bool EnableSsl { get; set; }
        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void btSendMail_Click(object sender, EventArgs e)
        {
            List<string> user = new List<string>();
            user.Add(tbReceiver.Text.Trim());
            List<string> file = new List<string>();

            var result = Send(user, tbTitle.Text, tbContent.Text, file);

            if (result.CompareTo("成功") == 0)
            {
                // MessageBox.Show("【SendEmailJob】 寄送成功! ");
                richTextBox1.AppendText(Environment.NewLine + System.DateTime.Now.ToString() +  " " + result.ToString());

            }
            else { 
                richTextBox1.AppendText(Environment.NewLine + System.DateTime.Now.ToShortTimeString() + " " + result.ToString());
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click_1(object sender, EventArgs e)
        {
            int i = 0;
            var site_list = stationSvc.get_station_list();

            archiveLowData archiveData = new archiveLowData();

            foreach (var item in site_list)
            {
                archiveData.archiveData(item.SiteID.Substring(0, 9));

                i++;
            }
            lbMsgTitle.Text = System.DateTime.Now.ToString() + " 水位管理 - 資料搬移完成！";
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // string date1 = dtSelect1.Value.ToString("yyyy-MM-dd") + " "+System.DateTime.Now.AddHours(-2) + ":00:00";
            string date1 = DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH") + ":00:00";
            if (textBox1.Text.Trim().Length > 0)
            {
                date1 = dtSelect1.Value.ToString("yyyy-MM-dd ") + textBox1.Text + ":00:00";
            }
            
            var site_list = stationSvc.get_station_list();
             
            procSensorSvc procSensor = new procSensorSvc();
            foreach (var item in site_list)
            {
                procSensor.archiveData_test(item.SiteID.Substring(0, 9), date1);
            }
            autoTask = false;
            lbMsgTitle.Text = System.DateTime.Now.ToString() + " invdayhour - 完成！";
        }

        private void button3_Click(object sender, EventArgs e)
        {
            string date1 = dtSelect1.Value.ToString("yyyy-MM-dd");
            string date2 = dtSelect2.Value.ToString("yyyy-MM-dd");
            procArchiveSensorHourly sensorSvc = new procArchiveSensorHourly();
            //單跑一次
            //string t1 = DateTime.Now.AddHours(-1).ToString("yyyy-MM-dd HH");
            //sensorSvc.insertData(lbSiteID_sensor.Text.Substring(0, 9), t1);
            //執行期間內每個小時
            foreach (DateTime time in EachHour(DateTime.Parse(date1), DateTime.Parse(date2)))
            {
                sensorSvc.insertData(lbSiteID_sensor.Text.Substring(0, 9), time.ToString("yyyy-MM-dd HH"));
            }
            lbMsgTitle.Text = System.DateTime.Now.ToString() + " 完成！";


            //跑全站，期間內每個小時
            //var site_list = stationSvc.get_station_list();
            //foreach (var item in site_list)
            //{
            //    foreach (DateTime time in EachHour(DateTime.Parse(date1), DateTime.Parse(date2)))
            //    {
            //        sensorSvc.insertData(lbSiteID_sensor.Text.Substring(0, 9), time.ToString("yyyy-MM-dd HH"));
            //    }
            //}
        }

        private void btSyncErr_Click(object sender, EventArgs e)
        {
            autoTask = true;
            svc.syncErrData();
            autoTask = false;
        }

        //test for email format
        //private void button3_Click(object sender, EventArgs e)
        //{
        //    if(IsValidEmail(textBox2.Text))
        //    {
        //        label3.Text = "OK";
        //    }
        //    else
        //    {
        //        label3.Text = "X";
        //    }
        //}

        //bool IsValidEmail(string strIn)
        //{
        //    // Return true if strIn is in valid e-mail format.
        //    return Regex.IsMatch(strIn, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        //}
    }
}
