using AppData;
using NKC_SDK;
using SteamWare;
using System;
using System.Data;
using System.Linq;

namespace NKC_WF.WebUserControls
{
    public partial class cmp_kittingSmart : BaseUserControl
    {
        #region Protected Properties

        protected DS_App.BinsDataTable currBinTab
        {
            get
            {
                return DLMan.taBN.getByItemID(itemIdSelected);
            }
        }

        protected DS_App.CartsDataTable currCartTab
        {
            get
            {
                return DLMan.taCR.getByItemID(itemIdSelected);
            }
        }

        /// <summary>
        /// ID univoco da IP
        /// </summary>
        protected string DeviceId
        {
            set
            {
                hfDeviceId.Value = value;
            }
            get
            {
                return hfDeviceId.Value;
            }
        }

        /// <summary>
        /// Comando barcode letto
        /// </summary>
        protected string lastCmd
        {
            get
            {
                return hfLastBCode.Value;
            }
            set
            {
                hfLastBCode.Value = value;
                lastValidCmd = value;
            }
        }

        /// <summary>
        /// Ultimo object letto
        /// </summary>
        protected string lastObject
        {
            get
            {
                return hfLastObject.Value;
            }
            set
            {
                hfLastObject.Value = value;
            }
        }

        /// <summary>
        /// ULTIMO Comando barcode VALIDO (!="") letto
        /// </summary>
        protected string lastValidCmd
        {
            get
            {
                return hfLastValidBCode.Value;
            }
            set
            {
                // solo se è !=""
                if (!string.IsNullOrEmpty(value))
                {
                    hfLastValidBCode.Value = value;
                }
            }
        }

        /// <summary>
        /// Sheet selezionato...
        /// </summary>
        protected int SheetID
        {
            set
            {
                hfSheetID.Value = value.ToString();
            }
            get
            {
                int answ = 0;
                int.TryParse(hfSheetID.Value, out answ);
                return answ;
            }
        }

        #endregion Protected Properties

        #region Public Properties

        public int itemIdSelected
        {
            get
            {
                int answ = 0;
                int.TryParse(hfItemID.Value, out answ);
                return answ;
            }
            set
            {
                hfItemID.Value = value.ToString();
                bool showBtn = value != 0;
                // fix visibilità
                lbtCancel.Visible = showBtn;
            }
        }

        /// <summary>
        /// PackList corrente...
        /// </summary>
        public int PackListID
        {
            set
            {
                hfBatchID.Value = value.ToString();
            }
            get
            {
                int answ = 0;
                int.TryParse(hfBatchID.Value, out answ);
                return answ;
            }
        }

        #endregion Public Properties

        #region Private Methods

        private void Cmp_barcode_eh_doRefresh(object sender, EventArgs e)
        {
            bool doRaiseEv = false;
            // processo evento..
            lastCmd = cmp_barcode.inputAcquired.ToUpper();
            doRaiseEv = processLastCmd(doRaiseEv);

            // reset comando
            cmp_barcode.inputAcquired = "";
            // aggiorno...
            doUpdate();
            if (doRaiseEv)
            {
                raiseEvent();
            }
        }

        private void Cmp_barcode_eh_doReset(object sender, EventArgs e)
        {
            resetIcons();
        }

        private void cmp_KS_BinCart_eh_doRefresh(object sender, EventArgs e)
        {
            displInfo("PAINT PART added");
            // resetto BIN & CART
            resetBin();
            resetCart();
            resetItem();
        }

        private void cmp_KS_Items_eh_doRefresh(object sender, EventArgs e)
        {
            displInfo("PART added");
            // resetto BIN & CART
            resetBin();
            resetCart();
            resetItem();
        }

        private void cmp_KS_OtherItemsCart_eh_doRefresh(object sender, EventArgs e)
        {
            displInfo("Other PART added");
            // resetto BIN & CART
            resetBin();
            resetCart();
            resetItem();
        }

        private void doUpdate()
        {
            fixVisibility();
        }

