using System;
using Microsoft.VisualBasic;
using static iMESCore.Base.iMESComSubroutine;
using static iMESCore.Base.iMESComXML;
using static iMESCore.Base.iMESConst;
using iMESCore.Settings;
using System.Web.Services;
using System.Data;
using Microsoft.VisualBasic.CompilerServices;

namespace wsABC
{

    public class wsWIP
    {

        private iMESCore.Settings.AppSettings objSetting = new iMESCore.Settings.AppSettings();
        private System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();       // 用以讀取Xml字串
        private DateTime ArriveTime;              // 送達時間
        private string strIdentity;               // Identity XML字串
        private string strReturnValue;            // ReturnValue XML字串
        private string strException;              // Exception XML字串
        private string strResult;                 // Result XML字串
        private string strMessage;                // Message XML字串
        private string strServiceName = "wsWIP_ABC";   // ServiceName
        private string strResourceDir = "Resources";
        private kcWIP.clsLot objLot = new kcWIP.clsLot();
        private kcSYS.clsSYSUserLog objSYS = new kcSYS.clsSYSUserLog();   // 宣告Sys的物件
        private MEStc_ABC.clsLot  clsLot  = new MEStc_ABC.clsLot();   // 宣告Sys的物件

        public wsWIP()
        {
            try
            {
                strResourceDir = System.IO.Path.Combine("wsUpdateResource", objSetting["ResourceDir"].ToString());
            }
            catch (Exception)
            { }
        }

        public string HelloWorld(string InXml)
        {
            return "HelloWorld";
        }

