using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text.RegularExpressions;
using AR;

namespace Project
{
    public partial class FMain
    {

        Tuple<int, List<string>> BarcodeRegExProcess(
            List<Class.RegexPattern> patterns,
            List<Class.RegexPattern> patternsEx,
            Class.VisionData vdata, string barcodeSymbol,
            string bcd, out bool IgnoreBarcode, out bool findregex)
        {
            //var patterns = PUB.Result.BCDPattern;
            IgnoreBarcode = false;
            findregex = false;

            //get : same symbol data
            List<Class.RegexPattern> pats;
            if (patterns != null)
            {
                if (barcodeSymbol.isEmpty() == false) pats = patterns.Where(t => t.IsEnable == true && (string.IsNullOrEmpty(t.Symbol) || t.Symbol == barcodeSymbol)).OrderBy(t => t.Seq).ToList();
                else pats = patterns.Where(t => t.IsEnable == true).OrderBy(t => t.Seq).ToList();
            }
            else pats = new List<Class.RegexPattern>();


            List<Class.RegexPattern> patsEx;
            if (patternsEx == null) patsEx = new List<Class.RegexPattern>();
            else
            {
                if (barcodeSymbol.isEmpty() == false) patsEx = patternsEx.Where(t => string.IsNullOrEmpty(t.Symbol) || t.Symbol == barcodeSymbol).OrderBy(t => t.Seq).ToList();
                else patsEx = patternsEx.Where(t => t.IsEnable == true).OrderBy(t => t.Seq).ToList();
            }



            //모델정보의  허용  심볼인지  확인한다  221017
            var vm = PUB.Result.vModel;
            if (vm != null)
            {
                if (vm.BCD_DM == false && barcodeSymbol == "2")
                {
                    PUB.log.AddAT($"Inactive in model(DM):{bcd}");
                    IgnoreBarcode = true;
                    return new Tuple<int, List<string>>(0, new List<string>());
                }
                else if (vm.BCD_1D == false && (barcodeSymbol == "6" || barcodeSymbol == "11"))
                {
                    PUB.log.AddAT($"Inactive in model(1D):{bcd}");
                    IgnoreBarcode = true;
                    return new Tuple<int, List<string>>(0, new List<string>());
                }
                else if (vm.BCD_QR == false && (barcodeSymbol == "1"))
                {
                    PUB.log.AddAT($"Inactive in model(QR):{bcd}");
                    IgnoreBarcode = true;
                    return new Tuple<int, List<string>>(0, new List<string>());
                }
            }

            //check barcode pattern
            if (pats.Any() == false)
            {
                PUB.log.AddAT($"No registered pattern(SYM={barcodeSymbol}) Model:{vm.Title}");
                return new Tuple<int, List<string>>(0, new List<string>());
            }

            //이 바코드가 무시바코드에 있는지 먼저 검사한다 220718
            foreach (var pt in patsEx)
            {
                //skip disable item
                if (pt.IsEnable == false) continue;

                //check regex
                var regx = new Regex(pt.Pattern, RegexOptions.IgnoreCase, new TimeSpan(0, 0, 10));
                if (regx.IsMatch(bcd))
                {
                    PUB.log.AddAT($"Ignore barcode:{bcd},PAT:{pt.Pattern},SYM:{pt.Symbol}");
                    IgnoreBarcode = true;
                    break;
                }
            }
            if (IgnoreBarcode)
            {
                return new Tuple<int, List<string>>(0, new List<string>());
            }


            //동작중에 들어오는 바코드의 자동처리코드 추가 250926
            if (PUB.sm.Step == eSMStep.RUN || PUB.sm.Step == eSMStep.PAUSE || PUB.sm.Step == eSMStep.WAITSTART)
            {

                var OPT_PrinterOff = VAR.BOOL[eVarBool.Opt_DisablePrinter];
                var OPT_CameraOff = PUB.OPT_CAMERA();
                var OPT_BYPASS = PUB.OPT_BYPASS();

                if (OPT_BYPASS == false)
                {
                    //기본 벤더이름
                    if (PUB.Result.vModel.Def_Vname.isEmpty() == false)
                    {
                        if (vdata.VNAME.Equals(PUB.Result.vModel.Def_Vname) == false)
                        {
                            vdata.VNAME = PUB.Result.vModel.Def_Vname;
                            vdata.VNAME_Trust = true;
                            PUB.log.Add($"Defaul V.Name Set to {PUB.Result.vModel.Def_Vname}");
                        }
                    }

                    //기본 MFG
                    if (PUB.Result.vModel.Def_MFG.isEmpty() == false)
                    {
                        if (vdata.MFGDATE.Equals(PUB.Result.vModel.Def_MFG) == false)
                        {
                            vdata.MFGDATE = PUB.Result.vModel.Def_MFG;
                            vdata.MFGDATE_Trust = true;
                            PUB.log.Add($"Defaul MFGDATE Set to {PUB.Result.vModel.Def_MFG}");
                        }
                    }

                    //파트넘버무시
                    if (PUB.Result.vModel.IgnorePartNo)
                    {
                        vdata.PARTNO_Trust = true;
                    }

                    //배치무시
                    if (PUB.Result.vModel.IgnoreBatch)
                    {

                    }

                    //프린트를 하지 않는 경우에는 프린트 위치를 자동으로 처리한다.
                    if (OPT_PrinterOff == true)
                    {
                        vdata.PrintPositionData = "0";
                        vdata.PrintPositionCheck = true;
                    }
                }
                else
                {
                    if (vdata.VNAME_Trust == false)
                    {
                        vdata.VNAME = "BYPASS";
                        vdata.VNAME_Trust = true;
                    }
                }
            }

            var ValueApplyCount = 0;
            ValueApplyCount = 0;
            List<string> list = new List<string>();
            findregex = false;
            foreach (var pt in pats)
            {
                //skip disable item
                if (pt.IsEnable == false) continue;

                var regx = new Regex(pt.Pattern, RegexOptions.IgnoreCase, new TimeSpan(0, 0, 10));
                if (regx.IsMatch(bcd))
                {
                    findregex = true;
                    //find data
                    var matchs = regx.Matches(bcd);
                    foreach (System.Text.RegularExpressions.Match mat in matchs)
                    {

                        if (vdata == null) ValueApplyCount += 1;
                        else
                        {
                            foreach (var matchdata in pt.Groups)
                            {
                                if (matchdata.GroupNo <= mat.Groups.Count)
                                {
                                    var data = mat.Groups[matchdata.GroupNo];
                                    if (PUB.SetBCDValue(vdata, matchdata.TargetPos, data.Value, pt.IsTrust))
                                        ValueApplyCount += 1;
                                }
                            }
                        }
                    }

                    if (vdata != null && pt.IsAmkStd)// && bcdObj.barcodeSymbol == "1")
                    {
                        vdata.QRInputRaw = bcd;
                    }

                    if (vdata != null)
                        PUB.log.AddI($"[{pt.Description}]=>{bcd}");

                    list.Add(pt.Customer + "|" + pt.Description);
                }
                else
                {
                    //PUB.log.AddAT($"(X)Match ({pt.Pattern}) Data={bcd}");
                }
            }
            return new Tuple<int, List<string>>(ValueApplyCount, list);
        }

