using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.IO;
using MySql.Data.MySqlClient;
using System.Configuration;
using Dapper;
using solarApp.Model;

namespace solarApp.Service
{
    public class operateCSV
    {
        string Connection1 = ConfigurationManager.ConnectionStrings["mySql"].ConnectionString;
        /// <summary>
        /// 讀取CSV檔案通過文字格式
        /// </summary>
        /// <param name="strpath"></param>
        /// <returns></returns>
        public DataTable readCsvTxt(string strpath)
        {
            int intColCount = 0;
            bool blnFlag = true;
            DataTable mydt = new DataTable("myTableName");

            DataColumn mydc;
            DataRow mydr;

            string strline;
            string[] aryline;

            System.IO.StreamReader mysr = new System.IO.StreamReader(strpath);

            while ((strline = mysr.ReadLine()) != null)
            {
                aryline = strline.Split(',');

                if (blnFlag)
                {
                    blnFlag = false;
                    intColCount = aryline.Length;
                    for (int i = 0; i < aryline.Length; i++)
                    {
                        mydc = new DataColumn(aryline[i]);
                        mydt.Columns.Add(mydc);
                    }
                }

                mydr = mydt.NewRow();
                for (int i = 0; i < intColCount; i++)
                {
                    mydr[i] = aryline[i];
                }
                mydt.Rows.Add(mydr);
            }

            return mydt;
        }

        /// <summary>
        /// 利用SQL查詢CSV
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        //public DataTable readCsvSql(string path, string filename, string deviceName)
        //{
        //    string strconn = string.Format(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=Text;", path);
        //    string sql = string.Format("SELECT * FROM [{0}]", filename);
        //    using (OleDbConnection conn = new OleDbConnection(strconn))
        //    {
        //        DataTable dtTable = new DataTable();
        //        OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);
        //        try
        //        {
        //            adapter.Fill(dtTable);
        //            logHelper.WriteLog(string.Format("[裝置]:{0}-->讀取檔案-->結果:成功", deviceName));
        //        }
        //        catch (Exception ex)
        //        {
        //            dtTable = new DataTable();
        //            logHelper.WriteLog(string.Format("[裝置]:{0}-->讀取檔案-->結果:{1}", deviceName, ex.Message));
        //            throw ex;
        //        }
        //        return dtTable;
        //    }

        //}

        /// <summary>
        /// 讀取CSV檔案
        /// </summary>
        /// <param name="mycsvdt"></param>
        /// <param name="filepath"></param>
        /// <returns></returns>
        public void createColumnHour(ref DataTable mycsvdt, string filepath)
        {
            string strpath = filepath; //csv檔案的路徑
            try
            {
                int intColCount = 0;
                bool blnFlag = true;

                DataColumn mydc; 

                string strline;
                string[] aryline;
                StreamReader mysr = new StreamReader(strpath, System.Text.Encoding.Default);

                int rowIndex = 0;
                while ((strline = mysr.ReadLine()) != null)
                {
                    rowIndex += 1;
                    if (rowIndex < 4) continue;
                    aryline = strline.Split(new char[] { ',' });

                    //給datatable加上列名 
                    if (blnFlag)
                    {
                        blnFlag = false;
                        intColCount = aryline.Length;
                        int col = 0;
                        for (int i = 0; i < aryline.Length; i++)
                        {
                            col = i + 1;
                            mydc = new DataColumn(col.ToString());
                            mycsvdt.Columns.Add(mydc);
                        }
                        //最後一欄 放 Inv編號
                        mydc = new DataColumn("inv");
                        mycsvdt.Columns.Add(mydc);
                    }
                    break;
                } 

            }
            catch (Exception e)
            {
                //throw (Stack.GetErrorStack(strpath + "讀取CSV檔案中的資料出錯." + e.Message, "OpenCSVFile("));
                //return false;
            }
        }

        public void createColumnDay(ref DataTable mycsvdt, string filepath)
        {
            string strpath = filepath; //csv檔案的路徑
            try
            {
                int intColCount = 0;
                bool blnFlag = true;

                DataColumn mydc;

                string strline;
                string[] aryline;
                StreamReader mysr = new StreamReader(strpath, System.Text.Encoding.Default);

                int rowIndex = 0;
                while ((strline = mysr.ReadLine()) != null)
                {
                    rowIndex += 1;
                    if (rowIndex < 3) continue;
                    aryline = strline.Split(new char[] { ',' });

                    //給datatable加上列名 
                    if (blnFlag)
                    {
                        blnFlag = false;
                        intColCount = aryline.Length;
                        int col = 0; int col6 = 0;
                        for (int i = 0; i < aryline.Length; i++)
                        {
                            col = i + 1;
                            mydc = new DataColumn(col.ToString());
                            mycsvdt.Columns.Add(mydc);
                        }
                        ////最後一欄 放 Inv編號
                        //mydc = new DataColumn("inv");
                        //mycsvdt.Columns.Add(mydc);
                    }
                    break;
                }

            }
            catch (Exception e)
            {
                //throw (Stack.GetErrorStack(strpath + "讀取CSV檔案中的資料出錯." + e.Message, "OpenCSVFile("));
                //return false;
            }
        }