        [WebMethod(Description = "Execute Check In by LotNo")]
        public string Exe_CheckIn(string InXml)
        {
            string Exe_CheckInRet = default(string);

            long LotStamp;
            string LotNo = default(string), LinkName, UserNo = default(string);

            DataTable dtAttrib;
            DataTable dtEquipment;
            DataTable dtEquipmentChamber;
            DataRow drData;

            DataTable dtMTLLot;

            System.Xml.XmlNodeList xmlList;
            string ShiftNo = "N/A";
            string LotRecord = defString;
            int i;
            var CheckInTime = defDateTime;
            string RuleNo = ""; // Added by Jialing 2011/02/18

            ArriveTime = DateTime.Now;

            try
            {
                // 讀取InXml字串
                xmlDoc.LoadXml(InXml);
                UserNo = GetXMLCurUserNo(xmlDoc);

                // 組Identity字串
                strIdentity = CombineXMLIdentity(Environment.MachineName, UserNo, Conversions.ToString(ArriveTime));

                // 開始解譯InXml字串
                if (xmlDoc.DocumentElement.GetElementsByTagName("lotstamp").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("lotstamp").Item(0).SelectNodes("value").Count > 0)
                    {
                        LotStamp = Conversions.ToLong(xmlDoc.DocumentElement.GetElementsByTagName("lotstamp").Item(0).SelectNodes("value").Item(0).InnerText);
                    }
                    else
                    {
                        throw new iMESException.MESException("0000-200002", "[%LotStamp%] [%Not Found%]");
                    }
                }
                else
                {
                    throw new iMESException.MESException("0000-200002", "[%LotStamp%] [%Not Found%]");
                }
                if (xmlDoc.DocumentElement.GetElementsByTagName("lotno").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("lotno").Item(0).SelectNodes("value").Count > 0)
                    {
                        LotNo = xmlDoc.DocumentElement.GetElementsByTagName("lotno").Item(0).SelectNodes("value").Item(0).InnerText;
                    }
                    else
                    {
                        throw new iMESException.MESException("0000-200002", "[%LotNo%] [%Not Found%]");
                    }
                }
                else
                {
                    throw new iMESException.MESException("0000-200002", "[%LotNo%] [%Not Found%]");
                }
                if (xmlDoc.DocumentElement.GetElementsByTagName("linkname").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("linkname").Item(0).SelectNodes("value").Count > 0)
                    {
                        LinkName = xmlDoc.DocumentElement.GetElementsByTagName("linkname").Item(0).SelectNodes("value").Item(0).InnerText;
                    }
                    else
                    {
                        throw new iMESException.MESException("0000-200002", "[%LinkName%] [%Not Found%]");
                    }
                }
                else
                {
                    throw new iMESException.MESException("0000-200002", "[%LinkName%] [%Not Found%]");
                }
                // Added by Jialing 2011/02/18
                if (xmlDoc.DocumentElement.GetElementsByTagName("ruleno").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("ruleno").Item(0).SelectNodes("value").Count > 0)
                    {
                        RuleNo = xmlDoc.DocumentElement.GetElementsByTagName("ruleno").Item(0).SelectNodes("value").Item(0).InnerText;
                    }
                }
                if (xmlDoc.DocumentElement.GetElementsByTagName("shiftno").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("shiftno").Item(0).SelectNodes("value").Count > 0)
                    {
                        ShiftNo = xmlDoc.DocumentElement.GetElementsByTagName("shiftno").Item(0).SelectNodes("value").Item(0).InnerText;
                    }
                }
                if (xmlDoc.DocumentElement.GetElementsByTagName("lotrecord").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("lotrecord").Item(0).SelectNodes("value").Count > 0)
                    {
                        LotRecord = xmlDoc.DocumentElement.GetElementsByTagName("lotrecord").Item(0).SelectNodes("value").Item(0).InnerText;
                    }
                }

                // 加入CheckIntime By carl 2007/06/04
                if (xmlDoc.DocumentElement.GetElementsByTagName("checkintime").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("checkintime").Item(0).SelectNodes("value").Count > 0)
                    {
                        CheckInTime = Conversions.ToDate(xmlDoc.DocumentElement.GetElementsByTagName("checkintime").Item(0).SelectNodes("value").Item(0).InnerText);
                    }
                }

                // 1.取出CheckIn Data, Attrib --------------------------------------------------------------------------------------------
                // <attrib>
                // <name>..</name> <type>..</type>
                // <value>
                // <attribno>..</attribno>
                // <attribtype>..</attribtype>
                // <attribsequence>..</attribsequence>
                // <attribsource>..</attribsource>
                // <attribphase>..</attribphase>
                // <attribvalue>..</attribvalue>
                // </value>
                // <desc></desc>
                // </attrib>
                dtAttrib = new DataTable("Attrib");
                dtAttrib.Columns.Add("AttribNo", Type.GetType("System.String"));
                dtAttrib.Columns.Add("AttribType", Type.GetType("System.Int32"));
                dtAttrib.Columns.Add("AttribSequence", Type.GetType("System.Int32"));
                dtAttrib.Columns.Add("AttribSource", Type.GetType("System.Int32"));
                dtAttrib.Columns.Add("AttribPhase", Type.GetType("System.Int32"));
                dtAttrib.Columns.Add("AttribValue", Type.GetType("System.String"));
                dtAttrib.Columns.Add("SaveToLotPropertyNo", Type.GetType("System.String"));
                // 2015-12-16, Joe, Add
                dtAttrib.Columns.Add("TestValue", Type.GetType("System.String"));
                dtAttrib.Columns.Add("QCItemNo", Type.GetType("System.String"));
                dtAttrib.Columns.Add("Result", Type.GetType("System.String"));
                dtAttrib.Columns.Add("Result_INT", Type.GetType("System.Int32"));
                dtAttrib.Columns.Add("FactorSerial", Type.GetType("System.String"));
                dtAttrib.Columns.Add("SerialNo", Type.GetType("System.Int32"));
                dtAttrib.Columns.Add("MEMO", Type.GetType("System.String"));
                dtAttrib.Columns.Add("ComponentNo", Type.GetType("System.String"));

                if (xmlDoc.DocumentElement.GetElementsByTagName("attrib").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("attrib").Item(0).SelectNodes("value").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("attrib").Item(0).SelectNodes("value");
                        var loopTo = xmlList.Count - 1;
                        for (i = 0; i <= loopTo; i++)
                        {
                            if (xmlList[i].SelectNodes("attribno").Count == 0 | xmlList[i].SelectNodes("attribtype").Count == 0 | xmlList[i].SelectNodes("attribsequence").Count == 0 | xmlList[i].SelectNodes("attribsource").Count == 0 | xmlList[i].SelectNodes("attribphase").Count == 0 | xmlList[i].SelectNodes("attribvalue").Count == 0)
                            {
                                throw new iMESException.MESException("0000-200002", "[%AttribNo%], [%AttribType%], [%AttribSequence%], [%AttribSource%], [%AttribPhase%], [%AttribValue%] [%cannotbeempty%]");
                            }
                            // 將資料存入暫存Table
                            drData = dtAttrib.NewRow();
                            drData["AttribNo"] = xmlList[i].SelectNodes("attribno").Item(0).InnerText;
                            drData["AttribType"] = xmlList[i].SelectNodes("attribtype").Item(0).InnerText;
                            drData["AttribSequence"] = xmlList[i].SelectNodes("attribsequence").Item(0).InnerText;
                            drData["AttribSource"] = xmlList[i].SelectNodes("attribsource").Item(0).InnerText;
                            drData["AttribPhase"] = xmlList[i].SelectNodes("attribphase").Item(0).InnerText;
                            drData["AttribValue"] = xmlList[i].SelectNodes("attribvalue").Item(0).InnerText;
                            if (xmlList[i].SelectNodes("savetolotpropertyno").Count > 0)
                            {
                                drData["SaveToLotPropertyNo"] = xmlList[i].SelectNodes("savetolotpropertyno").Item(0).InnerText;
                            }
                            else
                            {
                                drData["SaveToLotPropertyNo"] = "";
                            }
                            // 2015-12-16, Joe, Add
                            drData["TestValue"] = xmlList[i].SelectNodes("attribvalue").Item(0).InnerText;
                            if (xmlList[i].SelectNodes("qcitemno").Count > 0)
                            {
                                drData["QCItemNo"] = xmlList[i].SelectNodes("qcitemno").Item(0).InnerText;
                            }
                            if (xmlList[i].SelectNodes("result").Count > 0)
                            {
                                drData["Result"] = xmlList[i].SelectNodes("result").Item(0).InnerText;
                            }
                            if (xmlList[i].SelectNodes("result_int").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("result_int").Item(0).InnerText))
                            {
                                if (Information.IsNumeric(xmlList[i].SelectNodes("result_int").Item(0).InnerText))
                                {
                                    drData["Result_INT"] = xmlList[i].SelectNodes("result_int").Item(0).InnerText;
                                }
                                else
                                {
                                    throw new iMESException.MESException("0000-200011", "Result_INT must be numeric");
                                }
                            }
                            if (xmlList[i].SelectNodes("factorserial").Count > 0)
                            {
                                drData["FactorSerial"] = xmlList[i].SelectNodes("factorserial").Item(0).InnerText;
                            }
                            if (xmlList[i].SelectNodes("serialno").Count > 0 && !string.IsNullOrEmpty(xmlList[i].SelectNodes("serialno").Item(0).InnerText))
                            {
                                drData["SerialNo"] = xmlList[i].SelectNodes("serialno").Item(0).InnerText;
                            }
                            dtAttrib.Rows.Add(drData);
                        }
                    }
                }

                // 2.取出CheckIn Data, Equipment --------------------------------------------------------------------------------------------
                // <equipment>
                // <name>..</name> <type>..</type>
                // <value>
                // <equipmentno>..</equipmentno>
                // <loadport>..</loadport>
                // </value>
                // <desc></desc>
                // </equipment>
                dtEquipment = new DataTable("Equipment");
                dtEquipment.Columns.Add("EquipmentNo", Type.GetType("System.String"));
                dtEquipment.Columns.Add("LoadPort", Type.GetType("System.Int16"));

                if (xmlDoc.DocumentElement.GetElementsByTagName("equipment").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("equipment").Item(0).SelectNodes("value").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("equipment").Item(0).SelectNodes("value");
                        var loopTo1 = xmlList.Count - 1;
                        for (i = 0; i <= loopTo1; i++)
                        {
                            if (xmlList[i].SelectNodes("equipmentno").Count == 0)
                            {
                                throw new iMESException.MESException("0000-200002", "[%EquipmentNo%] [%cannotbeempty%]");
                            }

                            // 將資料存入暫存Table
                            drData = dtEquipment.NewRow();
                            drData["EquipmentNo"] = xmlList[i].SelectNodes("equipmentno").Item(0).InnerText;
                            if (xmlList[i].SelectNodes("loadport").Count > 0)
                            {
                                drData["LoadPort"] = xmlList[i].SelectNodes("loadport").Item(0).InnerText;
                            }
                            dtEquipment.Rows.Add(drData);
                        }
                    }
                }
                //TsungyYu 2021/06/10取出 Chamber--------------------------------------------------------------------------------------------

                dtEquipmentChamber = new DataTable("EquipmentChamber");
                dtEquipmentChamber.Columns.Add("EquipmentNo", System.Type.GetType("System.String"));
                dtEquipmentChamber.Columns.Add("BelongEquipmentNo", System.Type.GetType("System.String"));
                if (xmlDoc.DocumentElement.GetElementsByTagName("equipmentchamber").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("equipmentchamber").Item(0).SelectNodes("value").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("equipmentchamber").Item(0).SelectNodes("value");
                        var loopTo1 = xmlList.Count - 1;
                        for (i = 0; i <= loopTo1; i++)
                        {
                            if (xmlList[i].SelectNodes("equipmentno").Count == 0)
                            {
                                throw new iMESException.MESException("0000-200002", "[%EquipmentNo%] [%cannotbeempty%]");
                            }
                            //將資料存入暫存Table
                            drData = dtEquipmentChamber.NewRow();
                            drData["EquipmentNo"] = xmlList[i].SelectNodes("equipmentno").Item(0).InnerText;
                            drData["BelongEquipmentNo"] = xmlList[i].SelectNodes("belongequipmentno").Item(0).InnerText;
                            dtEquipmentChamber.Rows.Add(drData);
                        }
                    }
                }
                // 多人加工
                DataTable dtLoginState;
                dtLoginState = new DataTable("tblLoginState");
                dtLoginState.Columns.Add("UserNo", Type.GetType("System.String"));
                dtLoginState.Columns.Add("UserName", Type.GetType("System.String"));
                dtLoginState.Columns.Add("CheckInTime", Type.GetType("System.DateTime"));

                if (xmlDoc.DocumentElement.GetElementsByTagName("loginstate").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("loginstate").Item(0).SelectNodes("value").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("loginstate").Item(0).SelectNodes("value");
                        var loopTo2 = xmlList.Count - 1;
                        for (i = 0; i <= loopTo2; i++)
                        {
                            if (xmlList[i].SelectNodes("userno").Count == 0 || xmlList[i].SelectNodes("username").Count == 0 || xmlList[i].SelectNodes("checkintime").Count == 0)
                            {
                                throw new iMESException.MESException("0000-200002", "[%userno%], [%username%], [%checkintime%] [%not found%]");
                            }
                            // 將資料存入暫存Table
                            drData = dtLoginState.NewRow();
                            drData["UserNo"] = xmlList[i].SelectNodes("userno").Item(0).InnerText;
                            drData["UserName"] = xmlList[i].SelectNodes("username").Item(0).InnerText;
                            drData["CheckInTime"] = xmlList[i].SelectNodes("checkintime").Item(0).InnerText;
                            dtLoginState.Rows.Add(drData);
                        }
                    }
                }

                // 模治具
                DataTable dtAccessory;
                dtAccessory = new DataTable("Accessory");
                dtAccessory.Columns.Add("EquipmentNo", Type.GetType("System.String"));
                dtAccessory.Columns.Add("AccessoryNo", Type.GetType("System.String"));
                dtAccessory.Columns.Add("AccessoryVersion", Type.GetType("System.String"));
                dtAccessory.Columns.Add("AccessoryType", Type.GetType("System.String"));
                dtAccessory.Columns.Add("AccumulateQty", Type.GetType("System.Decimal"));

                if (xmlDoc.DocumentElement.GetElementsByTagName("accessory").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("accessory").Item(0).SelectNodes("value").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("accessory").Item(0).SelectNodes("value");
                        var loopTo3 = xmlList.Count - 1;
                        for (i = 0; i <= loopTo3; i++)
                        {
                            if (xmlList[i].SelectNodes("equipmentno").Count == 0 || xmlList[i].SelectNodes("accessoryno").Count == 0 || xmlList[i].SelectNodes("accessoryversion").Count == 0 || xmlList[i].SelectNodes("accessorytype").Count == 0 || xmlList[i].SelectNodes("accumulateqty").Count == 0)
                            {
                                throw new iMESException.MESException("0000-200002", "[%equipmentno%], [%accessoryno%], [%accessoryversion%], [%accessorytype%],[%accumulateqty%] [%not found%]");
                            }
                            // 將資料存入暫存Table
                            drData = dtAccessory.NewRow();
                            drData["EquipmentNo"] = xmlList[i].SelectNodes("equipmentno").Item(0).InnerText;
                            drData["AccessoryNo"] = xmlList[i].SelectNodes("accessoryno").Item(0).InnerText;
                            drData["AccessoryVersion"] = xmlList[i].SelectNodes("accessoryversion").Item(0).InnerText;
                            drData["AccessoryType"] = xmlList[i].SelectNodes("accessorytype").Item(0).InnerText;
                            drData["AccumulateQty"] = xmlList[i].SelectNodes("accumulateqty").Item(0).InnerText;
                            dtAccessory.Rows.Add(drData);
                        }
                    }
                }
                else
                {
                    // Kevin 20140106,區分沒選模治具與沒顯示模治具,介面沒顯示模治具則設為Nothing
                    dtAccessory = null;
                }

                dtMTLLot = new DataTable("Temp_MaterialLot");
                dtMTLLot.Columns.Add("MaterialNo", Type.GetType("System.String"));
                dtMTLLot.Columns.Add("MaterialLotNo", Type.GetType("System.String"));

                if (xmlDoc.DocumentElement.GetElementsByTagName("temp_materiallot").Count > 0)
                {
                    if (xmlDoc.GetElementsByTagName("temp_materiallot").Item(0).SelectNodes("value").Count > 0)
                    {
                        xmlList = xmlDoc.GetElementsByTagName("temp_materiallot").Item(0).SelectNodes("value");
                        var loopTo4 = xmlList.Count - 1;
                        for (i = 0; i <= loopTo4; i++)
                        {
                            // 將資料存入暫存Table
                            drData = dtMTLLot.NewRow();
                            drData["MaterialNo"] = xmlList[i].SelectNodes("materialno").Item(0).InnerText;
                            drData["MaterialLotNo"] = xmlList[i].SelectNodes("materiallotno").Item(0).InnerText;
                            dtMTLLot.Rows.Add(drData);
                        }
                    }
                }

                // 3.檢查投料點在機台的料是否足夠 -------------------------------------------------------------------------------------------
                objLot.ChkMaterialOnEquipment(LotNo, dtEquipment);

                // 4.Update CheckIn----------------------------------------------------------------------------------------------------------
                string LanguageMode = GetXMLLanguageMode(xmlDoc);
                objLot.BR_CheckIn(LotStamp, LotNo, LinkName, dtAttrib, dtEquipment, UserNo, ShiftNo, LotRecord, CheckInTime, RuleNo, dtLoginState, dtAccessory, dtMTLLot, LanguageMode, dtEquipmentChamber);

                // 5.Return Value------------------------------------------------------------------------------------------------------------
                strException = "";
                strResult = "success";

                objSYS.AddEventLog(strServiceName, UserNo, "LotNo", LotNo, DateTime.Now, "Exe_CheckIn", ComputerName: GetXMLCurComputer(xmlDoc));
            }

            catch (iMESException.MESException ex)
            {
                strReturnValue = "";
                switch (ex.ErrorCode.ToString() ?? "")
                {
                    case "IPQCNO":
                        {
                            strException = CombineXMLException(ex.ErrorCode.ToString(), TranslateMsg(ex.Message, GetXMLLanguageMode(xmlDoc), strResourceDir), "IPQCNO", ex.StackTrace);
                            break;
                        }

                    default:
                        {
                            strException = CombineXMLException(Conversions.ToString(ex.ErrorCode), TranslateMsg(ex.Message, GetXMLLanguageMode(xmlDoc), strResourceDir), "Exe_CheckIn fail!", ex.StackTrace);
                            break;
                        }
                }
                strResult = "fail";
                objSYS.AddErrorLog_ErrorCode(strServiceName, UserNo, "LotNo", LotNo, DateTime.Now, strException, ComputerName: GetXMLCurComputer(xmlDoc), ErrorCode: Conversions.ToString(ex.ErrorCode));
            }

            catch (Exception ex)
            {
                strReturnValue = "";
                strException = CombineXMLException(defWSErrCode, ex.Message, "Exe_CheckIn fail!", ex.StackTrace);
                strResult = "fail";
                objSYS.AddErrorLog_ErrorCode(strServiceName, UserNo, "LotNo", LotNo, DateTime.Now, strException, ComputerName: GetXMLCurComputer(xmlDoc));
            }

            finally
            {
                // 將各部份之XML字串組起來並傳出
                Exe_CheckInRet = CombineXMLResponse(strIdentity, strReturnValue, strException, strResult, "");

            }
            return Exe_CheckInRet;

        }
         
    }
}