using System;
using System.Data;
using System.Runtime.InteropServices;
using Microsoft.VisualBasic;
using Microsoft.VisualBasic.CompilerServices;
using static iMESCore.Base.iMESConst;
using static iMESCore.Base.iMESComXML;

namespace AutoLoaderLib_C
{
    static class modAutoLoaderLibrary
    {
        public enum GroupType
        {
            UserGroup = 0,       // 使用者群組
            IssueGroup = 1,          // 簽核群組
            EquipmentGroup = 2,      // 設備工程師群組
            InventoryGroup = 3,      // 庫房工程師群組
            ReportGroup = 4,         // 報表使用群組
            ERFDispositionGroup = 5, // 異常處理群組
            ERFMailccGroup = 6      // 附件收件人群組
        }

        private static string InXml, OutXml, strIdentity, strParameter, XmlData, XmlSchema;

        #region 計算最大、最小、總合、平方根、良品數

        public static bool funCalculateMinMaxSumSqr(DataRow rowRawData, string colFieldName, ref DataRow rowReslut, DataRow rowRawData_SpecYield, string min_colFieldName, string max_colFieldName, DataRow rowRawData_SpecAvg, DataRow rowRawData_SpecEng, string colFieldName_IR = defString, bool blnGoodFlag_Yield = true, bool blnGoodFlag_Avg = true, bool blnGoodFlag_AOI = true)