        public bool readCsvFile(ref DataTable mycsvdt, string filepath, string InvID, int intColCount, bool readTitle)
        {
            string strpath = filepath; //csv檔案的路徑
            try
            {  
                DataColumn mydc;
                DataRow mydr;

                string strline;
                string[] aryline;
                StreamReader mysr = new StreamReader(strpath, System.Text.Encoding.Default);

                int rowIndex = 0;
                while ((strline = mysr.ReadLine()) != null)
                {
                    rowIndex += 1;
                    if (readTitle)
                    {
                        if (rowIndex < 3 && InvID == "")
                            continue;// 欄位需要取：row 3 invId , row 4 欄位名稱也需要讀取完 
                        else if (rowIndex <= 4 && InvID == "")
                            readTitle = false;
                        else { //inv  
                            if (rowIndex <= 3) continue;
                            readTitle = false;
                        }
                    }
                    else if (rowIndex < 4) continue;  
                    
                    aryline = strline.Split(new char[] { ',' });     
                    //填充資料並加入到datatable中
                    mydr = mycsvdt.NewRow();
                    if (InvID != "")
                    { // hour
                        for (int i = 0; i < intColCount - 1; i++)
                        {
                            mydr[i] = aryline[i];
                        }
                        if (!string.IsNullOrEmpty(InvID))
                            mydr["inv"] = InvID;
                    }
                    else
                    { // day
                        for (int i = 0; i < intColCount; i++)
                            mydr[i] = aryline[i];
                    }
                    mycsvdt.Rows.Add(mydr);
                }                
            }
            catch (Exception ex)
            {
                //throw (Stack.GetErrorStack(strpath + "讀取CSV檔案中的資料出錯." + e.Message, " readCsvFile"));
                throw ex;
                return false;
            }
            return true;
        }


        public void taoYuan_createColumnHour(ref DataTable mycsvdt, string filepath)
        {
            string strpath = filepath; //csv檔案的路徑
            try
            {
                int intColCount = 0;
                bool blnFlag = true;

                DataColumn mydc;

                string strline;
                string[] aryline;
                StreamReader mysr = new StreamReader(strpath, System.Text.Encoding.Default);

                int rowIndex = 0;
                while ((strline = mysr.ReadLine()) != null)
                {
                    rowIndex += 1;
                    if (rowIndex < 4) continue;
                    aryline = strline.Split(new char[] { ',' });

                    //給datatable加上列名 
                    if (blnFlag)
                    {
                        blnFlag = false;
                        intColCount = aryline.Length;
                        int col = 0;
                        for (int i = 0; i < aryline.Length; i++)
                        {
                            col = i + 1;
                            mydc = new DataColumn(col.ToString());
                            mycsvdt.Columns.Add(mydc);
                        } 
                    }
                    break;
                }

            }
            catch (Exception e)
            {
                //throw (Stack.GetErrorStack(strpath + "讀取CSV檔案中的資料出錯." + e.Message, "OpenCSVFile("));
                //return false;
            }
        }
        /// <summary>
        /// 太陽能光電 桃園全虹
        /// </summary>
        /// <param name="mycsvdt"></param>
        /// <param name="filepath"></param>
        /// <param name="InvID"></param>
        /// <param name="intColCount"></param>
        /// <param name="readTitle"></param>
        /// <returns></returns>
        public bool taoYuan_readCsvFile(ref DataTable mycsvdt, string filepath,  int intColCount, bool readTitle)
        {
            string strpath = filepath; //csv檔案的路徑
            try
            {
                DataColumn mydc;
                DataRow mydr;

                string strline;
                string[] aryline;
                StreamReader mysr = new StreamReader(strpath, System.Text.Encoding.Default);

                int rowIndex = 0;
                while ((strline = mysr.ReadLine()) != null)
                {
                    rowIndex += 1;
                    if (readTitle && rowIndex == 1) { 
                        readTitle = false;
                        continue;
                    }

                    aryline = strline.Split(new char[] { ',' });
                    //填充資料並加入到datatable中
                    mydr = mycsvdt.NewRow();
                     
                    for (int i = 0; i < intColCount - 1; i++)
                    {
                        mydr[i] = aryline[i];
                    }  
                    mycsvdt.Rows.Add(mydr);
                }
            }
            catch (Exception ex)
            {
                //throw (Stack.GetErrorStack(strpath + "讀取CSV檔案中的資料出錯." + e.Message, " readCsvFile"));
                throw ex;
                return false;
            }
            return true;
        }