        private void fixVisibility()
        {
            // reset grafico
            cmp_KS_Cart.Visible = cmp_KS_Cart.CartID > 0 && (cmp_KS_BinCart.BinID + cmp_KS_OtherItemsCart.OtherItemID + cmp_KS_Items.ItemID == 0);
            cmp_KS_BinCart.Visible = cmp_KS_BinCart.BinID > 0;
            cmp_KS_OtherItemsCart.Visible = cmp_KS_OtherItemsCart.OtherItemID > 0;
            cmp_KS_Items.Visible = cmp_KS_Items.ItemID > 0;
            // fix btn reset!
            lbtResetSel.Visible = (itemIdSelected != 0);
        }

        /// <summary>
        /// Processo il DataMatrix letto
        /// </summary>
        /// <param name="tipoCod"></param>
        /// <param name="rawData"></param>
        /// <param name="codeInt"></param>
        private void processItemSuggestion(codeType tipoCod, string rawData, int codeInt)
        {
            DS_App.ItemListDataTable tabItem = null;
            DataLayer DLMan = new DataLayer();
            divInfo.Visible = false;
            // processo suggerimenti x ITEM / cart / bin dato suo RawData (Dtmx) e Cod univoco (intero)
            switch (tipoCod)
            {
                case codeType.Cart:
                    // primo step: verifico dal codice CART l'ordine da cui deriva...
                    var tabOrdini = DLMan.taOL.getByCart(rawData);
                    if (tabOrdini.Count == 0)
                    {
                        displError($"{traduci("KS_PIS_CartNotFound")} {rawData}, {traduci("ErrPleaseRetry")}");
                        resetCart();
                    }
                    else
                    {
                        var rigaOrd = tabOrdini[0];
                        // ora si va sulla tab delle PackListDet x cercare ordine legato al Cart... prendo quella attiva!
                        var tabPLD = DLMan.taPLD.getRunByOrdExtCode(rigaOrd.OrderExtCode);
                        // controllo se trovo righe...
                        if (tabPLD.Count == 0)
                        {
                            displError($"KIT REQuest: PackList not found for Cart {rawData} --> OrdExtCode {rigaOrd.OrderExtCode}, {traduci("ErrPleaseRetry")}");
                            resetCart();
                        }
                        else
                        {
                            // mostro CART!
                            string descr = "-";
                            try
                            {
                                descr = rigaOrd.OrderExtCode;
                            }
                            catch
                            { }
                            setCart(rawData, codeInt, descr);
                            // verifico se il cart sia già stato messo in scarico (in quel caso dico già ok...)
                            var tabLog = DLMan.taPLog.getByCartId(codeInt);
                            if (tabLog.Count > 0)
                            {
                                // per scrupolo sistemo la data di kitting...
                                DLMan.taCR.setKitStart(codeInt);
                                // verifico se sia completo --> reset... altrimenti lascio così...
                                var tabCOK = DLMan.taCOK.GetData();
                                // cerco se sia "green" numWait + numReady + numOtherWait = 0
                                var tabGreen = tabCOK.Where(x => (x.NumPzWaiting + x.NumPzBinAvail + x.OtherQtyWait == 0) && x.CartDtmx == rawData).ToList();
                                if (tabGreen.Count > 0)
                                {
                                    // verifico se sia SECONDA lettura
                                    if (lastObject == rawData)
                                    {
                                        // --> metto cart in scarico e registro LOG come se avesse appena letto 1:1 ogni Dtmx
                                        DLMan.taPLog.closeCart(codeInt);
                                        lgInfo($"cmp_kittingSmart | taPLog.closeCart | codeInt: {codeInt} | rawData: {rawData}");
                                        // mostro che ho fatto
                                        displInfo($"OK: CART removed {rawData}");
                                        lastObject = "";
                                        // resetto BIN & CART
                                        resetBin();
                                        resetCart();
                                    }
                                    else
                                    {
                                        lastObject = rawData;
                                        displInfo($"Cart already completed, please read CART another time: Cart {rawData}");
                                    }
                                    resetCart();
                                }
                            }
                            else
                            {
                                // recupero da tab di check complessiva
                                var tabPLCheck = DLMan.taPLC.GetData(rawData);
                                if (tabPLCheck.Count == 0)
                                {
                                    displError($"ERROR evaluating CART: {rawData}");
                                    resetCart();
                                }
                                else
                                {
                                    var rigaCheck = tabPLCheck[0];
                                    // verifico penalty (vedere stored: pezzi da leggere >= pezzi del cart...)
                                    if (rigaCheck.NumPenalty == 0)
                                    {
                                        // verifico se sia SECONDA lettura
                                        if (lastObject == rawData)
                                        {
                                            // --> metto cart in scarico e registro LOG come se avesse appena letto 1:1 ogni Dtmx
                                            DLMan.taPLog.acquireCart(rawData, currIpAddress, user_std.UtSn.userNameAD);
                                            lgInfo($"cmp_kittingSmart | taPLog.acquireCart | rawData: {rawData} | UserName: {user_std.UtSn.userNameAD} | currIpAddress: {currIpAddress}");
                                            displInfo($"OK: CART acquired {rawData} - item confirmed");
                                            lastObject = "";
                                            // eseguo comando x spostare i PAINT nel cart corretto...
                                            DLMan.taKL.updateCartForBin(rawData);
                                            lgInfo($"cmp_kittingSmart | taKL.updateCartForBin | rawData: {rawData}");
                                            // resetto BIN & CART
                                            resetBin();
                                            resetCart();
                                        }
                                        else
                                        {
                                            lastObject = rawData;
                                            displError($"Please read CART another time: Cart {rawData}");
                                        }
                                    }
                                    else
                                    {
                                        displError($"ERROR CART contains KIT already on download: {rawData}");
                                        resetCart();
                                    }
                                }
                            }
                        }
                    }
                    break;

                case codeType.BinProcessed:
                    // recupero la tab OKIB x iniziare a controllare i dati...
                    var tabOKIB = DLMan.taOKIB.getByBinDtmxProc(rawData);
                    // PRIMO: verifico SE ho delle righe valide...
                    if (tabOKIB.Count == 0)
                    {
                        displError($"BIN: Code not found {rawData}, {traduci("ErrPleaseRetry")}");
                        // reset preliminare
                        resetBin();
                    }
                    else
                    {
                        var listPainted = tabOKIB.Where(x => !x.IsPaintDateNull()).ToList();
                        if (listPainted.Count == 0)
                        {
                            displError($"BIN: Paint Date missing for item {tabOKIB[0].ItemDesc} | order {tabOKIB[0].OrderExtCode}, {traduci("ErrPleaseRetry")}");
                            // reset preliminare
                            resetBin();
                        }
                        else
                        {
                            var listAvailable = tabOKIB.Where(x => !x.IsPaintDateNull() && x.IsOnCartDateNull()).ToList();
                            if (listAvailable.Count == 0)
                            {
                                displError($"BIN: No item available for pickup on target CART for code {rawData} | item {tabOKIB[0].ItemDesc} | order {tabOKIB[0].OrderExtCode}, {traduci("ErrPleaseRetry")}");
                                // reset preliminare
                                resetBin();
                            }
                            else
                            {
                                // verifico SE ci sia ALMENO UN CART in postazione (iniziato KIT ma NON finito)...
                                var listCartAvailable = tabOKIB.Where(x => !x.IsCartKitStartNull() && x.IsCartKitEndNull()).ToList();
                                if (listCartAvailable.Count == 0)
                                {
                                    displError($"BIN: No CART available to proceed: {rawData} | item {tabOKIB[0].ItemDesc} | order {tabOKIB[0].OrderExtCode}");
                                    // reset preliminare
                                    resetBin();
                                }
                                else
                                {
                                    // mostro BIN!
                                    string descr = "-";
                                    try
                                    {
                                        descr = tabOKIB[0].OrderExtCode;
                                    }
                                    catch
                                    { }
                                    setBin(rawData, codeInt, descr);
                                    // verifico se il Bin sia già stato messo in scarico (in quel caso dico già ok...)
                                    var listBinAcquired = tabOKIB.Where(x => !x.IsCartKitStartNull() && x.IsCartKitEndNull() && !x.IsBinKitStartNull()).ToList();
                                    if (listBinAcquired.Count > 0)
                                    {
                                        // verifico se sia GIA' stato completato KIT...
                                        var listBinNotCompleted = tabOKIB.Where(x => !x.IsCartKitStartNull() && x.IsCartKitEndNull() && !x.IsBinKitStartNull() && x.IsBinKitEndNull()).ToList();
                                        if (listBinNotCompleted.Count == 0)
                                        {
                                            displError($"BIN: already completed: {rawData} | item {tabOKIB[0].ItemDesc} | order {tabOKIB[0].OrderExtCode}");
                                            // reset preliminare
                                            resetBin();
                                        }
                                    }
                                    else
                                    {
                                        // processing...
                                        if (lastObject == rawData)
                                        {
                                            // seconda lettura x indicare in scarico
                                            DLMan.taBN.updateKitting(codeInt, true, false);
                                            lgInfo($"cmp_kittingSmart | taBN.updateKitting | BinID: {codeInt} | BinDtmx: {rawData} | recStart: true | recEnd: false");
                                            // resetto BIN & CART
                                            resetBin();
                                            resetCart();
                                        }
                                        else
                                        {
                                            // chiedo seconda lettura
                                            lastObject = rawData;
                                            displError($"Please read BIN another time: BIN {rawData}");
                                            // reset preliminare
                                            resetBin();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    break;

                case codeType.Item:
                    // recupero la tab ITEMS x iniziare a controllare i dati...
                    tabItem = DLMan.taIL.getBySearch(codeInt, rawData, 0, 999);
                    if (tabItem.Count == 0)
                    {
                        displError($"{traduci("ErrPartNotFound")} {rawData}, {traduci("ErrPleaseRetry")}");
                        showItemDetail(false, null, true);
                    }
                    else if (tabItem.Count == 1)
                    {
                        var itemRow = tabItem[0];
                        showItemDetail(true, itemRow, false);
                        // verifico se ITEM sia o meno stato caricato sul CART x delivery finale
                        if (!itemRow.IsOnCartDateNull())
                        {
                            // se caricato --> mostro che è già a posto
                            displError($"{traduci("ErrPartAlreadyOnCart")} {rawData}, {traduci("ErrPleaseRetry")}");
                            resetItem();
                        }
                        else
                        {
                            // imposto controllo...
                            cmp_KS_Items.ItemID = codeInt;
                            cmp_KS_Items.NeedSecOp = !string.IsNullOrEmpty(itemRow.PostProcList);
                            cmp_KS_Items.NeedPaint = !string.IsNullOrEmpty(itemRow.ProcessesReq) && itemRow.ProcessesReq == "PaintFlag";
                            // controllo!
                            cmp_KS_Items.doUpdate();
                        }
                    }
                    break;

                case codeType.OtherItem:
                    // recupero la tab OKOI x iniziare a controllare i dati...
                    var tabOKOI = DLMan.taOKOI.getByOtherItemDtmx(rawData);
                    // PRIMO: verifico SE ho delle righe valide...
                    if (tabOKOI.Count == 0)
                    {
                        displError($"{traduci("ErrPartNotFound")} {rawData}, {traduci("ErrPleaseRetry")}");
                        // reset preliminare
                        resetOtherItem();
                    }
                    else
                    {
                        var listAvailable = tabOKOI.Where(x => x.IsOnCartDateNull()).ToList();
                        if (listAvailable.Count == 0)
                        {
                            displError($"{traduci("ErrPartNoItemAvail")} {rawData} | item {tabOKOI[0].OtherItemDesc} | order {tabOKOI[0].OrderExtCode}, {traduci("ErrPleaseRetry")}");
                            // reset preliminare
                            resetOtherItem();
                        }
                        else
                        {
                            // verifico SE ci sia ALMENO UN CART in postazione (iniziato KIT ma NON finito)...
                            var listCartAvailable = tabOKOI.Where(x => !x.IsCartKitStartNull() && x.IsCartKitEndNull()).ToList();
                            if (listCartAvailable.Count == 0)
                            {
                                displError($"{traduci("ErrPartNoCartAvail")}: {rawData} | PART {tabOKOI[0].OtherItemExtCode} {tabOKOI[0].OtherItemDesc}  | order {tabOKOI[0].OrderExtCode}");
                                // reset preliminare
                                resetOtherItem();
                            }
                            else
                            {
                                string descr = "-";
                                try
                                {
                                    descr = tabOKOI[0].OtherItemExtCode;
                                }
                                catch
                                { }
                                // mostro OtherItem!
                                setOtherItem(rawData, codeInt, descr);
                            }
                        }
                    }
                    break;

                default:
                    lastObject = "";
                    break;
            }
        }

        private bool processLastCmd(bool doRaiseEv)
        {
            if (string.IsNullOrEmpty(lastCmd)) doRaiseEv = true;
            // processiamo barcode letto
            decodedData decoData = DLMan.decodeBcode(lastCmd);
            switch (decoData.codeType)
            {
                case codeType.UNK:
                    cmp_barcode.showOutput(cssClass.danger, $"Unknown Data: {decoData.rawData} --> no action");
                    resetSelection();
                    doRaiseEv = true;
                    break;

                case codeType.Item:
                    cmp_barcode.showOutput(cssClass.success, $"Valid IT Code: {decoData.rawData}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;

                case codeType.ItemGeneric:
                    cmp_barcode.showOutput(cssClass.success, $"Valid IG Code: {decoData.rawData}");
                    //processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;

                case codeType.OtherItem:
                    cmp_barcode.showOutput(cssClass.success, $"Valid Generic PART Code: {decoData.rawData}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;

                case codeType.Material:
                    cmp_barcode.showOutput(cssClass.warning, $"Material - ignored: {decoData.description}");
                    doRaiseEv = true;
                    break;

                case codeType.Sheet:
                    cmp_barcode.showOutput(cssClass.warning, $"Sheet - ignored: {decoData.description}");
                    doRaiseEv = true;
                    break;

                case codeType.Stack:
                    cmp_barcode.showOutput(cssClass.warning, $"BUNK - ignored: {decoData.description}");
                    doRaiseEv = true;
                    break;

                case codeType.Batch:
                    cmp_barcode.showOutput(cssClass.warning, $"Batch - ignored: {decoData.description}");
                    doRaiseEv = true;
                    break;

                case codeType.Cart:
                    cmp_barcode.showOutput(cssClass.success, $"Valid CR Code: {decoData.description}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    doRaiseEv = true;
                    break;

                case codeType.Bin:
                    cmp_barcode.showOutput(cssClass.warning, $"WRONG BIN CODE (BN) - Ignored: {decoData.description}");
                    doRaiseEv = true;
                    break;

                case codeType.BinProcessed:
                    cmp_barcode.showOutput(cssClass.success, $"Valid BP Code: {decoData.description}");
                    processItemSuggestion(decoData.codeType, decoData.rawData, decoData.codeInt);
                    break;

                default:
                    cmp_barcode.showOutput(cssClass.danger, $"Unknown Data: {decoData.rawData} --> no action");
                    resetSelection();
                    break;
            }
            return doRaiseEv;
        }

        private void resetBin()
        {
            cmp_KS_BinCart.BinID = 0;
            fixVisibility();
        }

        private void resetCart()
        {
            cmp_KS_BinCart.CartID = 0;
            cmp_KS_OtherItemsCart.CartID = 0;
            cmp_KS_Cart.CartID = 0;
            cmp_KS_Items.CartID = 0;
            fixVisibility();
        }

        private void resetIcons()
        {
            lblDestination.CssClass = "text-secondary";
            lblDestination.Text = "";
            lblLastBCode.Text = "";
            lbtCancel.Visible = false;
            lbtResetSel.Visible = (itemIdSelected != 0);
        }

        private void resetItem()
        {
            itemIdSelected = 0;
            cmp_KS_Items.ItemID = 0;
            fixVisibility();
        }

        private void resetOtherItem()
        {
            cmp_KS_OtherItemsCart.OtherItemID = 0;
            fixVisibility();
        }

        private void resetShowData()
        {
            cmp_KS_Cart.Visible = false;
            cmp_KS_BinCart.Visible = false;
            cmp_KS_OtherItemsCart.Visible = false;
            cmp_KS_Items.Visible = false;
        }

        /// <summary>
        /// Imposta il bin sugli oggetti dipendenti
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="codeInt"></param>
        /// <param name="Description"></param>
        private void setBin(string rawData, int codeInt, string Description)
        {
            cmp_KS_BinCart.BinID = codeInt;
            cmp_KS_BinCart.BinDtmx = rawData;
            cmp_KS_BinCart.BinDesc = Description;
            cmp_KS_BinCart.doUpdate();
            fixVisibility();
        }

        /// <summary>
        /// Imposta il cart sugli oggetti dipendenti
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="codeInt"></param>
        /// <param name="Description"></param>
        private void setCart(string rawData, int codeInt, string Description)
        {
            cmp_KS_BinCart.CartID = codeInt;
            cmp_KS_BinCart.CartDtmx = rawData;
            cmp_KS_BinCart.CartDesc = Description;
            cmp_KS_BinCart.doUpdate();
            cmp_KS_OtherItemsCart.CartID = codeInt;
            cmp_KS_OtherItemsCart.CartDtmx = rawData;
            cmp_KS_OtherItemsCart.CartDesc = Description;
            cmp_KS_OtherItemsCart.doUpdate();
            cmp_KS_Cart.CartID = codeInt;
            cmp_KS_Cart.CartDtmx = rawData;
            cmp_KS_Cart.CartDesc = Description;
            cmp_KS_Cart.doUpdate();
            cmp_KS_Items.CartID = codeInt;
            cmp_KS_Items.CartDtmx = rawData;
            cmp_KS_Items.CartDesc = Description;
            cmp_KS_Items.doUpdate();
            fixVisibility();
        }

        /// <summary>
        /// Imposta il codice Item sugli oggetti dipendenti
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="codeInt"></param>
        private void setItem(string rawData, int codeInt)
        {
            itemIdSelected = codeInt;
            cmp_KS_Items.ItemID = codeInt;
            cmp_KS_Items.ItemDtmx = rawData;
            cmp_KS_Items.doUpdate();
            fixVisibility();
        }

        /// <summary>
        /// Imposta il codice OtherItem sugli oggetti dipendenti
        /// </summary>
        /// <param name="rawData"></param>
        /// <param name="codeInt"></param>
        /// <param name="Description"></param>
        private void setOtherItem(string rawData, int codeInt, string Description)
        {
            cmp_KS_OtherItemsCart.OtherItemID = codeInt;
            cmp_KS_OtherItemsCart.OtherItemDtmx = rawData;
            cmp_KS_OtherItemsCart.OtherItemDesc = Description;
            cmp_KS_OtherItemsCart.doUpdate();
            fixVisibility();
        }

        /// <summary>
        /// Mostra o nasconde dettaglio su ITEM letto
        /// </summary>
        /// <param name="showItem"></param>
        /// <param name="itemRow"></param>
        /// <param name="showError"></param>
        private void showItemDetail(bool showItem, DS_App.ItemListRow itemRow, bool showError)
        {
            resetShowData();
            divItemDet.Visible = showItem;
            divError.Visible = showError;
            if (showError)
            {
                displError("Item not found");
            }
            if (showItem)
            {
                lblItemCode.Text = itemRow.ItemExtCode;
                lblItemDesc.Text = itemRow.ItemDesc;
                lblItemDtmx.Text = itemRow.ItemDtmx;
                // cerco kit --> cart...
                string cartDtmx = "-";
                try
                {
                    var tabCart = DLMan.taCR.getByItemID(itemRow.ItemID);
                    if (tabCart != null && tabCart.Count > 0)
                    {
                        cartDtmx = tabCart[0].CartDtmx;
                    }
                }
                catch
                { }
                lblItemCartDtmx.Text = cartDtmx;
                setItem(itemRow.ItemDtmx, itemRow.ItemID);
                // CONTROLLO SIA in stato 1 --> worked, 2--> selected, 100--> parked...
                switch (itemRow.StatusID)
                {
                    case 0:
                        displError(traduci("ErrPartNotReady"));
                        break;

                    case 1:
                    case 2:
                    case 100:
                        doUpdate();
                        break;

                    case 3:
                        displError(traduci("ErrPartAlreadyOnCart"));
                        break;

                    case 4:
                        // fino a concorrenza qta richiesta sposto, POI do errori
                        displError(traduci("ErrAllPartAlreadyOnBin"));
                        break;

                    case 5:
                        displError(traduci("ErrPartAlreadyOnKit"));
                        break;

                    case 990:
                        displError(traduci("ErrPartSt990"));
                        break;

                    case 991:
                        displError(traduci("ErrPartSt991"));
                        break;

                    default:
                        displError(traduci("ErrPartStUnkn"));
                        break;
                }
            }
            lbtResetSel.Visible = (itemIdSelected != 0);
        }

        #endregion Private Methods

        #region Protected Methods

        /// <summary>
        /// Mostra ERROR ed effettua reset vari...
        /// </summary>
        /// <param name="errorMessage"></param>
        protected void displError(string errorMessage)
        {
            lblErrorMsg.Text = errorMessage;
            divError.Visible = true;
            divInfo.Visible = false;
            resetSelection();
        }

        /// <summary>
        /// Mostra INFO ed effettua reset vari...
        /// </summary>
        /// <param name="infoMessage"></param>
        protected void displInfo(string infoMessage)
        {
            lblSuccessMsg.Text = infoMessage;
            divError.Visible = false;
            divInfo.Visible = true;
            resetSelection();
        }

        protected void lbtCancel_Click(object sender, EventArgs e)
        {
            resetSelection();
            showItemDetail(false, null, false);
        }

        protected void lbtResetSel_Click(object sender, EventArgs e)
        {
            var tabSheet = DLMan.taSHL.getByItemID(itemIdSelected);
            if (tabSheet.Count == 1)
            {
                resetShowData();
                // resetto sheet selezionato...
                DLMan.taIL.updateSheetStatusPU(tabSheet[0].SheetID, PlaceCod);
                lgInfo($"cmp_kittingSmart | taIL.updateSheetStatusPU | SheetID: {tabSheet[0].SheetID} | PlaceCod: {PlaceCod}");
                resetSelection();
                showItemDetail(false, null, false);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                lastObject = "";
                resetShowData();
                resetIcons();
                updateCurrData();
            }
            cmp_barcode.eh_doRefresh += Cmp_barcode_eh_doRefresh;
            cmp_barcode.eh_doReset += Cmp_barcode_eh_doReset;
            cmp_KS_BinCart.eh_doRefresh += cmp_KS_BinCart_eh_doRefresh;
            cmp_KS_OtherItemsCart.eh_doRefresh += cmp_KS_OtherItemsCart_eh_doRefresh;
            cmp_KS_Items.eh_doRefresh += cmp_KS_Items_eh_doRefresh;
        }

        /// <summary>
        /// Reset selezione item + blocchi suggerimento + sel REDIS x pagina unload
        /// </summary>
        protected void resetSelection()
        {
            // elimino item sel...
            itemIdSelected = 0;
            resetShowData();
            bool fatto = ComLib.resetItemPickup(SheetID, DeviceId);
            lgInfo($"cmp_kittingSmart | ComLib.resetItemPickup | SheetID: {SheetID} | DeviceId: {DeviceId} | done: {fatto}");
        }

        /// <summary>
        /// Aggiorna dati correnti (IP, batch, sheet...)
        /// </summary>
        protected void updateCurrData()
        {
            // FORSE 5/5?!?
            DataLayer DLMan = new DataLayer();
            var sheetList = DLMan.taSHL.getByMLStatus(PackListID, 3, 5);
            if (sheetList.Count > 0)
            {
                SheetID = sheetList[0].SheetID;
            }
            DeviceId = ComLib.GetIPAddress().Replace(".", "0").Replace(":", "0");
        }

        #endregion Protected Methods
    }
}