        {
            bool funCalculateMinMaxSumSqrRet = default(bool);


            // //符合規格的顆數(AVG)
            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecAvg[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecAvg[max_colFieldName], false)))
            {
                switch (Strings.Mid(colFieldName, 1, 3).ToUpper() ?? "")
                {
                    case "ESD": // 計算ESD的Yield時IR必須也要是Pass
                        {
                            if ((colFieldName_IR ?? "") != defString)
                            {
                                if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName_IR])), rowRawData_SpecAvg[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName_IR])), rowRawData_SpecAvg[max_colFieldName], false)))
                                {
                                    // //更新
                                    rowReslut.BeginEdit();
                                    // //Max
                                    if (Conversions.ToBoolean(Operators.ConditionalCompareObjectLess(rowReslut["MaxValue"], decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), false)))
                                    {
                                        rowReslut["MaxValue"] = decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
                                    }
                                    // //Min
                                    if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowReslut["MinValue"], -9999, false)) || Conversions.ToBoolean(Operators.ConditionalCompareObjectGreater(rowReslut["MinValue"], decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), false)))
                                    {
                                        rowReslut["MinValue"] = decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
                                    }
                                    // //IR必須要過ESD才能算
                                    if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecEng[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecEng[max_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName_IR])), rowRawData_SpecEng[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName_IR])), rowRawData_SpecEng[max_colFieldName], false)))


                                    {
                                        // //Yield Die數加一
                                        rowReslut["GoodQty1"] = Convert.ToInt32(rowReslut["GoodQty1"]) + 1;
                                        // Else
                                        // blnGoodFlag_Yield = False
                                    }

                                    // //不包含AOIBin欄位判斷Yield
                                    if (colFieldName.ToString().ToUpper() != "AOIBIN")
                                    {
                                        if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[max_colFieldName], false)))
                                        {
                                        }
                                        else
                                        {
                                            blnGoodFlag_AOI = false;
                                        }
                                    }

                                    if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[max_colFieldName], false)))
                                    {
                                    }
                                    else
                                    {
                                        blnGoodFlag_Yield = false;
                                    }

                                    // '計算IR符合ESD規格的顆數
                                    if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName_IR])), rowRawData_SpecEng[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName_IR])), rowRawData_SpecEng[max_colFieldName], false)))
                                    {
                                        rowReslut["IRFitESDSpecQty"] = Convert.ToInt32(rowReslut["IRFitESDSpecQty"]) + 1;
                                    }
                                    // //Sum
                                    rowReslut["SumValue"] = (decimal)rowReslut["SumValue"] + 
                                        decimal.Parse(rowRawData[colFieldName].ToString());
                                    // //SumSqr
                                    rowReslut["SqrValue"] = (double)rowReslut["SqrValue"] +
                                        Math.Pow((double)decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), 2d);
                                    // //Avg Die數加一
                                    rowReslut["GoodQty2"] = Convert.ToInt32(rowReslut["GoodQty2"]) + 1;
                                    // //更新
                                    rowReslut.EndEdit();
                                    // //
                                    funCalculateMinMaxSumSqrRet = true;         // //此電性在規格內
                                }
                                else
                                {
                                    // '計算IR符合ESD規格的顆數
                                    if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName_IR])), rowRawData_SpecEng[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName_IR])), rowRawData_SpecEng[max_colFieldName], false)))
                                    {
                                        rowReslut["GoodQty1"] = Convert.ToInt32(rowReslut["GoodQty1"]) + 1;
                                        rowReslut["IRFitESDSpecQty"] = Convert.ToInt32(rowReslut["IRFitESDSpecQty"]) + 1;
                                        // Else
                                        // blnGoodFlag_Yield = False
                                    }

                                    // //不包含AOIBin欄位判斷Yield
                                    if (colFieldName.ToString().ToUpper() != "AOIBIN")
                                    {
                                        if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[max_colFieldName], false)))
                                        {
                                        }
                                        else
                                        {
                                            blnGoodFlag_AOI = false;
                                        }
                                    }

                                    if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[max_colFieldName], false)))
                                    {
                                    }
                                    else
                                    {
                                        blnGoodFlag_Yield = false;
                                    }

                                    funCalculateMinMaxSumSqrRet = false;        // //回傳此電性在規格外
                                    blnGoodFlag_Avg = false;
                                }
                            }
                            else
                            {
                                throw new Exception("無法取得檔案中" + colFieldName_IR + "所對應的電性欄位!!");
                            }

                            break;
                        }

                    default:
                        {
                            // //更新
                            rowReslut.BeginEdit();
                            // //Max
                            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectLess(rowReslut["MaxValue"], decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), false)))
                            {
                                rowReslut["MaxValue"] = decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
                            }
                            // //Min
                            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowReslut["MinValue"], -9999, false)) || Conversions.ToBoolean(Operators.ConditionalCompareObjectGreater(rowReslut["MinValue"], decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), false)))
                            {
                                rowReslut["MinValue"] = decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
                            }
                            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecEng[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecEng[max_colFieldName], false)))
                            {
                                // //Die數加一
                                rowReslut["GoodQty1"] = Convert.ToInt32(rowReslut["GoodQty1"]) + 1;
                                // Else
                                // blnGoodFlag_Yield = False
                            }
                            // //不包含AOIBin欄位判斷Yield
                            if (colFieldName.ToString().ToUpper() != "AOIBIN")
                            {
                                if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[max_colFieldName], false)))
                                {
                                }
                                else
                                {
                                    blnGoodFlag_AOI = false;
                                }
                            }
                            // //
                            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[max_colFieldName], false)))
                            {
                            }
                            else
                            {
                                blnGoodFlag_Yield = false;
                            }
                            // //Sum
                            rowReslut["SumValue"] = (decimal)rowReslut["SumValue"] +
                                decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
                            // //SumSqr
                            rowReslut["SqrValue"] = (double)rowReslut["SqrValue"] +
                                Math.Pow((double)decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), 2d);
                            // //Avg Die數加一
                            rowReslut["GoodQty2"] = Convert.ToInt32(rowReslut["GoodQty2"]) + 1;
                            // //更新
                            rowReslut.EndEdit();
                            // //
                            funCalculateMinMaxSumSqrRet = true;                 // //此電性在規格內
                            break;
                        }
                }
            }
            else
            {
                if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecEng[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecEng[max_colFieldName], false)))
                {
                    // //Die數加一
                    rowReslut["GoodQty1"] = Convert.ToInt32(rowReslut["GoodQty1"]) + 1;
                    // Else
                    // blnGoodFlag_Yield = False
                }
                // //不包含AOIBin欄位判斷Yield
                if (colFieldName.ToString().ToUpper() != "AOIBIN")
                {
                    if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[max_colFieldName], false)))
                    {
                    }
                    else
                    {
                        blnGoodFlag_AOI = false;
                    }
                }
                if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_SpecYield[max_colFieldName], false)))
                {
                }
                else
                {
                    blnGoodFlag_Yield = false;
                }
                // '計算IR符合ESD規格的顆數
                if (Strings.Mid(colFieldName, 1, 3).ToUpper() == "ESD" && Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName_IR])), rowRawData_SpecEng[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName_IR])), rowRawData_SpecEng[max_colFieldName], false)))

                {
                    rowReslut["IRFitESDSpecQty"] = Convert.ToInt32(rowReslut["IRFitESDSpecQty"]) + 1;
                }
                funCalculateMinMaxSumSqrRet = false;                        // //回傳此電性在規格外
                blnGoodFlag_Avg = false;
            }

            return funCalculateMinMaxSumSqrRet;
            // End If

        }


        public static bool funCalculateMinMaxSumSqr(DataRow rowRawData, string colFieldName, ref DataRow rowReslut, bool blnChkSpecFlag, DataRow rowRawData_Spec = null, DataRow rowRawData_Spec_AVG = null, string min_colFieldName = defString, string max_colFieldName = defString)

        {
            bool funCalculateMinMaxSumSqrRet = default(bool);

            // //依傳入值判斷是否要判規格
            if (blnChkSpecFlag == true)
            {
                // //不可為Nothing
                if (rowRawData_Spec == null)
                {
                    throw new Exception("必須傳入規格定義資料(YIELD)!!");
                }
                // //不可為Nothing
                if (rowRawData_Spec_AVG == null)
                {
                    throw new Exception("必須傳入規格定義資料(AVG)!!");
                }
                // //不可為defString
                if ((max_colFieldName ?? "") == defString)
                {
                    throw new Exception("必須傳入規格電性最大欄位定義資料!!");
                }
                // //不可為defString
                if ((min_colFieldName ?? "") == defString)
                {
                    throw new Exception("必須傳入規格電性最小欄位定義資料!!");
                }
            }
            // //更新
            rowReslut.BeginEdit();
            // //Max
            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectLess(rowReslut["MaxValue"], decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), false)))
            {
                rowReslut["MaxValue"] = decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
            }
            // //Min
            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowReslut["MinValue"], 0, false)) || Conversions.ToBoolean(Operators.ConditionalCompareObjectGreater(rowReslut["MinValue"], decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), false)))
            {
                rowReslut["MinValue"] = decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
            }
            // //依傳入值判斷是否要判規格
            if (blnChkSpecFlag == true)
            {
                // //規格最大、最小都為零時不需要判(AVG)
                if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowRawData_Spec_AVG[min_colFieldName], 0, false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowRawData_Spec_AVG[max_colFieldName], 0, false)))
                {
                    // //Sum
                    rowReslut["SumValue"] = (decimal)rowReslut["SumValue"] +
                        decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
                    // //SumSqr
                    rowReslut["SqrValue"] = (double)rowReslut["SqrValue"] +
                        Math.Pow((double)decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), 2d);
                    // //Die數加一
                    rowReslut["GoodQty1"] = Convert.ToInt32(rowReslut["GoodQty1"]) + 1;
                }
                // //符合規格的顆數(良品數)
                else if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_Spec_AVG[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLess(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_Spec_AVG[max_colFieldName], false)))
                {
                    // //Sum
                    rowReslut["SumValue"] = (decimal)rowReslut["SumValue"] +
                        decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
                    // //SumSqr
                    rowReslut["SqrValue"] = (double)rowReslut["SqrValue"] +
                        Math.Pow((double)decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), 2d);
                    // //Die數加一
                    rowReslut["GoodQty1"] = Convert.ToInt32(rowReslut["GoodQty1"]) + 1;
                }
                // //規格最大、最小都為零時不需要判(YIELD)
                if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowRawData_Spec[min_colFieldName], 0, false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowRawData_Spec[max_colFieldName], 0, false)))
                {
                    // //Pass數加一
                    rowReslut["GoodQty2"] = Convert.ToInt32(rowReslut["GoodQty2"]) + 1;
                    funCalculateMinMaxSumSqrRet = true;         // //此電性不需判斷規格(是)
                }
                // //符合規格的顆數(良品數)
                else if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_Spec[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLess(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_Spec[max_colFieldName], false)))
                {
                    // //Pass數加一
                    rowReslut["GoodQty2"] = Convert.ToInt32(rowReslut["GoodQty2"]) + 1;
                    funCalculateMinMaxSumSqrRet = true;     // //回傳此電性是否在規格內(是)
                }
                else
                {
                    funCalculateMinMaxSumSqrRet = false;
                }    // //回傳此電性是否在規格內(否)
            }
            else
            {
                // //Sum
                rowReslut["SumValue"] = (decimal)rowReslut["SumValue"] +
                    decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
                // //SumSqr
                rowReslut["SqrValue"] = (double)rowReslut["SqrValue"] +
                    Math.Pow((double)decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), 2d);
                // //Pass數加一
                rowReslut["GoodQty1"] = Convert.ToInt32(rowReslut["GoodQty1"]) + 1;
                rowReslut["GoodQty2"] = Convert.ToInt32(rowReslut["GoodQty2"]) + 1;
                funCalculateMinMaxSumSqrRet = true;
            }             // //此電性不需判斷規格(是)
                          // //
            rowReslut.EndEdit();
            return funCalculateMinMaxSumSqrRet;

        }

        public static bool funCalculateMinMaxSumSqr(ref DataRow rowReslut, decimal valueQty, DataRow rowRawData_Spec, string min_colFieldName, string max_colFieldName)
        {
            bool funCalculateMinMaxSumSqrRet = default(bool);


            rowReslut.BeginEdit();
            // //Max
            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectLess(rowReslut["MaxValue"], valueQty, false)))
            {
                rowReslut["MaxValue"] = valueQty;
            }

            // //Min
            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowReslut["MinValue"], 0, false)) || Conversions.ToBoolean(Operators.ConditionalCompareObjectGreater(rowReslut["MinValue"], valueQty, false)))
            {
                rowReslut["MinValue"] = valueQty;
            }

            // //Sum
            rowReslut["SumValue"] = (decimal)rowReslut["SumValue"] + valueQty;

            // //SumSqr
            rowReslut["SqrValue"] = (double)rowReslut["SqrValue"] +
                Math.Pow((double)valueQty, 2d);

            // //符合規格的顆數(良品數)
            // //規格最大、最小都為零時不需要判,都算是Good
            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowRawData_Spec[min_colFieldName], 0, false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowRawData_Spec[max_colFieldName], 0, false)))
            {
                rowReslut["GoodQty1"] = Convert.ToInt32(rowReslut["GoodQty1"]) + 1;
                rowReslut["GoodQty2"] = Convert.ToInt32(rowReslut["GoodQty2"]) + 1;
                funCalculateMinMaxSumSqrRet = true;     // //回傳此電性是否在規格內(是)
            }
            else if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(valueQty, rowRawData_Spec[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLess(valueQty, rowRawData_Spec[max_colFieldName], false)))
            {
                rowReslut["GoodQty1"] = Convert.ToInt32(rowReslut["GoodQty1"]) + 1;
                rowReslut["GoodQty2"] = Convert.ToInt32(rowReslut["GoodQty2"]) + 1;
                funCalculateMinMaxSumSqrRet = true;     // //回傳此電性是否在規格內(是)
            }
            else
            {
                funCalculateMinMaxSumSqrRet = false;
            }    // //回傳此電性是否在規格內(否)
                 // //更新
            rowReslut.EndEdit();
            return funCalculateMinMaxSumSqrRet;

        }

        public static bool funCalculateMinMaxSumSqr(DataRow rowRawData, string colFieldName, ref DataRow rowReslut)
        {
            bool funCalculateMinMaxSumSqrRet = default(bool);

            // //更新
            rowReslut.BeginEdit();
            // //Max
            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectLess(rowReslut["MaxValue"], decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), false)))
            {
                rowReslut["MaxValue"] = decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
            }
            // //Min
            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowReslut["MinValue"], 0, false)) || Conversions.ToBoolean(Operators.ConditionalCompareObjectGreater(rowReslut["MinValue"], decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), false)))
            {
                rowReslut["MinValue"] = decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
            }
            // //更新
            rowReslut.EndEdit();
            // //Return
            funCalculateMinMaxSumSqrRet = true;
            return funCalculateMinMaxSumSqrRet;

        }

        // add by Lena, 2012/06/22
        public static bool funCalculateMinMaxSumSqr(string colFieldName, DataRow rowRawData, ref DataRow rowReslut, DataRow rowRawData_Spec, string min_colFieldName, string max_colFieldName)
        {
            bool funCalculateMinMaxSumSqrRet = default(bool);


            // '//符合規格的顆數(良品數)
            if (Conversions.ToBoolean(Operators.ConditionalCompareObjectGreaterEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_Spec[min_colFieldName], false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectLessEqual(decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), rowRawData_Spec[max_colFieldName], false)))
            {

                // //更新
                rowReslut.BeginEdit();
                // //Max
                if (Conversions.ToBoolean(Operators.ConditionalCompareObjectLess(rowReslut["MaxValue"], decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), false)))
                {
                    rowReslut["MaxValue"] = decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
                }
                // //Min
                if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowReslut["MinValue"], -9999, false)) || Conversions.ToBoolean(Operators.ConditionalCompareObjectGreater(rowReslut["MinValue"], decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), false)))
                {
                    rowReslut["MinValue"] = decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
                }

                // //Sum
                rowReslut["SumValue"] = (decimal)rowReslut["SumValue"] +
                    decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));

                // //SumSqr
                rowReslut["SqrValue"] = (double)rowReslut["SqrValue"] +
                    Math.Pow((double)decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), 2d);

                // //Yield Die數加一
                rowReslut["GoodQty1"] = Convert.ToInt32(rowReslut["GoodQty1"]) + 1;

                // //Avg Die數加一
                rowReslut["GoodQty2"] = Convert.ToInt32(rowReslut["GoodQty2"]) + 1;

                // //更新
                rowReslut.EndEdit();
                funCalculateMinMaxSumSqrRet = true;     // //回傳此電性是否在規格內(是)
            }

            // '//規格最大、最小都為零時不需要判,都算是Good
            else if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowRawData_Spec[min_colFieldName], 0, false)) && Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowRawData_Spec[max_colFieldName], 0, false)))
            {

                // //更新
                rowReslut.BeginEdit();
                // //Max
                if (Conversions.ToBoolean(Operators.ConditionalCompareObjectLess(rowReslut["MaxValue"], decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), false)))
                {
                    rowReslut["MaxValue"] = decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
                }
                // //Min
                if (Conversions.ToBoolean(Operators.ConditionalCompareObjectEqual(rowReslut["MinValue"], -9999, false)) || Conversions.ToBoolean(Operators.ConditionalCompareObjectGreater(rowReslut["MinValue"], decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), false)))
                {
                    rowReslut["MinValue"] = decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));
                }

                // //Sum
                rowReslut["SumValue"] = (decimal)rowReslut["SumValue"] +
                    decimal.Parse(Conversions.ToString(rowRawData[colFieldName]));

                // //SumSqr
                rowReslut["SqrValue"] = (double)rowReslut["SqrValue"] +
                    Math.Pow((double)decimal.Parse(Conversions.ToString(rowRawData[colFieldName])), 2d);

                // //Yield Die數加一
                rowReslut["GoodQty1"] = Convert.ToInt32(rowReslut["GoodQty1"]) + 1;

                // //Avg Die數加一
                rowReslut["GoodQty2"] = Convert.ToInt32(rowReslut["GoodQty2"]) + 1;

                // //更新
                rowReslut.EndEdit();
                funCalculateMinMaxSumSqrRet = true;     // //回傳此電性是否在規格內(是)
            }

            else
            {
                funCalculateMinMaxSumSqrRet = false;
            }    // //回傳此電性是否在規格內(否)

            return funCalculateMinMaxSumSqrRet;

        }

        #endregion

        #region --- Transaction Output ---

        public static object OutputSQLNoneQuery(ref string strCommandText)
        {

            bool blnTransactionLog = false;

            try
            {
                blnTransactionLog = Conversions.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["TransactionLog"]);
            }
            catch (Exception ex)
            {
                blnTransactionLog = false;
            }

            if (blnTransactionLog == false)
                return default(Object);

            var tfc = new System.CodeDom.Compiler.TempFileCollection(System.Configuration.ConfigurationSettings.AppSettings["OutputSQLPath"], true);
            string FileName = tfc.AddExtension("SQL");
            string ErrorLogFile = System.Configuration.ConfigurationSettings.AppSettings["ErrorLogPath"] + Strings.Format(DateTime.Now, "yyyyMMdd").ToString() + "_Error.Log";
            FileName = FileName.Insert(FileName.LastIndexOf(@"\") + 1, "TX" + DateTime.Now.ToString("yyyyMMddHHmmssfff"));

            try
            {
                using (var sw = System.IO.File.AppendText(FileName))
                {
                    sw.WriteLine(strCommandText.Replace(Constants.vbCrLf, " "));
                    sw.Flush();
                }
            }
            catch (Exception ex)
            {
                try
                {
                    using (var sw = System.IO.File.AppendText(ErrorLogFile))
                    {
                        sw.WriteLine(ex.Message + ex.StackTrace);
                        sw.Flush();
                    }
                }
                catch (Exception e1)
                {
                }
            }
            finally
            {
                System.IO.File.Delete(tfc.BasePath + ".tmp");
            }

            return default(Object);

        }

        // Public Function OutputSQLNoneQuery_UPD(ByRef CollectionSQL As Collection)

        // Dim blnTransactionLog As Boolean = False

        // Try
        // blnTransactionLog = CType(System.Configuration.ConfigurationSettings.AppSettings("TransactionLog"), Boolean)
        // Catch ex As Exception
        // blnTransactionLog = False
        // End Try

        // If blnTransactionLog = False Then Exit Function

        // Dim tfc As New System.CodeDom.Compiler.TempFileCollection(System.Configuration.ConfigurationSettings.AppSettings("OutputSQLPath"), True)
        // Dim FileName As String = tfc.AddExtension("SQL")
        // Dim ErrorLogFile As String = System.Configuration.ConfigurationSettings.AppSettings("ErrorLogPath") & Format(Now, "yyyyMMdd").ToString & "_Error.Log"
        // FileName = FileName.Insert(FileName.LastIndexOf("\") + 1, "TX" & Now.ToString("yyyyMMddHHmmssfff"))
        // Dim strCommandText As String = String.Empty

        // Try
        // Using sw As System.IO.StreamWriter = System.IO.File.AppendText(FileName)
        // For Each strCommandText In CollectionSQL
        // sw.WriteLine(strCommandText.Replace(vbCrLf, " "))
        // Next strCommandText
        // sw.Flush()
        // End Using
        // Catch ex As Exception
        // Try
        // Using sw As System.IO.StreamWriter = System.IO.File.AppendText(ErrorLogFile)
        // sw.WriteLine(ex.Message & ex.StackTrace)
        // sw.Flush()
        // End Using
        // Catch e1 As Exception
        // End Try
        // Finally
        // System.IO.File.Delete(tfc.BasePath & ".tmp")
        // End Try

        // End Function

        public static object OutputSQLNoneQuery_AttachFile(ref string strCommandText, ref string AttachName, ref string aBody, object DataType)
        {

            bool blnTransactionLog = false;

            try
            {
                blnTransactionLog = Conversions.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["TransactionLog"]);
            }
            catch (Exception ex)
            {
                blnTransactionLog = false;
            }

            if (blnTransactionLog == false)
                return default(Object);

            var tfc1 = new System.CodeDom.Compiler.TempFileCollection(System.Configuration.ConfigurationSettings.AppSettings["OutputSQLPath"], true);
            var tfc2 = new System.CodeDom.Compiler.TempFileCollection(System.Configuration.ConfigurationSettings.AppSettings["AttachFilePath"], true);
            string FileName = tfc1.AddExtension("SQL");
            string AttachFile = tfc2.AddExtension("TXT");
            string ErrorLogFile = System.Configuration.ConfigurationSettings.AppSettings["ErrorLogPath"] + Strings.Format(DateTime.Now, "yyyyMMdd").ToString() + "_Error.Log";
            FileName = FileName.Insert(FileName.LastIndexOf(@"\") + 1, "TX" + DateTime.Now.ToString("yyyyMMddHHmmssfff"));
            AttachFile = AttachFile.Insert(AttachFile.LastIndexOf(@"\") + 1, AttachName);

            try
            {
                // //Output File
                if (aBody != null)
                {
                    string sFileSource = AttachFile;
                    if (System.IO.File.Exists(sFileSource))
                    {
                        try
                        {
                            System.IO.File.Delete(sFileSource);
                            using (var sw = System.IO.File.AppendText(sFileSource))
                            {
                                sw.WriteLine(aBody);
                                sw.Flush();
                            }
                        }
                        catch (System.IO.IOException ex)
                        {
                        }
                    }
                    else
                    {
                        using (var sw = System.IO.File.AppendText(sFileSource))
                        {
                            sw.WriteLine(aBody);
                            sw.Flush();
                        }
                    }
                }
                // //輸出格式 = SQL Command;DataType;FilePath
                strCommandText += ";" + DataType.ToString() + ";" + AttachFile;
                using (var sw = System.IO.File.AppendText(FileName))
                {
                    sw.WriteLine(strCommandText.Replace(Constants.vbCrLf, " "));
                    sw.Flush();
                }
            }
            catch (Exception ex)
            {
                try
                {
                    using (var sw = System.IO.File.AppendText(ErrorLogFile))
                    {
                        sw.WriteLine(ex.Message + ex.StackTrace);
                        sw.Flush();
                    }
                }
                catch (Exception e1)
                {
                }
            }
            finally
            {
                System.IO.File.Delete(tfc1.BasePath + ".tmp");
                System.IO.File.Delete(tfc2.BasePath + ".tmp");
            }

            return default(Object);

        }

        public static object OutputSQLNoneQuery_AttachFile(ref string strCommandText, ref string AttachName, ref byte[] aBody, object DataType)
        {

            bool blnTransactionLog = false;

            try
            {
                blnTransactionLog = Conversions.ToBoolean(System.Configuration.ConfigurationSettings.AppSettings["TransactionLog"]);
            }
            catch (Exception ex)
            {
                blnTransactionLog = false;
            }

            if (blnTransactionLog == false)
                return default(Object);

            var tfc1 = new System.CodeDom.Compiler.TempFileCollection(System.Configuration.ConfigurationSettings.AppSettings["OutputSQLPath"], true);
            var tfc2 = new System.CodeDom.Compiler.TempFileCollection(System.Configuration.ConfigurationSettings.AppSettings["AttachFilePath"], true);
            string FileName = tfc1.AddExtension("SQL");
            string AttachFile = tfc2.AddExtension(AttachName.Substring(AttachName.Length - 3, 3).ToUpper());
            string ErrorLogFile = System.Configuration.ConfigurationSettings.AppSettings["ErrorLogPath"] + Strings.Format(DateTime.Now, "yyyyMMdd").ToString() + "_Error.Log";
            FileName = FileName.Insert(FileName.LastIndexOf(@"\") + 1, "TX" + DateTime.Now.ToString("yyyyMMddHHmmssfff"));
            AttachFile = AttachFile.Insert(AttachFile.LastIndexOf(@"\") + 1, AttachName.Substring(0, AttachName.Length - 4));

            try
            {
                // //Output File
                if (aBody != null)
                {
                    string sFileSource = AttachFile;
                    if (System.IO.File.Exists(sFileSource))
                    {
                        try
                        {
                            System.IO.File.Delete(sFileSource);
                            var fs = new System.IO.FileStream(sFileSource, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
                            fs.Write(aBody, 0, aBody.Length);
                            fs.Close();
                        }
                        catch (System.IO.IOException ex)
                        {
                        }
                    }
                    else
                    {
                        var fs = new System.IO.FileStream(sFileSource, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write);
                        fs.Write(aBody, 0, aBody.Length);
                        fs.Close();
                    }
                }
                // //輸出格式 = SQL Command;DataType;FilePath
                strCommandText += ";" + DataType.ToString() + ";" + AttachFile;
                using (var sw = System.IO.File.AppendText(FileName))
                {
                    sw.WriteLine(strCommandText.Replace(Constants.vbCrLf, " "));
                    sw.Flush();
                }
            }
            catch (Exception ex)
            {
                try
                {
                    using (var sw = System.IO.File.AppendText(ErrorLogFile))
                    {
                        sw.WriteLine(ex.Message + ex.StackTrace);
                        sw.Flush();
                    }
                }
                catch (Exception e1)
                {
                }
            }
            finally
            {
                System.IO.File.Delete(tfc1.BasePath + ".tmp");
                System.IO.File.Delete(tfc2.BasePath + ".tmp");
            }

            return default(Object);

        }

        #endregion

        #region Invoke

        /// <summary>
    /// 叫用Web Service, 並回傳Response XML
    /// </summary>
    /// <param name="Method">要呼叫哪一個WebService的方法, ex: wsWIP.LoadLotBasis</param>
    /// <param name="InXml">InXml</param>
    /// <param name="Customize">是否客製的WebService</param>
    /// <returns></returns>
        public static string InvokeSrv(string Method, string InXml, bool Customize = false)
        {

            object result;

            try
            {

                using (var ws = new wsInvoke.wsInvoke())
                {
                    ws.Url = modWIN.LocalizeWebService(ws.Url.ToString(), Customize);
                    ws.EnableDecompression = true;
                    result = ws.invokeSrv(Method, new object[] { InXml });
                }
            }

            catch (Exception ex)
            {
                throw;
            }

            return Conversions.ToString(result);

        }

        /// <summary>
    /// 叫用Web Service, 回傳Response XML
    /// </summary>
    /// <param name="Method">要呼叫哪一個WebService的方法, ex: wsWIP.LoadLotBasis</param>
    /// <param name="InXml">InXml</param>
    /// <param name="buffer">用來取回byte資料或傳入byte資料</param>
    /// <param name="Customize">是否客製的WebService</param>
    /// <returns></returns>
        public static string InvokeSrv(string Method, string InXml, byte[] buffer, bool Customize = false)
        {

            object result;

            try
            {

                using (var ws = new wsInvoke.wsInvoke())
                {
                    ws.Url = modWIN.LocalizeWebService(ws.Url.ToString(), Customize);
                    ws.EnableDecompression = true;
                    result = ws.invokeSrv(Method, new object[] { InXml, buffer });
                }
            }

            catch (Exception ex)
            {
                throw;
            }

            return Conversions.ToString(result);

        }

        /// <summary>
    /// 叫用Web Service, 並回傳Response XML
    /// </summary>
    /// <param name="Method">要呼叫哪一個WebService的方法, ex: wsWIP.LoadLotBasis</param>
    /// <param name="InXml">InXml</param>
    /// <param name="pDataSet">接收結果的DataSet</param>
    /// <param name="Customize">是否客製的WebService</param>
    /// <returns></returns>
        public static string InvokeSrv(string Method, string InXml, ref DataSet pDataSet, bool Customize = false)
        {

            object result;

            try
            {

                using (var ws = new wsInvoke.wsInvoke())
                {
                    ws.Url = modWIN.LocalizeWebService(ws.Url.ToString(), Customize);
                    ws.EnableDecompression = true;
                    result = ws.invokeSrv_DataSet(Method, InXml, ref pDataSet);
                }
            }

            catch (Exception ex)
            {
                throw;
            }

            return Conversions.ToString(result);

        }

        #endregion


        // 發Mail功能 非群組與群組發送
        public static string SendMultiEmail(ref string FileName, ref string EmailSubject, string EmailBody = defString, string GroupNo = defString, byte[] AttachFile = null, GroupType GroupType = GroupType.UserGroup)
        {
            string SendMultiEmailRet = default(string);
            // GroupType
            // 0:User Group (使用者群組)
            // 1:Issue Group (簽核群組) 
            // 2:Equipment Group(設備工程師群組) 
            // 3:Inventory Group(庫房工程師群組) 
            // 4:Report Group(報表使用群組) 
            // 5:ERF Disposition Group(異常處理群組) 
            // 6:ERF Mail ccGroup(附件收件人群組)

            try
            {

                strIdentity = CombineXMLIdentity(modWIN.gComputerName, "AUTORUN", DateTime.Now.ToString());
                strParameter = CombineXMLParameter("groupno", "GroupNo", "String", CInput(GroupNo), "");
                strParameter = strParameter + CombineXMLParameter("emailsubject", "EmailSubject", "String", EmailSubject, "");
                strParameter = strParameter + CombineXMLParameter("emailbody", "EmailBody", "String", EmailBody, "");
                strParameter = strParameter + CombineXMLParameter("grouptype", "GroupType", "Integer", GroupType.ToString(), "");
                strParameter = strParameter + CombineXMLParameter("attachfilename", "AttachFileName", "String", FileName, "");
                var XmlDoc = new System.Xml.XmlDocument();

                InXml = modWIN.CombineXMLRequest(ref strIdentity, ref strParameter);

                // OutXml = wsWIP.SendEmailAndAttachFileToGroup(InXml, AttachFile)
                OutXml = InvokeSrv("wsWIP.SendEmailAndAttachFileToGroup", InXml, AttachFile);

                XmlDoc.LoadXml(OutXml);

                if (modWIN.chkExecutionSuccess(ref XmlDoc))  // 找出Exception訊並顯示出來
                {
                    SendMultiEmailRet = "success";
                }
                else
                {
                    SendMultiEmailRet = "fail";
                }

                XmlDoc = null;
            }

            catch (Exception ex)
            {
                SendMultiEmailRet = "fail;" + ex.Message;
            }

            return SendMultiEmailRet;

        }
    }
}