        public bool clear_inv(string timeType) 
        {
            bool result = false;
            StringBuilder ss = new StringBuilder();
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                switch (timeType)
                {
                    case "hour": ss.Append("truncate table solar_import.src_inv;"); break;
                    case "day": ss.Append("truncate table solar_import.src_inv_day;");  break;
                } 
                conn.Execute(ss.ToString()); 
                conn.Clone();
            }     
            return false;
         }

        public void taoYuan_insertHour2DB(ref DataTable dt, string dest_table)
        {
            List<src_inv_count> ds;
            StringBuilder ss = new StringBuilder();
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                ss.Clear();

                int i = 0;
                foreach (DataRow row in dt.Rows) //sun_taoyuan
                {
                    ss.Append(@"insert into solar_import."+ dest_table + @"(c1 , c2 , c3 , c4 , c5 , c6 , c7 , c8 , c9 , c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30, c31, c32, c33, c34, c35, c36, c37, c38, c39, c40, c41, c42, c43, c44, c45, c46, c47, c48, c49, c50, c51, c52, c53, c54, c55, c56, c57, c58) 
values( '" + row.Field<string>("1").ToString() + "', " + 
       "'" + row.Field<string>("2").ToString() + "' , " +
       "'" + row.Field<string>("3").ToString() + "' , " +
       "'" + row.Field<string>("4").ToString() + "' , " +
       "'" + row.Field<string>("5").ToString() + "' , " +
       "'" + row.Field<string>("6").ToString() + "' , " +
       "'" + row.Field<string>("7").ToString() + "' , " +
       "'" + row.Field<string>("8").ToString() + "' , " +
       "'" + row.Field<string>("9").ToString() + "' , " +
       "'" + row.Field<string>("10").ToString() + "' ," +
       "'" + row.Field<string>("11").ToString() + "' ," +
       "'" + row.Field<string>("12").ToString() + "' ," +
       "'" + row.Field<string>("13").ToString() + "' ," +
       "'" + row.Field<string>("14").ToString() + "' ," +
       "'" + row.Field<string>("15").ToString() + "' ," +
       "'" + row.Field<string>("16").ToString() + "' ," +
       "'" + row.Field<string>("17").ToString() + "' ," +
       "'" + row.Field<string>("18").ToString() + "' ," +
       "'" + row.Field<string>("19").ToString() + "' ," +
       "'" + row.Field<string>("20").ToString() + "' ," +
       "'" + row.Field<string>("21").ToString() + "' ," +
       "'" + row.Field<string>("22").ToString() + "' ," +
       "'" + row.Field<string>("23").ToString() + "' ," +
       "'" + row.Field<string>("24").ToString() + "' ," +
       "'" + row.Field<string>("25").ToString() + "' ," +
       "'" + row.Field<string>("26").ToString() + "' ," +
       "'" + row.Field<string>("27").ToString() + "' ," +
       "'" + row.Field<string>("28").ToString() + "' ," +
       "'" + row.Field<string>("29").ToString() + "' ," +
       "'" + row.Field<string>("30").ToString() + "' ," +
       "'" + row.Field<string>("31").ToString() + "' ," +
       "'" + row.Field<string>("32").ToString() + "' ," +
       "'" + row.Field<string>("33").ToString() + "' ," +
       "'" + row.Field<string>("34").ToString() + "' ," +
       "'" + row.Field<string>("35").ToString() + "' ," +
       "'" + row.Field<string>("36").ToString() + "' ," +
       "'" + row.Field<string>("37").ToString() + "' ," +
       "'" + row.Field<string>("38").ToString() + "' ," +
       "'" + row.Field<string>("39").ToString() + "' ," +
       "'" + row.Field<string>("40").ToString() + "' ," +
       "'" + row.Field<string>("41").ToString() + "' ," +
       "'" + row.Field<string>("42").ToString() + "' ," +
       "'" + row.Field<string>("43").ToString() + "' ," +
       "'" + row.Field<string>("44").ToString() + "' ," +
       "'" + row.Field<string>("45").ToString() + "' ," +
       "'" + row.Field<string>("46").ToString() + "' ," +
       "'" + row.Field<string>("47").ToString() + "' ," +
       "'" + row.Field<string>("48").ToString() + "' ," +
       "'" + row.Field<string>("49").ToString() + "' ," +
       "'" + row.Field<string>("50").ToString() + "' ," +
       "'" + row.Field<string>("51").ToString() + "' ," +
       "'" + row.Field<string>("52").ToString() + "' ," +
       "'" + row.Field<string>("53").ToString() + "' ," +
       "'" + row.Field<string>("54").ToString() + "' ," +
       "'" + row.Field<string>("55").ToString() + "' ," +
       "'" + row.Field<string>("56").ToString() + "' ," +
       "'" + row.Field<string>("57").ToString() + "' ," +
       "'" + row.Field<string>("58").ToString() + "'   );");

                    if (i % 100 == 0)
                    {
                        conn.Execute(ss.ToString());
                        ss.Clear();
                    }
                    i++;
                }
                if (ss.Length > 0)
                {
                    conn.Execute(ss.ToString());
                    ss.Clear();
                }
                //ss.Clear();
                //ss.Append(@"select inv, left(c1, 10) date, count(*) ct from src_inv where c1 <> '欄位名稱' group by inv, left(c1, 10)");
                //ds = conn.Query<src_inv_count>(ss.ToString()).AsList<src_inv_count>();
                conn.Clone();
            }
            //return ds;
        }