        /// <summary>
        /// barcod eprocess
        /// </summary>
        void BarcodeProcess()
        {
            //coffee
            //get regexpress patterns
            var patterns = PUB.Result.BCDPattern;
            var itemC = PUB.Result.ItemDataC;
            var vdata = itemC.VisionData;

            //No Run - Confirm Data
            if (vdata.Confirm) return;
            var vm = PUB.Result.vModel;

            lock (vdata.barcodelist)
            {
                foreach (var item in vdata.barcodelist)
                {
                    //var src = item.Value.barcodeSource;
                    var bcd = item.Value.Data;
                    var bcdObj = item.Value;

                    //already checked
                    if (bcdObj.RegExConfirm) continue;

                    var ValueApplyCount = BarcodeRegExProcess(PUB.Result.BCDPattern, PUB.Result.BCDIgnorePattern, vdata, bcdObj.barcodeSymbol, bcd, out bool IgnoreBcd, out bool findregex);
                    bcdObj.Ignore = IgnoreBcd;

                    //기타바코드 무시기능 적용 221018
                    if (vm != null && vm.IgnoreOtherBarcode == true && findregex == false)
                        bcdObj.Ignore = true;

                    bcdObj.RefExApply = (ValueApplyCount?.Item1 ?? 0) > 0;
                    bcdObj.RegExConfirm = true;
                }
            }

            //assign customer code - fixed data
            if (vdata.CUSTCODE.isEmpty() && VAR.STR[eVarString.JOB_CUSTOMER_CODE].isEmpty() == false)
            {
                vdata.CUSTCODE = VAR.STR[eVarString.JOB_CUSTOMER_CODE];
                PUB.log.Add($"Cutomer Code 고정값 사용 : {vdata.CUSTCODE}");
            }

            //SiD CONVERT
            if (VAR.BOOL[eVarBool.Opt_SIDConvert])
            {
                if (PUB.flag.get(eVarBool.FG_WAIT_LOADERINFO) == false && VAR.BOOL[eVarBool.JOB_Empty_SIDConvertInfo] == false)
                {
                    //원본시드(sid0)가 비어있는데 sid과 확정되었다면 변환작업을 진행한다
                    if (vdata.SID0.isEmpty() && vdata.SID.isEmpty() == false && vdata.SID_Trust)
                    {
                        //이 sid가 존재여부확인 후 없는 sid라면 더이상 처리하지 않는다 230510
                        if (PUB.Result.DTSidConvertEmptyList.Contains(vdata.SID))
                        {
                            //존재하지 않는 SID로 이미 확인되었다
                        }
                        else if (PUB.Result.DTSidConvertMultiList.Contains(vdata.SID))
                        {
                            //다중sid로 인해 처리하지 않는다
                        }
                        else
                        {
                            var newsid = PUB.SIDCovert(vdata.SID, "SPS_BarcodeProcess", out bool converr);
                            if (converr)
                            {
                                if (PUB.sm.Step == eSMStep.RUN)
                                    PUB.log.AddE(newsid);
                            }
                            else
                            {
                                vdata.SID0 = vdata.SID;
                                vdata.SID = newsid;
                            }
                        }

                    }
                }
            }

            //정규식혹은 바코드 룰에 의해 데이터가 바뀌었더라도 모델 기준으로 진행한다
            if (PUB.Result.vModel.Def_Vname.isEmpty() == false)
            {
                if (itemC.VisionData.VNAME.Equals(PUB.Result.vModel.Def_Vname) == false)
                {
                    itemC.VisionData.VNAME = PUB.Result.vModel.Def_Vname.Trim();
                    itemC.VisionData.VNAME_Trust = true;
                    PUB.log.Add($"Defaul V.Name Set to {PUB.Result.vModel.Def_Vname}");
                }
            }
            if (PUB.Result.vModel.Def_MFG.isEmpty() == false)
            {
                if (itemC.VisionData.MFGDATE.Equals(PUB.Result.vModel.Def_MFG) == false)
                {
                    itemC.VisionData.MFGDATE = PUB.Result.vModel.Def_MFG.Trim();
                    itemC.VisionData.MFGDATE_Trust = true;
                    PUB.log.Add($"Defaul MFGDATE Set to {PUB.Result.vModel.Def_MFG}");
                }
            }

            //릴ID 신규발행
            if (PUB.sm.Step == eSMStep.RUN && vdata.CUSTCODE.isEmpty() == false)
            {
                if (VAR.BOOL[eVarBool.Opt_NewReelID])
                {
                    if (itemC.VisionData.RIDNew == false)
                    {
                        var newid = PUB.MakeNewREELID(itemC.VisionData.SID);// Amkor.RestfulService.Allocation_Unique_ReelID_AmkorSTD(itemC.VisionData.CUSTCODE, "4", "A", out string errmsg);
                        if (newid.success == true)
                        {
                            //backup origin reel id
                            itemC.VisionData.RID0 = itemC.VisionData.RID;

                            //set new reel id
                            PUB.log.Add("new reelid bacodeprecess");
                            itemC.VisionData.SetRID(newid.newid, "SPS:CHKDATACOMPLETE");// = newid;
                            itemC.VisionData.RIDNew = true; //applied new reel id

                            //서버의수량업데이트기능이 켜져있다면 해당 값을 제거해준다. (다시 조회되도록 함)
                            if (VAR.BOOL[eVarBool.Opt_ServerQty])
                            {
                                //이미 수량업데이트된 경우이므로 복원시켜준다
                                if (itemC.VisionData.QTY0.isEmpty() == false)
                                {
                                    PUB.log.AddAT($"릴아이디 변경으로 인해 수량을 복원합니다({itemC.VisionData.QTY}->{itemC.VisionData.QTY0})");
                                    itemC.VisionData.QTY = itemC.VisionData.QTY0;
                                    itemC.VisionData.QTY0 = string.Empty;
                                }
                            }
                        }
                        else
                        {
                            var logtime = VAR.TIME.RUN((int)eVarTime.LOG_NEWIDERROR);
                            if (logtime.TotalSeconds >= 3000)
                            {
                                PUB.log.AddAT($"Reel_ID 생성실패 : {newid.message}");
                                VAR.TIME.Update(eVarTime.LOG_NEWIDERROR);
                            }
                        }
                    }
                }
            }


            //바코드가 변경된 경우이다, 자동채우기 기능이 있다면 사용한다
            bool NewBarcodeUpdated = false;
            //[WMS] SID정보테이블에서 정보 추출(프린트정보는 없음)
            //[WMS] 에서 중복검색되면 팝업을 해야하므로 이것을 먼저 처리한다.
            if (VAR.BOOL[eVarBool.Opt_ApplySIDInfo] && vdata.BarcodeTouched == true)
            {
                Boolean Apply = true;

                //select columns
                List<string> fields = new List<string>();
                if (VAR.BOOL[eVarBool.Opt_SID_Apply_CustCode] && vdata.CUSTCODE.isEmpty()) fields.Add("CUST_CODE");
                if (VAR.BOOL[eVarBool.Opt_SID_Apply_PartNo] && (vdata.PARTNO.isEmpty() || vdata.PARTNO_Trust == false)) fields.Add("PART_NO");
                if (VAR.BOOL[eVarBool.Opt_SID_Apply_VenderName] && (vdata.VNAME_Trust == false || vdata.VNAME.isEmpty())) fields.Add("VENDOR_NM");
                if (VAR.BOOL[eVarBool.Opt_SID_Apply_SID] && (vdata.SID_Trust == false || vdata.SID.isEmpty())) fields.Add("SID");
                if (VAR.BOOL[eVarBool.Opt_SID_Apply_batch] && (vdata.SID_Trust == false || vdata.BATCH.isEmpty())) fields.Add("BATCH_NO"); //220921

                //where coluns
                List<string> wheres = new List<string>();
                if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_CustCode])
                {
                    if (vdata.CUSTCODE.isEmpty() == false) wheres.Add($"CUST_CODE='{vdata.CUSTCODE.PadLeft(10,'0')}'");
                    else Apply = false;
                }
                if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_PartNo])
                {
                    if (vdata.PARTNO_Trust && vdata.PARTNO.isEmpty() == false) wheres.Add($"PART_NO='{vdata.PARTNO}'");
                    else Apply = false;
                }
                if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_SID])
                {
                    if (VAR.BOOL[eVarBool.Opt_SIDConvert]) //if sid convert logic
                    {
                        if (vdata.SID_Trust && vdata.SID0.isEmpty() == false && vdata.SID.isEmpty() == false) wheres.Add($"SID='{vdata.SID}'");
                        else Apply = false;
                    }
                    else
                    {
                        if (vdata.SID_Trust && vdata.SID.isEmpty() == false) wheres.Add($"SID='{vdata.SID}'");
                        else Apply = false;
                    }
                }
                if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_VLOT])  //221013
                {
                    if (vdata.VLOT_Trust && vdata.VLOT.isEmpty() == false) wheres.Add($"VENDER_LOT = '{vdata.VLOT}'");
                    else Apply = false;
                }

                //if query data . no error
                if (Apply && fields.Count > 0 && wheres.Count > 0)
                {
                    var mcname = VAR.BOOL[eVarBool.Use_Conveyor] ? PUB.MCCode : SETTING.Data.McName;

                    var TableName = "VW_GET_MAX_QTY_VENDOR_LOT";
                    var whereState = " where " + string.Join(" and ", wheres);
                    var selectFields = string.Join(",", fields);

                    var SQL = $"select top 1 {selectFields} from {TableName} WITH(NOLOCK) {whereState}";
                    var SQLC = $"select count(*)  from {TableName} WITH(NOLOCK) {whereState}";

                    //정보가 여러개 존재하면 선택화면으로 처리해야한다
                    //var cntvalue = (DBHelper.ExecuteScalar(SQLC)?.ToString() ?? "0").toInt();
                    //if (cntvalue > 1)
                    //{
                    //    VAR.STR[eVarString.MULTISID_QUERY] = $"select {selectFields} from {TableName} WITH(NOLOCK) {whereState}";
                    //    VAR.STR[eVarString.MULTISID_FIELDS] = selectFields;
                    //    return EResultKeyence.MultiSID;
                    //}

                    //if (PUB.Result.ItemDataC.VisionData.LastQueryStringWMS.Equals(SQL) == false) //같은 쿼리는 처리하지 않는다
                    //{
                    //    if (PUB.GetSIDInfo_And_SetData(fields, ref vdata, SQL, SQLC))
                    //        NewBarcodeUpdated = true;

                    //    PUB.Result.ItemDataC.VisionData.LastQueryStringWMS = SQL;
                    //}

                }
            }

            //SID정보테이블에서 정보 추출
            if (VAR.BOOL[eVarBool.Opt_ApplySIDInfo] && vdata.BarcodeTouched == true)
            {
                Boolean Apply = true;

                //select columns
                List<string> fields = new List<string>();
                if (VAR.BOOL[eVarBool.Opt_SID_Apply_CustCode] && vdata.CUSTCODE.isEmpty()) fields.Add("CustCode");
                if (VAR.BOOL[eVarBool.Opt_SID_Apply_PartNo] && (vdata.PARTNO.isEmpty() || vdata.PARTNO_Trust == false)) fields.Add("PartNo");
                if (VAR.BOOL[eVarBool.Opt_SID_Apply_PrintPos] && vdata.PrintPositionData.isEmpty()) fields.Add("PrintPosition");
                if (VAR.BOOL[eVarBool.Opt_SID_Apply_VenderName] && (vdata.VNAME_Trust == false || vdata.VNAME.isEmpty())) fields.Add("VenderName");
                if (VAR.BOOL[eVarBool.Opt_SID_Apply_SID] && (vdata.SID_Trust == false || vdata.SID.isEmpty())) fields.Add("SID");
                if (VAR.BOOL[eVarBool.Opt_SID_Apply_batch] && (vdata.SID_Trust == false || vdata.BATCH.isEmpty())) fields.Add("batch"); //220921
                if (VAR.BOOL[eVarBool.Opt_SID_Apply_qty] && (vdata.SID_Trust == false || vdata.QTYMAX.isEmpty())) fields.Add("qtymax"); //220921
                fields.Add("attach"); //231026

                //where coluns
                List<string> wheres = new List<string>();
                //wheres.Add($"MC='{COMM.SETTING.Data.McName}");
                if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_CustCode])
                {
                    if (vdata.CUSTCODE.isEmpty() == false) wheres.Add($"CustCode='{vdata.CUSTCODE.PadLeft(10, '0')}'");
                    else Apply = false;
                }
                if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_PartNo])
                {
                    if (vdata.PARTNO_Trust && vdata.PARTNO.isEmpty() == false) wheres.Add($"PartNo='{vdata.PARTNO}'");
                    else Apply = false;
                }
                if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_SID])
                {
                    if (VAR.BOOL[eVarBool.Opt_SIDConvert]) //if sid convert logic
                    {
                        if (vdata.SID_Trust && vdata.SID0.isEmpty() == false && vdata.SID.isEmpty() == false)
                            wheres.Add($"SID='{vdata.SID}'");
                        else Apply = false;
                    }
                    else
                    {
                        if (vdata.SID_Trust && vdata.SID.isEmpty() == false) wheres.Add($"SID='{vdata.SID}'");
                        else Apply = false;
                    }
                }
                if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_VLOT])  //221013
                {
                    if (vdata.VLOT_Trust && vdata.VLOT.isEmpty() == false)
                        wheres.Add($"(VenderLot like '{vdata.VLOT}' or VenderLot like '%,{vdata.VLOT}' or VenderLot like '{vdata.VLOT},%' or VenderLot like '%,{vdata.VLOT},%')");
                    else Apply = false;
                }

                if (Apply && VAR.BOOL[eVarBool.Opt_SID_Where_MC])  //231006
                {
                    if (AR.SETTING.Data.McName.isEmpty() == false)
                        wheres.Add($"attach='{AR.SETTING.Data.McName}'");
                    else Apply = false;
                }

                //if query data . no error
                if (Apply && fields.Count > 0 && wheres.Count > 0)
                {

                    var mcname = SETTING.Data.McName;
                    if (VAR.BOOL[eVarBool.Use_Conveyor]) mcname = PUB.MCCode;

                    var SQL = "select top 1 " + string.Join(",", fields) +
                        " from K4EE_Component_Reel_SID_Information WITH(NOLOCK)" +
                        " where mc='" + mcname + "' and " + string.Join(" and ", wheres) +
                        " order by wdate desc";

                    var SQLC = "select count(*)" +
                  " from K4EE_Component_Reel_SID_Information WITH(NOLOCK)" +
                  " where mc='" + mcname + "' and " + string.Join(" and ", wheres);

                    if (PUB.Result.ItemDataC.VisionData.LastQueryStringSID.Equals(SQL) == false)
                    {
                        if (PUB.GetSIDInfo_And_SetData(fields, ref vdata, SQL, SQLC) == true)
                            NewBarcodeUpdated = true;

                        PUB.Result.ItemDataC.VisionData.LastQueryStringSID = SQL;
                    }
                }
            }

            //시드변환정보에서 정보 추출
            if (VAR.BOOL[eVarBool.Opt_ApplySIDConv] && vdata.BarcodeTouched == true)
            {
                Boolean Apply = true;

                //select columns
                List<string> fields = new List<string>();
                if (VAR.BOOL[eVarBool.Opt_Conv_Apply_CustCode] && vdata.CUSTCODE.isEmpty()) fields.Add("CustCode");
                if (VAR.BOOL[eVarBool.Opt_Conv_Apply_PartNo] && (vdata.PARTNO.isEmpty() || vdata.PARTNO_Trust == false)) fields.Add("PartNo");
                if (VAR.BOOL[eVarBool.Opt_Conv_Apply_PrintPos] && vdata.PrintPositionData.isEmpty()) fields.Add("PrintPosition");
                if (VAR.BOOL[eVarBool.Opt_Conv_Apply_VenderName] && (vdata.VNAME_Trust == false || vdata.VNAME.isEmpty())) fields.Add("VenderName");
                if (VAR.BOOL[eVarBool.Opt_Conv_Apply_SID] && (vdata.SID_Trust == false || vdata.SID.isEmpty())) fields.Add("SID");
                if (VAR.BOOL[eVarBool.Opt_Conv_Apply_Batch] && (vdata.SID_Trust == false || vdata.BATCH.isEmpty())) fields.Add("batch"); //220921
                if (VAR.BOOL[eVarBool.Opt_Conv_Apply_QtyMax] && (vdata.SID_Trust == false || vdata.QTYMAX.isEmpty())) fields.Add("qtymax"); //220921


                //where coluns
                List<string> wheres = new List<string>();
                //wheres.Add($"MC='{COMM.SETTING.Data.McName}");
                if (Apply && VAR.BOOL[eVarBool.Opt_Conv_Where_CustCode])
                {
                    if (vdata.CUSTCODE.isEmpty() == false) wheres.Add($"CustCode='{vdata.CUSTCODE.PadLeft(10, '0')}'");
                    else Apply = false;
                }
                if (Apply && VAR.BOOL[eVarBool.Opt_Conv_Where_PartNo])
                {
                    if (vdata.PARTNO_Trust && vdata.PARTNO.isEmpty() == false) wheres.Add($"PartNo='{vdata.PARTNO}'");
                    else Apply = false;
                }
                if (Apply && VAR.BOOL[eVarBool.Opt_Conv_Where_SID])
                {
                    if (VAR.BOOL[eVarBool.Opt_SIDConvert]) //if sid convert logic
                    {
                        if (vdata.SID_Trust && vdata.SID0.isEmpty() == false && vdata.SID.isEmpty() == false)
                            wheres.Add($"SIDTo='{vdata.SID}'");
                        else Apply = false;
                    }
                    else
                    {
                        if (vdata.SID_Trust && vdata.SID.isEmpty() == false) wheres.Add($"SIDTo='{vdata.SID}'");
                        else Apply = false;
                    }
                }
                if (VAR.BOOL[eVarBool.Opt_Conv_Where_VLOT])  //221013
                {
                    if (vdata.VLOT_Trust && vdata.VLOT.isEmpty() == false)
                        wheres.Add($"(VenderLot like '{vdata.VLOT}' or VenderLot like '%,{vdata.VLOT}' or VenderLot like '{vdata.VLOT},%' or VenderLot like '%,{vdata.VLOT},%')");
                    else Apply = false;
                }


                //if query data . no error
                if (Apply && fields.Count > 0 && wheres.Count > 0)
                {

                    var mcname = SETTING.Data.McName;
                    if (VAR.BOOL[eVarBool.Use_Conveyor]) mcname = PUB.MCCode;

                    var SQL = "select top 1 " + string.Join(",", fields) +
                        " from K4EE_Component_Reel_SID_Convert WITH(NOLOCK)" +
                        " where " + string.Join(" and ", wheres) +
                        " order by wdate desc";

                    var SQLC = "select count(*)" +
                  " from K4EE_Component_Reel_SID_Convert WITH(NOLOCK)" +
                  " where " + string.Join(" and ", wheres);

                    if (PUB.Result.ItemDataC.VisionData.LastQueryStringCNV.Equals(SQL) == false)
                    {
                        if (PUB.GetSIDInfo_And_SetData(fields, ref vdata, SQL, SQLC) == true)
                            NewBarcodeUpdated = true;

                        PUB.Result.ItemDataC.VisionData.LastQueryStringCNV = SQL;
                    }
                }
            }

            //기존 작업에서 데이터를 찾아서 쓴다
            if (VAR.BOOL[eVarBool.Opt_ApplyJobInfo] && vdata.BarcodeTouched == true)
            {
                Boolean Apply = true;

                //select columns
                List<string> fields = new List<string>();

                if (VAR.BOOL[eVarBool.Opt_Job_Apply_CustCode] && vdata.CUSTCODE.isEmpty()) fields.Add("CUSTCODE");
                if (VAR.BOOL[eVarBool.Opt_Job_Apply_PartNo] && (vdata.PARTNO.isEmpty() || vdata.PARTNO_Trust == false)) fields.Add("PARTNO");
                if (VAR.BOOL[eVarBool.Opt_Job_Apply_PrintPos] && vdata.PrintPositionData.isEmpty()) fields.Add("POS");
                if (VAR.BOOL[eVarBool.Opt_Job_Apply_VenderName] && (vdata.VNAME_Trust == false || vdata.VNAME.isEmpty())) fields.Add("VNAME");
                if (VAR.BOOL[eVarBool.Opt_Job_Apply_SID] && (vdata.SID_Trust == false || vdata.SID.isEmpty())) fields.Add("SID");

                //where coluns
                List<string> wheres = new List<string>();
                if (VAR.BOOL[eVarBool.Opt_Job_Where_CustCode])
                {
                    if (vdata.CUSTCODE.isEmpty() == false) wheres.Add($"CUSTCODE='{vdata.CUSTCODE.PadLeft(10, '0')}'");
                    else Apply = false;
                }
                if (VAR.BOOL[eVarBool.Opt_Job_Where_PartNo])
                {
                    if (vdata.PARTNO_Trust && vdata.PARTNO.isEmpty() == false) wheres.Add($"PARTNO='{vdata.PARTNO}'");
                    else Apply = false;
                }
                if (VAR.BOOL[eVarBool.Opt_Job_Where_SID])
                {
                    if (vdata.SID_Trust && vdata.SID.isEmpty() == false) wheres.Add($"SID='{vdata.SID}'");
                    else Apply = false;
                }
                if (VAR.BOOL[eVarBool.Opt_Job_Where_VLOT])
                {
                    if (vdata.VLOT_Trust && vdata.VLOT.isEmpty() == false) wheres.Add($"VenderLot='{vdata.VLOT}'");
                    else Apply = false;
                }

                //if query data . no error
                if (Apply && fields.Count > 0 && wheres.Count > 0)
                {
                    PUB.log.Add($"DATABAES : RESULT QUERY");

                    var SQL = "select top 1 " + string.Join(",", fields) +
                        " from K4EE_Component_Reel_Result WITH(NOLOCK) " +
                        $" where mc = '{AR.SETTING.Data.McName}'" +
                        $" and  prnattach = 1 and  stime >= '{DateTime.Now.AddHours(-3).ToString("yyyy-MM-dd HH:mm:ss")}'" +
                        $" and " + string.Join(" and ", wheres) +
                        $" order by wdate desc";

                    if (PUB.Result.ItemDataC.VisionData.LastQueryStringJOB.Equals(SQL) == false)
                    {
                        if (PUB.GetSIDInfo_And_SetData(fields, ref vdata, SQL, ""))
                            NewBarcodeUpdated = true;

                        PUB.Result.ItemDataC.VisionData.LastQueryStringJOB = SQL;
                    }
                }
            }


            if (PUB.sm.Step == eSMStep.RUN)
            {
                bool BatchValueOK = false;
                if (PUB.Result.vModel.IgnoreBatch) BatchValueOK = true;
                else BatchValueOK = itemC.VisionData.BATCH.isEmpty() == false;

                bool partnoValueOK = false;
                if (PUB.Result.vModel.IgnorePartNo) partnoValueOK = true;
                else partnoValueOK = itemC.VisionData.PARTNO.isEmpty() == false;

                var CVMode = VAR.BOOL[eVarBool.Use_Conveyor];
                if (itemC.VisionData.VNAME.isEmpty() == false &&
                itemC.VisionData.VLOT.isEmpty() == false &&
                itemC.VisionData.SID.Length == 9 &&
                itemC.VisionData.MFGDATE.isEmpty() == false &&
                partnoValueOK &&
                BatchValueOK &&
                itemC.VisionData.RID.isEmpty() == false)
                {
                    //모든값이 입력되어 있다면 조건 체크후 진행할 수 있도록 한다
                    CheckDataComplte(itemC, "SPS-BARCODEPROCESS", false); //2206211400
                }
                //CheckDataComplte(PUB.Result.ItemDataC, "SPS-BARCODEPROCESS");
            }

            //바코드 처리 여부 변경
            if (vdata.BarcodeTouched == true && NewBarcodeUpdated == false)
            {
                vdata.BarcodeTouched = false;
                var a = PUB.Result.ItemDataC.VisionData.BarcodeTouched;
            }


        }
    }
}