using System;
using System.Data;
using System.IO;
using Microsoft.VisualBasic.CompilerServices;
using static iMESCore.DataBase.iMESSql;

namespace AutoLoaderLib_C
{

    public class ParseQEL : EPIParseTemplate
    {


        // 呼叫父類別的建構子
        public ParseQEL(string paramSourcePath, string paramDestinationPath, string paramQueuePath, string paramFailPath) : base(paramSourcePath, paramDestinationPath, paramQueuePath, paramFailPath)
        {

        }

        /// <summary>
    /// 設定暫存資料表的欄位
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    /// <remarks></remarks>
        internal override bool AddColumns(DataTable dt)
        {

            bool blnResult = false;

            try
            {

                dt.Columns.Add("WaferID", Type.GetType("System.String"));
                dt.Columns.Add("POS", Type.GetType("System.Decimal"));
                dt.Columns.Add("LOP1", Type.GetType("System.Decimal"));
                dt.Columns.Add("LOP2", Type.GetType("System.Decimal"));
                dt.Columns.Add("WLP1", Type.GetType("System.Decimal"));
                dt.Columns.Add("WLD1", Type.GetType("System.Decimal"));
                dt.Columns.Add("VF1", Type.GetType("System.Decimal"));
                dt.Columns.Add("VF2", Type.GetType("System.Decimal"));

                blnResult = true;
            }

            catch (Exception ex)
            {

                throw;

            }

            return blnResult;

        }

        /// <summary>
    /// 將暫存資料表寫入資料庫
    /// </summary>
    /// <param name="dt"></param>
    /// <returns></returns>
    /// <remarks></remarks>
        internal override bool InsertTable(DataTable dt)
        {

            bool blnResult = false;
            string strSQL_Raw;
            string strSQL_Avg;
            string WaferID = "";
            decimal LOP1 = 0m;
            decimal LOP2 = 0m;
            decimal WLP1 = 0m;
            decimal WLD1 = 0m;
            decimal VF1 = 0m;
            decimal VF2 = 0m;

            strSQL_Raw = " INSERT INTO TBL_LEDLD_EL_Q_RAW " + "             (WaferID, CreateDate, POS, LOP1, LOP2, WLP1, WLD1, VF1, VF2) " + " VALUES      ('{0}', SYSDATE, {1}, {2}, {3}, {4}, {5}, {6}, {7}) ";


            strSQL_Avg = " INSERT INTO TBL_LEDLD_EL_Q " + "             (WaferID, CreateDate, LOP1, LOP2, WLP1, WLD1, VF1, VF2) " + " VALUES      ('{0}', SYSDATE, {1}, {2}, {3}, {4}, {5}, {6}) ";


            try
            {

                using (var oTran = objConnection.BeginTransaction())
                {

                    try
                    {

                        using (var cmd = CreateCommand())
                        {

                            cmd.Connection = objConnection;
                            cmd.Transaction = oTran;

                            if (dt.Rows.Count > 0)
                            {

                                for (int i = 0, loopTo = dt.Rows.Count - 1; i <= loopTo; i++)
                                {

                                    cmd.CommandText = string.Format(strSQL_Raw, dt.Rows[i]["WaferID"], dt.Rows[i]["POS"], dt.Rows[i]["LOP1"], dt.Rows[i]["LOP2"], dt.Rows[i]["WLP1"], dt.Rows[i]["WLD1"], dt.Rows[i]["VF1"], dt.Rows[i]["VF2"]);








                                    cmd.ExecuteNonQuery();

                                    WaferID = Conversions.ToString(dt.Rows[i]["WaferID"]);
                                    LOP1 = LOP1 + (decimal)dt.Rows[i]["LOP1"];
                                    LOP2 = LOP2 + (decimal)dt.Rows[i]["LOP2"];
                                    WLP1 = WLP1 + (decimal)dt.Rows[i]["WLP1"];
                                    WLD1 = WLD1 + (decimal)dt.Rows[i]["WLD1"];
                                    VF1 = VF1 + (decimal)dt.Rows[i]["VF1"];
                                    VF2 = VF2 + (decimal)dt.Rows[i]["VF2"];

                                }

                                cmd.CommandText = string.Format(strSQL_Avg, WaferID, LOP1 / dt.Rows.Count, LOP2 / dt.Rows.Count, WLP1 / dt.Rows.Count, WLD1 / dt.Rows.Count, VF1 / dt.Rows.Count, VF2 / dt.Rows.Count);







                                cmd.ExecuteNonQuery();

                            }

                        }

                        oTran.Commit();

                        blnResult = true;
                    }

                    catch (Exception ex)
                    {

                        oTran.Rollback();
                        throw;

                    }

                }
            }

            catch (Exception ex)
            {

                throw;

            }

            return blnResult;

        }

        /// <summary>
    /// 解析資料, 並寫入暫存資料表
    /// </summary>
    /// <param name="dt"></param>
    /// <param name="file"></param>
    /// <returns></returns>
    /// <remarks></remarks>
        internal override bool ParsingFile(DataTable dt, string file)
        {

            bool blnResult = false;
            DataRow dr = null;
            string line;
            string[] tmpData;
            bool startParsing = false;
            string WaferID;

            try
            {

                // 檔名即為 WaferID
                var fi = new FileInfo(file);
                WaferID = fi.Name.Replace(fi.Extension, "");
                fi = null;

                using (var sr = new StreamReader(file))
                {

                    do
                    {

                        line = sr.ReadLine();

                        if (!string.IsNullOrEmpty(line))
                        {

                            if (startParsing)
                            {

                                tmpData = line.Split(',');

                                dr = dt.NewRow();

                                dr["WaferID"] = WaferID;
                                dr["POS"] = Convert.ToDecimal(tmpData[0].Trim());
                                dr["LOP1"] = Convert.ToDecimal(tmpData[4].Trim());
                                dr["LOP2"] = Convert.ToDecimal(tmpData[14].Trim());
                                dr["WLP1"] = Convert.ToDecimal(tmpData[6].Trim());
                                dr["WLD1"] = Convert.ToDecimal(tmpData[5].Trim());
                                dr["VF1"] = Convert.ToDecimal(tmpData[3].Trim());
                                dr["VF2"] = Convert.ToDecimal(tmpData[13].Trim());

                                dt.Rows.Add(dr);
                            }


                            else if (line.IndexOf("PosX") >= 0 && line.IndexOf("PosY") >= 0)
                            {
                                startParsing = true;

                            }

                        }
                    }

                    while (!(line == null));

                    blnResult = true;

                }
            }

            catch (Exception ex)
            {

                throw;
            }

            finally
            {

                if (dr != null)
                {
                    dr = null;
                }

            }

            return blnResult;

        }

    }
}