        public List<src_inv_count> insertHour2DB(ref DataTable dt) {
            List<src_inv_count> ds;
            StringBuilder ss = new StringBuilder();
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open(); 
                ss.Clear();

                int i = 0;
                foreach (DataRow row in dt.Rows)
                {
                    ss.Append(@"insert into solar_import.src_inv(c1 ,c2 ,c3 ,c4 ,c5 ,c6 ,c7 ,c8 ,c9 ,c10 ,c11 ,c12 ,c13 ,c14 ,c15 ,c16 ,c17 ,c18 ,c19 ,inv) 
                                    values( '"+ row.Field<string>("1").ToString() + "' ,'" + row.Field<string>("2").ToString() + "' ,'" + row.Field<string>("3").ToString() + "' ," +
                                    "'" + row.Field<string>("4").ToString() + "' ,'" + row.Field<string>("5").ToString() + "' ,'" + row.Field<string>("6").ToString() + "' ," +
                                    "'" + row.Field<string>("7").ToString() + "' ,'"+ row.Field<string>("8").ToString() + "' ,'" + row.Field<string>("9").ToString() + "' ," +
                                    "'" + row.Field<string>("10").ToString() + "' ,'" + row.Field<string>("11").ToString() + "' ,'" + row.Field<string>("12").ToString() + "' ," +
                                    "'" + row.Field<string>("13").ToString() + "' ,'" + row.Field<string>("14").ToString() + "' ,'" + row.Field<string>("15").ToString() + "' ," +
                                    "'" + row.Field<string>("16").ToString() + "', '" + row.Field<string>("17").ToString() + "', '" + row.Field<string>("18").ToString() + "'," +
                                    "'" + row.Field<string>("19").ToString() + "' ,'" + row.Field<string>("inv").ToString() + "' );"); 

                    if (i % 10 == 0)
                    {
                        conn.Execute(ss.ToString());
                        ss.Clear(); 
                    }
                    i++;
                }
                if (ss.Length > 0)
                {
                    conn.Execute(ss.ToString());
                    ss.Clear();
                }
                ss.Clear();
                ss.Append(@"select inv, left(c1, 10) date, count(*) ct from src_inv where c1 <> '欄位名稱' group by inv, left(c1, 10)");
                 ds = conn.Query<src_inv_count>(ss.ToString()).AsList<src_inv_count>(); 
                conn.Clone();
            }
            return ds; 
        }

        public bool insertDay2DB(ref DataTable dt)
        {
            bool result = false;
            StringBuilder ss = new StringBuilder();
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                int i = 0;
                foreach (DataRow row in dt.Rows)
                {
                    ss.Append(@"INSERT INTO solar_import.src_inv_day( c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24, c25, c26, c27, c28, c29, c30, c31, c32, c33, c34, c35, c36, c37, c38, c39, c40, c41, c42, c43, c44, c45, c46, c47, c48, c49, c50, c51, c52, c53, c54, c55)  
values( '" 
 + row.Field<string>("1").ToString() + "' ,'" 
 + row.Field<string>("2").ToString() + "' ,'" 
 + row.Field<string>("3").ToString() + "' ,'"
 + row.Field<string>("4").ToString() + "' ,'"
 + row.Field<string>("5").ToString() + "' ,'"
 + row.Field<string>("6").ToString() + "' ,'"
 + row.Field<string>("7").ToString() + "' ,'"
 + row.Field<string>("8").ToString() + "' ,'"
 + row.Field<string>("9").ToString() + "' ,'"
+ row.Field<string>("10").ToString() + "' ,'"
+ row.Field<string>("11").ToString() + "' ,'"
+ row.Field<string>("12").ToString() + "' ,'"
+ row.Field<string>("13").ToString() + "' ,'"
+ row.Field<string>("14").ToString() + "' ,'"
+ row.Field<string>("15").ToString() + "' ,'"
+ row.Field<string>("16").ToString() + "' ,'"
+ row.Field<string>("17").ToString() + "' ,'"
+ row.Field<string>("18").ToString() + "' ,'"
+ row.Field<string>("19").ToString() + "' ,'"
+ row.Field<string>("20").ToString() + "' ,'"
+ row.Field<string>("21").ToString() + "' ,'"
+ row.Field<string>("22").ToString() + "' ,'"
+ row.Field<string>("23").ToString() + "' ,'"
+ row.Field<string>("24").ToString() + "' ,'"
+ row.Field<string>("25").ToString() + "' ,'"
+ row.Field<string>("26").ToString() + "' ,'"
+ row.Field<string>("27").ToString() + "' ,'"
+ row.Field<string>("28").ToString() + "' ,'"
+ row.Field<string>("29").ToString() + "' ,'"
+ row.Field<string>("30").ToString() + "' ,'"
+ row.Field<string>("31").ToString() + "' ,'"
+ row.Field<string>("32").ToString() + "' ,'"
+ row.Field<string>("33").ToString() + "' ,'"
+ row.Field<string>("34").ToString() + "' ,'"
+ row.Field<string>("35").ToString() + "' ,'"
+ row.Field<string>("36").ToString() + "' ,'"
+ row.Field<string>("37").ToString() + "' ,'"
+ row.Field<string>("38").ToString() + "' ,'"
+ row.Field<string>("39").ToString() + "' ,'"
+ row.Field<string>("40").ToString() + "' ,'"
+ row.Field<string>("41").ToString() + "' ,'"
+ row.Field<string>("42").ToString() + "' ,'"
+ row.Field<string>("43").ToString() + "' ,'"
+ row.Field<string>("44").ToString() + "' ,'"
+ row.Field<string>("45").ToString() + "' ,'"
+ row.Field<string>("46").ToString() + "' ,'"
+ row.Field<string>("47").ToString() + "' ,'"
+ row.Field<string>("48").ToString() + "' ,'"
+ row.Field<string>("49").ToString() + "' ,'"
+ row.Field<string>("50").ToString() + "' ,'"
+ row.Field<string>("51").ToString() + "' ,'"
+ row.Field<string>("52").ToString() + "' ,'"
+ row.Field<string>("53").ToString() + "' ,'"
+ row.Field<string>("54").ToString() + "' ,'"
+ row.Field<string>("55").ToString() + "');");   

                    if (i % 10 == 0)
                    {
                        conn.Execute(ss.ToString());
                        ss.Clear();
                    }
                    i++;
                }
                if (ss.Length > 0)
                {
                    conn.Execute(ss.ToString());
                    ss.Clear();
                }
                conn.Clone();
            }
            return result;
        }

        public bool archive_data(string timeType) 
        {
            bool result = false;
            string ss;
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();

                if (timeType == "hour")
                { //匯入小時資料哦
                    // 1.src_day to master inv_day  
                    ss = @" delete from solar_master.inverter_history_hour where powerStationID = 22;

                         INSERT INTO solar_master.inverter_history_hour(PowerStationId, INVERTERID, `TIMESTAMP`, Irradiance, 
AC1V, AC1A, AC1W, AC1F, AC1WH, AC2V, AC2A, AC2W, AC2F, AC2WH, AC3V, AC3A, AC3W, AC3F, AC3WH, 
DC1V, DC1A, DC1W, DC1KW, DC1WH, DC2V, DC2A, DC2W, DC2KW, DC2WH, DC3V, DC3A, DC3W, DC3KW, DC3WH, DC4V, DC4A, DC4W, DC4KW, DC4WH, DC5V, DC5A, DC5W, DC5KW, DC5WH, 
PR, RA1, RA2, RA3, RA4, RA5, DCKW, ACKW, KWH, TODAYKWH, TOTALKWH, KWHKWP) 

select 22 as PowerStationId, invId, reportdate, irr, 
AC1V, AC1A, 0, 0, 0,   
AC2V, AC2A, 0, 0, 0,   
AC3V, AC3A, 0, 0, 0, 
DC1V, DC1A, DC1W, 0, 0,    
DC2V, DC2A, DC2W, 0, 0,
0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 
0, 0, 0, 0, 0, 
0 as PR, RA as RA1, 0, 0, 0, 0,
0 as DCKW, 0 as ACKW, wh as 'KWH', wh as TODAYKWH, wh as TOTALKWH, 0 as KWHKWP
from solar_import.v_inv_hour_hj ;";
                    conn.Execute(ss);
                }
                else
                {//匯入 day 資料
                    // 1.src_day to master inv_day  
                    ss = @" delete from solar_master.inverter_history_day where powerStationID = 22;

                         insert into solar_master.inverter_history_day(powerStationID, inverterID, `TIMESTAMP`, irradiance, PR, kwh, todayKWH, totalKWh, kwhkwp) 
                         select '22' as powerStationID, CONCAT('0802500010100', right(a.inv, 2) ) invID,   concat(a.reportDate,' 00:00:00')  ts, round(a.irr, 8) irr,
			                         round(a.pr, 8) pr,  round(a.kwh, 8)kwh,  round((a.totalkWh - b.totalkWh), 8) as todaykWh,  round(a.totalkWh, 8) totalkWh,  round(a.kwhkwp, 8)kwhkwp
                         from solar_import.v_inv_day_huijing a join 
                          ( # 把今天的值 放到明天
		                        select reportDate, DATE(DATE_ADD(reportDate, INTERVAL +1 DAY)) day_1, totalkWh, inv 
		                        from solar_import.v_inv_day_huijing
	                        )b on a.inv = b.inv and a.reportDate = b.day_1;";
                    conn.Execute(ss);

                    // 2.month
                    ss = @"  delete from solar_master.inverter_history_month where powerStationID = 22;

                         insert into solar_master.inverter_history_month(powerstationid, inverterid, `TIMESTAMP`, irradiance, PR, kwh, todayKWH, totalKWh, kwhkwp) 
                         select 22 powerstationid, inverterid, concat(left(`TIMESTAMP`, 7), '-01 00:00:00') , avg(irradiance) irr, 
					                        avg(PR) PR, SUM(kwh) kwh, max(todaykwh)todaykwh, max(totalkwh)totalkwh, avg(kwhkwp) kwhkwp
                         from solar_master.inverter_history_day
                         where powerStationID = 22
                         group by left(`TIMESTAMP`, 7) , inverterid;";
                    conn.Execute(ss);

                    // 3.station day  
                    ss = @"  delete from solar_master.power_station_history_day where powerstationID = 22;
        INSERT INTO solar_master.power_station_history_day( PowerStationId, `TIMESTAMP`, SITEID, SITETYPE, TODAYKWH, TOTALKWH, KWHKWP, 
									PR, MP, SOLARHOUR, MONEY, TOTALMONEY, CARBON, TOTALCARBON)  
		select b.id PowerStationId, a.reportdate, b.siteID, a.siteType, a.TODAYKWH, a.TOTALKWH, a.KWHKWP, a.PR, a.MP, a.SOLARHOUR,
			(KWH * PowerRate)	MONEY, (a.TOTALKWH * PowerRate) TOTALMONEY, 
			(KWH * CarbonRate) CARBON, round((a.TOTALKWH * CarbonRate), 4) TOTALCARBON
		from 
		(
				select concat(DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d'), ' 00:00:00') reportdate, '080250001' siteid, 0 siteType, round((sum(KWH)), 6) KWH,
							 round((sum(TODAYKWH)), 6) TODAYKWH, round((max(TOTALKWH)), 6) TOTALKWH, round((avg(KWHKWP)), 6) KWHKWP, 
							 round((avg(PR)), 6) PR,  0 as MP, 0 SOLARHOUR
				 from solar_master.inverter_history_day a  
				 where powerstationID = 22 and DATE_FORMAT(a.`TIMESTAMP`,'%Y-%m-%d') between '2020-01-01' and '2021-08-31'
				 group by powerstationID, DATE_FORMAT(`TIMESTAMP`,'%Y-%m-%d')
		)a join 
		( 
				select id, `code` siteID, PowerRate, (select `value` from solar_master.`variable` where `name` = 'CarbonRate') as CarbonRate, SolarType
				from solar_master.power_station
				where `code` =  '080250001'				
		) b on a.siteID = b.siteID ;";
                    conn.Execute(ss);


                    // 4.station month
                    ss = @"  delete from solar_master.power_station_history_month where powerstationID = 22;
        INSERT INTO solar_master.power_station_history_month( PowerStationId, `TIMESTAMP`, SITEID, SITETYPE, MonthKWH, TOTALKWH, KWHKWP, 
									PR, MP, SOLARHOUR, MONEY, TOTALMONEY, CARBON, TOTALCARBON) 

		select b.id PowerStationId, a.reportdate, b.siteID, a.siteType, a.MonthKWH, a.TOTALKWH, a.KWHKWP, a.PR, a.MP, a.SOLARHOUR,
			(MonthKWH * PowerRate)	MONEY, (a.TOTALKWH * PowerRate) TOTALMONEY, 
			(MonthKWH * CarbonRate) CARBON, round((a.TOTALKWH * CarbonRate), 4) TOTALCARBON
		from 
		(
				select concat(DATE_FORMAT(`TIMESTAMP`,'%Y-%m'), '-01 00:00:00') reportdate, '080250001' siteid, 0 siteType,  
							 round((sum(TODAYKWH)), 6) MonthKWH, round((max(TOTALKWH)), 6) TOTALKWH, round((avg(KWHKWP)), 6) KWHKWP, 
							 round((avg(PR)), 6) PR,  0 as MP, 0 SOLARHOUR
				 from solar_master.power_station_history_day a  
				 where powerstationID = 22 and DATE_FORMAT(a.`TIMESTAMP`,'%Y-%m') between '2020-01' and '2021-08'
				 group by powerstationID, DATE_FORMAT(a.`TIMESTAMP`,'%Y-%m')
		)a join 
		( 
				select id, `code` siteID, PowerRate, (select `value` from solar_master.`variable` where `name` = 'CarbonRate') as CarbonRate, SolarType
				from solar_master.power_station
				where `code` =  '080250001'				
		) b on a.siteID = b.siteID 	;";
                    conn.Execute(ss);

                    // 5. sensor day
                    ss = @"  delete from solar_master.sensor_history_day where powerstationID = 22;
        insert solar_master.sensor_history_day(powerStationID, `TIMESTAMP`, irradiance, Temperature)
  select 22 powerstationid, concat(left(`TIMESTAMP`, 10), ' 00:00:00') , round(avg(irradiance), 6) irradiance , 0 Temperature
  from solar_master.inverter_history_day 
  where powerStationID = 22
	group by left(`TIMESTAMP`, 10) 	;";
                    conn.Execute(ss);

                    // 6. sensor month
                    ss = @"  delete from solar_master.sensor_history_month where powerstationID = 22;
        insert solar_master.sensor_history_month(powerStationID, `TIMESTAMP`, irradiance, Temperature)
  select 22 powerstationid, concat(left(`TIMESTAMP`, 7), '-01 00:00:00') , round(avg(irradiance), 6) irradiance , 0 Temperature
  from solar_master.inverter_history_day 
  where powerStationID = 22
	group by left(`TIMESTAMP`, 7);";
                    conn.Execute(ss);
                }
            }
            return result;
        }

        /// <summary>
        /// 建立 view, 已建立 目前用不到
        /// </summary>
        /// <returns></returns>
        public bool create_view()
        {
            bool result = false;
            string ss;
            using (MySqlConnection conn = new MySqlConnection(Connection1))
            {
                conn.Open();
                int i = 0;
                // 1.src_day to master inv_day  
                ss = @" create view v_inv_hour_hj as 
	select 
		c1 as reportdate
		,round(c2 , 6) as  DC2A
		,round(c3 , 6) as  DC1A
		,round(c4 , 6) as   wh
		,round(c5 , 6) as  DC2W
		,round(c6 , 6) as  DC1W
		,round(c7 , 6) as  DC1V
		,round(c8 , 6) as  DC2V
		,round(c9 , 6) as  irr
		,round(c10, 6) as  RA
		#,c11 as  (c6 + c5) / 1000
		,round(c12, 6) as  AC1A
		,round(c13, 6) as  AC2A
		,round(c14, 6) as  AC3A
		,round(c15, 6) as  AC1V
		,round(c16, 6) as  AC2V
		,round(c17, 6) as  AC3V 
		-- ,c18 機內溫度(°C)				
		-- ,c19 裝置容量(kWp)	
		,CONCAT('0802500010100', right(inv, 2) ) as  invID 
	from src_inv
	where c1 <> '欄位名稱';";
                conn.Execute(ss);

                ss = @"create view v_inv_day_huijing
as 
		select 
		c1 reportDate,
		round(c2 , 6) as kWp,
		round(c3 , 6) as kWh,
		round(c4 , 6) as irr,
		round(c5 , 6) as kwhkwp,
		round(c6 , 6) as totalkWh,
		round(c7 , 6) as PR, 
		(select inv1 from v_invID_day_huijing) inv
		from src_inv_day
		where c1 not in ('裝置名稱', '欄位名稱') 
union
	 select 
			c1 reportDate,
			round(c8 , 6) as kWp,
			round(c9 , 6) as kWh,
			round(c10, 6) as irr,
			round(c11, 6) as kwhkwp,
			round(c12, 6) as totalkWh,
			round(c13, 6) as PR,
			(select inv2 from v_invID_day_huijing) inv
		from src_inv_day
		where c1 not in ('裝置名稱', '欄位名稱')  
union
	 select 			
			c1 reportDate,
			round(c14, 6) as kWp,
			round(c15, 6) as kWh,
			round(c16, 6) as irr,
			round(c17, 6) as kwhkwp,
			round(c18, 6) as totalkWh,
			round(c19, 6) as PR,
			(select inv3 from v_invID_day_huijing) inv
		from src_inv_day
		where c1 not in ('裝置名稱', '欄位名稱')  
union
	 select 			
			c1 reportDate,
			round(c20, 6) as kWp,
			round(c21, 6) as kWh,
			round(c22, 6) as irr,
			round(c23, 6) as kwhkwp,
			round(c24, 6) as totalkWh,
			round(c25, 6) as PR,
			(select inv4 from v_invID_day_huijing) inv
		from src_inv_day
		where c1 not in ('裝置名稱', '欄位名稱')  
union
	 select 
			c1 reportDate,
			round(c26, 6) as kWp,
			round(c27, 6) as kWh,
			round(c28, 6) as irr,
			round(c29, 6) as kwhkwp,
			round(c30, 6) as totalkWh,
			round(c31, 6) as PR,
			(select inv5 from v_invID_day_huijing) inv
		from src_inv_day
		where c1 not in ('裝置名稱', '欄位名稱')  
union
	 select 			
			c1 reportDate,
			round(c32, 6) as kWp,
			round(c33, 6) as kWh,
			round(c34, 6) as irr,
			round(c35, 6) as kwhkwp,
			round(c36, 6) as totalkWh,
			round(c37, 6) as PR,
			(select inv6 from v_invID_day_huijing) inv
		from src_inv_day
		where c1 not in ('裝置名稱', '欄位名稱')  
union
	 select 			
			c1 reportDate,
			round(c38, 6) as kWp,
			round(c39, 6) as kWh,
			round(c40, 6) as irr,
			round(c41, 6) as kwhkwp,
			round(c42, 6) as totalkWh,
			round(c43, 6) as PR,
			(select inv7 from v_invID_day_huijing) inv
		from src_inv_day
		where c1 not in ('裝置名稱', '欄位名稱')  
union
	 select 			
			c1 reportDate,
			round(c44, 6) as kWp,
			round(c45, 6) as kWh,
			round(c46, 6) as irr,
			round(c47, 6) as kwhkwp,
			round(c48, 6) as totalkWh,
			round(c49, 6) as PR,
			(select inv8 from v_invID_day_huijing) inv
		from src_inv_day
		where c1 not in ('裝置名稱', '欄位名稱')  
union
	 select 			
			c1 reportDate,
			round(c50, 6) as kWp,
			round(c51, 6) as kWh,
			round(c52, 6) as irr,
			round(c53, 6) as kwhkwp,
			round(c54, 6) as totalkWh,
			round(c55, 6) as PR,
			(select inv9 from v_invID_day_huijing) inv
		from src_inv_day
		where c1 not in ('裝置名稱', '欄位名稱');

create view v_invID_day_huijing as 
select c2  as inv1, c8 as inv2, c14 as inv3, c20 as inv4, c26 as inv5, c32 as inv6, c38 as inv7, c44 as inv8, c50 as inv9	
from src_inv_day where c1 = '裝置名稱';";
                conn.Execute(ss);
            }
            return result;
        }
    }
}
 
