Imports System.IO
Imports System.IO.Ports
Imports System.Management
Imports System.Reflection.Emit
Imports System.Text
Imports Mysqlx.XDevAPI.Relational
Imports Newtonsoft.Json.Linq

Public Class mainForm
    Public projectName As String = "OrderPackingProcessor Ver."
    Public projectVer As String = "3.0.9"

    Private apiItemOutURL As String = "item-outflows/page"

    Private Enum scanList
        itemcode
        prodcode
        faceshot
        eyeshot
        maxscan
    End Enum

    Public Enum codeStateList
        ERP
        MES
    End Enum
    Public codeState(codeStateList.MES) As String

    Public Enum itemCode
        code
        name
        count
        face
        eye
        chkCount
        serialNum
        type
        pkCode
        prodCode
        id
    End Enum
    Private itemCommand(itemCode.count) As String

    Private Enum directData
        code
        name
        count
        id
    End Enum

    Private Enum parsingCode
        data
        row
        id
        itemcount
        regDate
        accuount
        code   '' resultcode 등등 code 명령어 전부
        name   '' name 명령어 전부
        orderDetail
        orderSheet
        ordererCode
        ordererName
        phone
        zip
        address
        refer
        item
        state
    End Enum
    Private apiCommand(parsingCode.state) As String

    Private Enum txbNameList
        name
        nowCount
        targetCount
    End Enum
    Private txbNameSelect(txbNameList.targetCount) As String

    Private Enum typeList
        prodSet
        prodFace
        prodEye
        prodBody
    End Enum

    Private Enum setInfoList
        topSerial
        midSerial
        botSerial
        topshot
        midshot
        botshot
        model
        abroad
        agency
        modelNum
        typeNum
        prodCode
    End Enum
    Private setInfo(setInfoList.prodCode) As String

    Private Enum optionCkbList
        weight
        barcode
        printer
        api
    End Enum
    Private optionCkb(optionCkbList.api) As CheckBox

    Private Enum optionTxbList
        comCode
        erpCode
        mesCode
        weightPlus
        weightMinus
        autoCount
    End Enum
    Private optionTxb(optionTxbList.autoCount) As TextBox

    Private Enum printTxbList
        name
        label
        barcode
        text
        labro
        lazeb
    End Enum
    Private optionprint(printTxbList.lazeb) As TextBox

    Private Enum apiDataList
        regData
        accountCode
        accountName
        ordererCode
        ordererName
        phone
        zip
        refer
        address
    End Enum
    Private apiData(apiDataList.address) As String
    Private orderCode As String
    Public invoiceCode As String

    Private Const saveCountName As String = "PackingCount"
    Private Const saveLogNameOrder As String = "LogDataOrder"
    Private Const saveLogNamePack As String = "LogDataPack"

    Private Const packKey As String = "pack"

    ''데이터베이스 관련
    Private DBCmd As String

    ''스캔 바코드 문자 길이
    Private Const oldProdCodeLength As Int16 = 12   '12자리 제품시리얼번호
    Private Const newProdCodeLength As Int16 = 16   '16자리 제품시리얼번호
    Private Const lowProdCodeLength As Int16 = 13   '보급형모델 88코드
    Private Const comCodeLength As Int16 = 8
    Private Const stateLength As Int16 = 14
    Private Const serialCount As Int16 = 3

    ''api 제품 검색 관련(변경요망)
    Private apiSearch As String = "createdAtFrom"
    Public prodArray(,) As String
    Private apiArray(,) As String
    Private donePkList As New List(Of Integer) ''포장 끝난 itemCode 인덱스

    ''DB 제품 검색 관련
    Private ScanArray(,) As String
    Private scanCode() As String

    Private setFace As String = "0"
    Private setEye As String = "0"

    ''리스트 텍스트박스 위치
    Const prodInfoStartCol As Int16 = 5
    Const prodInfoHeight As Int16 = 50
    Const locplus As Int16 = 10

    ''Config 저장 관련
    Private Enum saveList
        ckbData
        comport
        divideCode
        print
        lastCount
        maxSave
    End Enum
    Private saveCommand(saveList.maxSave) As String

    ''옵션 화면 관련
    Private textChange As Boolean = False  '' 설정 텍스트 박스 변경 여부
    Private ckbChange As Boolean = False  '' 체크박스 변경 여부
    Private printChange As Boolean = False '' 프린터 설정 변경 여부


    ''패킹 저장 물품 관련
    Private eventArray(,) As String
    Private autoUse As Integer

    Private orderSwitch As Boolean = False
    Private workSuccess As Boolean = False '' 작업 성공 여부(초기화 작업)
    Private programRunSwitch As Boolean = False

    Private prodInfoWidth(txbNameList.targetCount), prodInfoRow(txbNameList.targetCount) As Int16
    Private txbArrayList(,) As TextBox

    Public uuidCode As String   ''UUID 코드 저장 (아직 어디다 써야할 지 모르겠음.)
    Private playCode As String   '' 스캔 바코드(포장 진행 시)

    Private typeNum As String
    Private modelNum As String
    Private TDUseCompare As Boolean
    Private LdmUseCompare As Boolean

    Private mesDate As DateTime

    Public weightSum As Integer
    Public weightResult As Integer
    Public weightOkNg As Boolean = False

    Private modeSwitch As Boolean = True '' false : 전표 모드 / true : 패킹 모드

    Public InputCnt As Long
    Public InputCntVal As Integer = 15

    Private countReset As Boolean = False
    Private autoCountReady As Boolean = True
    Private autoSuccess As Boolean = False
    Private autoCount As Int32 = 0

    Private printSerial() As String

    Private Enum defaultList
        regDate
        accCode
        accName
        chrCode
        warehouse
        ordCode
        ordName
        country
        recName
        phone
        zip
        address
        refer
    End Enum
    Private defaultData(defaultList.refer) As String

    ''보급형 88코드
    Private lowProdList As New HashSet(Of String) ''value: 88_Code

    '' 세트코드
    Private setCodeUse As Boolean = False  ''세트 코드 번호를 사용했냐 안했냐 구분
    Private Const setCodeSort As String = "PK"

    ''중량선별기
    Public weightStart As Boolean = False
    Private autoWeight As Integer

    Private Sub SetInputCnt()
        InputCnt = InputCntVal
        barTimer.Enabled = True
    End Sub

    Private Sub barTimer_Tick(sender As Object, e As EventArgs) Handles barTimer.Tick
        If InputCnt Then
            InputCnt -= 1
        Else
            barTimer.Enabled = False

            If chbUseBarcode.Checked Then
                btnOK_Click(sender, e)
            Else
                txbProdSN.Focus()
                txbProdSN.Refresh()
            End If
        End If
    End Sub

    Private Sub txbProdSN_TextChanged(sender As Object, e As EventArgs) Handles txbProdSN.TextChanged
        Dim tmpStr As String

        If InputCnt = 0 And chbUseBarcode.Checked = True Then
            tmpStr = txbProdSN.Text
            If (Len(tmpStr) > 1) Then
                tmpStr = Mid(tmpStr, Len(tmpStr), 1)
                txbProdSN.Clear()
                txbProdSN.AppendText(tmpStr)
            End If
            SetInputCnt()
        End If
    End Sub

    Private Sub mainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        StartFormSet()
        varDataSetting()
        dgvRefresh()
        fullLoad(sender, e)
        loadLowProdBarcode()
        If rdbMode2.Checked = True Then
            loadConfig(saveList.lastCount)
        End If

        countView()
        eventRelease()

        txbProdSN.Focus()
    End Sub

    Private Sub StartFormSet()
        Me.Text = projectName & projectVer
        pnOption.Visible = False
        Me.Size = New Size(1920, 1080)
        'Me.WindowState = FormWindowState.Maximized
    End Sub
    Private Sub loadLowProdBarcode() '' 보급형 88 코드 가지고 오기
        Dim cmd = "SELECT 88_Code FROM " & applyPlistDB & " WHERE 88_Code IS NOT NULL"
        If DBQueryReader(cmd) Then
            For i = 0 To sqlDataQuery.Length - 1
                lowProdList.Add(sqlDataQuery(i))
            Next
        End If
    End Sub
    Private Sub countView()
        If loadLocalFile() Then
            countOut()
        End If
    End Sub

    Private Function loadLocalFile() As Boolean
        Try
            Dim filePath, fileName, strData As String
            Dim saveYear As String = DateAndTime.Year(Now)
            Dim saveMonth As String = Format(Now, "MM")
            Dim saveDay As String = Format(Now, "dd")
            Dim saveDate As String = saveYear & "-" & saveMonth & "-" & saveDay

            filePath = System.AppDomain.CurrentDomain.BaseDirectory & "\" & saveCountName
            dirUse(filePath)
            fileName = filePath & "\" & saveYear & "_" & saveMonth & ".csv"

            If File.Exists(fileName) Then
                strData = File.ReadAllText(fileName)

                If UBound(Split(strData, saveDate)) > 0 Then
                    strData = Mid(strData, InStr(strData, saveDate), InStr(strData, vbCrLf) - 1)
                    viewCountSet(strData)
                End If

            End If

            Return True
        Catch ex As Exception
            errorOut("로드오류")
            errorGen("Local 수량을 불러오는데 오류가 발생하였습니다." & ex.Message)
            Return False
        End Try

    End Function

    Private Sub viewCountSet(textCount As String)
        textCount = Mid(textCount, InStr(textCount, ",") + 1, textCount.Length)

        If UBound(Split(textCount, ",")) = (item_product_max_index + item_component_max_index + 1) Then
            For i = 0 To item_product_max_index
                If UBound(Split(textCount, ",")) > 0 Then
                    product_packing_cnt_list(i).com_count = Mid(textCount, 1, InStr(textCount, ",") - 1)
                    textCount = Mid(textCount, InStr(textCount, ",") + 1, textCount.Length)
                Else
                    product_packing_cnt_list(i).com_count = Mid(textCount, 1, textCount.Length)
                End If
            Next

            For i = 0 To item_component_max_index
                If UBound(Split(textCount, ",")) > 0 Then
                    component_packing_cnt_list(i).com_count = Mid(textCount, 1, InStr(textCount, ",") - 1)
                    textCount = Mid(textCount, InStr(textCount, ",") + 1, textCount.Length)
                Else
                    component_packing_cnt_list(i).com_count = Mid(textCount, 1, textCount.Length)
                End If
            Next
        Else
            errorOut("로드오류")
            errorGen("카운트 양식이 맞지 않습니다.")
        End If
    End Sub

    Private Sub eventRelease()
        Dim selectEvent(0) As String
        Dim selectCount As Int16 = 0
        Dim eventName As String
        Dim dupSwitch As Boolean = False

        cboPacking.Items.Clear()

        If dgvEvent.Rows.Count > 1 Then
            For i = 0 To dgvEvent.Rows.Count - 2

                dupSwitch = False
                eventName = dgvEvent.Rows(i).Cells(1).Value.ToString

                If i = 0 Then
                    ReDim selectEvent(selectCount)
                    selectEvent(selectCount) = eventName
                    selectCount += 1
                Else
                    For dup = 0 To selectEvent.Length - 1
                        If selectEvent(dup) = eventName Then
                            dupSwitch = True
                            Exit For
                        End If
                    Next
                End If

                If dupSwitch = False Then
                    ReDim Preserve selectEvent(selectCount)
                    selectEvent(selectCount) = eventName
                    cboPacking.Items.Add(eventName)

                    selectCount += 1
                End If
            Next

        ElseIf dgvEvent.Rows.Count = 1 Then
            cboPacking.Text = "없음"

        Else
            errorOut("데이터오류")
            errorGen("저장된 패킹 리스트를 불러오는데 오류가 발생하였습니다.")
            If pnMain.Visible = True Then
                btnOption.PerformClick()
            End If
        End If

        cboPacking.SelectedIndex = -1
        cboPacking.Text = "선택!"
    End Sub

    Private Sub cboPacking_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboPacking.SelectedIndexChanged
        autoSuccess = False
        successTimer.Enabled = False
        countReset = True
        resetFunc()
        packingReset()

        If rdbMode2.Checked = True Then
            If txbAutoCount.Text.Replace(" ", "") = "" Then
                autoCount = -1
                errorGen("포장하려는 수량을 알 수 없습니다. 확인하여 주십시오.")
            Else
                If autoCount = 0 Then
                    autoCount = Val(txbAutoCount.Text)
                End If
            End If

            If rdbMode2.Checked = True And rdbAuto2.Checked = True Then

                If weightSelect() Then
                    errorOut("무게확인불가")
                    errorGen("전체 무게를 확인할 수가 없습니다.")
                End If
                If weightSettingForm.ShowDialog() = DialogResult.No Then
                    errorOut("무게세팅오류")
                    errorGen("무게를 세팅하는데 오류가 발생하였습니다.")
                End If
            End If

            txbPacking.Text = autoCount

        End If

        txbProdSN.Focus()
    End Sub

    Private Function MasCodeParsing() As String

        If playCode.Length >= stateLength And playCode.Length <> newProdCodeLength Then
            If InStr(1, playCode, codeState(codeStateList.ERP)) > 0 Then
                Return "ERPORDER"
            ElseIf InStr(1, playCode, codeState(codeStateList.MES)) > 0 Then
                Return "MESORDER"
            Else
                Return "NONORDER"
            End If
        Else
            If lowProdList.Contains(playCode) Then
                Return "CHECKERROR"
            End If
            If playCode.Length = oldProdCodeLength Or playCode.Length = newProdCodeLength Then
                Return "PRODSCAN"
            ElseIf playCode.Length > comCodeLength Then
                Return "COMSCAN"
            Else
                Return "NONPACK"
            End If
        End If
    End Function

    Private Function MasWorkCheck() As Boolean
        Dim worknum As Integer = WorkNowState()

        If RequestCount = worknum Then
            Return True
        Else
            WorkCount = worknum
            Return False
        End If
    End Function

    Private Function WorkNowState() As Integer

        If rdbAuto2.Checked = True Then
            DBCmd = "SELECT COUNT(Number) FROM " & applySalesDB & " WHERE ConnectPack = '" & playCode & "' AND Weight > 0"
        Else
            DBCmd = "SELECT COUNT(Number) FROM " & applySalesDB & " WHERE ConnectPack = '" & playCode & "'"
        End If

        Dim worknum As String = DBQueryScalar(DBCmd)

        If worknum = "False" Then
            Return 0
        End If

        Return Val(worknum)
    End Function

    ''대량 포장 수량 카운트 및 시간 측정
    Private RequestCount As Integer = 0  '' 요청수량   S
    Private WorkCount As Integer = 0  '' 작업 수량    T
    Private LeftOverCount As Integer = 0 '' 남은수량  E

    Private nowFullCount As Integer = 0  ' 현재 수량 N
    Private nowFullCountBack As Integer = 0 ' 현재 수량 백업 

    Private tgtFullCount As Integer = 0  ' 전체 수량 P

    Private SaveOrderName As String = String.Empty

    Private StartTime As TimeSpan
    Private EndTime As TimeSpan
    Private UseTime As TimeSpan
    Private AverTime As TimeSpan

    Private StartSwitch As Boolean = False '' 작업 완료 여부 스위치 ON/OFF
    Private WorkSwitch As Boolean = False '' 패킹중 여부 스위치 ON/OFF

    Private Function beforeDataDel() As Boolean

        If prodArray.GetLength(1) <= 0 Then
            Return True
        End If

        For i = 0 To prodArray.GetLength(1) - 1
            prodArray(itemCode.chkCount, i) = 0
            prodArray(itemCode.serialNum, i) = String.Empty
        Next

        Return False
    End Function

    Private Function MasPlayFunc() As Boolean
        txbResult.Text = "확인중..."
        txbResult.BackColor = Color.Yellow
        txbResult.Refresh()

        Select Case MasCodeParsing()
            Case "ERPORDER"

                errorOut("ERP 불량")
                errorGen("ERP코드는 현재 사용할 수 없습니다.")
                Return False

            Case "MESORDER"

                MassValueReset()

                If ckbAPIuse.Checked = True Then

                    If mesCodeCompare() Then
                        Return False
                    End If

                    If rdbMesDbAPI.Checked = True Then
                        If useAPIRun() Then
                            Return False
                        End If
                    Else
                        If useAPIDirect() Then
                            Return False
                        End If
                    End If

                Else

                    If stateCodeCompare() Then
                        Return False
                    End If

                    If nonAPIRun() Then
                        Return False
                    End If

                End If

                If ListSetting() Then
                    errorOut("등록오류")
                    errorGen("품목 리스트를 생성하는 과정에서 오류가 발생하였습니다.")
                    Return False
                End If

                MassProdProcess()

                If rdbMode2.Checked = True And rdbAuto2.Checked = True Then

                    If weightSelect() Then
                        errorOut("무게확인불가")
                        errorGen("전체 무게를 확인할 수가 없습니다.")
                    End If
                    If weightSettingForm.ShowDialog() = DialogResult.No Then
                        errorOut("무게세팅오류")
                        errorGen("무게를 세팅하는데 오류가 발생하였습니다.")
                    End If
                End If

                SaveOrderName = playCode
                StartSwitch = False
                StartUpdate(DateTime.Now.TimeOfDay)

                successGen("읽기완료")
                Return True

            Case "PRODSCAN"

                If rdbMode2.Checked = True And rdbAuto2.Checked = True Then

                    If StartSwitch = False Then
                        weightSum = 0
                        weightResult = 0
                        For i = 0 To prodArray.GetLength(1) - 1
                            prodArray(itemCode.chkCount, i) = 0
                            txbColorReset(i, txbArrayList(i, txbNameList.name))
                            txbColorReset(i, txbArrayList(i, txbNameList.nowCount))
                            txbArrayList(i, txbNameList.targetCount).Text = prodArray(itemCode.chkCount, i)
                            txbColorReset(i, txbArrayList(i, txbNameList.targetCount))
                        Next

                        If usePacking() Then
                            Return False
                        End If

                        If weightCompare() Then
                            Return False
                        End If

                        If packingSerial() Then
                            Return False
                        End If

                        If comCountSet() Then
                            Return False
                        End If

                        If countCompare() Then
                            Return False
                        End If

                        weightSum = weightData()
                        'weightSum = 45

                        If weightSum = -1 Then
                            Return False
                        End If

                        If weightSum = 0 Then
                            errorOut("무게없음")
                            errorGen("목표 무게를 알 수 없습니다.")
                            Return False
                        Else
                            If weightRun() = False Then
                                Return False
                            End If
                        End If

                        If weightReg() Then
                            successGen("확인 완료")
                            nowFullCount = tgtFullCount
                            Return True
                        Else
                            Return False
                        End If

                    Else
                        errorOut("데이터없음")
                        errorGen("전표 데이터를 먼저 출력하여 주십시오.")
                        Return False
                    End If

                Else

                    If StartSwitch = False Then

                        If WorkSwitch = True Then
                            If ckbPrinter.Checked = True Then
                                ReDim printSerial(0)
                            End If

                            For i = 0 To prodArray.GetLength(1) - 1
                                prodArray(itemCode.chkCount, i) = 0
                                prodArray(itemCode.serialNum, i) = String.Empty
                                txbColorReset(i, txbArrayList(i, txbNameList.name))
                                txbColorReset(i, txbArrayList(i, txbNameList.nowCount))
                                txbArrayList(i, txbNameList.targetCount).Text = prodArray(itemCode.chkCount, i)
                                txbColorReset(i, txbArrayList(i, txbNameList.targetCount))
                            Next
                        End If

                        If serialPackCompare() Then

                            If serialDupCheck() Then
                                Return False
                            End If

                            If prodCodeSearch() Then
                                Return False
                            End If

                            If searchData() Then
                                If shotComparison() Then
                                    Return False
                                End If
                            Else
                                Return False
                            End If

                            For c = 0 To prodArray.GetLength(1) - 1
                                If prodArray(itemCode.type, c) = 1 Then
                                    prodArray(itemCode.chkCount, c) = prodArray(itemCode.count, c)
                                End If
                            Next

                            If MasProdCompareFunc() Then
                                successGen("확인 완료")
                                Return True
                            Else
                                Return False
                            End If

                        Else
                            Return False
                        End If
                    Else
                        errorOut("데이터없음")
                        errorGen("전표 데이터를 먼저 출력하여 주십시오.")
                        Return False
                    End If

                End If

            Case "COMSCAN"
                errorOut("번호불량")
                errorGen("구성품은 처리 대상이 아닙니다. 제품을 스캔하여 주십시오.")
                Return False

            Case "NONPACK"
                errorOut("번호불량")
                errorGen("알 수 없는 바코드 번호입니다. 번호를 확인하여 주십시오.")
                Return False

            Case "NONORDER"
                errorOut("전표불량")
                errorGen("존재하지 않는 전표번호입니다. 번호를 확인하여 주십시오.")
                Return False
            Case "CHECKERROR"
                errorOut("등록오류")
                errorGen("보급형 상품입니다.")
                Return False
            Case Else
                errorOut("동작불량")
                errorGen("잘못된 동작입니다. 관리자에게 문의하십시오.")
                Return False
        End Select
    End Function

    Private Function MasProdCompareFunc() As Boolean
        Const regType As Int16 = 0

        Try
            For i = 0 To prodArray.GetLength(1) - 1
                For n = 0 To scanCode.Length - 1

                    If prodArray(itemCode.code, i) = scanCode(n) Then   '' instr 에서 식으로 변경

                        If prodArray(itemCode.count, i) = prodArray(itemCode.chkCount, i) Then
                            errorOut("등록오류")
                            errorGen("더이상 포장할 필요가 없는 제품입니다.")
                            Return False
                        End If

                        If prodScanCompare(i) Then
                            errorOut("등록오류")
                            errorGen("샷 수가 맞지 않습니다.")
                            Return False
                        End If

                        If WorkSwitch = True Then

                            nowFullCount = nowFullCountBack + 1
                            WorkSwitch = False

                        Else

                            nowFullCount += 1

                        End If

                        prodArray(itemCode.chkCount, i) += 1
                        txbArrayList(i, txbNameList.targetCount).Text = prodArray(itemCode.chkCount, i)

                        If prodArray(itemCode.count, i) = prodArray(itemCode.chkCount, i) Then
                            txbArrayList(i, txbNameList.name).BackColor = Color.Green
                            txbArrayList(i, txbNameList.nowCount).BackColor = Color.Green
                            txbArrayList(i, txbNameList.targetCount).BackColor = Color.Green

                            txbArrayList(i, txbNameList.name).ForeColor = Color.Black
                            txbArrayList(i, txbNameList.nowCount).ForeColor = Color.Black
                            txbArrayList(i, txbNameList.targetCount).ForeColor = Color.Black
                        Else
                            txbArrayList(i, txbNameList.targetCount).ForeColor = Color.Blue
                        End If

                        If prodArray(itemCode.serialNum, i) = Nothing Then
                            prodArray(itemCode.serialNum, i) = playCode
                        Else
                            prodArray(itemCode.serialNum, i) = prodArray(itemCode.serialNum, i) & "/" & playCode
                        End If

                        prodArray(itemCode.type, i) = regType
                        prodArray(itemCode.prodCode, i) = setInfo(setInfoList.prodCode)

                        If ckbPrinter.Checked = True Then

                            Dim SerialCount As Integer = printSerial.Length

                            If SerialCount > 1 Or printSerial(0) <> "" Then
                                ReDim Preserve printSerial(SerialCount)
                                printSerial(SerialCount) = playCode
                            Else
                                printSerial(SerialCount - 1) = playCode
                            End If

                        End If

                        Return True
                    End If
                Next
            Next

            errorOut("등록오류")
            errorGen("포장 품목에 존재하지 않는 제품입니다.")
            Return False
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("포장 품목 확인 중 오류가 발생하였습니다." & ex.Message)
            Return False
        End Try
    End Function

    Private Sub btnOK_Click(sender As Object, e As EventArgs) Handles btnOK.Click
        If txbProdSN.Text.Replace(" ", "") = "" Then
            errorOut("등록오류")
            errorGen("바코드를 입력하여 주십시오.")
            txbProdSN.Focus()
            Exit Sub
        End If


        If rdbMode2.Checked = True And rdbNew.Checked = True Then

            playCode = txbProdSN.Text    '' 시리얼 코드 전역 변수

            If MasPlayFunc() Then
                If playCode.Length < stateLength Or playCode.Length = newProdCodeLength Then
                    If nowFullCount = tgtFullCount Then
                        If chbUseBarcode.Checked = True Then
                            saveStart()
                        End If
                    End If
                End If
            End If
        Else

            If workSuccess = True Or programRunSwitch = False Then
                resetPlay()
                programRunSwitch = True
                workSuccess = False
            End If

            mainClear()
            cartClear()
            txbCheckWeight.Text = String.Empty

            playCode = txbProdSN.Text    '' 시리얼 코드 전역 변수

            If rdbMode2.Checked = True And rdbBef.Checked = True Then
                If autoCountReady = False Then
                    errorOut("수량오류")
                    errorGen("제한 수량 설정이 완료되지 않았습니다. 설정을 완료하여 주십시오.")
                    Exit Sub
                End If

                If cboPacking.SelectedIndex = -1 Then
                    errorOut("선택없음")
                    errorGen("패킹을 선택하지 않았습니다.")
                    Exit Sub
                End If

                If autoCount <= 0 Then
                    errorOut("수량초과")
                    errorGen("포장을 완료하였습니다. 다음 포장을 선택하여 주십시오.")
                    Exit Sub
                End If

                autoSuccess = False
                successTimer.Enabled = False

            Else
                If userAccess = "" And ckbAPIuse.Checked = True And modeSwitch = False Then
                    errorOut("등록오류")
                    errorGen("로그인을 진행하여 주십시오.")
                    Exit Sub
                End If
            End If

            If packingRun() Then
                If playCode.Length < stateLength Or playCode.Length = newProdCodeLength Then
                    If nowFullCount = tgtFullCount Then
                        If chbUseBarcode.Checked = True Then
                            saveStart()
                        End If
                    End If
                End If
            End If

        End If

        txbProdSN.Focus()
    End Sub

    Private Sub btnStart_Click(sender As Object, e As EventArgs) Handles btnStart.Click

        If nowFullCount = tgtFullCount Then
            saveStart()
        Else
            errorGen("포장을 전부 진행하지 않았습니다.")
        End If

        txbProdSN.Focus()
    End Sub

    Private Sub saveStart()
        If scanInfoReg() Then

            If rdbMode2.Checked = True And rdbNew.Checked = True Then
                WorkUpdate(WorkCount + 1)
                txbWork.ForeColor = Color.Blue '' 작업 수량 업데이트

                LeftOverUpdate(LeftOverCount - 1)
                txbLeftOver.ForeColor = Color.Red  '' 잔여 수량 업데이트

                UseUpdate(DateTime.Now.TimeOfDay - StartTime)  '' 소요 시간 업데이트

                Dim AverResult As Integer = CInt(UseTime.TotalSeconds)
                AverResult = AverResult / WorkCount
                AverageUpdate(TimeSpan.FromSeconds(AverResult))  '' 평균 시간 업데이트

                If rdbAuto2.Checked = True Then
                    For i = 0 To txbArrayList.GetLength(1) - 1

                        txbArrayList(i, txbNameList.nowCount).Text = txbArrayList(i, txbNameList.targetCount).Text
                        txbArrayList(i, txbNameList.name).BackColor = Color.Green
                        txbArrayList(i, txbNameList.nowCount).BackColor = Color.Green
                        txbArrayList(i, txbNameList.targetCount).BackColor = Color.Green
                    Next
                End If

                If RequestCount = WorkCount Then
                    StartSwitch = True
                    EndUpdate(DateTime.Now.TimeOfDay)
                Else
                    nowFullCount = nowFullCountBack
                End If

                WorkSwitch = True
            End If

            successTimer.Enabled = True
            txbResult.Text = "등록완료"
            txbResult.BackColor = Color.Green
        Else
            txbResult.Text = "저장실패"
            txbResult.BackColor = Color.Red
        End If

        workSuccess = True
        btnStart.Focus()
    End Sub

    Private Function useAPIDirect() As Boolean
        If stateCodeRun_API() Then
            mesShotSearch()

            If stateinfoRun_API() Then
                Return False
            End If
        End If
        Return True
    End Function

    Private Function stateinfoRun_API() As Boolean
        Try
            DBCmd = "select distinct on(os.receiver_phone_number) io.created_at,co.code,co.name,os.customer_id,os.receiver_name,os.receiver_phone_number,os.receiver_zip_code,io.description,os.receiver_address from order_details od join order_sheets os on os.id = od.order_sheet_id join item_outflows io on io.order_detail_id = od.id left outer join companies co on co.id = os.partner_id where os.code = '" & playCode & "' and od.deleted_at is null;"

            If pgDBQueryReader(DBCmd) Then
                For i = 0 To pgDataQuery.Length - 1
                    apiData(i) = pgDataQuery(i)
                Next

                If apiData(apiDataList.refer) = "0" Then
                    apiData(apiDataList.refer) = String.Empty
                End If

                Return True
            Else
                errorOut("데이터오류")
                errorGen("고객 데이터가 존재하지 않습니다. 데이터를 확인하여 주십시오.")
                Return False
            End If

        Catch ex As Exception
            errorOut("데이터오류")
            errorGen("Postgre 고객 데이터 불러오는 중 오류 발생 !! : " & ex.Message)
            Return False
        End Try
    End Function

    Private Function stateCodeRun_API() As Boolean
        Try
            Const colCount As Int16 = 4

            DBCmd = "select it.code,it.name,io.expected_out_count,io.id from order_details od join items it on it.id = od.item_id join order_sheets os on os.id = od.order_sheet_id join item_outflows io on io.order_detail_id = od.id where os.code = '" & playCode & "' and od.deleted_at is null and io.state = 'registered';"
            If pgDBQueryReader(DBCmd) Then
                Dim RowCount As Int16 = (pgDataQuery.Length / colCount) - 1
                Dim dataSetCount As Int32 = 0
                ReDim prodArray(itemCode.id, RowCount)

                For row = 0 To RowCount
                    For col = 0 To colCount - 1
                        Select Case col
                            Case directData.code
                                prodArray(itemCode.code, row) = pgDataQuery(dataSetCount)
                            Case directData.name
                                prodArray(itemCode.name, row) = pgDataQuery(dataSetCount)
                            Case directData.count
                                prodArray(itemCode.count, row) = pgDataQuery(dataSetCount)
                            Case directData.id
                                prodArray(itemCode.id, row) = pgDataQuery(dataSetCount)
                            Case Else
                                MsgBox("잘못된 경로 개입입니다. useAPIDirect !", vbCritical)
                                Return False
                        End Select

                        dataSetCount += 1
                    Next

                    prodArray(itemCode.chkCount, row) = 0
                    prodArray(itemCode.serialNum, row) = Nothing

                    nowFullCount += prodArray(itemCode.count, row)

                Next

                Return True
            Else
                errorOut("데이터오류")
                errorGen("데이터가 존재하지 않습니다. 데이터를 확인하여 주십시오.")
                Return False
            End If
        Catch ex As Exception
            errorOut("데이터오류")
            errorGen("Postgre 데이터 불러오는 중 오류 발생 !! : " & ex.Message)
            Return False
        End Try

    End Function

    Private Function nonAPIRun() As Boolean

        If stateCodeRun() Then
            If stateCodeShot() Then
                If stateInfoRun() Then
                    Return False
                End If
            End If
        End If

        Return True
    End Function

    Private Function stateInfoRun() As Boolean
        DBCmd = "SELECT Orderer_Name,Phone_Number FROM " & applyOrderDB & " WHERE Order_Code = '" & playCode & "' GROUP BY Order_Code"
        If DBQueryReader(DBCmd) Then
            If sqlDataQuery.Length = 2 Then
                apiData(apiDataList.ordererName) = sqlDataQuery(0)
                apiData(apiDataList.phone) = sqlDataQuery(1)
            Else
                errorOut("데이터오류")
                errorGen("서로 다른 데이터가 존재합니다.")
                Return False
            End If
        Else
            errorOut("데이터오류")
            errorGen("데이터가 존재하지 않습니다..")
            Return False
        End If

        Return True
    End Function

    Private Function stateCodeShot() As Boolean
        Dim shotCount As String
        For i = 0 To prodArray.GetLength(1) - 1
            If prodArray(itemCode.face, i) = "0" Then
                DBCmd = "SELECT FaceShot FROM " & applyPlistDB & " WHERE ItemCode = '" & prodArray(itemCode.code, i) & "'"

                shotCount = DBQueryScalar(DBCmd)

                If shotCount = "False" Then
                    errorOut("등록오류")
                    errorGen("등록되지 않은 제품 번호입니다.")
                    Return False
                End If

                prodArray(itemCode.face, i) = shotCount
            End If

            If prodArray(itemCode.eye, i) = "0" Then
                DBCmd = "SELECT EyeShot FROM " & applyPlistDB & " WHERE ItemCode = '" & prodArray(itemCode.code, i) & "'"

                shotCount = DBQueryScalar(DBCmd)

                If shotCount = "False" Then
                    errorOut("등록오류")
                    errorGen("등록되지 않은 제품 번호입니다.")
                    Return False
                End If

                prodArray(itemCode.eye, i) = shotCount
            End If
        Next

        Return True
    End Function

    Private Function stateCodeRun() As Boolean
        Try
            Const colCount As Int16 = 5
            DBCmd = "SELECT Item_Code,Item_Name,Item_Count,Apply_Face,Apply_Eye FROM " & applyOrderDB & " WHERE Order_Code = '" & playCode & "'"
            If DBQueryReader(DBCmd) Then
                Dim RowCount As Int16 = (sqlDataQuery.Length / colCount) - 1
                Dim dataSetCount As Int32 = 0
                ReDim prodArray(itemCode.prodCode, RowCount)

                For row = 0 To RowCount
                    For col = 0 To colCount - 1
                        prodArray(col, row) = sqlDataQuery(dataSetCount)

                        If col = itemCode.count Then
                            nowFullCount += prodArray(itemCode.count, row)
                        End If

                        dataSetCount += 1
                    Next
                Next

                Return True
            Else
                errorOut("등록오류")
                errorGen("전표코드에 대한 데이터가 존재하지 않습니다.")
                Return False
            End If
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("품목 리스트를 정리하는 도중 오류가 발생하였습니다.")
            Return False
        End Try

    End Function

    Private Function stateCodeExist() As Boolean
        DBCmd = Val(DBQueryScalar("SELECT COUNT(Order_Code) FROM " & applyOrderDB & " WHERE Order_Code = '" & playCode & "'"))

        If DBCmd = 0 Then
            Return True
        End If

        Return False
    End Function

    Private Function mesCodeCompare() As Boolean
        DBCmd = "SELECT COUNT(Order_Code) FROM " & applyOrderDB & " WHERE Order_Code = '" & playCode & "'"

        Dim orderCount As String = DBQueryScalar(DBCmd)

        If orderCount = "False" Then
            errorOut("데이터오류")
            errorGen("데이터를 불러올 수 없습니다.")
            Return True
        End If

        If orderCount > 0 Then
            errorOut("데이터오류")
            errorGen("이미 작업한 데이터 입니다.")
            Return True
        End If

        Return False
    End Function

    Private Function stateCodeCompare() As Boolean
        DBCmd = "SELECT COUNT(Order_Code) FROM " & applyOrderDB & " WHERE Order_Code = '" & playCode & "'"
        Dim orderCount As Integer = Val(DBQueryScalar(DBCmd))

        If orderCount = 0 Then
            errorOut("등록오류")
            errorGen("해당 전표 코드에 대한 데이터가 존재하지 않습니다.")
            Return True
        End If

        DBCmd = "SELECT COUNT(Order_Code) FROM " & applyOrderDB & " WHERE Order_Code = '" & playCode & "' AND Packing_Code IS null"
        Dim compareCount As Integer = Val(DBQueryScalar(DBCmd))

        If compareCount = 0 Then
            errorOut("등록오류")
            errorGen("이미 포장 완료 처리된 제품입니다.")
            Return True
        End If

        If compareCount = orderCount Then
            Return False
        Else
            errorOut("등록오류")
            errorGen("이미 포장된 제품이 존재합니다. 번호를 확인하여 주십시오.")
            Return True
        End If
    End Function

    Private Function useAPIRun() As Boolean
        If mesRunning() Then
            Return False
        Else
            Return True
        End If
    End Function

    Private Sub prodProcess()
        For i = 0 To prodArray.GetLength(1) - 1
            If prodArray(itemCode.type, i) = dbCode.comDBcode Then

                prodArray(itemCode.chkCount, i) = prodArray(itemCode.count, i)
                tgtFullCount += prodArray(itemCode.count, i)
                txbArrayList(i, txbNameList.targetCount).Text = prodArray(itemCode.chkCount, i)

                txbArrayList(i, txbNameList.name).BackColor = Color.Green
                txbArrayList(i, txbNameList.nowCount).BackColor = Color.Green
                txbArrayList(i, txbNameList.targetCount).BackColor = Color.Green

                prodArray(itemCode.type, i) = prodArray(itemCode.type, i)
            End If
        Next
    End Sub

    Private Sub MassProdProcess()
        For i = 0 To prodArray.GetLength(1) - 1

            tgtFullCount += prodArray(itemCode.count, i)

            If prodArray(itemCode.face, i) = "-1" And prodArray(itemCode.eye, i) = "-1" Then

                prodArray(itemCode.chkCount, i) = prodArray(itemCode.count, i)
                prodArray(itemCode.type, i) = 1
                prodArray(itemCode.face, i) = 0
                prodArray(itemCode.eye, i) = 0
                txbArrayList(i, txbNameList.targetCount).Text = 0

                If rdbAuto2.Checked = True Then

                    txbArrayList(i, txbNameList.name).Enabled = True
                    txbArrayList(i, txbNameList.nowCount).Enabled = True
                    txbArrayList(i, txbNameList.targetCount).Enabled = True

                Else

                    txbArrayList(i, txbNameList.name).Enabled = False
                    txbArrayList(i, txbNameList.nowCount).Enabled = False
                    txbArrayList(i, txbNameList.targetCount).Enabled = False

                End If

                nowFullCountBack += prodArray(itemCode.count, i)

                'txbArrayList(i, txbNameList.name).BackColor = Color.Green
                'txbArrayList(i, txbNameList.nowCount).BackColor = Color.Green
                'txbArrayList(i, txbNameList.targetCount).BackColor = Color.Green
            Else

                If rdbAuto2.Checked = True Then
                    txbArrayList(i, txbNameList.targetCount).Text = prodArray(itemCode.count, i)
                    txbArrayList(i, txbNameList.name).BackColor = Color.Green
                    txbArrayList(i, txbNameList.nowCount).BackColor = Color.Green
                    txbArrayList(i, txbNameList.targetCount).BackColor = Color.Green
                End If

                prodArray(itemCode.type, i) = 0

            End If
        Next

    End Sub

    Private Function packingRun() As Boolean

        Select Case codeParsing()

            Case "PACKING"

                If cboPacking.SelectedIndex = -1 Then
                    errorOut("선택없음")
                    errorGen("패킹을 선택하지 않았습니다.")
                    Return False
                End If

                If packingSetting() Then
                    Return False
                End If

                If ListSetting() Then
                    errorOut("등록오류")
                    errorGen("품목 리스트를 생성하는 과정에서 오류가 발생하였습니다.")
                    Return False
                End If

                If rdbMode2.Checked = True And rdbAuto1.Checked = True Then
                    prodProcess()
                End If

                successGen("읽기완료")
                Return True

            Case "ERPORDER"

                If stateCodeCompare() Then
                    Return False
                End If

                If nonAPIRun() Then
                    Return False
                End If

                If ListSetting() Then
                    errorOut("등록오류")
                    errorGen("품목 리스트를 생성하는 과정에서 오류가 발생하였습니다.")
                    Return False
                End If

                successGen("읽기완료")
                Return True

            Case "MESORDER"

                If ckbAPIuse.Checked = True Then
                    If mesCodeCompare() Then
                        Return False
                    End If

                    If rdbMesDbAPI.Checked = True Then
                        If useAPIRun() Then
                            Return False
                        End If
                    Else
                        If useAPIDirect() Then
                            Return False
                        End If
                    End If

                Else

                    If stateCodeCompare() Then
                        Return False
                    End If

                    If nonAPIRun() Then
                        Return False
                    End If

                End If

                If ListSetting() Then
                    errorOut("등록오류")
                    errorGen("품목 리스트를 생성하는 과정에서 오류가 발생하였습니다.")
                    Return False
                End If

                If rdbMode2.Checked = True And rdbNew.Checked = True Then
                    MassProdProcess()
                End If

                successGen("읽기완료")
                Return True

            Case "PRODSCAN"

                If rdbMode2.Checked = True And rdbAuto2.Checked = True Then

                    tgtFullCount = 0
                    weightSum = 0
                    weightResult = 0

                    txbCfaceSN.Text = playCode

                    If OneDBSearch() Then
                        Return False
                    End If

                    For i = 0 To prodArray.GetLength(1) - 1
                        prodArray(itemCode.chkCount, i) = 0
                    Next

                    If usePacking() Then
                        Return False
                    End If

                    If weightCompare() Then
                        Return False
                    End If

                    If packingSerial() Then
                        Return False
                    End If

                    If comCountSet() Then
                        Return False
                    End If

                    If countCompare() Then
                        Return False
                    End If

                    weightSum = weightData()

                    If weightSum = -1 Then
                        Return False
                    End If

                    If weightSum = 0 Then
                        weightResult = weightSum
                    Else
                        If weightRun() = False Then
                            Return False
                        End If
                    End If

                    If weightReg() Then
                        Return True
                    Else
                        Return False
                    End If

                Else
                    If serialPackCompare() Then

                        If serialDupCheck() Then
                            Return False
                        End If

                        If prodCodeSearch() Then
                            Return False
                        End If

                        If searchData() Then
                            If shotComparison() Then
                                Return False
                            End If
                        Else
                            Return False
                        End If

                        If stateScanCompare() Then
                            successGen("처리완료")
                            Return True
                        Else
                            Return False
                        End If

                    Else
                        Return False
                    End If
                End If

            Case "COMSCAN"

                Dim comCode As String = comCodeSearch()

                If comCode = "False" Then
                    Return False
                End If

                If comCodeCompare() Then
                    Return False
                End If

                If stateComCompare(comCode) Then
                    successGen("처리완료")
                    Return True
                Else
                    Return False
                End If

            Case "STATEERROR"
                errorOut("등록오류")
                errorGen("포장 내역이 존재하지 않습니다. 포장 내역을 불러와 주십시오.")
                Return False

            Case "LENGTHERROR"
                errorOut("등록오류")
                errorGen("알 수 없는 바코드 번호입니다. 바코드 번호를 확인하여 주십시오.")
                Return False
            Case "NONORDER"
                errorOut("등록오류")
                errorGen("알 수 없는 전표코드 입니다. 전표 번호를 확인하여 주십시오.")
                Return False

            Case "MODEERROR"
                errorOut("모드오류")
                errorGen("패킹 모드에서는 전표 번호를 사용할 수 없습니다.")
                Return False
            Case "-1"
                errorOut("등록오류")
                errorGen("코드를 파싱하는 도중 오류가 발생하였습니다.")
                Return False
            Case Else
                errorOut("등록오류")
                errorGen("잘못된 접근입니다. 관리자에게 문의하여 주십시오.")
                Return False
        End Select

    End Function

    Private Function OneDBSearch() As Boolean
        DBCmd = "SELECT Ct_Model,Ct_Abroad,Ct_Agency,Ct_Max_ShotCnt FROM " & applyCartDB & " WHERE Product_SN = '" & playCode & "'"
        If DBQueryReader(DBCmd) Then
            txbCmodel.Text = sqlDataQuery(0)
            txbCnt.Text = sqlDataQuery(1)
            txbCagent.Text = sqlDataQuery(2)
            txbCfaceShot.Text = sqlDataQuery(3)

            Return False
        Else
            Return True
        End If
    End Function

    Private Function weightCompare() As Boolean
        DBCmd = "SELECT Weight FROM " & applySalesDB & " WHERE PackingCode = '" & playCode & "'"
        Dim weight As String = DBQueryScalar(DBCmd)

        If weight = "False" Then
            errorOut("무게오류")
            errorGen("무게 데이터 검색을 진행할 수 없습니다.")
            Return True
        End If

        If weight <> "0" Then
            errorOut("무게오류")
            errorGen("무게 측정을 진행한 데이터입니다.")
            Return True
        End If

        Return False
    End Function

    Private Function countCompare() As Boolean
        For i = 0 To prodArray.GetLength(1) - 1

            If prodArray(itemCode.count, i) <> prodArray(itemCode.chkCount, i) Then
                errorOut("수량오류")
                errorGen("수량이 맞지 않는 품목이 존재합니다. 제품을 확인하여 주십시오.")
                Return True
            End If
        Next
        Return False
    End Function

    Private Function comCountSet() As Boolean
        Dim query_component_sales_packing_cnt As String = Nothing
        Dim sales_packing_cnt_col_nm As String
        For i = 0 To item_component_max_index
            If item_component_list(i).sales_packing_cnt_col_nm <> Nothing Then
                sales_packing_cnt_col_nm = item_component_list(i).sales_packing_cnt_col_nm
            Else
                sales_packing_cnt_col_nm = 0
            End If

            If query_component_sales_packing_cnt <> Nothing Then
                query_component_sales_packing_cnt = query_component_sales_packing_cnt & ", " & sales_packing_cnt_col_nm
            Else
                query_component_sales_packing_cnt = sales_packing_cnt_col_nm
            End If
        Next

        DBCmd = "SELECT " & query_component_sales_packing_cnt & " FROM " & applySalesDB & " WHERE PackingCode = '" & playCode & "'"

        If DBQueryReader(DBCmd) Then
            If sqlDataQuery.Length - 1 = item_component_max_index Then
                For i = 0 To item_component_max_index
                    If sqlDataQuery(i) <> 0 Then
                        tgtFullCount += sqlDataQuery(i)
                        For arr = 0 To prodArray.GetLength(1) - 1

                            If prodArray(itemCode.type, arr) = dbCode.comDBcode Then
                                If i = prodArray(itemCode.prodCode, arr) Then
                                    prodArray(itemCode.chkCount, arr) += sqlDataQuery(i)
                                    Exit For
                                End If
                            End If
                        Next
                    End If
                Next
            Else
                errorOut("수량오류")
                errorGen("구성품 수량을 가져오는 단계에서 오류가 발생하였습니다.")
                Return True
            End If

        Else
            errorOut("수량오류")
            errorGen("구성품 수량을 확인할 수 없습니다.")
            Return True
        End If

        Return False
    End Function

    Private Function packingSerial() As Boolean
        Dim prodSerial(item_product_max_index) As String
        Dim query_product_serial As String = Nothing

        '제품 ProdCode는 1부터 시작하기에 (1)부터 조회
        For i = 1 To item_product_max_index
            If item_product_list(i).sales_packing_serial_col_nm <> Nothing Then
                If query_product_serial <> Nothing Then
                    query_product_serial = query_product_serial & ", " & item_product_list(i).sales_packing_serial_col_nm
                Else
                    query_product_serial = item_product_list(i).sales_packing_serial_col_nm
                End If
            End If
        Next

        DBCmd = "SELECT " & query_product_serial & " FROM " & applySalesDB & " WHERE PackingCode = '" & playCode & "'"
        If DBQueryReader(DBCmd) Then
            For i = 0 To sqlDataQuery.Length - 1
                prodSerial(i) = sqlDataQuery(i)
            Next
        Else
            errorOut("시리얼오류")
            errorGen("전체 시리얼 번호에 대한 내용을 확인할 수 없습니다.")
            Return True
        End If


        For i = 0 To prodSerial.Length - 1
            If prodSerial(i) <> "" And prodSerial(i) <> "0" Then
                Dim model, type, color, face, eye As String
                Dim singleRun As Boolean = False   '' 세트인지 아닌지 (세트일 경우 두 개의 샷 수가 나옴)
                Dim successBol As Boolean = False
                Dim parsingData As String
                Dim serialArr() As String
                Dim readData As String = prodSerial(i)
                Dim slashNum As Int16 = UBound(Split(readData, ","))
                Dim deviceTypeCode As String = ""

                For cnt = 0 To slashNum
                    tgtFullCount += 1
                    If cnt = slashNum Then
                        parsingData = readData
                    Else
                        parsingData = Mid(readData, 1, InStr(readData, ",") - 1)
                        readData = Mid(readData, InStr(readData, ",") + 1, readData.Length)
                    End If

                    If parsingData.Length = oldProdCodeLength Then      '12자리 제품시리얼번호
                        model = Mid(parsingData, 1, 1)
                        type = Mid(parsingData, 2, 1)
                        color = Mid(parsingData, 11, 1)
                    ElseIf parsingData.Length = newProdCodeLength Then  '16자리 제품시리얼번호
                        model = Mid(parsingData, 1, 2)
                        type = Mid(parsingData, 15, 1)
                        color = Mid(parsingData, 3, 1)
                    End If

                    DBCmd = "SELECT DeviceTypeCode FROM " & ApplyModelInfoDB & " WHERE ModelCode = '" & modelNum & "' LIMIT 1"
                    If DBQueryReader(DBCmd) Then
                        deviceTypeCode = sqlDataQuery(0)
                    End If

                    If deviceTypeCode = "D" Then    '분리형 디바이스 : PRO, LUX, ALPHA	
                        If type = typeList.prodSet Then
                            singleRun = True
                        End If
                    End If

                    If singleRun = True Then
                        DBCmd = "SELECT b.Ct_Max_ShotCnt FROM " & applyProdDB & " AS a INNER JOIN " & applyCartDB & " AS b ON a.FaceCart_SN = b.Product_SN OR a.EyeCart_SN = b.Product_SN WHERE a.Product_SN = '" & playCode & "'"
                        If DBQueryReader(DBCmd) Then
                            face = sqlDataQuery(0)
                            eye = sqlDataQuery(1)
                        Else
                            errorOut("샷수오류")
                            errorGen("세트 샷 수에 대한 정보가 존재하지 않습니다.")
                            Return True
                        End If
                    Else
                        DBCmd = "SELECT Ct_Max_ShotCnt FROM " & applyCartDB & " WHERE Product_SN = '" & playCode & "'"
                        Dim shotData As String = DBQueryScalar(DBCmd)
                        If shotData <> "False" Then
                            If type = typeList.prodEye Then
                                face = 0
                                eye = shotData
                            Else
                                face = shotData
                                eye = 0
                            End If
                        Else

                            DBCmd = "SELECT COUNT(NUMBER) FROM " & applyNonTDDB & " WHERE Product_SN = '" & playCode & "'"

                            Dim ExistData As String = DBQueryScalar(DBCmd)

                            If ExistData > 0 Then
                                face = 0
                                eye = 0
                            Else
                                errorOut("샷수오류")
                                errorGen("단품 샷 수에 대한 정보가 존재하지 않습니다.")
                                Return True
                            End If

                        End If
                    End If

                    DBCmd = "SELECT ItemCode FROM " & applyPlistDB & " WHERE ModelNum = '" & model & "' and TypeNum = '" & type & "' and FaceShot = '" & face & "' and EyeShot = '" & eye & "' and ColorNum = '" & color & "'"

                    If DBQueryReader(DBCmd) Then
                        ReDim serialArr(sqlDataQuery.Length - 1)
                        For que = 0 To sqlDataQuery.Length - 1
                            successBol = False

                            For num = 0 To prodArray.GetLength(1) - 1
                                If sqlDataQuery(que) = prodArray(itemCode.code, num) Then
                                    prodArray(itemCode.chkCount, num) += 1
                                    successBol = True
                                    Exit For
                                End If
                            Next

                            If successBol = True Then
                                Exit For
                            End If

                        Next
                    Else
                        errorOut("코드오류")
                        errorGen("제품 코드에 대한 정보가 존재하지 않습니다.")
                        Return True
                    End If

                Next

            End If
        Next

        Return False
    End Function

    Private Function weightReg() As Boolean
        DBCmd = "UPDATE " & applySalesDB & " SET Weight = '" & weightResult & "' WHERE PackingCode = '" & playCode & "'"

        If DBCommand(DBCmd) Then

            For i = 0 To prodArray.GetLength(1) - 1

                txbArrayList(i, txbNameList.targetCount).Text = prodArray(itemCode.chkCount, i)

                txbArrayList(i, txbNameList.name).BackColor = Color.Green
                txbArrayList(i, txbNameList.nowCount).BackColor = Color.Green
                txbArrayList(i, txbNameList.targetCount).BackColor = Color.Green

            Next

            Return True
        Else
            For i = 0 To prodArray.GetLength(1) - 1

                txbArrayList(i, txbNameList.name).BackColor = Color.Red
                txbArrayList(i, txbNameList.nowCount).BackColor = Color.Red
                txbArrayList(i, txbNameList.targetCount).BackColor = Color.Red

            Next

            errorOut("등록오류")
            errorGen("무게 데이터를 등록할 수 없습니다.")
            Return False
        End If
    End Function

    Private Function weightData() As Integer
        DBCmd = "SELECT TargetWeight FROM " & applySalesDB & " WHERE PackingCode = '" & playCode & "'"

        Dim selectResult As String = DBQueryScalar(DBCmd)

        If selectResult = "False" Then
            errorOut("무게오류")
            errorGen("무게를 알 수 없습니다.")
            Return -1
        End If

        Return Val(selectResult)
    End Function

    Private Function usePacking() As Boolean
        DBCmd = "SELECT COUNT(NUMBER) FROM " & applySalesDB & " WHERE PackingCode = '" & playCode & "'"

        Dim selectResult As String = DBQueryScalar(DBCmd)

        If selectResult = "False" Then
            errorOut("데이터오류")
            errorGen("패킹 번호를 알 수 없습니다.")
            Return True
        End If

        If Val(selectResult) = 0 Then
            errorOut("데이터오류")
            errorGen("존재하지 않는 패킹 번호입니다.")
            Return True
        End If

        Return False
    End Function

    Private Function serialDupCheck() As Boolean
        If playCode.Length = lowProdCodeLength Then
            Return False
        End If
        For i = 0 To prodArray.GetLength(1) - 1
            If InStr(prodArray(itemCode.serialNum, i), playCode) > 0 Then
                errorOut("데이터오류")
                errorGen("이미 포장한 데이터입니다.")
                Return True
            End If
        Next

        Return False
    End Function

    Private Function serialPackCompare() As Boolean
        Dim commandStr As String
        If playCode.Length = lowProdCodeLength Then
            Return True
        End If

        If playCode.Length = oldProdCodeLength Then         '12자리 제품시리얼번호
            modelNum = Mid(playCode, 1, 1)
            typeNum = Mid(playCode, 2, 1)
        ElseIf playCode.Length = newProdCodeLength Then     '16자리 제품시리얼번호
            modelNum = Mid(playCode, 1, 2)
            typeNum = Mid(playCode, 15, 1)
        Else
            errorOut("시리얼번호오류")
            errorGen("잘못된 시리얼 번호입니다.")
            Return False
        End If

        DBCmd = "SELECT TDUseYn, LdmUseYn FROM " & ApplyModelInfoDB & " WHERE ModelCode = '" & modelNum & "' LIMIT 1"
        If DBQueryReader(DBCmd) Then
            If sqlDataQuery(1) = "Y" Then
                LdmUseCompare = True
            ElseIf sqlDataQuery(0) = "Y" Then
                TDUseCompare = True
            Else
                TDUseCompare = False
            End If
        Else
            TDUseCompare = False

            errorOut("등록오류")
            errorGen("존재하지 않는 모델 번호입니다.")
            Return False
        End If

        DBCmd = "SELECT SalesPackingSerialColNm FROM " & applyPlistDB & " WHERE ModelNum = '" & modelNum & "' AND TypeNum = " & typeNum & " GROUP BY ProdCode"
        If DBQueryReader(DBCmd) Then
            commandStr = sqlDataQuery(0)
        Else
            errorOut("등록오류")
            errorGen("존재하지 않는 타입 번호입니다.")
            Return False
        End If

        DBCmd = "SELECT COUNT(" & commandStr & ") FROM " & applySalesDB &
                " WHERE " & commandStr & " LIKE '%" & playCode & "%'" &
                " AND PackingCode NOT LIKE 'null_%'"

        If DBQueryScalar(DBCmd) > "0" Or DBQueryScalar(DBCmd) = "False" Then
            If rdbMode2.Checked = True And rdbAuto1.Created = True Then
                If MsgBox("중복된 데이터가 존재합니다. 해당 바코드 데이터를 삭제하시겠습니까?", vbOKCancel + vbExclamation) = MsgBoxResult.Ok Then

                    failDataReset(playCode)

                    If rdbNew.Checked = True Then

                        DBCmd = "SELECT COUNT(NUMBER) FROM " & applySalesDB & " WHERE ConnectPack = '" & SaveOrderName & "'"

                        Dim ApplyCount As String = DBQueryScalar(DBCmd)

                        If ApplyCount = "False" Then
                            errorOut("DB오류")
                            errorGen("작업 수량을 확인할 수 없습니다.")
                            Return False
                        End If

                        Dim ApplyCountInt As Integer = Val(ApplyCount)

                        WorkUpdate(ApplyCount)
                        LeftOverUpdate(RequestCount - ApplyCount)

                    Else

                        autoCount += 1
                        txbPacking.Text = autoCount

                    End If

                    Return True
                Else
                    errorOut("등록오류")
                    errorGen("이미 포장된 제품입니다. 번호를 확인하여 주십시오.")
                    Return False
                End If
            Else
                errorOut("등록오류")
                errorGen("이미 포장된 제품입니다. 번호를 확인하여 주십시오.")
                Return False
            End If
        End If

        Return True
    End Function


    Private Function serialOrderCompare() As Boolean
        DBCmd = "SELECT COUNT(Order_Code) FROM " & applyOrderDB & " WHERE Serial_Number like '%" & playCode & "%'"

        Dim queryCount As String = DBQueryScalar(DBCmd)

        If queryCount > "0" Or queryCount = "False" Then
            Return False
        End If

        Return True
    End Function
    Private Function packingSetting() As Boolean
        Const colCount As Int16 = 8
        Dim rowCount As Integer = 0
        Dim sucSwitch As Boolean = False
        Dim packName As String = cboPacking.SelectedItem

        ReDim prodArray(itemCode.prodCode, rowCount)

        For i = 0 To dgvEvent.Rows.Count - 2
            If dgvEvent.Rows(i).Cells(1).Value = packName Then
                ReDim Preserve prodArray(itemCode.prodCode, rowCount)

                If countReset = True Then
                    autoCount = dgvEvent.Rows(i).Cells(9).Value
                    countReset = False
                End If


                For col = 2 To colCount
                    If col = colCount Then
                        prodArray(itemCode.type, rowCount) = dgvEvent.Rows(i).Cells(col).Value

                    ElseIf col = colCount - 1 Then
                        prodArray(itemCode.prodCode, rowCount) = dgvEvent.Rows(i).Cells(col).Value

                    Else
                        prodArray(col - 2, rowCount) = dgvEvent.Rows(i).Cells(col).Value

                        If col = 4 Then '' 3번째 데이터가 개수 데이터에 해당
                            nowFullCount += dgvEvent.Rows(i).Cells(col).Value
                        End If
                    End If

                Next

                rowCount += 1
                sucSwitch = True
            End If
        Next

        If sucSwitch = True Then
            Return False
        Else
            errorOut("등록오류")
            errorGen("패킹하기 위한 데이터를 불러오지 못했습니다. 설정창에서 확인하여 주십시오.")
            Return True
        End If

    End Function

    Private Function comCodeCompare() As Boolean
        Dim codeResult As String = Nothing
        setInfo(setInfoList.prodCode) = Nothing

        DBCmd = "SELECT ProdCode FROM " & applyClistDB & " WHERE Barcode = '" & playCode & "'"

        If DBQueryReader(DBCmd) <> 0 Then

            For i = 0 To sqlDataQuery.Length - 1
                If codeResult = Nothing Then
                    codeResult = sqlDataQuery(i)
                Else
                    If codeResult <> sqlDataQuery(i) Then
                        errorOut("등록오류")
                        errorGen("제품 데이터가 서로 맞지 않습니다. 관리자에게 문의하여 주십시오.")
                        Return True
                    End If
                End If
            Next

            If codeResult <> Nothing Then
                setInfo(setInfoList.prodCode) = codeResult
                Return False
            Else
                errorOut("등록오류")
                errorGen("등록되지 않은 제품입니다. 관리자에게 제품 등록을 문의하여 주십시오.")
                Return True
            End If

        Else
            errorOut("등록오류")
            errorGen("등록되지 않은 제품입니다. 관리자에게 제품 등록을 문의하여 주십시오.")
            Return True
        End If
    End Function

    Private Function shotComparison() As Boolean
        Dim runCount As Int32 = 0
        Dim faceCShot As Int32 = 0
        Dim eyeCshot As Int32 = 0
        If setInfo(setInfoList.topSerial) <> "NULL" And setInfo(setInfoList.midSerial) <> "NULL" And setInfo(setInfoList.botSerial) <> "NULL" Then
            setFace = setInfo(setInfoList.midshot)
            setEye = setInfo(setInfoList.botshot)
        Else
            If setInfo(setInfoList.topSerial) <> "NULL" Then
                setFace = setInfo(setInfoList.topshot)
                setEye = "0"
            ElseIf setInfo(setInfoList.midSerial) <> "NULL" Then
                setFace = "0"
                setEye = setInfo(setInfoList.midshot)
            ElseIf setInfo(setInfoList.botSerial) <> "NULL" Then
                setFace = setInfo(setInfoList.botshot)
                setEye = "0"
            Else
                setFace = "0"
                setEye = "0"
            End If
        End If

        faceCShot = setFace
        eyeCshot = setEye

        For i = 0 To ScanArray.GetLength(1) - 1
            If ScanArray(scanList.faceshot, i) = faceCShot And ScanArray(scanList.eyeshot, i) = eyeCshot Then
                runCount = runShotFunc(i, runCount)
            End If

            If runCount = -1 Then
                errorOut("등록오류")
                errorGen("샷 수 확인 중 오류가 발생하였습니다.")
                Return True
            End If
        Next

        Return False
    End Function

    Private Function shotCompare() As Boolean
        Const scanFace As Int16 = 2
        Const scanEye As Int16 = 3
        Dim runCount As Int32 = 0
        Dim nonShotSwitch As Boolean = False
        setFace = 0
        setEye = 0

        ReDim scanCode(0)

        If setInfo(setInfoList.topSerial) <> "NULL" And setInfo(setInfoList.midSerial) <> "NULL" And setInfo(setInfoList.botSerial) <> "NULL" Then
            setFace = setInfo(setInfoList.midshot)
            setEye = setInfo(setInfoList.botshot)
        Else
            If setInfo(setInfoList.topSerial) <> "NULL" Then
                setFace = setInfo(setInfoList.topshot)
                setEye = "0"
            ElseIf setInfo(setInfoList.midSerial) <> "NULL" Then
                setFace = "0"
                setEye = setInfo(setInfoList.midshot)
            ElseIf setInfo(setInfoList.botSerial) <> "NULL" Then
                setFace = setInfo(setInfoList.botshot)
                setEye = "0"
            Else
                setFace = "0"
                setEye = "0"
            End If
        End If

        For i = 0 To ScanArray.GetLength(0) - 1
            If ScanArray(i, scanFace) = setFace And ScanArray(i, scanEye) = setEye Then
                runCount = runShotFunc(i, runCount)
            Else

            End If

            If runCount = -1 Then
                errorOut("등록오류")
                errorGen("샷 수 확인 중 오류가 발생하였습니다.")
                Return False
            End If
        Next

        If scanCode(0) = Nothing Then
            errorOut("등록오류")
            errorGen("해당 샷 수와 맞는 제품 데이터가 존재하지 않습니다.")
            Return False
        End If

        Return True
    End Function

    Private Function runShotFunc(num As Int16, runcount As Integer) As Integer
        If runcount = 0 Then
            ReDim scanCode(runcount)
            setInfo(setInfoList.prodCode) = ScanArray(scanList.prodcode, num)
        Else
            If setInfo(setInfoList.prodCode) <> ScanArray(scanList.prodcode, num) Then
                errorOut("정보오류")
                errorGen("등록되어 있는 ProdCode가 서로 맞지 않습니다.")
                Return -1
            End If

            ReDim Preserve scanCode(runcount)
        End If

        scanCode(runcount) = ScanArray(scanList.itemcode, num)
        Return runcount + 1
    End Function

    Private Function scanInfoReg() As Boolean
        Dim packingCode As String
        invoiceCode = String.Empty

        txbResult.Text = "등록중..."
        txbResult.BackColor = Color.Yellow

        If rdbMode1.Checked = True Or (rdbMode2.Checked = True And rdbAuto1.Checked = True) Then

            packingCode = packingCode_Choice()

            If packingCode = "False" Then
                Return False
            End If

            If dbPackNumCompare(packingCode) Then
                Return False
            End If

            If rdbMode1.Checked = True Then

                txbPacking.Text = packingCode

                ' 무게측정
                If weightRun() = False Then
                    Return False
                End If

                If invDataGet() = False Then
                    Return False
                End If
            Else
                If weightSelect() Then
                    Return True
                End If
            End If

            If dbRegType(packingCode) Then
                Return False
            End If

        Else
            packingCode = playCode
        End If

        If countSaveRun(packingCode) Then
            If printPlay(packingCode) Then
                Return True
            Else
                Return False
            End If
        Else
            Return False
        End If

    End Function

    Private Function invDataGet() As Boolean
        If ckbInv.Checked = True Then
            invForm.ShowDialog()
            If invForm.successSwitch = True Then
                Return True
            Else
                Return False
            End If
        Else
            Return True
        End If

    End Function

    Private Function countSaveRun(packingCode As String) As Boolean

        If saveNowCount() Then  '' 포장 수량 저장
            failDataReset(packingCode)
            Return False   ''실패
        End If


        If rdbMode2.Checked = False Or rdbAuto2.Checked = False Then

            If ckbNEWDB.Checked = True Then
                If packingDBSave(packingCode) Then  '' 패킹 데이터 수량 저장
                    failDataReset(packingCode)
                    Return False
                End If

                If packingDBSerial(packingCode) Then  '' 패킹 데이터 시리얼 번호 저장
                    failDataReset(packingCode)
                    Return False
                End If
            Else
                If packingDBSaveOld(packingCode) Then
                    failDataReset(packingCode)
                    Return False
                End If

                If packingDBSerialOld(packingCode) Then
                    failDataReset(packingCode)
                    Return False
                End If
            End If
        End If

        If saveDBReg() Then  '' db 개수 저장
            failDataReset(packingCode)
            Return False
        End If

        If saveLocalFile() Then ''로컬 개수 저장
            Return False
        End If

        countView()

        If saveLogOrder(packingCode) Then  '' logData 전표내역 저장
            Return False
        End If

        If saveLogData(packingCode) Then  '' logdata 패킹내역 저장
            Return False
        End If

        If rdbMode2.Checked = True Then
            autoCount -= 1
            saveConfig(saveList.lastCount)
            txbPacking.Text = autoCount
        End If

        Return True

    End Function

    Private Function packingDBSaveOld(packingCode As String) As Boolean
        Dim query_product_cnt As String = Nothing
        '제품 ProdCode ProSet(1),LuxSet(2)는 같은 컬럼을 사용하고 있어, ProSet(1),LuxSet(2)는 아래에서 따로 합산
        For i = prodDB.proface To item_product_max_index
            If item_product_list(i).sales_packing_cnt_col_nm <> Nothing And item_product_list(i).cnt > 0 Then
                query_product_cnt = query_product_cnt & ", " & item_product_list(i).sales_packing_cnt_col_nm & " = '" & item_product_list(i).cnt & "'"
            End If
        Next

        Dim query_component_cnt As String = Nothing
        For i = 0 To item_component_max_index
            If item_component_list(i).sales_packing_cnt_col_nm <> Nothing And item_component_list(i).cnt > 0 Then
                query_component_cnt = query_component_cnt & ", " & item_component_list(i).sales_packing_cnt_col_nm & " = '" & item_component_list(i).cnt & "'"
            End If
        Next

        DBCmd = "UPDATE " & applySalesDB &
                  " SET Set_Cnt = '" & item_product_list(prodDB.proset).cnt + item_product_list(prodDB.luxset).cnt & "'" &
                     query_product_cnt &
                     query_component_cnt &
                " WHERE PackingCode = '" & packingCode & "'"

        If DBCommand(DBCmd) = False Then
            errorOut("등록오류")
            errorGen("데이터베이스에 수량 등록을 하는 과정에서 오류가 발생하였습니다.")
            Return True
        End If

        Return False
    End Function

    Private Function packingDBSerialOld(packingCode As String) As Boolean
        Try
            Dim setSerial As String = Nothing
            Dim faceSerial As String = Nothing
            Dim eyeSerial As String = Nothing
            Dim searchCode, fullCode As String

            If item_product_list(prodDB.proset).serial <> Nothing Then
                If item_product_list(prodDB.proset).serial.ToString.Replace(" ", "") <> "" Then
                    setSerial = item_product_list(prodDB.proset).serial
                End If
            End If

            If item_product_list(prodDB.luxset).serial <> Nothing Then
                If item_product_list(prodDB.luxset).serial.ToString.Replace(" ", "") <> "" Then
                    If setSerial = Nothing Then
                        setSerial = item_product_list(prodDB.luxset).serial
                    Else
                        setSerial = setSerial & "/" & item_product_list(prodDB.luxset).serial
                    End If
                End If
            End If

            If setSerial <> Nothing Then
                Dim slashCount As Int16 = UBound(Split(setSerial, "/"))
                fullCode = setSerial

                For i = 0 To slashCount
                    If i = slashCount Then
                        searchCode = Mid(fullCode, 1, fullCode.Length)
                    Else
                        searchCode = Mid(fullCode, 1, InStr(fullCode, "/") - 1)
                        fullCode = Mid(fullCode, InStr(fullCode, "/") + 1, fullCode.Length)
                    End If

                    DBCmd = "SELECT FaceCart_SN,EyeCart_SN FROM " & applyProdDB & " WHERE Product_SN = '" & searchCode & "'"

                    If DBQueryReader(DBCmd) Then
                        If faceSerial <> Nothing And eyeSerial <> Nothing Then
                            faceSerial = faceSerial & "/" & sqlDataQuery(0)
                            eyeSerial = eyeSerial & "/" & sqlDataQuery(1)
                        Else
                            faceSerial = sqlDataQuery(0)
                            eyeSerial = sqlDataQuery(1)
                        End If
                    End If
                Next
            End If

            Dim query_product_serial As String = Nothing
            For i = prodDB.proface To item_product_max_index
                query_product_serial = query_product_serial & ", " & item_product_list(i).sales_packing_serial_col_nm & " = '" & item_product_list(i).serial & "'"
            Next

            DBCmd = "UPDATE " & applySalesDB &
                      " SET `Data` = NOW()" &
                          ", Main_Product_SN = '" & setSerial & "'" &
                          ", Main_FACE_SN = '" & faceSerial & "'" &
                          ", Main_EYE_SN = '" & eyeSerial & "'" &
                          query_product_serial &
                     " WHERE PackingCode = '" & packingCode & "'"

            If DBCommand(DBCmd) Then
                Return False
            End If

            errorOut("등록오류")
            errorGen("시리얼 번호 관련 데이터베이스 저장에 실패하였습니다.")
            Return True
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("오류가 발생하였습니다. :: " & ex.Message)
            Return True
        End Try

    End Function

    Private Function packingDBSave(packingCode As String) As Boolean
        countCommandFunc(countSaveList.normal)
        DBCmd = dbCountReg(applySalesDB, False)

        If DBCmd = "FAIL" Then
            errorOut("등록오류")
            errorGen("데이터베이스 명령어를 설정하는 과정에서 오류가 발생하였습니다.")
            Return True
        End If

        DBCmd = DBCmd & " WHERE PackingCode = '" & packingCode & "'"

        If DBCommand(DBCmd) = False Then
            errorOut("등록오류")
            errorGen("데이터베이스에 수량 등록을 하는 과정에서 오류가 발생하였습니다.")
            Return True
        End If

        Return False
    End Function

    Private Function packingDBSerial(packingCode As String) As Boolean
        DBCmd = updateDBSerial()

        If DBCmd = "FAIL" Then
            errorOut("등록오류")
            errorGen("시리얼 번호를 정리하는 과정에서 오류가 발생하였습니다.")
            Return True
        End If

        DBCmd = DBCmd & " WHERE PackingCode = '" & packingCode & "'"

        If DBCommand(DBCmd) Then

            DBCmd = "UPDATE " & applySalesDB & " SET `Data` = NOW() WHERE packingCode = '" & packingCode & "'"

            If DBCommand(DBCmd) Then
                Return False
            Else
                errorOut("등록오류")
                errorGen("데이터베이스에 입력 날짜를 입력하는 과정에서 오류가 발생하였습니다.")
                Return True
            End If

        End If

        errorOut("등록오류")
        errorGen("데이터베이스에 시리얼 번호를 입력하는 과정에서 오류가 발생하였습니다.")
        Return True
    End Function

    Private Function updateDBSerial() As String
        Try
            Dim commandDB As String = "UPDATE " & applySalesDB & " SET "

            For i = 1 To item_product_max_index

                If item_product_list(i).serial = "" Then
                    item_product_list(i).serial = "null"
                Else
                    item_product_list(i).serial = "'" & item_product_list(i).serial & "'"
                End If

                If i <> item_product_max_index Then
                    commandDB = commandDB & item_product_list(i).sales_packing_serial_col_nm & "=" & item_product_list(i).serial & ", "
                Else
                    commandDB = commandDB & item_product_list(i).sales_packing_serial_col_nm & "=" & item_product_list(i).serial
                End If
            Next

            Return commandDB
        Catch ex As Exception
            Return "FAIL"
        End Try
    End Function

    Private Function saveDBReg() As Boolean
        If saveDBInsert() Then
            Return True
        End If

        saveDBCount()

        If saveDBUpdate() Then
            Return True
        End If

        Return False
    End Function

    Private Function saveDBUpdate() As Boolean
        Dim nowToday As String = Format(Now, "yyyy") & "-" & Format(Now, "MM") & "-" & Format(Now, "dd")
        DBCmd = dbCountReg(applyCountDB, True)

        If DBCmd = "FAIL" Then
            errorOut("등록오류")
            errorGen("데이터베이스 명령어를 설정하는 과정에서 오류가 발생하였습니다.")
            Return True
        End If

        DBCmd = DBCmd & "," & countCommand(prodDB.packingCount) & " = '" & product_packing_cnt_list(prodDB.packingCount).db_count & "' WHERE DATETIME = '" & nowToday & "'"

        If DBCommand(DBCmd) = False Then
            errorOut("등록오류")
            errorGen("데이터베이스에 수량 등록을 하는 과정에서 오류가 발생하였습니다.")
            Return True
        End If

        Return False
    End Function

    Private Function dbCountReg(dbTable As String, saveType As Boolean) As String
        Try
            Dim dbStart As String = "UPDATE " & dbTable & " SET "
            Dim updateCom As String = Nothing
            Dim prodCount As Integer = 0

            For i = 1 To countCommand.Length - 1
                If countCommand(i) <> Nothing Then
                    If i <= item_product_max_index Then
                        prodCount = countSet(i, saveType, True)

                        If updateCom = Nothing Then
                            updateCom = countCommand(i) & " = " & "'" & prodCount & "'"
                        Else
                            updateCom = updateCom & "," & countCommand(i) & " = " & "'" & prodCount & "'"
                        End If
                    Else

                        prodCount = countSet(i, saveType, False)

                        If updateCom = Nothing Then
                            updateCom = countCommand(i) & " = " & "'" & prodCount & "'"
                        Else
                            updateCom = updateCom & "," & countCommand(i) & " = " & "'" & prodCount & "'"
                        End If
                    End If
                End If
            Next

            updateCom = dbStart & updateCom

            Return updateCom
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("데이터베이스에 저장할 카운트 작업이 제대로 진행되지 않았습니다.")
            Return "FAIL"
        End Try

    End Function

    Private Function countSet(cnt As Int16, saveType As Boolean, prodType As Boolean) As Integer  '' saveType : true - DBCount 저장 , false - DBSalePacking 저장 / prodType : true - prod 저장 , false - 구성품 저장
        Dim saveCount As Integer

        If saveType = True Then
            If prodType = True Then
                saveCount = product_packing_cnt_list(cnt).db_count
            Else
                saveCount = component_packing_cnt_list(cnt - product_packing_cnt_list.Length).db_count
            End If
        Else
            If prodType = True Then
                saveCount = item_product_list(cnt).cnt
            Else
                saveCount = item_component_list(cnt - item_product_list.Length).cnt
            End If
        End If

        Return saveCount
    End Function

    Private Sub saveDBCount()
        For i = 0 To item_product_max_index
            product_packing_cnt_list(i).db_count += item_product_list(i).cnt
        Next

        For i = 0 To item_component_max_index
            component_packing_cnt_list(i).db_count += item_component_list(i).cnt
        Next
    End Sub

    Private Function saveDBInsert() As Boolean
        Try
            Dim enumCount As Int16 = 0
            Dim nowToday As String = Format(Now, "yyyy") & "-" & Format(Now, "MM") & "-" & Format(Now, "dd")
            Dim reCnt As String = DBQueryScalar("SELECT NUMBER FROM " & applyCountDB & " WHERE DATETIME = '" & nowToday & "'")

            If reCnt = "False" Then
                errorOut("등록오류")
                errorGen("현재 날짜 수량을 불러올 수 없습니다.")
                Return True
            End If

            If reCnt = 0 Then
                DBCmd = "INSERT INTO " & applyCountDB & "(DATETIME) VALUE ('" & nowToday & "')"
                If DBCommand(DBCmd) Then
                    ''성공
                Else
                    errorOut("등록오류")
                    errorGen("데이터 베이스 수량 초기 입력을 진행할 수 없습니다.")
                    Return True
                End If
            End If

            If rdbMode1.Checked = True Then

                Dim query_packing_count As String = Nothing
                For i = 1 To item_product_max_index
                    If product_packing_cnt_list(i).packing_cnt_col_nm <> Nothing Then
                        query_packing_count = query_packing_count & ", " & product_packing_cnt_list(i).packing_cnt_col_nm
                    Else
                        query_packing_count = query_packing_count & ", 0"
                    End If
                Next
                For i = 0 To item_component_max_index
                    If component_packing_cnt_list(i).packing_cnt_col_nm <> Nothing Then
                        query_packing_count = query_packing_count & ", " & component_packing_cnt_list(i).packing_cnt_col_nm
                    Else
                        query_packing_count = query_packing_count & ", 0"
                    End If
                Next

                DBCmd = "SELECT PackingCount " & query_packing_count & " FROM " & applyCountDB & " WHERE DATETIME = '" & nowToday & "'"

                countCommandFunc(countSaveList.normal)
            Else
                If rdbAuto1.Checked = True Then

                    Dim query_packing_count As String = Nothing
                    For i = 1 To item_product_max_index
                        If product_packing_cnt_list(i).ap_packing_cnt_col_nm <> Nothing Then
                            query_packing_count = query_packing_count & ", " & product_packing_cnt_list(i).ap_packing_cnt_col_nm
                        Else
                            query_packing_count = query_packing_count & ", 0"
                        End If
                    Next
                    For i = 0 To item_component_max_index
                        If component_packing_cnt_list(i).ap_packing_cnt_col_nm <> Nothing Then
                            query_packing_count = query_packing_count & ", " & component_packing_cnt_list(i).ap_packing_cnt_col_nm
                        Else
                            query_packing_count = query_packing_count & ", 0"
                        End If
                    Next

                    DBCmd = "SELECT AutoPackCnt " & query_packing_count & " FROM " & applyCountDB & " WHERE DATETIME = '" & nowToday & "'"

                    countCommandFunc(countSaveList.autopack)
                Else

                    Dim query_packing_count As String = Nothing
                    For i = 1 To item_product_max_index
                        If product_packing_cnt_list(i).aw_packing_cnt_col_nm <> Nothing Then
                            query_packing_count = query_packing_count & ", " & product_packing_cnt_list(i).aw_packing_cnt_col_nm
                        Else
                            query_packing_count = query_packing_count & ", 0"
                        End If
                    Next
                    For i = 0 To item_component_max_index
                        If component_packing_cnt_list(i).aw_packing_cnt_col_nm <> Nothing Then
                            query_packing_count = query_packing_count & ", " & component_packing_cnt_list(i).aw_packing_cnt_col_nm
                        Else
                            query_packing_count = query_packing_count & ", 0"
                        End If
                    Next

                    DBCmd = "SELECT AutoWeightCnt " & query_packing_count & " FROM " & applyCountDB & " WHERE DATETIME = '" & nowToday & "'"

                    countCommandFunc(countSaveList.autoWeight)
                End If
            End If


            If DBQueryReader(DBCmd) Then
                For i = 0 To countCommand.Length - 1
                    If i <= item_product_max_index Then
                        product_packing_cnt_list(i).db_count = sqlDataQuery(i)
                    Else
                        enumCount = i - product_packing_cnt_list.Length
                        component_packing_cnt_list(enumCount).db_count = sqlDataQuery(i)
                    End If
                Next

                Return False
            Else
                errorOut("등록오류")
                errorGen("제품 수량에 대한 데이터를 불러올 수 없습니다.")
                Return True
            End If
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("수량 데이터 처리 과정에서 오류가 발생하였습니다.")
            Return True
        End Try
    End Function

    Private Function saveLogOrder(packingCode As String) As Boolean
        Try
            If modeSwitch = False Then
                Dim filePath, fileName, strData, saveData As String
                Dim saveDate As String = DateAndTime.Year(Now) & "-" & DateAndTime.Month(Now) & "-" & DateAndTime.Day(Now)
                Dim saveTime As String = DateAndTime.Hour(Now) & ":" & DateAndTime.Minute(Now) & ":" & DateAndTime.Second(Now)
                Dim startForm As String = "Order_Code,PackingDate,PackingTime,Orderer_Name,Phone_Number,Item_Code,Item_Name,Item_Count,Apply_Face,Apply_Eye,Invoice_Number,Packing_Code,Serial_Number"

                filePath = System.AppDomain.CurrentDomain.BaseDirectory & "\" & saveLogNameOrder
                dirUse(filePath)
                fileName = filePath & "\" & saveDate & ".csv"

                If orderCode = Nothing Or invoiceCode = Nothing Then
                    errorOut("정보값오류")
                    errorGen("전표번호 혹은 송장번호의 데이터가 잘못되었습니다.")
                    Return True
                End If

                For i = 0 To prodArray.GetLength(1) - 1
                    saveData = orderCode & "," & saveDate & "," & saveTime & "," & apiData(apiDataList.ordererName) & "," & apiData(apiDataList.phone) & "," & prodArray(itemCode.code, i) & "," & prodArray(itemCode.name, i) & "," & prodArray(itemCode.count, i) & "," & prodArray(itemCode.face, i) & "," & prodArray(itemCode.eye, i) & "," & invoiceCode & "," & packingCode & "," & prodArray(itemCode.serialNum, i)

                    If File.Exists(fileName) = True Then
                        strData = File.ReadAllText(fileName, Encoding.UTF8)

                        If strData = vbCrLf Or strData = Nothing Or strData = "" Then
                            strData = startForm & vbCrLf & saveData & vbCrLf
                        Else
                            strData = strData & saveData & vbCrLf
                        End If
                    Else
                        strData = startForm & vbCrLf & saveData & vbCrLf
                    End If

                    File.WriteAllText(fileName, strData, Encoding.UTF8)
                Next
            End If

            Return False

        Catch ex As Exception
            errorOut("등록오류")
            errorGen("LogData Order save fail!" & ex.Message)
            Return True
        End Try

    End Function

    Private Function createStartForm(target As String) As String
        Dim sb As New StringBuilder()
        If target = saveLogNamePack Then
            sb.Append("PackingTime")
            sb.Append(",PackingCode")
            sb.Append(",Packing_Count")
            For i = 1 To item_product_max_index
                sb.Append("," & item_product_list(i).sales_packing_cnt_col_nm)
                sb.Append("," & item_product_list(i).sales_packing_serial_col_nm)
            Next

        ElseIf target = saveCountName Then
            sb.Append("TestDate")
            sb.Append(",Packing_Count")
            For i = 1 To item_product_max_index
                sb.Append("," & product_packing_cnt_list(i).packing_cnt_col_nm)
            Next

        End If

        For i = 0 To item_component_max_index
            Dim item_name As String = "N/A"
            DBCmd = "SELECT ItemName FROM " & applyClistDB & " WHERE ProdCode = '" & i & "' LIMIT 1"

            If DBQueryReader(DBCmd) Then
                item_name = sqlDataQuery(0)
            End If

            item_name = "," & Replace(item_name, ",", "_")
            sb.Append(item_name)
        Next

        Return sb.ToString()
    End Function

    Private Function saveLogData(packingCode As String) As Boolean
        Try
            Dim filePath, fileName, strData As String
            Dim saveDate As String = DateAndTime.Year(Now) & "-" & DateAndTime.Month(Now) & "-" & DateAndTime.Day(Now)
            Dim saveTime As String = DateAndTime.Hour(Now) & ":" & DateAndTime.Minute(Now) & ":" & DateAndTime.Second(Now)
            Dim startForm As String = createStartForm(saveLogNamePack)

            filePath = System.AppDomain.CurrentDomain.BaseDirectory & "\" & saveLogNamePack
            dirUse(filePath)
            fileName = filePath & "\" & saveDate & ".csv"

            Dim saveData As String = saveTime & "," & packingCode & "," & logDataSet()

            If saveData = "FAIL" Then
                errorOut("저장오류")
                errorGen("LogDataPacking에 저장할 데이터가 잘못되었습니다.")
                Return True
            End If

            If File.Exists(fileName) = True Then
                strData = File.ReadAllText(fileName, Encoding.UTF8)

                If strData = vbCrLf Or strData = Nothing Or strData = "" Then
                    strData = startForm & vbCrLf & saveData & vbCrLf
                Else
                    strData = strData & saveData & vbCrLf
                End If
            Else
                strData = startForm & vbCrLf & saveData & vbCrLf
            End If

            File.WriteAllText(fileName, strData, Encoding.UTF8)

            Return False
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("LogData Packing save fail!" & ex.Message)
            Return True
        End Try

    End Function

    Private Function logDataSet() As String
        Try
            Dim saveData As String = Nothing

            For i = 0 To item_product_max_index

                saveData = saveLocalData(saveData, item_product_list(i).cnt)

                If i <> prodDB.packingCount Then
                    saveData = saveLocalData(saveData, item_product_list(i).serial)
                End If

            Next

            For i = 0 To item_component_max_index
                saveData = saveLocalData(saveData, item_component_list(i).cnt)
            Next

            Return saveData

        Catch ex As Exception
            errorOut("등록오류")
            errorGen("LogData를 정리하는 도중 오류가 발생하였습니다.")
            Return "FAIL"
        End Try
    End Function

    Private Function saveLocalFile() As Boolean

        Try
            Dim filePath, fileName, saveData, strData As String

            Dim saveYear As String = DateAndTime.Year(Now)
            Dim saveMonth As String = Format(Now, "MM")
            Dim saveDay As String = Format(Now, "dd")
            Dim saveDate As String = saveYear & "-" & saveMonth & "-" & saveDay
            Dim StartForm As String = createStartForm(saveCountName)

            filePath = System.AppDomain.CurrentDomain.BaseDirectory & "\" & saveCountName
            dirUse(filePath)
            fileName = filePath & "\" & saveYear & "_" & saveMonth & ".csv"

            saveData = saveLocalCount()

            saveData = saveDate & "," & saveData

            If saveData = "N" Then
                errorOut("저장오류")
                errorGen("로컬 세이브 데이터를 처리하는 도중 오류가 발생하였습니다.")
                Return True
            End If

            If File.Exists(fileName) = True Then
                strData = File.ReadAllText(fileName, Encoding.UTF8)

                If strData = vbCrLf Or strData = Nothing Or strData = "" Then
                    strData = StartForm & vbCrLf & saveData & vbCrLf

                Else
                    If UBound(Split(strData, saveDate)) > 0 Then
                        strData = Mid(strData, 1, InStr(strData, saveDate) - 1)
                        strData = strData & saveData & vbCrLf
                    Else
                        strData = strData & saveData & vbCrLf
                    End If

                End If
            Else
                strData = StartForm & vbCrLf & saveData & vbCrLf
            End If

            File.WriteAllText(fileName, strData, Encoding.UTF8)

            Return False
        Catch ex As Exception
            errorOut("저장오류")
            errorGen("Local Count save fail!" & Err.Description)
            Return True
        End Try

    End Function

    Private Function saveLocalCount() As String
        Try
            Dim strData As String = Nothing
            For i = 0 To item_product_max_index
                product_packing_cnt_list(i).com_count += item_product_list(i).cnt
                strData = saveLocalData(strData, product_packing_cnt_list(i).com_count)
            Next

            For i = 0 To item_component_max_index
                component_packing_cnt_list(i).com_count += item_component_list(i).cnt
                strData = saveLocalData(strData, component_packing_cnt_list(i).com_count)
            Next

            Return strData
        Catch ex As Exception
            Return "N"
        End Try

    End Function

    Private Function saveLocalData(str As String, data As String) As String
        If str = Nothing Then
            Return data
        Else
            Return str & "," & data
        End If
    End Function

    Private Function saveNowCount() As Boolean
        clearNowCount()

        For i = 0 To prodArray.GetLength(1) - 1
            If packingCountset(prodArray(itemCode.type, i), prodArray(itemCode.prodCode, i), prodArray(itemCode.count, i), prodArray(itemCode.serialNum, i)) Then
                Return True    ''실패

            End If
        Next

        item_product_list(prodDB.packingCount).cnt += 1

        Return False
    End Function

    Private Sub clearNowCount()
        For i = 0 To item_product_max_index
            item_product_list(i).cnt = "0"
            item_product_list(i).serial = Nothing
        Next

        For i = 0 To item_component_max_index
            item_component_list(i).cnt = "0"
        Next
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs)
        invForm.ShowDialog()
    End Sub


    Private Sub dirUse(filePath As String)
        If Dir(filePath, vbDirectory) = "" Then
            MkDir(filePath)
        End If
    End Sub

    Private Function weightRun() As Boolean
        Try
            If ckbWeight.Checked = True Then

                If rdbAuto2.Checked = False Then
                    If weightSelect() Then
                        Return False
                    End If
                End If

                If weightSum = -1 Then
                    errorOut("무게오류")
                    errorGen("무게 데이터가 존재하지 않습니다.")
                    Return False
                End If

                If rdbWeightAuto.Checked = True Then
                    weightOkNg = False
                    weightStart = True

                    If weightForm.ShowDialog() = DialogResult.OK Then
                        Return True
                    Else
                        errorOut("무게불일치")
                        Return False
                    End If

                Else
                    weightForm.ShowDialog()
                    If weightOkNg = True Then
                        Return True
                    Else
                        errorOut("무게오류")
                        errorGen("무게 데이터가 일치하지 않습니다. 제품을 확인하여 주십시오.")
                        Return False
                    End If
                End If
            Else
                weightResult = 0
                Return True
            End If

        Catch ex As Exception
            errorOut("무게오류")
            errorGen("무게 측정을 실행하는 도중 오류가 발생하였습니다" & vbCrLf & ex.Message)
            Return False
        End Try
    End Function

    Private Function weightSelect() As Boolean
        Dim dbFrom As String = Nothing

        Try

            weightSum = 0

            For i = 0 To prodArray.GetLength(1) - 1
                If prodArray(itemCode.type, i) = 0 Then
                    dbFrom = applyPlistDB
                Else
                    dbFrom = applyClistDB
                End If

                DBCmd = "SELECT Weight FROM " & dbFrom & " WHERE ItemCode = '" & prodArray(itemCode.code, i) & "'"
                Dim dbResult As String = DBQueryScalar(DBCmd)

                If dbResult = "False" Then
                    errorOut("무게오류")
                    errorGen("제품 데이터 중 무게 데이터를 알 수 없는 데이터가 존재합니다. 관리자에게 문의하여 주십시오.")
                    Return True
                End If

                Dim weightNow As Int16 = Val(dbResult) * Val(prodArray(itemCode.count, i))

                weightSum = weightSum + weightNow

            Next

            Return False

        Catch ex As Exception
            errorOut("무게오류")
            errorGen("무게 데이터를 산출하는 도중 오류가 발생하였습니다." & vbCrLf & ex.Message)
            Return True
        End Try

    End Function

    Private Function dbRegType(choiceNum As String) As Boolean
        If ckbNewSave.Checked = True Then
            If dbRegist(choiceNum) Then
                Return False
            Else
                Return True
            End If
        Else
            If dbPackNumReg(choiceNum) Then
                If orderSave(choiceNum) Then
                    Return False
                Else
                    failDataReset(choiceNum)
                    Return True
                End If
            Else
                Return True
            End If
        End If
    End Function

    Private Sub failDataReset(packData As String)
        orderFailBack(packData)
        packFailBack(packData)
    End Sub

    Private Sub orderFailBack(packnum As String)
        DBCmd = "SELECT COUNT(Packing_Code) FROM " & applyOrderDB & " WHERE Packing_Code = '" & packnum & "'"

        Dim failResult As String = DBQueryScalar(DBCmd)

        If failResult = "False" Then
            Exit Sub
        End If

        If failResult > 0 Then
            DBCmd = "UPDATE " & applyOrderDB & " SET Invoice_Number = NULL, Packing_Code = NULL, Serial_Number = NULL, release_state = NULL WHERE Packing_Code = '" & packnum & "'"
            If DBCommand(DBCmd) = False Then
                MsgBox("삭제하지 못했습니다.", vbCritical)
            End If
        End If

    End Sub

    Private Sub packFailBack(packNum As String)

        DBCmd = "SELECT COUNT(NUMBER) from " & applySalesDB & " WHERE PackingCode = '" & packNum & "'"

        Dim failResult As String = DBQueryScalar(DBCmd)

        If failResult = "False" Then
            Exit Sub
        End If

        If failResult > 0 Then
            DBCmd = "DELETE FROM " & applySalesDB & " WHERE PackingCode = '" & packNum & "'"
            If DBCommand(DBCmd) = False Then
                MsgBox("삭제하지 못했습니다.", vbCritical)
            End If
        End If
    End Sub

    Private Function orderSave(choiceNum As String) As Boolean
        Try
            Dim nowToday As String = Format(Now, "yyyy") & "-" & Format(Now, "MM") & "-" & Format(Now, "dd")
            Dim invParsing As String

            If invoiceCode = String.Empty Then
                invParsing = "NULL"
            Else
                invParsing = Chr(39) & invoiceCode & Chr(39)
            End If

            If modeSwitch = False Then

                If loginForm.loginUse = True And ckbAPIuse.Checked = True Then
                    apiData(apiDataList.regData) = Mid(apiData(apiDataList.regData), 1, InStr(apiData(apiDataList.regData), " ") - 1)

                    For i = 0 To prodArray.GetLength(1) - 1
                        DBCmd = "INSERT INTO " & applyOrderDB & "(DATETIME,Order_Code,DATE,Account_Code,Account_Name,Orderer_Code,Orderer_Name,Receiver_Name,Phone_Number,ZipCode,Address,Shipment_Date,Item_Code,Item_Name,Item_Count,Apply_Face,Apply_Eye,Invoice_Number,Packing_Code,Serial_Number,release_state) VALUE(Now(),'" & orderCode & "','" & apiData(apiDataList.regData) & "','" & apiData(apiDataList.accountCode) & "','" & apiData(apiDataList.accountName) & "','" & apiData(apiDataList.ordererCode) & "','" & apiData(apiDataList.ordererName) & "','" & apiData(apiDataList.ordererName) & "','" & apiData(apiDataList.phone) & "','" & apiData(apiDataList.zip) & "','" & apiData(apiDataList.address) & "','" & nowToday & "','" & prodArray(itemCode.code, i) & "','" & prodArray(itemCode.name, i) & "','" & prodArray(itemCode.count, i) & "','" & prodArray(itemCode.face, i) & "','" & prodArray(itemCode.eye, i) & "'," & invParsing & ",'" & choiceNum & "','" & prodArray(itemCode.serialNum, i) & "','release')"
                        If DBCommand(DBCmd) = False Then
                            errorOut("등록오류")
                            errorGen("전표 데이터 등록 도중 오류가 발생하였습니다.")
                            Return False
                        End If
                    Next

                    '         If apiSerialData() Then              20241122 수정
                    '        Return False                    20241122 수정
                    ' End If

                    If mesDataReg() Then
                        Return False
                    End If

                Else
                    If setCodeUse = True Then

                        If setCodeInsert() Then


                            For i = 0 To prodArray.GetLength(1) - 1
                                DBCmd = "SELECT COUNT(Order_Code) FROM " & applyOrderDB & " WHERE Order_Code = '" & orderCode & "' AND Item_Code = '" & prodArray(itemCode.code, i) & "'"

                                Dim rowStr As String = DBQueryScalar(DBCmd)

                                If rowStr = "False" Then
                                    errorOut("데이터오류")
                                    errorGen("세트 코드에 대한 데이터를 저장하는 도중 오류가 발생하였습니다.")
                                    Return False
                                End If

                                If rowStr = 0 Then
                                    DBCmd = "INSERT INTO " & applyOrderDB & "(DATETIME,Order_Code,DATE,Account_Code,Account_Name,Charge_Code,Warehouse,Orderer_Code,Orderer_Name,Country,Receiver_Name,Phone_Number,ZipCode,Address,Refer,Shipment_Date,Item_Code,Item_Name,Item_Count,Apply_Face,Apply_Eye,Invoice_Number,Packing_Code,Serial_Number,release_state) VALUE(Now(),'" & orderCode & "'," & defaultData(defaultList.regDate) & "," & defaultData(defaultList.accCode) & "," & defaultData(defaultList.accName) & "," & defaultData(defaultList.chrCode) & "," & defaultData(defaultList.warehouse) & "," & defaultData(defaultList.ordCode) & "," & defaultData(defaultList.ordName) & "," & defaultData(defaultList.country) & "," & defaultData(defaultList.recName) & "," & defaultData(defaultList.phone) & "," & defaultData(defaultList.zip) & "," & defaultData(defaultList.address) & "," & defaultData(defaultList.refer) & ",'" & nowToday & "','" & prodArray(itemCode.code, i) & "','" & prodArray(itemCode.name, i) & "','" & prodArray(itemCode.count, i) & "','" & prodArray(itemCode.face, i) & "','" & prodArray(itemCode.eye, i) & "'," & invParsing & ",'" & choiceNum & "','" & prodArray(itemCode.serialNum, i) & "','release')"
                                Else
                                    DBCmd = "UPDATE " & applyOrderDB & " SET Shipment_Date = '" & nowToday & "', Item_Count = '" & prodArray(itemCode.count, i) & "', Invoice_Number = " & invParsing & ", Packing_Code='" & choiceNum & "',Serial_Number='" & prodArray(itemCode.serialNum, i) & "',release_state='release' WHERE Order_Code = '" & orderCode & "' AND Item_Code = '" & prodArray(itemCode.code, i) & "'"
                                End If

                                If DBCommand(DBCmd) = False Then
                                    errorOut("데이터오류")
                                    errorGen("세트 코드에 대한 데이터를 저장하는 도중 오류가 발생하였습니다.")
                                    Return False
                                End If

                            Next

                            If setCodeDelete() Then
                                Return True
                            Else
                                Return False
                            End If

                        Else
                            Return False
                        End If

                    Else
                        For i = 0 To prodArray.GetLength(1) - 1
                            DBCmd = "UPDATE " & applyOrderDB & " SET Shipment_Date = '" & nowToday & "', Invoice_Number = " & invParsing & ", Packing_Code='" & choiceNum & "',Serial_Number='" & prodArray(itemCode.serialNum, i) & "',release_state='release' WHERE Order_Code = '" & orderCode & "' AND Item_Code = '" & prodArray(itemCode.code, i) & "'"
                            If DBCommand(DBCmd) = False Then
                                errorOut("등록오류")
                                errorGen("전표 데이터 등록 도중 오류가 발생하였습니다.")
                                Return False
                            End If
                        Next
                    End If
                End If
            End If

            Return True
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("오류가 발생하였습니다. ::" & ex.Message)
            Return False
        End Try

    End Function

    Private Function setCodeDelete() As Boolean
        DBCmd = "DELETE FROM " & applyOrderDB & " WHERE Order_Code = '" & orderCode & "' AND Item_Code LIKE 'PK%'"
        If DBCommand(DBCmd) Then
            Return True
        Else
            errorOut("삭제오류")
            errorGen("세트 코드 삭제 도중 오류가 발생하였습니다.")
            Return False
        End If
    End Function

    Private Function setCodeInsert() As Boolean
        For i = 0 To defaultList.refer
            defaultData(i) = String.Empty
        Next

        DBCmd = "SELECT DATE,Account_Code,Account_Name,Charge_Code,Warehouse,Orderer_Code,Orderer_Name,Country,Receiver_Name,Phone_Number,ZipCode,Address,Refer FROM " & applyOrderDB & " WHERE Order_Code = '" & orderCode & "' GROUP BY Order_Code"

        If DBQueryReader(DBCmd) Then
            For i = 0 To sqlDataQuery.Length - 1
                If sqlDataQuery(i).ToString = "0" Then
                    defaultData(i) = "NULL"
                Else
                    defaultData(i) = Chr(39) & sqlDataQuery(i) & Chr(39)
                End If
            Next

            Return True
        Else
            errorOut("등록오류")
            errorGen("구매 고객 기본 데이터를 불러오는 도중 오류가 발생하였습니다.")
            Return False
        End If
    End Function

    Private Function mesDataReg() As Boolean
        Dim jsonData, apiResult As String

        If setCodeUse = True Then

            For i = 0 To apiArray.GetLength(1) - 1
                If apiArray(itemCode.type, i) = 0 Then

                    If invoiceCode = "NULL" Then
                        jsonData = "{""expectedOutCount"":" & apiArray(itemCode.count, i) & ",""serialNumber"":""" & apiArray(itemCode.serialNum, i) & """}"
                    Else
                        jsonData = "{""expectedOutCount"":" & apiArray(itemCode.count, i) & ",""serialNumber"":""" & apiArray(itemCode.serialNum, i) & """,""invoiceNumber"":""" & invoiceCode & """}"
                    End If

                Else
                    If invoiceCode = "NULL" Then
                        jsonData = "{""expectedOutCount"":" & apiArray(itemCode.count, i) & "}"
                    Else
                        jsonData = "{""expectedOutCount"":" & apiArray(itemCode.count, i) & ",""invoiceNumber"":""" & invoiceCode & """}"
                    End If

                End If

                apiResult = apiRequest_PUT(jsonData, apiArray(itemCode.id, i))

                If apiResult = "-1" Then
                    errorOut("MES오류")
                    errorGen("MES에 해당 데이터가 존재하지 않습니다. 확인하여 주십시오.")
                    Return True
                End If
            Next

        Else

            For i = 0 To prodArray.GetLength(1) - 1
                If prodArray(itemCode.type, i) = 0 Then

                    If invoiceCode = "NULL" Then
                        jsonData = "{""expectedOutCount"":" & prodArray(itemCode.count, i) & ",""serialNumber"":""" & prodArray(itemCode.serialNum, i) & """}"
                    Else
                        jsonData = "{""expectedOutCount"":" & prodArray(itemCode.count, i) & ",""serialNumber"":""" & prodArray(itemCode.serialNum, i) & """,""invoiceNumber"":""" & invoiceCode & """}"
                    End If

                Else
                    If invoiceCode = "NULL" Then
                        jsonData = "{""expectedOutCount"":" & prodArray(itemCode.count, i) & "}"
                    Else
                        jsonData = "{""expectedOutCount"":" & prodArray(itemCode.count, i) & ",""invoiceNumber"":""" & invoiceCode & """}"
                    End If

                End If

                apiResult = apiRequest_PUT(jsonData, prodArray(itemCode.id, i))

                If apiResult = "-1" Then
                    errorOut("MES오류")
                    errorGen("MES에 해당 데이터가 존재하지 않습니다. 확인하여 주십시오.")
                    Return True
                End If
            Next
        End If

        Return False
    End Function

    ' Private Function apiSerialData() As Boolean     20241122 수정
    '     Try
    'If apiArray Is Nothing Then
    'Throw New Exception("apiArray가 초기화되지 않았습니다!")
    'End If
    '
    'Dim serialArr(prodArray.GetLength(1) - 1) As String

    'For i = 0 To prodArray.GetLength(1) - 1
    '           serialArr(i) = prodArray(itemCode.serialNum, i)
    'Next

    'For api = 0 To apiArray.GetLength(1) - 1
    'For chk = 0 To prodArray.GetLength(1) - 1

    'If apiArray(itemCode.code, api) = prodArray(itemCode.code, chk) Then
    '                   serialArr(chk) = apiItemReg(serialArr(chk), chk, api)
    'Else
    'If InStr(prodArray(itemCode.pkCode, chk), apiArray(itemCode.code, api)) > 0 Then
    '                       serialArr(chk) = apiItemReg(serialArr(chk), chk, api)
    'End If
    'End If
    '
    'If serialArr(chk) = "FAIL" Then
    'Return True
    'End If

    'Next
    'Next

    'Return False
    'Catch ex As Exception
    '       errorOut("세트오류")
    '       errorGen("오류 발생!! :: " & ex.Message)
    'Return True
    'End Try
    ' End Function

    Private Function apiItemReg(serStr As String, chkNum As Int16, apiNum As Int16) As String
        Try
            If prodArray(itemCode.type, chkNum) = 0 Then
                Dim slashSet As Int16 = UBound(Split(serStr, "/"))
                apiArray(itemCode.type, apiNum) = 0
                For i = 0 To apiArray(itemCode.count, apiNum) - 1
                    If i = slashSet Then
                        If apiArray(itemCode.serialNum, apiNum) = String.Empty Then
                            apiArray(itemCode.serialNum, apiNum) = serStr
                        Else
                            apiArray(itemCode.serialNum, apiNum) = apiArray(itemCode.serialNum, apiNum) & "/" & serStr
                        End If
                    Else
                        Dim serialData As String = Mid(serStr, 1, InStr(serStr, "/") - 1)
                        serStr = Mid(serStr, InStr(serStr, "/") + 1, serStr.Length)

                        If apiArray(itemCode.serialNum, apiNum) = String.Empty Then
                            apiArray(itemCode.serialNum, apiNum) = serialData
                        Else
                            apiArray(itemCode.serialNum, apiNum) = apiArray(itemCode.serialNum, apiNum) & "/" & serialData
                        End If
                    End If
                Next
            End If

            If serStr = String.Empty Then
                Return String.Empty
            End If

            Return serStr
        Catch ex As Exception
            errorOut("세트오류")
            errorGen("오류 발생!! :: " & ex.Message)
            Return "FAIL"
        End Try
    End Function

    Private Function mesDataReg(num As Int16) As Boolean
        Dim jsonData, apiResult As String

        If prodArray(itemCode.type, num) = 0 Then

            If invoiceCode = "NULL" Then
                jsonData = "{""expectedOutCount"":" & prodArray(itemCode.count, num) & ",""serialNumber"":""" & prodArray(itemCode.serialNum, num) & """}"
            Else
                jsonData = "{""expectedOutCount"":" & prodArray(itemCode.count, num) & ",""serialNumber"":""" & prodArray(itemCode.serialNum, num) & """,""invoiceNumber"":""" & invoiceCode & """}"
            End If

        Else
            If invoiceCode = "NULL" Then
                jsonData = "{""expectedOutCount"":" & prodArray(itemCode.count, num) & "}"
            Else
                jsonData = "{""expectedOutCount"":" & prodArray(itemCode.count, num) & ",""invoiceNumber"":""" & invoiceCode & """}"
            End If

        End If

        apiResult = apiRequest_PUT(jsonData, prodArray(itemCode.id, num))

        If apiResult = "-1" Then
            errorOut("MES오류")
            errorGen("MES에 해당 데이터가 존재하지 않습니다. 확인하여 주십시오.")
            Return True
        End If

        Return False
    End Function

    'Private Function mesDataPut(arrayNum As Int16) As Boolean
    '    Dim jsonData, outID, apiResult As String

    '    outID = item_set(itemCode.id, arrayNum)

    '    If item_set(8, arrayNum) = 1 Then
    '        jsonData = "{""expectedOutCount"":" & item_set(itemCode.expectedCount, arrayNum) & ",""serialNumber"":""" & item_set(itemCode.serialNum, arrayNum) & """}"
    '    Else
    '        jsonData = "{""expectedOutCount"":" & item_set(itemCode.expectedCount, arrayNum) & "}"
    '    End If

    '    apiResult = apiRequest_PUT(jsonData, outID)

    '    If apiResult = "-1" Then
    '        Return False
    '    End If

    '    Return True
    'End Function

    Private Function dbPackNumCompare(choiceNum As String) As Boolean
        DBCmd = "SELECT COUNT(PackingCode) FROM " & applySalesDB & " WHERE PackingCode = '" & choiceNum & "'"

        If Val(DBQueryScalar(DBCmd)) > 0 Then
            errorOut("등록오류")
            errorGen("중복된 패킹 코드가 존재합니다.")
            Return True
        End If

        Return False
    End Function

    Private Function dbPackNumReg(choiceNum As String) As Boolean
        If rdbMode2.Checked = True Then
            DBCmd = "INSERT INTO " & applySalesDB & "(PackingCode,TargetWeight,ConnectPack) VALUE('" & choiceNum & "','" & weightSum & "','" & SaveOrderName & "')"
        Else
            DBCmd = "INSERT INTO " & applySalesDB & "(PackingCode,Weight) VALUE('" & choiceNum & "','" & weightResult & "')"
        End If

        If DBCommand(DBCmd) Then
            Return True
        Else
            errorOut("등록오류")
            errorGen("패킹 데이터를 입력하는 과정에서 오류가 발생하였습니다.")
            Return False
        End If
    End Function

    Private Function dbRegist(choiceNum As String) As Boolean
        Try
            Dim nowDate As String = Format(Now, "yyyy") & "-" & Format(Now, "MM") & "-" & Format(Now, "dd")
            Dim nowTime As String = Format(Now, "HH") & ":" & Format(Now, "mm") & ":" & Format(Now, "ss")

            DBCmd = "INSERT INTO " & applyPackDB & "(PackingCode,PackingDate,PackingTime,Worker,Weight) VALUE('" & choiceNum & "','" & nowDate & "','" & nowTime & "','" & useUserID & "','" & weightResult & "')"
            If DBCommand(DBCmd) = False Then
                errorOut("등록오류")
                errorGen("초반 데이터를 등록하는 과정에서 오류가 발생하였습니다.")
                Return False
            End If

            For i = 0 To prodArray.GetLength(1) - 1
                DBCmd = "INSERT INTO " & applyHistoryDB & "(PackingCode,ItemCode,ItemCount,SerialNumber) VALUE('" & choiceNum & "','" & prodArray(itemCode.code, i) & "','" & prodArray(itemCode.count, i) & "','" & prodArray(itemCode.serialNum, i) & "')"
                If DBCommand(DBCmd) = False Then
                    errorOut("등록오류")
                    errorGen("데이터 내역을 등록하는 과정에서 오류가 발생하였습니다.")
                    Return False
                End If
            Next

            txbPacking.Text = choiceNum
            txbPacking.BackColor = Color.Moccasin
            Return True
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("데이터를 등록하는 과정에서 오류가 발생하였습니다." & vbCrLf & ex.Message)
            Return False
        End Try

    End Function

    Private Function packingCode_Choice() As String
        Try
            Dim choiceData As String = Nothing
            Dim selectData As String = Nothing

            For i = 0 To prodArray.GetLength(1) - 1
                Dim codeData As String = prodArray(itemCode.serialNum, i)
                If codeData <> Nothing Then
                    Dim slashCount As Int16 = UBound(Split(codeData, "/"))
                    For n = 0 To slashCount
                        If slashCount = 0 Then
                            selectData = codeData
                        Else
                            If InStr(codeData, "/") > 0 Then
                                selectData = Mid(codeData, 1, InStr(codeData, "/") - 1)
                                codeData = Mid(codeData, InStr(codeData, "/") + 1, codeData.Length)
                            Else
                                selectData = codeData
                            End If
                        End If

                        If choiceData <> Nothing Then
                            If choiceData > selectData Then
                                choiceData = selectData
                            End If
                        Else
                            choiceData = selectData
                        End If
                    Next
                End If
            Next

            If choiceData = Nothing Then
                Return orderCode
            Else
                If choiceData.Length = oldProdCodeLength Or choiceData.Length = newProdCodeLength Then
                    Return choiceData
                Else
                    Return orderCode
                End If
            End If

        Catch ex As Exception
            errorOut("등록오류")
            errorGen("패킹 번호를 선정하는 과정에서 문제가 발생하였습니다." & vbCrLf & ex.Message)
            Return "False"
        End Try

    End Function

    Private Function stateComCompare(comCode As String) As Boolean
        Const regType As Int16 = 1
        Try
            For i = 0 To prodArray.GetLength(1) - 1
                If InStr(comCode, prodArray(itemCode.code, i)) > 0 Then
                    If prodArray(itemCode.count, i) = prodArray(itemCode.chkCount, i) Then
                        MsgBox("더이상 포장할 필요가 없는 제품입니다.", vbCritical)
                        Return False
                    End If

                    prodArray(itemCode.chkCount, i) += 1
                    tgtFullCount += 1
                    txbArrayList(i, txbNameList.targetCount).Text = prodArray(itemCode.chkCount, i)

                    If prodArray(itemCode.count, i) = prodArray(itemCode.chkCount, i) Then
                        txbArrayList(i, txbNameList.name).BackColor = Color.Green
                        txbArrayList(i, txbNameList.nowCount).BackColor = Color.Green
                        txbArrayList(i, txbNameList.targetCount).BackColor = Color.Green

                        txbArrayList(i, txbNameList.name).ForeColor = Color.Black
                        txbArrayList(i, txbNameList.nowCount).ForeColor = Color.Black
                        txbArrayList(i, txbNameList.targetCount).ForeColor = Color.Black
                    Else
                        txbArrayList(i, txbNameList.targetCount).ForeColor = Color.Blue
                    End If

                    prodArray(itemCode.serialNum, i) = playCode

                    prodArray(itemCode.type, i) = regType
                    prodArray(itemCode.prodCode, i) = setInfo(setInfoList.prodCode)


                    Return True
                End If
            Next

            errorOut("등록오류")
            errorGen("포장 품목에 존재하지 않는 제품입니다.")
            Return False
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("포장 품목 확인 중 오류가 발생하였습니다." & vbCrLf & ex.Message)
            Return False
        End Try
    End Function

    Private Function comCodeSearch() As String
        Try
            Dim comCode As String = Nothing
            DBCmd = "SELECT ItemCode FROM " & applyClistDB & " WHERE Barcode = '" & playCode & "'"

            If DBQueryReader(DBCmd) Then
                For i = 0 To sqlDataQuery.Length - 1
                    If comCode = Nothing Then
                        comCode = sqlDataQuery(i)
                    Else
                        comCode = comCode & "/" & sqlDataQuery(i)
                    End If
                Next
            Else
                errorOut("등록오류")
                errorGen("해당 품목에 대한 데이터가 존재하지 않습니다. 바코드를 확인하여 주십시오.")
                Return "False"
            End If

            Return comCode

        Catch ex As Exception
            errorOut("등록오류")
            errorGen("제품 리스트를 설정하는 과정에서 오류가 발생하였습니다." & vbCrLf & ex.Message)
            Return "False"
        End Try

    End Function

    Private Function stateScanCompare() As Boolean
        Const regType As Int16 = 0
        Try
            For i = 0 To prodArray.GetLength(1) - 1
                If donePkList.Contains(i) Then Continue For
                For n = 0 To scanCode.Length - 1

                    If prodArray(itemCode.code, i) = scanCode(n) Then   '' instr 에서 식으로 변경

                        'If prodArray(itemCode.count, i) = prodArray(itemCode.chkCount, i) Then
                        '    errorOut("등록오류")
                        '    errorGen("더이상 포장할 필요가 없는 제품입니다.")
                        '    Return False
                        'End If

                        If prodScanCompare(i) Then
                            errorOut("등록오류")
                            errorGen("샷 수가 맞지 않습니다.")
                            Return False
                        End If

                        prodArray(itemCode.chkCount, i) += 1
                        tgtFullCount += 1
                        txbArrayList(i, txbNameList.targetCount).Text = prodArray(itemCode.chkCount, i)

                        If prodArray(itemCode.count, i) = prodArray(itemCode.chkCount, i) Then
                            txbArrayList(i, txbNameList.name).BackColor = Color.Green
                            txbArrayList(i, txbNameList.nowCount).BackColor = Color.Green
                            txbArrayList(i, txbNameList.targetCount).BackColor = Color.Green

                            txbArrayList(i, txbNameList.name).ForeColor = Color.Black
                            txbArrayList(i, txbNameList.nowCount).ForeColor = Color.Black
                            txbArrayList(i, txbNameList.targetCount).ForeColor = Color.Black
                            donePkList.Add(i)
                        Else
                            txbArrayList(i, txbNameList.targetCount).ForeColor = Color.Blue
                        End If

                        If prodArray(itemCode.serialNum, i) = Nothing Then
                            prodArray(itemCode.serialNum, i) = playCode
                        Else
                            If Not playCode.Length = lowProdCodeLength Then
                                prodArray(itemCode.serialNum, i) = prodArray(itemCode.serialNum, i) & "/" & playCode
                            End If
                        End If

                        prodArray(itemCode.type, i) = regType
                        prodArray(itemCode.prodCode, i) = setInfo(setInfoList.prodCode)

                        If ckbPrinter.Checked = True Then

                            Dim SerialCount As Integer = printSerial.Length

                            If SerialCount > 1 Or printSerial(0) <> "" Then
                                ReDim Preserve printSerial(SerialCount)
                                printSerial(SerialCount) = playCode
                            Else
                                printSerial(SerialCount - 1) = playCode
                            End If

                        End If

                        Return True
                    End If
                Next
            Next

            For Each scanData As String In scanCode
                For Each b As Integer In donePkList
                    If prodArray(itemCode.code, b) = scanData Then
                        errorOut("등록오류")
                        errorGen("더이상 포장할 필요가 없는 제품입니다.")
                        Return False
                    End If
                Next
            Next
            errorOut("등록오류")
            errorGen("포장 품목에 존재하지 않는 제품입니다.")
            Return False
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("포장 품목 확인 중 오류가 발생하였습니다." & ex.Message)
            Return False
        End Try

    End Function

    Private Function prodScanCompare(prodNum As Int16) As Boolean
        If prodArray(itemCode.face, prodNum) = setFace And prodArray(itemCode.eye, prodNum) = setEye Then
            Return False
        Else
            Return True
        End If
    End Function

    Private Function codeParsing() As String

        Try
            If playCode.Length >= stateLength And playCode.Length <> newProdCodeLength Then

                setCodeUse = False


                If modeSwitch = True And rdbMode2.Checked = True And rdbBef.Checked = True Then
                    Return "MODEERROR"
                Else
                    nowFullCount = 0
                    If InStr(1, playCode, codeState(codeStateList.ERP)) > 0 Then
                        Return "ERPORDER"
                    ElseIf InStr(1, playCode, codeState(codeStateList.MES)) > 0 Then
                        Return "MESORDER"
                    Else
                        Return "NONORDER"
                    End If
                End If
            Else
                If orderSwitch = True Then

                    If playCode.Length = oldProdCodeLength Or playCode.Length = newProdCodeLength Or lowProdList.Contains(playCode) Then
                        Return "PRODSCAN"
                    ElseIf playCode.Length > comCodeLength Then
                        Return "COMSCAN"
                    Else
                        Return "LENGTHERROR"
                    End If
                Else
                    If playCode = packKey Then
                        nowFullCount = 0
                        Return "PACKING"
                    Else
                        Return "STATEERROR"
                    End If
                End If
            End If
        Catch ex As Exception
            Return "-1"
        End Try
    End Function

    Private Function searchData() As Boolean
        If playCode.Length = lowProdCodeLength Then
            For i = 0 To setInfoList.prodCode
                setInfo(i) = "NULL"
            Next
            Return True
        End If
        Const serialShot As Int16 = 3    '' 시리얼 번호와 샷 수 enum 의 차이 / 시리얼 번호 null 일 때 샷 수에 null 값 집어 넣기 위해 사용

        For i = 0 To setInfoList.prodCode
            setInfo(i) = Nothing
        Next

        If serialSearch() Then

            For i = 0 To serialCount - 1
                If setInfo(i) <> "NULL" Then
                    If shotSearch(i) Then
                        If typeSearch(i) Then
                            Return False
                        End If
                    Else
                        Return False
                    End If
                Else
                    setInfo(i + serialShot) = "NULL"
                End If
            Next
            setInfoOut()
            Return True

        Else
            Return False
        End If
    End Function

    Private Sub setInfoOut()
        If setInfo(setInfoList.topSerial) <> "NULL" And setInfo(setInfoList.midSerial) <> "NULL" And setInfo(setInfoList.botSerial) <> "NULL" Then
            txbMdevSN.Text = setInfo(setInfoList.topSerial)
            txbMfaceSN.Text = setInfo(setInfoList.midSerial)
            txbMeyeSN.Text = setInfo(setInfoList.botSerial)
            txbMdevShot.Text = setInfo(setInfoList.topshot)
            txbMfaceShot.Text = setInfo(setInfoList.midshot)
            txbMeyeShot.Text = setInfo(setInfoList.botshot)
            txbMmodel.Text = setInfo(setInfoList.model)
            txbMnt.Text = setInfo(setInfoList.abroad)
            txbMagent.Text = setInfo(setInfoList.agency)
        Else
            txbCfaceSN.Text = setInfo(setInfoList.topSerial)
            txbCeyeSN.Text = setInfo(setInfoList.midSerial)
            txbCbodySN.Text = setInfo(setInfoList.botSerial)
            txbCfaceShot.Text = setInfo(setInfoList.topshot)
            txbCeyeShot.Text = setInfo(setInfoList.midshot)
            txbCbodyShot.Text = setInfo(setInfoList.botshot)
            txbCmodel.Text = setInfo(setInfoList.model)
            txbCnt.Text = setInfo(setInfoList.abroad)
            txbCagent.Text = setInfo(setInfoList.agency)
        End If

    End Sub

    Private Function typeSearch(type As Int16) As Boolean
        Const queryCount As Int16 = 3

        If setInfo(setInfoList.topSerial) <> "NULL" And setInfo(setInfoList.midSerial) <> "NULL" And setInfo(setInfoList.botSerial) <> "NULL" Then
            If type = setInfoList.topSerial Then
                DBCmd = "SELECT Model,Abroad,Agency FROM " & applyDivDB & " WHERE Product_SN = '" & setInfo(type) & "'"
            Else
                DBCmd = "SELECT Ct_Model,Ct_Abroad,Ct_Agency FROM " & applyCartDB & " WHERE Product_SN = '" & setInfo(type) & "'"
            End If
        Else
            If TDUseCompare = True Then
                DBCmd = "SELECT Ct_Model,Ct_Abroad,Ct_Agency FROM " & applyCartDB & " WHERE Product_SN = '" & setInfo(type) & "'"
            ElseIf LdmUseCompare = True Then
                DBCmd = "SELECT Ct_Model,Ct_Abroad,Ct_Agency FROM " & ApplyLdmDB & " WHERE Product_SN = '" & setInfo(type) & "'"
            Else
                DBCmd = "SELECT Ct_Model,Ct_Abroad,Ct_Agency FROM " & applyNonTDDB & " WHERE Product_SN = '" & setInfo(type) & "'"
            End If

        End If

        If DBQueryReader(DBCmd) Then
            If sqlDataQuery.Length = queryCount Then

                If setInfo(setInfoList.model) = Nothing And setInfo(setInfoList.abroad) = Nothing And setInfo(setInfoList.agency) = Nothing Then
                    setInfo(setInfoList.model) = sqlDataQuery(0)
                    setInfo(setInfoList.abroad) = sqlDataQuery(1)
                    setInfo(setInfoList.agency) = sqlDataQuery(2)
                    Return False
                Else
                    If setInfo(setInfoList.model) = sqlDataQuery(0) And setInfo(setInfoList.abroad) = sqlDataQuery(1) And setInfo(setInfoList.agency) = sqlDataQuery(2) Then
                        Return False
                    Else
                        errorOut("등록오류")
                        errorGen("모델, 국가번호, 대리점 번호 중 하나가 일치하지 않습니다. (" & setInfo(type) & ")")
                        Return True
                    End If
                End If
            Else
                errorOut("등록오류")
                errorGen("시리얼 번호 중 중복된 데이터가 존재합니다. (" & setInfo(type) & ")")
                Return True
            End If
        Else
            errorOut("등록오류")
            errorGen("시리얼 번호 중 존재하지 않는 번호가 존재합니다. (" & setInfo(type) & ")")
            Return True
        End If
    End Function

    Private Function serialSearch() As Boolean
        Dim deviceTypeCode As String = ""

        DBCmd = "SELECT DeviceTypeCode FROM " & ApplyModelInfoDB & " WHERE ModelCode = '" & modelNum & "' LIMIT 1"

        If DBQueryReader(DBCmd) Then
            deviceTypeCode = sqlDataQuery(0)
        End If

        If deviceTypeCode = "D" Then    '분리형 디바이스 : PRO, LUX, ALPHA
            If typeNum = typeList.prodSet Then
                DBCmd = "SELECT FaceCart_SN,EyeCart_SN FROM " & applyProdDB & " WHERE Product_SN = '" & playCode & "'"
                If DBQueryReader(DBCmd) Then
                    If sqlDataQuery.Length = serialCount - 1 Then
                        setInfo(setInfoList.topSerial) = playCode
                        setInfo(setInfoList.midSerial) = sqlDataQuery(0)
                        setInfo(setInfoList.botSerial) = sqlDataQuery(1)
                    Else
                        errorOut("등록오류")
                        errorGen("제품의 중복 번호가 존재합니다. 번호를 확인하여 주십시오.")
                        Return False
                    End If
                Else
                    errorOut("등록오류")
                    errorGen("제품의 정보 입력 데이터가 존재하지 않습니다. 정보입력을 진행하여 주십시오.")
                    Return False
                End If
            ElseIf typeNum = typeList.prodFace Then
                setInfo(setInfoList.topSerial) = playCode
                setInfo(setInfoList.midSerial) = "NULL"
                setInfo(setInfoList.botSerial) = "NULL"

            ElseIf typeNum = typeList.prodEye Then
                setInfo(setInfoList.topSerial) = "NULL"
                setInfo(setInfoList.midSerial) = playCode
                setInfo(setInfoList.botSerial) = "NULL"

            Else
                setInfo(setInfoList.topSerial) = "NULL"
                setInfo(setInfoList.midSerial) = "NULL"
                setInfo(setInfoList.botSerial) = playCode

            End If
        Else
            setInfo(setInfoList.topSerial) = playCode
            setInfo(setInfoList.midSerial) = "NULL"
            setInfo(setInfoList.botSerial) = "NULL"
        End If

        Return True
    End Function

    Private Function shotSearch(type As Int16) As Boolean

        If setInfo(setInfoList.topSerial) <> "NULL" And setInfo(setInfoList.midSerial) <> "NULL" And setInfo(setInfoList.botSerial) <> "NULL" Then
            If type = setInfoList.topSerial Then
                DBCmd = "SELECT FW_VER FROM " & applyDivDB & " WHERE Product_SN = '" & setInfo(type) & "'"
            Else
                DBCmd = "SELECT Ct_Max_ShotCnt FROM " & applyCartDB & " WHERE Product_SN = '" & setInfo(type) & "'"
            End If
        Else

            If TDUseCompare = True Then
                DBCmd = "SELECT Ct_Max_ShotCnt FROM " & applyCartDB & " WHERE Product_SN = '" & setInfo(type) & "'"
            ElseIf LdmUseCompare = True Then
                DBCmd = "SELECT Ct_Max_ShotCnt FROM " & ApplyLdmDB & " WHERE Product_SN = '" & setInfo(type) & "'"
            Else
                DBCmd = "SELECT COUNT(Number) FROM " & applyNonTDDB & " WHERE Product_SN = '" & setInfo(type) & "'"
            End If

        End If

        Dim shotcnt As String = DBQueryScalar(DBCmd)

        If shotcnt = "False" Then
            errorOut("등록오류")
            errorGen("샷 수에 대한 데이터가 존재하지 않습니다.")
            Return False
        End If

        If TDUseCompare = False And LdmUseCompare = False Then
            If shotcnt > 0 Then
                shotcnt = 0
            Else
                errorOut("등록오류")
                errorGen("시리얼 번호에 대한 데이터가 존재하지 않습니다.")
                Return False
            End If
        End If

        Select Case type
            Case setInfoList.topSerial
                setInfo(setInfoList.topshot) = shotcnt
            Case setInfoList.midSerial
                setInfo(setInfoList.midshot) = shotcnt
            Case setInfoList.botSerial
                setInfo(setInfoList.botshot) = shotcnt
            Case Else
                errorOut("등록오류")
                errorGen("처리 과정에서 오류가 발생하였습니다.")
                Return False
        End Select

        Return True
    End Function

    Private Function prodCodeSearch() As Boolean
        Try
            If playCode.Length <> lowProdCodeLength Then
                If modelNum = Nothing Or typeNum = Nothing Then
                    errorOut("등록오류")
                    errorGen("해당 시리얼 번호의 모델과 타입을 알 수 없습니다.")
                    Return True
                End If
            End If


            Dim queryCount As Integer = 0
            Dim codeColor As String
            If playCode.Length = oldProdCodeLength Then     '12자리 제품시리얼번호
                codeColor = Mid(playCode, 11, 1)
            ElseIf playCode.Length = newProdCodeLength Then '16자리 제품시리얼번호
                codeColor = Mid(playCode, 3, 1)
            End If
            If playCode.Length = lowProdCodeLength Then
                DBCmd = "SELECT ItemCode,ProdCode,FaceShot,EyeShot FROM " & applyPlistDB & " WHERE 88_Code = '" & playCode & "'"
            Else
                DBCmd = "SELECT ItemCode,ProdCode,FaceShot,EyeShot FROM " & applyPlistDB & " WHERE ModelNum = '" & modelNum & "' AND TypeNum = '" & typeNum & "' AND ColorNum = '" & codeColor & "'"
            End If

            If DBQueryReader(DBCmd) Then
                Dim sqlCount As Integer = sqlDataQuery.Length
                ReDim ScanArray(scanList.eyeshot, (sqlCount / scanList.maxscan) - 1)
                For i = 0 To (sqlCount / scanList.maxscan) - 1
                    For cnt = 0 To scanList.eyeshot
                        ScanArray(cnt, i) = sqlDataQuery(queryCount)
                        queryCount += 1
                    Next
                Next
                Return False
            Else
                errorOut("등록오류")
                errorGen("해당 품목에 대한 데이터가 존재하지 않습니다. 바코드를 확인하여 주십시오.")
                Return True
            End If
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("제품 리스트를 설정하는 과정에서 오류가 발생하였습니다.")
            Return True
        End Try

    End Function

    Private Function mesRunning() As Boolean
        If mesDateSet() Then
            errorOut("등록오류")
            errorGen("MES 형식과 맞지 않는 코드 번호 입니다.")
            Return False
        End If
        Dim searchData As String = "createdAtFrom=" & mesDate & "&createdAtTo=" & mesDate.AddDays(1) & ""

        Dim apiResult As String = apiRequest_GET(apiItemOutURL, searchData)
        If apiResult = "-1" Then
            errorOut("등록오류")
            errorGen("등록된 데이터가 존재하지 않습니다.")
            Return False
        End If

        If mesParsing(apiResult) Then
            Return False
        End If

        mesShotSearch()
        Return True
    End Function

    Private Function mesDateSet() As Boolean
        Const yearFront As Int16 = 20
        Const dateLength As Int16 = 6
        If UBound(Split(playCode, codeState(codeStateList.MES))) > 0 Then
            If UBound(Split(playCode, "-")) > 0 Then
                Dim useDate As String = Mid(playCode, InStr(playCode, codeState(codeStateList.MES)) + codeState(codeStateList.MES).Length, InStr(playCode, "-") - codeState(codeStateList.MES).Length - 1)
                If useDate.Length = dateLength Then
                    useDate = yearFront & Mid(useDate, 1, 2) & "-" & Mid(useDate, 3, 2) & "-" & Mid(useDate, 5, 2)
                    mesDate = Convert.ToDateTime(useDate)
                    Return False
                End If
            End If
        End If
        Return True
    End Function

    Private Sub mesShotSearch()
        For i = 0 To prodArray.GetLength(1) - 1
            DBCmd = "SELECT FaceShot,EyeShot FROM " & applyPlistDB & " WHERE ItemCode = '" & prodArray(itemCode.code, i) & "'"
            If DBQueryReader(DBCmd) Then
                prodArray(itemCode.face, i) = sqlDataQuery(0)
                prodArray(itemCode.eye, i) = sqlDataQuery(1)
            Else
                prodArray(itemCode.face, i) = 0
                prodArray(itemCode.eye, i) = 0
            End If
        Next
    End Sub

    Private Function mesParsing(pData As String) As Boolean
        Try
            Dim dataCount As Int16 = 0
            Dim codeExist As Boolean = False
            donePkList.Clear()
            ReDim prodArray(itemCode.id, 0)
            ReDim apiData(apiDataList.address)

            Dim jQuery As JObject = JObject.Parse(pData)
            pData = jQuery.SelectToken(apiCommand(parsingCode.code)).ToString

            If pData <> "SUCCESS" Then
                errorOut("등록오류")
                errorGen("Data를 불러오는데 실패하였습니다.")
                Return True
            End If

            pData = jQuery.SelectToken(apiCommand(parsingCode.data)).ToString
            jQuery = JObject.Parse(pData)
            pData = jQuery.SelectToken(apiCommand(parsingCode.row)).ToString

            If pData = "[]" Then
                errorOut("MES오류")
                errorGen("MES에 존재하지 않은 데이터입니다.")
                Return True
            End If

            Dim jsArray = JArray.Parse(pData)


            For cnt = 0 To jsArray.Count - 1
                Dim orderInfo As String = jsArray(cnt)(apiCommand(parsingCode.orderDetail)).ToString

                If jsArray(cnt)(apiCommand(parsingCode.state)).ToString <> "canceled" Then
                    If orderInfo <> Nothing Then
                        jQuery = JObject.Parse(orderInfo)
                        orderInfo = jQuery.SelectToken(apiCommand(parsingCode.orderSheet)).ToString
                        jQuery = JObject.Parse(orderInfo)
                        pData = jQuery.SelectToken(apiCommand(parsingCode.code)).ToString
                        If pData = playCode Then
                            ReDim Preserve prodArray(itemCode.id, dataCount)
                            prodArray(itemCode.id, dataCount) = jsArray(cnt)(apiCommand(parsingCode.id)).ToString
                            apiData(apiDataList.refer) = jsArray(cnt)(apiCommand(parsingCode.refer)).ToString

                            apiData(apiDataList.ordererCode) = jQuery.SelectToken(apiCommand(parsingCode.ordererCode)).ToString
                            apiData(apiDataList.ordererName) = jQuery.SelectToken(apiCommand(parsingCode.ordererName)).ToString
                            apiData(apiDataList.phone) = jQuery.SelectToken(apiCommand(parsingCode.phone)).ToString
                            apiData(apiDataList.zip) = jQuery.SelectToken(apiCommand(parsingCode.zip)).ToString
                            apiData(apiDataList.address) = Replace(jQuery.SelectToken(apiCommand(parsingCode.address)).ToString, "'", "\'")

                            prodArray(itemCode.count, dataCount) = jsArray(cnt)(apiCommand(parsingCode.itemcount)).ToString
                            apiData(apiDataList.regData) = jsArray(cnt)(apiCommand(parsingCode.regDate)).ToString

                            Dim parterInfo As String = jsArray(cnt)(apiCommand(parsingCode.accuount)).ToString
                            If parterInfo <> Nothing Then
                                jQuery = JObject.Parse(parterInfo)
                                apiData(apiDataList.accountCode) = jQuery.SelectToken(apiCommand(parsingCode.code)).ToString
                                apiData(apiDataList.accountName) = jQuery.SelectToken(apiCommand(parsingCode.name)).ToString
                            Else
                                apiData(apiDataList.accountCode) = String.Empty
                                apiData(apiDataList.accountName) = String.Empty
                            End If


                            Dim itemInfo As String = jsArray(cnt)(apiCommand(parsingCode.item)).ToString
                            If itemInfo <> Nothing Then
                                jQuery = JObject.Parse(itemInfo)
                                prodArray(itemCode.code, dataCount) = jQuery.SelectToken(apiCommand(parsingCode.code)).ToString
                                prodArray(itemCode.name, dataCount) = jQuery.SelectToken(apiCommand(parsingCode.name)).ToString
                            Else
                                errorOut("등록오류")
                                errorGen("등록 데이터 중 제품이 등록되어 있지 않는 항목이 존재합니다.")
                                Return False
                            End If

                            prodArray(itemCode.chkCount, dataCount) = 0
                            prodArray(itemCode.serialNum, dataCount) = Nothing

                            nowFullCount += prodArray(itemCode.count, dataCount)
                            dataCount += 1
                            codeExist = False

                        Else
                            If prodArray(itemCode.code, 0) = "" Then
                                codeExist = True
                            End If

                        End If
                    End If
                End If
            Next


            If codeExist = True Then
                errorOut("등록오류")
                errorGen("등록된 코드 번호가 존재하지 않습니다. 번호를 확인하여 주십시오.")
                Return True
            Else
                Return False
            End If
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("MES 데이터를 처리하는 도중 오류가 발생하였습니다." & vbCrLf & ex.Message)
            Return True
        End Try

    End Function

    Private SetPKCode As String = String.Empty
    Private SetIdCode() As Integer

    Private Function PKCodeCheck() As Boolean
        ReDim SetIdCode(prodArray.GetLength(1) - 1)

        For i = 0 To prodArray.GetLength(1) - 1
            If i = 0 Then
                SetPKCode = prodArray(itemCode.code, i)
            Else
                If SetPKCode <> prodArray(itemCode.code, i) Then
                    errorGen("서로 다른 세트 코드가 존재합니다. 확인하여 주십시오." & vbCrLf)
                    Return True
                End If
            End If

            SetIdCode(i) = prodArray(itemCode.id, i)
        Next

        gbProdList.Text = "■ 출고 조건 : " & SetPKCode

        If RequestCount = 0 Then
            Dim worknum As Integer = WorkNowState()

            If worknum >= prodArray.GetLength(1) Then
                errorGen("이미 작업 완료된 코드입니다. 확인 바랍니다." & vbCrLf)
                Return True
            End If

            txbRequest.ForeColor = Color.Black
            txbRequest.BackColor = SystemColors.Window
            RequestUpdate(prodArray.GetLength(1))

            txbWork.ForeColor = Color.Black
            txbWork.BackColor = SystemColors.Window
            WorkUpdate(worknum)

            txbLeftOver.ForeColor = Color.Black
            txbLeftOver.BackColor = SystemColors.Window
            LeftOverUpdate(prodArray.GetLength(1) - worknum)

        End If

        Return False
    End Function



    Private Function PKCodeSearch() As Boolean
        DBCmd = "SELECT un.ItemCode,un.ItemName,pk.ProdCount,ifnull(pd.FaceShot,-1),ifnull(pd.EyeShot ,-1),un.ProdCode FROM " & applyPKCodeDB & " AS pk INNER JOIN (SELECT ItemCode,ProdCode,ItemName FROM " & applyPlistDB & " UNION SELECT ItemCode,ProdCode,ItemName FROM " & applyClistDB & ") AS un ON pk.ProdCode = un.ItemCode LEFT JOIN " & applyPlistDB & " AS pd ON pk.ProdCode = pd.ItemCode WHERE pk.PKCode = '" & SetPKCode & "' ORDER BY ifnull(pd.FaceShot,-1) desc"

        If DBQueryReader(DBCmd) Then
            Dim dataCount As Integer = 0
            Dim rowNum As Integer = (sqlDataQuery.Length / 6) - 1
            ReDim prodArray(itemCode.id, rowNum)

            For i = 0 To rowNum
                For n = 0 To itemCode.chkCount

                    If n = itemCode.chkCount Then
                        prodArray(itemCode.prodCode, i) = sqlDataQuery(dataCount)
                    Else
                        prodArray(n, i) = sqlDataQuery(dataCount)
                    End If

                    dataCount += 1
                Next
                nowFullCount += prodArray(itemCode.count, i)
            Next

            Return False
        Else
            errorGen("해당 세트 코드에 대한 데이터가 존재하지 않습니다." & vbCrLf)
            Return True
        End If
    End Function

    Private Function ListSetting() As Boolean
        Try
            If StartSwitch = True Then
                If rdbMode2.Checked = True And rdbNew.Checked = True Then
                    nowFullCount = 0
                    If PKCodeCheck() Then
                        Return True
                    End If

                    If PKCodeSearch() Then
                        errorOut("등록오류")
                        Return True
                    End If
                Else
                    If setCodeParsing() = False Then
                        Return True
                    End If
                End If
            End If

            Dim prodInfoCol As Integer = 0
            Dim rowDataCount As Int32 = prodArray.GetLength(1) - 1
            ReDim txbArrayList(rowDataCount, txbNameList.targetCount)

            stateTxbClear()

            For row = 0 To rowDataCount
                For col = 0 To txbNameList.targetCount
                    Dim txtBox As TextBox = New TextBox

                    If row = 0 Then
                        prodInfoCol = prodInfoStartCol
                    Else
                        If col = txbNameList.name Then
                            prodInfoCol = prodInfoCol + prodInfoHeight + locplus
                        End If
                    End If

                    txtBox.Name = txbNameSelect(col) & row
                    pnProdList.Controls.Add(txtBox)

                    txbArrayList(row, col) = txtBox
                    txtBox.Font = New Font("한컴 고딕", 28, FontStyle.Bold)
                    txtBox.Size = New Size(prodInfoWidth(col), prodInfoHeight)
                    txtBox.Location = New Point(prodInfoRow(col), prodInfoCol)

                    If col = txbNameList.name Or col = txbNameList.nowCount Then
                        txtBox.Text = prodArray(col + 1, row)
                    Else
                        txtBox.Text = "0"
                    End If

                    txtBox.ReadOnly = True
                    pnProdList.Refresh()

                    txbColorReset(row, txtBox)
                Next

                txbArrayList(row, txbNameList.nowCount).TextAlign = HorizontalAlignment.Center
                txbArrayList(row, txbNameList.targetCount).TextAlign = HorizontalAlignment.Center

            Next

            orderCode = playCode
            orderSwitch = True

            If ckbPrinter.Checked = True Then
                ReDim printSerial(0)
            End If

            Return False
        Catch ex As Exception
            errorOut("등록오류")
            errorGen("리스트를 처리하는 도중 오류가 발생하였습니다." & vbCrLf & ex.Message)
            Return True
        End Try
    End Function

    Private Sub txbColorReset(row As Integer, setTb As TextBox)
        If row Mod 2 = 0 Then
            setTb.BackColor = Color.Moccasin
        Else
            setTb.BackColor = Color.Lavender
        End If

        setTb.Refresh()

    End Sub

    Private Function setCodeParsing() As Boolean
        Try
            Const colCount As Int16 = 5

            apiBackupData()

            For i = 0 To prodArray.GetLength(1) - 1
                If InStr(prodArray(itemCode.code, i), setCodeSort) > 0 Then
                    Dim existSwitch As Boolean = False
                    DBCmd = "SELECT un.ItemCode,un.ItemName,pk.ProdCount,pd.FaceShot,pd.EyeShot FROM " & applyPKCodeDB & " AS pk INNER JOIN (SELECT ItemCode,ProdCode,ItemName FROM " & applyPlistDB & " UNION SELECT ItemCode,ProdCode,ItemName FROM " & applyClistDB & ") AS un ON pk.ProdCode = un.ItemCode LEFT JOIN " & applyPlistDB & " AS pd ON pk.ProdCode = pd.ItemCode WHERE pk.PKCode = '" & prodArray(itemCode.code, i) & "'"

                    If DBQueryReader(DBCmd) Then
                        Dim dataSetCount As Int32 = 0
                        Dim RowCount As Int16 = (sqlDataQuery.Length / colCount) - 1
                        Dim setCodeArray(itemCode.eye)
                        nowFullCount -= prodArray(itemCode.count, i)

                        For row = 0 To RowCount
                            existSwitch = False
                            For col = 0 To colCount - 1

                                setCodeArray(col) = sqlDataQuery(dataSetCount)

                                If col = itemCode.count Then
                                    setCodeArray(itemCode.count) = setCodeArray(itemCode.count) * prodArray(itemCode.count, i)
                                    nowFullCount += setCodeArray(itemCode.count)
                                End If

                                dataSetCount += 1
                            Next

                            For chk = 0 To prodArray.GetLength(1) - 1
                                If prodArray(itemCode.code, chk) = setCodeArray(itemCode.code) Then
                                    prodArray(itemCode.count, chk) += (setCodeArray(itemCode.count))

                                    If prodArray(itemCode.pkCode, chk) = String.Empty Then
                                        prodArray(itemCode.pkCode, chk) = prodArray(itemCode.code, i)
                                    Else
                                        prodArray(itemCode.pkCode, chk) = prodArray(itemCode.pkCode, chk) & "/" & prodArray(itemCode.code, i)
                                    End If

                                    existSwitch = True
                                    Exit For
                                End If
                            Next

                            If existSwitch = False Then
                                Dim chkRowNum As Int16 = prodArray.GetLength(1)
                                ReDim Preserve prodArray(prodArray.GetLength(0) - 1, chkRowNum)
                                For svd = 0 To itemCode.eye
                                    prodArray(svd, prodArray.GetLength(1) - 1) = setCodeArray(svd)
                                Next

                                If prodArray(itemCode.pkCode, chkRowNum) = String.Empty Then
                                    prodArray(itemCode.pkCode, chkRowNum) = prodArray(itemCode.code, i)
                                Else
                                    prodArray(itemCode.pkCode, chkRowNum) = prodArray(itemCode.pkCode, chkRowNum) & "/" & prodArray(itemCode.code, i)
                                End If

                            End If

                        Next

                    Else
                        errorOut("세트오류")
                        errorGen("존재하지 않은 세트 코드가 존재합니다. 데이터를 요청하십시오.")
                        Return False
                    End If

                    For del = 0 To itemCode.prodCode
                        prodArray(del, i) = String.Empty
                    Next


                    existSwitch = False
                    Dim nowRow As Int16 = 0

                    For rc = 0 To prodArray.GetLength(1) - 1
                        If prodArray(itemCode.code, rc) <> String.Empty Then
                            For cc = 0 To itemCode.prodCode
                                prodArray(cc, nowRow) = prodArray(cc, rc)
                            Next
                            existSwitch = True
                            nowRow += 1
                        End If
                    Next

                    If existSwitch = True Then
                        setCodeUse = True
                        ReDim Preserve prodArray(prodArray.GetLength(0) - 1, nowRow - 1)
                    End If

                End If
            Next

            Return True
        Catch ex As Exception
            errorOut("세트오류")
            errorGen("세트 데이터를 처리하는 도중 오류가 발생하였습니다." & vbCrLf & ex.Message)
            Return False
        End Try

    End Function

    Private Sub apiBackupData()
        If ckbAPIuse.Checked = True Then
            ReDim apiArray(prodArray.GetLength(0) - 1, prodArray.GetLength(1) - 1)
            For i = 0 To prodArray.GetLength(1) - 1
                For n = 0 To prodArray.GetLength(0) - 1
                    apiArray(n, i) = prodArray(n, i)

                    If n = itemCode.type Then
                        If InStr(prodArray(itemCode.code, i), setCodeSort) > 0 Then
                            apiArray(n, i) = 1
                        End If
                    End If

                Next
            Next
        End If
    End Sub

    Private Sub stateTxbClear()
        Const setControls As Int16 = 3
        Dim clearRunSwitch As Boolean = False
        Dim nowTxbCount As Int32 = pnProdList.Controls.Count / setControls

        If nowTxbCount <> 0 Then
            clearRunSwitch = True
        Else
            clearRunSwitch = False
        End If

        If clearRunSwitch = True Then
            txbClearFunc(nowTxbCount)
        End If
    End Sub

    Private Sub txbClearFunc(txbCount As Int32)
        For i = txbCount - 1 To 0 Step -1
            pnProdList.Controls(txbNameSelect(txbNameList.name) & i).Dispose()
            pnProdList.Controls(txbNameSelect(txbNameList.nowCount) & i).Dispose()
            pnProdList.Controls(txbNameSelect(txbNameList.targetCount) & i).Dispose()
        Next
    End Sub

    Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
        End
    End Sub

    Private Sub btnLoginTest_Click(sender As Object, e As EventArgs) Handles btnLoginTest.Click
        If loginForm.loginUse = False Then
            loginForm.loginMode = True
            If loginForm.ShowDialog() = DialogResult.OK Then

                If rdbMode2.Checked = False Then
                    stateFormSetting()
                End If

                ckbAPIuse.Checked = True
            End If

        Else
            logOff()
            ckbAPIuse.Checked = False
        End If

        txbProdSN.Focus()

    End Sub

    Private Sub logOff()
        btnLoginTest.Text = "MES" & vbCrLf & "로그인"
        loginForm.loginUse = False
        userAccess = Nothing
        lbMESid.Text = "OFF"
    End Sub

    Private Sub varDataSetting()
        codeState(codeStateList.ERP) = txbIdenERP.Text
        codeState(codeStateList.MES) = txbIdenMES.Text

        apiCommand(parsingCode.data) = "data"
        apiCommand(parsingCode.row) = "rows"
        apiCommand(parsingCode.id) = "id"
        apiCommand(parsingCode.itemcount) = "expectedOutCount"
        apiCommand(parsingCode.regDate) = "createdAt"
        apiCommand(parsingCode.accuount) = "Partner"
        apiCommand(parsingCode.code) = "code"
        apiCommand(parsingCode.name) = "name"
        apiCommand(parsingCode.orderDetail) = "OrderDetail"
        apiCommand(parsingCode.orderSheet) = "OrderSheet"
        apiCommand(parsingCode.ordererCode) = "customerId"
        apiCommand(parsingCode.ordererName) = "receiverName"
        apiCommand(parsingCode.phone) = "receiverPhoneNumber"
        apiCommand(parsingCode.zip) = "receiverZipCode"
        apiCommand(parsingCode.refer) = "description"
        apiCommand(parsingCode.address) = "receiverAddress"
        apiCommand(parsingCode.item) = "Item"
        apiCommand(parsingCode.state) = "state"

        itemCommand(itemCode.code) = "code"
        itemCommand(itemCode.name) = "name"
        itemCommand(itemCode.count) = "expectedOutCount"

        txbNameSelect(txbNameList.name) = "txbProdName"
        txbNameSelect(txbNameList.nowCount) = "txbProdCountB"
        txbNameSelect(txbNameList.targetCount) = "txbProdCountC"

        prodInfoWidth(txbNameList.name) = 710
        prodInfoWidth(txbNameList.nowCount) = 110
        prodInfoWidth(txbNameList.targetCount) = 110

        prodInfoRow(txbNameList.name) = 5
        prodInfoRow(txbNameList.nowCount) = 718
        prodInfoRow(txbNameList.targetCount) = 828

        saveCommand(saveList.comport) = "ComportConfig"
        saveCommand(saveList.ckbData) = "CheckConfig"
        saveCommand(saveList.divideCode) = "DivideConfig"
        saveCommand(saveList.print) = "PrintConfig"
        saveCommand(saveList.lastCount) = "CountBackUp"

        optionCkb(optionCkbList.weight) = ckbWeight
        optionCkb(optionCkbList.barcode) = chbUseBarcode
        optionCkb(optionCkbList.printer) = ckbPrinter
        optionCkb(optionCkbList.api) = ckbAPIuse

        optionTxb(optionTxbList.comCode) = txbPCNum
        optionTxb(optionTxbList.erpCode) = txbIdenERP
        optionTxb(optionTxbList.mesCode) = txbIdenMES
        optionTxb(optionTxbList.weightPlus) = txbWeightPlus
        optionTxb(optionTxbList.weightMinus) = txbWeightMinus
        optionTxb(optionTxbList.autoCount) = txbAutoCount

        optionprint(printTxbList.name) = txbPrintName
        optionprint(printTxbList.label) = txblabelAd
        optionprint(printTxbList.barcode) = txbBarValue
        optionprint(printTxbList.text) = txbtxtValue
        optionprint(printTxbList.labro) = txblaBro
        optionprint(printTxbList.lazeb) = txblaZeb

        countDBCommand()

    End Sub

    Private Sub varClear()
        ReDim prodArray(0, 0)
        ReDim txbArrayList(0, 0)
        playCode = Nothing
        DBCmd = Nothing
        orderSwitch = False
        typeNum = Nothing
        scanCode = Nothing
        modelNum = Nothing
        weightSum = 0
        nowFullCount = Nothing
        tgtFullCount = Nothing
        playCode = Nothing
        invoiceCode = Nothing

        For i = 0 To apiDataList.address
            apiData(i) = Nothing
        Next

        For i = 0 To setInfoList.agency
            setInfo(i) = Nothing
        Next
    End Sub

    Private Sub startTxbResult()
        txbResult.Text = "대기중"
        txbResult.BackColor = Color.LemonChiffon
        If rdbMode1.Checked = True Then
            txbPacking.Text = "패킹 코드"
            txbPacking.BackColor = Color.Azure
        End If
    End Sub

    Private Sub successGen(outText As String)
        txbResult.Text = outText
        txbResult.BackColor = Color.Green
    End Sub

    Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
        resetPlay()
    End Sub

    Private Sub resetPlay()

        resetFunc()

        If modeSwitch = True And pnMain.Visible = True Then
            packingReset()
        End If

        txbResult.Text = "대기중"
        txbResult.BackColor = Color.LemonChiffon

        txbProdSN.Focus()
    End Sub

    Private Sub packingReset()
        playCode = packKey
        If packingRun() = False Then
            txbResult.BackColor = Color.Red
            txbResult.Text = "처리실패"
        End If
    End Sub

    Private Sub resetFunc()
        varClear()
        stateTxbClear()
        startTxbResult()
        mainClear()
        cartClear()
    End Sub

    Private Sub btnMore_Click(sender As Object, e As EventArgs) Handles btnMore.Click
        If loadLocalFile() Then
            countForm.ShowDialog()
        End If
    End Sub

    Private Sub countOut()
        txbCount.Text = product_packing_cnt_list(prodDB.packingCount).com_count
        txbProSet.Text = product_packing_cnt_list(prodDB.proset).com_count
        txbProFace.Text = product_packing_cnt_list(prodDB.proface).com_count
        txbProEye.Text = product_packing_cnt_list(prodDB.proeye).com_count
        txbProBody.Text = product_packing_cnt_list(prodDB.probody).com_count
        txbLuxSet.Text = product_packing_cnt_list(prodDB.luxset).com_count
        txbLuxFace.Text = product_packing_cnt_list(prodDB.luxface).com_count
        txbLuxEye.Text = product_packing_cnt_list(prodDB.luxeye).com_count
        txbLuxBody.Text = product_packing_cnt_list(prodDB.luxbody).com_count
        txbMAX.Text = product_packing_cnt_list(prodDB.maximum).com_count
        txbGel.Text = component_packing_cnt_list(comDB.gel).com_count
        txbAmp.Text = component_packing_cnt_list(comDB.ample).com_count
    End Sub

    Private Sub cartClear()
        carttextReset()
        cartColorReset()
        cartRefresh()
    End Sub

    Private Sub cartRefresh()
        txbCmodel.Refresh()
        txbCfaceSN.Refresh()
        txbCfaceShot.Refresh()
        txbCeyeSN.Refresh()
        txbCeyeShot.Refresh()
        txbCbodySN.Refresh()
        txbCbodyShot.Refresh()
        txbCmodel.Refresh()
        txbCagent.Refresh()
    End Sub

    Private Sub cartColorReset()
        txbCmodel.BackColor = Color.AliceBlue
        txbCfaceSN.BackColor = Color.AliceBlue
        txbCfaceShot.BackColor = Color.AliceBlue
        txbCeyeSN.BackColor = Color.AliceBlue
        txbCeyeShot.BackColor = Color.AliceBlue
        txbCbodySN.BackColor = Color.AliceBlue
        txbCbodyShot.BackColor = Color.AliceBlue
        txbCmodel.BackColor = Color.AliceBlue
        txbCagent.BackColor = Color.AliceBlue
    End Sub

    Private Sub carttextReset()
        txbCmodel.Text = "N/A"
        txbCfaceSN.Text = "N/A"
        txbCfaceShot.Text = "N/A"
        txbCeyeSN.Text = "N/A"
        txbCeyeShot.Text = "N/A"
        txbCbodySN.Text = "N/A"
        txbCbodyShot.Text = "N/A"
        txbCmodel.Text = "N/A"
        txbCagent.Text = "N/A"
    End Sub


    Private Sub mainClear()
        mainTextReset()
        mainColorReset()
        mainRefresh()
    End Sub

    Private Sub mainRefresh()
        txbMmodel.Refresh()
        txbMdevSN.Refresh()
        txbMdevShot.Refresh()
        txbMfaceSN.Refresh()
        txbMfaceShot.Refresh()
        txbMeyeSN.Refresh()
        txbMeyeShot.Refresh()
        txbMnt.Refresh()
        txbMagent.Refresh()
    End Sub

    Private Sub mainColorReset()
        txbMmodel.BackColor = Color.AliceBlue
        txbMdevSN.BackColor = Color.AliceBlue
        txbMdevShot.BackColor = Color.AliceBlue
        txbMfaceSN.BackColor = Color.AliceBlue
        txbMfaceShot.BackColor = Color.AliceBlue
        txbMeyeSN.BackColor = Color.AliceBlue
        txbMeyeShot.BackColor = Color.AliceBlue
        txbMnt.BackColor = Color.AliceBlue
        txbMagent.BackColor = Color.AliceBlue
    End Sub

    Private Sub mainTextReset()
        txbMmodel.Text = "N/A"
        txbMdevSN.Text = "N/A"
        txbMdevShot.Text = "N/A"
        txbMfaceSN.Text = "N/A"
        txbMfaceShot.Text = "N/A"
        txbMeyeSN.Text = "N/A"
        txbMeyeShot.Text = "N/A"
        txbMnt.Text = "N/A"
        txbMagent.Text = "N/A"
    End Sub

    Private Sub errorOut(errorStr As String)
        txbResult.Text = errorStr
        txbResult.BackColor = Color.Red
    End Sub

    Public Sub errorGen(errorDetail As String)
        errorOkNg.txbOkNg.Text = errorDetail
        errorOkNg.ShowDialog()
    End Sub

    ''옵션 화면

    Private Sub btnOption_Click(sender As Object, e As EventArgs) Handles btnOption.Click, btnOpExit.Click
        If pnMain.Visible = True Then
            autoSuccess = False
            successTimer.Enabled = False

            optionTxtClear()
            optionSetting()
            fullLoad(sender, e)
            dgvRefresh()
        Else
            If textChange = True Or ckbChange = True Or printChange = True Then
                If MsgBox("변경된 정보가 존재합니다. 저장하시겠습니까?", vbOKCancel + vbExclamation) = MsgBoxResult.Ok Then
                    For i = 0 To saveList.print
                        saveConfig(i)
                    Next
                End If
            End If
            fullLoad(sender, e)
            resetPlay()
            eventRelease()
            mainSetting()
            invEnable()

            programRunSwitch = False
            txbProdSN.Focus()
        End If

    End Sub

    Private Sub modeUpdate(sender As Object, e As EventArgs)
        If rdbMode1.Checked = True Then
            modeSetting(True, sender, e)
        Else
            modeSetting(False, sender, e)
        End If
    End Sub

    Private Sub optionTxtClear()
        txbWeightPlus.Text = Nothing
        txbWeightMinus.Text = Nothing
        txbEventName.Text = Nothing
        txbEvName.Text = Nothing
        txbEvCode.Text = Nothing
        txbEvCount.Text = Nothing
        txbEvFace.Text = Nothing
        txbEvEye.Text = Nothing
        txbEventDel.Text = Nothing
        txbIdenERP.Text = Nothing
        txbIdenMES.Text = Nothing
        textChange = False
        ckbChange = False
        printChange = False

        cmdSerial.Text = "스캔"

        cboComPort.Items.Clear()

        dgvEvent.Rows.Clear()
        dgvSearch.Rows.Clear()

        txbEvFace.Visible = True
        txbEvEye.Visible = True
    End Sub

    Private Sub cmdSerial_Click(sender As Object, e As EventArgs) Handles cmdSerial.Click
        If cmdSerial.Text = "스캔" Then
            LoadComport()
            cmdSerial.Text = "연결"
        Else
            weightForm.cmdSerialPort.Close()
            Dim serialName As String = cboComPort.SelectedItem
            openSerial(serialName)
            cmdSerial.Text = "스캔"
            saveConfig(saveList.comport)
        End If
    End Sub

    ' 추가: 설정 변경시 시리얼 포트 재연결을 위한 함수
    Private Sub ReconnectSerialPort()
        Try
            If ckbWeight.Checked = True AndAlso cboComPort.SelectedItem IsNot Nothing Then
                Dim serialName As String = cboComPort.SelectedItem.ToString()
                If serialName <> "" Then
                    'Debug.Print("=== 설정 변경으로 인한 시리얼 포트 재연결 ===")
                    'Debug.Print("serialName: [" & serialName & "]")
                    'Debug.Print("QW 체크 여부: " & rdbWeightQW.Checked)
                    openSerial(serialName)
                End If
            End If
        Catch ex As Exception
            Debug.Print("시리얼 포트 재연결 오류: " & ex.Message)
        End Try
    End Sub

    Private Function openSerial(serialName As String)
        Try
            If ckbWeight.Checked = True Then
                If serialName <> "" Or serialName <> Nothing Then
                    'Debug.Print("serialName: [" & serialName & "]")

                    If rdbWeightQW.Checked Then
                        ' QW 모드: QWSerialPort 사용
                        Debug.Print("QW 시리얼 포트 설정 시작")

                        ' 기존 포트들 정리
                        If weightForm.QWSerialPort.IsOpen = True Then
                            weightForm.QWSerialPort.Close()
                        End If
                        If weightForm.cmdSerialPort.IsOpen = True Then
                            weightForm.cmdSerialPort.Close()
                        End If

                        With weightForm.QWSerialPort
                            .PortName = serialName
                            .BaudRate = 4800
                            .DataBits = 8
                            .Parity = Parity.None
                            .StopBits = StopBits.One
                            .Handshake = Handshake.None
                            .Encoding = System.Text.Encoding.ASCII
                        End With

                        weightForm.QWSerialPort.Open()
                        Debug.Print("QW 시리얼 통신 성공: " & serialName)
                        Return False

                    Else
                        ' 일반 모드: cmdSerialPort 사용
                        Debug.Print("일반 시리얼 포트 설정 시작")

                        ' 기존 포트들 정리
                        If weightForm.cmdSerialPort.IsOpen = True Then
                            weightForm.cmdSerialPort.Close()
                        End If
                        If weightForm.QWSerialPort.IsOpen = True Then
                            weightForm.QWSerialPort.Close()
                        End If

                        With weightForm.cmdSerialPort
                            .PortName = serialName
                            .BaudRate = 9600
                            .DataBits = 8
                            .Parity = Parity.None
                            .StopBits = StopBits.One
                            .Handshake = Handshake.None
                        End With

                        weightForm.cmdSerialPort.Open()
                        Debug.Print("일반 시리얼 통신 성공: " & serialName)
                        Return False
                    End If

                Else
                    errorOut("통신설정오류")
                    errorGen("시리얼 포트를 설정하여 주십시오.")
                    If pnMain.Visible = True Then
                        btnOption.PerformClick()
                    End If
                    Return True
                End If
            End If
            Return False

        Catch ex As Exception
            errorOut("통신설정오류")
            errorGen("COM포트 에러 발생 : " & ex.Message & " (포트: " & serialName & ")")
            If pnMain.Visible = True Then
                btnOption.PerformClick()
            End If
            Return True
        End Try
    End Function

    Private Sub LoadComport()
        Dim port() As String

        Try
            cboComPort.Items.Clear()
            port = SerialPort.GetPortNames

            For i = 0 To port.Length - 1
                cboComPort.Items.Add(port(i))
            Next

            cboComPort.Text = "PRESS!"

        Catch ex As Exception
            errorOut("통신설정오류")
            errorGen("시리얼 포트를 불러오는 도중 오류가 발생하였습니다." & ex.Message)
        End Try
    End Sub

    Private Sub saveConfig(saveType As Int16)

        Try
            Dim filePath, filename, saveStr As String

            filePath = System.AppDomain.CurrentDomain.BaseDirectory() & "\Config"
            dirUse(filePath)
            filename = filePath & "\" & saveCommand(saveType) & ".ini"

            Select Case saveType
                Case saveList.comport
                    Dim modeNum As Int16
                    Dim autoNum As Int16
                    Dim weightNum As Int16
                    Dim apiDBNum As Int16
                    Dim MassNum As Int16

                    If rdbMode1.Checked = True Then
                        modeNum = 0
                    ElseIf rdbMode2.Checked = True Then
                        modeNum = 1
                    Else
                        modeNum = 2
                    End If

                    If rdbAuto1.Checked = True Then
                        autoNum = 0
                    ElseIf rdbAuto2.Checked = True Then
                        autoNum = 1
                    Else
                        autoNum = 2
                    End If

                    If rdbWeightAuto.Checked = True Then
                        weightNum = 0
                    ElseIf rdbWeightCAS.Checked = True Then
                        weightNum = 1
                    ElseIf rdbWeightQW.Checked = True Then
                        weightNum = 2
                    Else
                        weightNum = 3
                    End If

                    If rdbMesDbAPI.Checked = True Then
                        apiDBNum = 0
                    Else
                        apiDBNum = 1
                    End If

                    If rdbNew.Checked = True Then
                        MassNum = 0
                    Else
                        MassNum = 1
                    End If

                    saveStr = cboComPort.SelectedItem & "^" & modeNum & "^" & autoNum & "^" & weightNum & "^" & apiDBNum & "^" & MassNum

                Case saveList.ckbData
                    saveStr = optionCkb(optionCkbList.weight).Checked & "^" & optionCkb(optionCkbList.barcode).Checked & "^" & optionCkb(optionCkbList.printer).Checked & "^" & optionCkb(optionCkbList.api).Checked

                Case saveList.divideCode
                    saveStr = txbPCNum.Text & "^" & txbIdenERP.Text & "^" & txbIdenMES.Text & "^" & txbWeightPlus.Text & "^" & txbWeightMinus.Text & "^" & txbAutoCount.Text

                Case saveList.print
                    Dim paperUse As Int16
                    If rdbPaper20.Checked = True Then
                        paperUse = 0
                    ElseIf rdbPaper30.Checked = True Then
                        paperUse = 1
                    End If

                    saveStr = txbPrintName.Text & "^" & txblabelAd.Text & "^" & txbBarValue.Text & "^" & txbtxtValue.Text & "^" & txblaBro.Text & "^" & txblaZeb.Text & "^" & paperUse

                Case saveList.lastCount
                    saveStr = autoCount

                Case Else
                    errorOut("설정오류")
                    errorGen("Config 파일을 저장하는 과정에서 오류가 발생하였습니다.")
                    Exit Sub
            End Select

            If File.Exists(filename) = True Then
                File.Delete(filename)
            End If

            File.WriteAllText(filename, saveStr, Encoding.UTF8)

        Catch ex As Exception
            errorOut("설정오류")
            errorGen("Config 파일을 저장하는 과정에서 오류가 발생하였습니다." & ex.Message)
            Exit Sub
        End Try

    End Sub

    Private Sub fullLoad(sender As Object, e As EventArgs)
        For i = 0 To saveList.print
            loadConfig(i)
        Next
        autotitleUpdate()
        modeUpdate(sender, e)
    End Sub

    Private Sub loadConfig(saveType As Int16)
        Try
            Dim filePath, fileName As String
            Dim readData As String = Nothing
            Dim str As String = Nothing

            filePath = System.AppDomain.CurrentDomain.BaseDirectory & "\Config"
            dirUse(filePath)
            fileName = filePath & "\" & saveCommand(saveType) & ".ini"

            If File.Exists(fileName) = True Then
                readData = File.ReadAllText(fileName, Encoding.UTF8)

                If readData <> Nothing Or readData <> "" Then
                    Select Case saveType

                        Case saveList.ckbData
                            Dim textNum As Int16 = UBound(Split(readData, "^"))
                            If textNum > 0 Then
                                For i = 0 To textNum
                                    If i = textNum Then
                                        optionCkb(i).Checked = readData
                                    Else
                                        optionCkb(i).Checked = Mid(readData, 1, InStr(readData, "^") - 1)
                                        readData = Mid(readData, InStr(readData, "^") + 1, readData.Length)
                                    End If
                                Next
                            End If

                            If optionCkb(optionCkbList.api).Checked = True Then
                                gbMesDb.Enabled = True
                            Else
                                gbMesDb.Enabled = False
                            End If

                            If optionCkb(optionCkbList.weight).Checked = False Then
                                rdbWeightAuto.Checked = False
                                rdbWeightCAS.Checked = False
                                rdbWeightQW.Checked = False

                                rdbWeightAuto.Enabled = False
                                rdbWeightCAS.Enabled = False
                                rdbWeightQW.Enabled = False
                            Else
                                rdbWeightAuto.Enabled = True
                                rdbWeightCAS.Enabled = True
                                rdbWeightQW.Enabled = True
                            End If

                        Case saveList.comport
                            Dim textNum As Int16 = UBound(Split(readData, "^"))
                            Dim parsingCk As String
                            Dim savedComPort As String = ""

                            For i = 0 To textNum

                                If i = textNum Then
                                    parsingCk = Mid(readData, 1, readData.Length)
                                Else
                                    parsingCk = Mid(readData, 1, InStr(readData, "^") - 1)
                                    readData = Mid(readData, InStr(readData, "^") + 1, readData.Length)
                                End If

                                If i = 0 Then
                                    savedComPort = parsingCk ' COM 포트 정보 저장
                                    cboComPort.Items.Clear()

                                    If ckbWeight.Checked = True Then

                                        LoadComport()

                                        'For cnt = 0 To cboComPort.Items.Count - 1
                                        '    cboComPort.SelectedIndex = cnt
                                        '    If parsingCk = cboComPort.SelectedItem Then
                                        '        openSerial(parsingCk)
                                        '    End If
                                        'Next
                                        For cnt = 0 To cboComPort.Items.Count - 1
                                            If parsingCk = cboComPort.Items(cnt).ToString() Then
                                                cboComPort.SelectedIndex = cnt
                                                Exit For
                                            End If
                                        Next
                                    End If

                                ElseIf i = 1 Then

                                    If parsingCk = 0 Then
                                        rdbMode1.Checked = True
                                        rdbMode2.Checked = False
                                    ElseIf parsingCk = 1 Then
                                        rdbMode1.Checked = False
                                        rdbMode2.Checked = True
                                    Else
                                        rdbMode1.Checked = True
                                        rdbMode2.Checked = False
                                    End If

                                ElseIf i = 2 Then

                                    If parsingCk = 0 Then
                                        rdbAuto1.Checked = True
                                        rdbAuto2.Checked = False
                                    ElseIf parsingCk = 1 Then
                                        rdbAuto1.Checked = False
                                        rdbAuto2.Checked = True
                                    Else
                                        rdbAuto1.Checked = True
                                        rdbAuto2.Checked = False
                                    End If

                                ElseIf i = 3 Then

                                    If parsingCk = 0 Then
                                        rdbWeightAuto.Checked = True
                                        rdbWeightCAS.Checked = False
                                        rdbWeightQW.Checked = False
                                    ElseIf parsingCk = 1 Then
                                        rdbWeightAuto.Checked = False
                                        rdbWeightCAS.Checked = True
                                        rdbWeightQW.Checked = False
                                    ElseIf parsingCk = 2 Then
                                        rdbWeightAuto.Checked = False
                                        rdbWeightCAS.Checked = False
                                        rdbWeightQW.Checked = True
                                    Else
                                        rdbWeightAuto.Checked = False
                                        rdbWeightCAS.Checked = False
                                        rdbWeightQW.Checked = False
                                    End If

                                ElseIf i = 4 Then
                                    If parsingCk = 0 Then
                                        rdbMesDbAPI.Checked = True
                                        rdbMesDbPg.Checked = False
                                    Else
                                        rdbMesDbAPI.Checked = False
                                        rdbMesDbPg.Checked = True
                                    End If

                                ElseIf i = 5 Then
                                    If parsingCk = 0 Then
                                        rdbNew.Checked = True
                                        rdbBef.Checked = False
                                    Else
                                        rdbNew.Checked = False
                                        rdbBef.Checked = True
                                    End If
                                Else
                                    errorOut("설정오류")
                                    errorGen("Config 파일을 불러오는 과정에서 오류가 발생하였습니다.")
                                End If
                            Next
                            ' 모든 설정이 로드된 후 시리얼 포트 연결 시도
                            If savedComPort <> "" AndAlso ckbWeight.Checked = True Then
                                ' UI 업데이트가 완료되도록 잠시 대기 후 실행
                                Application.DoEvents()
                                'Debug.Print("=== 설정 로드 완료 후 시리얼 포트 연결 ===")
                                'Debug.Print("저장된 COM포트: " & savedComPort)
                                'Debug.Print("QW 체크 여부: " & rdbWeightQW.Checked)
                                'Debug.Print("CAS 체크 여부: " & rdbWeightCAS.Checked)
                                openSerial(savedComPort)
                            End If

                        Case saveList.divideCode
                            Dim textNum As Int16 = UBound(Split(readData, "^"))
                            If textNum > 0 Then
                                For i = 0 To textNum
                                    If i = textNum Then
                                        optionTxb(i).Text = readData
                                    Else
                                        optionTxb(i).Text = Mid(readData, 1, InStr(readData, "^") - 1)
                                        readData = Mid(readData, InStr(readData, "^") + 1, readData.Length)
                                    End If
                                Next
                            End If

                        Case saveList.print
                            Dim textNum As Int16 = UBound(Split(readData, "^"))
                            If textNum > 0 Then
                                For i = 0 To textNum
                                    If i = textNum Then
                                        If IsNumeric(readData) = True Then
                                            If readData = 0 Then
                                                rdbPaper20.Checked = True
                                            ElseIf readData = 1 Then
                                                rdbPaper30.Checked = True
                                            End If
                                        End If
                                    Else
                                        optionprint(i).Text = Mid(readData, 1, InStr(readData, "^") - 1)
                                        readData = Mid(readData, InStr(readData, "^") + 1, readData.Length)
                                    End If
                                Next
                            End If

                        Case saveList.lastCount

                            If readData = "" Then
                                If txbAutoCount.Text.Replace(" ", "") = "" Then
                                    txbAutoCount.Text = "0"
                                    autoCount = 0
                                Else
                                    autoCount = Val(txbAutoCount.Text)
                                End If
                            Else
                                autoCount = readData
                                txbPacking.Text = readData
                            End If

                        Case Else
                            errorOut("설정오류")
                            errorGen("Config 파일을 불러오는 과정에서 오류가 발생하였습니다.")
                            Exit Sub

                    End Select
                End If
            End If


        Catch ex As Exception
            MsgBox("저장된 데이터를 불러올 수 없습니다." & saveType & "::" & ex.Message, vbCritical)
        End Try

    End Sub

    Private Sub ckbWeight_Click(sender As Object, e As EventArgs) Handles ckbWeight.Click, chbUseBarcode.Click, ckbPrinter.Click, ckbAPIuse.Click, rdbMode1.Click, rdbMode2.Click, rdbAuto1.Click, rdbAuto2.Click, rdbWeightAuto.Click, rdbWeightCAS.Click, rdbWeightQW.Click, rdbMesDbAPI.Click, rdbMesDbPg.Click, rdbNew.Click, rdbBef.Click
        ckbChange = True

        ' 중량 관련 라디오 버튼이 변경된 경우 시리얼 포트 재연결
        If TypeOf sender Is RadioButton Then
            Dim changedRadio As RadioButton = DirectCast(sender, RadioButton)
            If changedRadio.Name.StartsWith("rdbWeight") AndAlso changedRadio.Checked Then
                ' 잠시 대기 후 재연결 (UI 업데이트 완료 후)
                Application.DoEvents()
                ReconnectSerialPort()
            End If
        End If
    End Sub

    Private Sub btnReg_Click(sender As Object, e As EventArgs) Handles btnReg.Click
        If txbEventName.Text.Replace(" ", "") = "" Then
            MsgBox("이벤트명을 작성하여 주세요.", vbExclamation)
        Else
            If txbEvName.Text.Replace(" ", "") = "" Then
                MsgBox("물품명을 선택하여 주세요.", vbExclamation)
            Else
                If txbEvCode.Text.Replace(" ", "") = "" Then
                    MsgBox("물품코드를 입력하여 주세요.", vbExclamation)
                Else
                    If txbEvCount.Text.Replace(" ", "") = "" Then
                        MsgBox("수량을 입력하여 주세요.", vbExclamation)
                    Else
                        If txbEvFace.Text.Replace(" ", "") = "" Then
                            MsgBox("페이스샷을 입력하여 주세요.", vbExclamation)
                        Else
                            If txbEvEye.Text.Replace(" ", "") = "" Then
                                MsgBox("눈가샷을 입력하여 주세요.", vbExclamation)
                            Else

                                If txbLimit.Text.Replace(" ", "") = "" Then
                                    MsgBox("제한 수량을 입력하여 주세요.", vbExclamation)
                                Else
                                    If eventDBReg(txbEventName.Text, txbEvCode.Text, txbEvCount.Text, txbLimit.Text) Then
                                        If dgvRefresh() Then
                                            txbEvCode.Text = Nothing
                                            txbEvName.Text = Nothing
                                            txbEvCount.Text = Nothing
                                            txbEvFace.Text = Nothing
                                            txbEvEye.Text = Nothing
                                            txbProdCode.Text = Nothing
                                            autoUse = Nothing
                                        Else
                                            MsgBox("불러오는 데이터의 규격이 맞지 않습니다", vbCritical)
                                        End If
                                    Else
                                        MsgBox("데이터 저장에 실패했습니다.", vbCritical)
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        End If
    End Sub

    Private Function eventDBReg(name As String, code As String, count As Integer, limit As Integer)
        DBCmd = "INSERT into " & applyPackEvent & "(EventName,ItemCode,ItemCount,LimitCount) VALUE('" & name & "','" & code & "','" & count & "','" & limit & "')"
        If DBCommand(DBCmd) Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub txbEvName_gotFocus(sender As Object, e As EventArgs) Handles txbEvName.GotFocus, txbEvCode.GotFocus
        txbEvSearch.Focus()
    End Sub

    Private Sub btnEvSearch_Click(sender As Object, e As EventArgs) Handles btnEvSearch.Click

        dgvSearch.Rows.Clear()

        If txbEvSearch.Text.Replace(" ", "") = "" Then
            MsgBox("검색하고자 하는 물품을 입력하여 주십시오.", vbExclamation)
            Exit Sub
        End If

        Dim searchData As String = txbEvSearch.Text
        eventProdSearch(searchData)

    End Sub

    Private Sub eventProdSearch(data As String)
        Const rowNum As Int16 = 6
        Dim colNum As Integer = 0
        Dim outputData() As String
        Dim sqlCount As Integer = 0

        DBCmd = "SELECT un.ItemCode, un.ProdCode, un.ItemName,pd.FaceShot,pd.EyeShot,if(pd.FaceShot is NULL,'1','0') FROM (SELECT ItemCode,ProdCode,ItemName FROM " & applyPlistDB & " UNION SELECT ItemCode,ProdCode,ItemName FROM " & applyClistDB & ") AS un LEFT join " & applyPlistDB & " AS pd ON pd.ItemCode = un.ItemCode WHERE un.ItemName LIKE '%" & data & "%'"

        If DBQueryReader(DBCmd) Then
            colNum = sqlDataQuery.Length / rowNum
            ReDim eventArray(colNum - 1, rowNum - 1)

            For col = 0 To colNum - 1
                ReDim outputData(rowNum - 1)
                For row = 0 To rowNum - 1

                    outputData(row) = sqlDataQuery(sqlCount)

                    If row = rowNum - 1 Then
                        dgvSearch.Rows.Add(outputData)
                    End If

                    sqlCount += 1
                Next
            Next

            dgvSearch.Rows(0).Selected = True

        Else
            MsgBox("데이터베이스에 존재하지 않는 데이터입니다.", vbExclamation)
        End If

        prodInfoOut(0)

    End Sub

    Private Sub txbEvSearch_KeyDown(sender As Object, e As KeyEventArgs) Handles txbEvSearch.KeyDown
        If e.KeyCode = Keys.Return Then
            btnEvSearch_Click(sender, New System.EventArgs)
        End If
    End Sub

    Private Sub txbEventName_KeyDown(sender As Object, e As KeyEventArgs) Handles txbEventName.KeyDown
        If e.KeyCode = Keys.Return Then
            btnReg_Click(sender, New System.EventArgs)
        End If
    End Sub

    Private Sub txbEventDel_KeyDown(sender As Object, e As KeyEventArgs) Handles txbEventDel.KeyDown
        If e.KeyCode = Keys.Return Then
            btnEventDel_Click(sender, New System.EventArgs)
        End If
    End Sub

    Private Sub dgvSearch_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvSearch.CellClick
        Dim selNum As Integer = dgvSearch.SelectedRows(0).Index
        prodInfoOut(selNum)
    End Sub

    Private Sub prodInfoOut(selNum As Integer)
        txbEvCode.Text = dgvSearch.Rows(selNum).Cells(0).Value
        txbProdCode.Text = dgvSearch.Rows(selNum).Cells(1).Value
        txbEvName.Text = dgvSearch.Rows(selNum).Cells(2).Value

        If dgvSearch.Rows(selNum).Cells(3).Value = "0" And dgvSearch.Rows(selNum).Cells(4).Value = "0" Then
            pnEvFace.Visible = False
            pnEvFace2.Visible = False
            pnEvEye.Visible = False
            pnEvEye2.Visible = False

        Else
            pnEvFace.Visible = True
            pnEvFace2.Visible = True
            pnEvEye.Visible = True
            pnEvEye2.Visible = True
        End If

        txbEvFace.Text = dgvSearch.Rows(selNum).Cells(3).Value
        txbEvEye.Text = dgvSearch.Rows(selNum).Cells(4).Value
        autoUse = dgvSearch.Rows(selNum).Cells(5).Value
    End Sub

    Private Sub txbEvCount_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txbEvCount.KeyPress, txbEvFace.KeyPress, txbEvEye.KeyPress
        If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub

    Private Sub btnEventDel_Click(sender As Object, e As EventArgs) Handles btnEventDel.Click
        If txbEventDel.Text.Replace(" ", "") = "" Then
            MsgBox("삭제할 이벤트명을 입력하여 주십시오.", vbExclamation)
            Exit Sub
        End If

        If eventNameDel(txbEventDel.Text) Then
            If dgvRefresh() Then
                MsgBox("삭제를 완료하였습니다.", vbInformation)
            Else
                MsgBox("불러오는 데이터 규격과 맞지 않습니다.", vbCritical)
            End If

        Else
            MsgBox("삭제를 진행하는 도중 오류가 발생하였습니다.", vbCritical)
        End If

        txbEventDel.Text = Nothing
    End Sub

    Private Function eventNameDel(eventName As String) As Boolean

        DBCmd = "DELETE FROM " & applyPackEvent & " WHERE EventName = '" & eventName & "'"

        If DBCommand(DBCmd) Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub btnEvRowDel_Click(sender As Object, e As EventArgs) Handles pnMassTime.Click

        Dim rowNum As Integer = dgvEvent.SelectedCells(0).RowIndex

        dgvEvent.Rows(rowNum).Selected = True

        If MsgBox("선택한 이벤트를 삭제하시겠습니까?", vbOKCancel + vbExclamation) = MsgBoxResult.Ok Then
            If deleteRowDB(dgvEvent.Rows(rowNum).Cells(0).Value) Then
                If dgvRefresh() Then
                    MsgBox("이벤트 삭제를 완료하였습니다.", vbInformation)
                    dgvEvent.Refresh()
                Else
                    MsgBox("불러오는 데이터의 규격이 맞지 않습니다", vbCritical)
                End If
            Else
                MsgBox("삭제 중 오류가 발생하였습니다.", vbExclamation)
            End If
        End If

    End Sub

    Private Function deleteRowDB(deleteNum As Integer) As Boolean
        DBCmd = "DELETE FROM " & applyPackEvent & " WHERE NUMBER = '" & deleteNum & "'"
        If DBCommand(DBCmd) Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub btnEvAllDel_Click(sender As Object, e As EventArgs) Handles btnEvAllDel.Click

        loginForm.loginMode = False
        loginForm.ShowDialog()

        If loginForm.runSwitch = True Then
            If MsgBox("등록된 데이터를 모두 삭제하시겠습니까?", vbOKCancel, vbExclamation) = MsgBoxResult.Ok Then
                If deleteAllEvent() Then
                    If dgvRefresh() Then
                        MsgBox("등록된 데이터가 모두 삭제되었습니다.", vbInformation)
                    Else
                        MsgBox("불러오는 데이터의 규격이 맞지 않습니다", vbCritical)
                    End If
                Else
                    MsgBox("전체 삭제 중 오류가 발생하였습니다")
                End If
            End If
        End If
    End Sub

    Private Function deleteAllEvent() As Boolean
        DBCmd = "DELETE FROM " & applyPackEvent & ""
        If DBCommand(DBCmd) Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub btnChange_Click(sender As Object, e As EventArgs) Handles btnChange.Click

        If rdbMode2.Checked = True Then
            loadConfig(saveList.lastCount)
        Else
            If modeSwitch = False Then
                packFormSetting()
            Else
                stateFormSetting()
            End If
        End If

        txbProdSN.Focus()
    End Sub

    Private Sub stateFormSetting()
        btnChange.Text = "패킹코드"
        gbPacking.Enabled = False
        gbPacking.Visible = False
        stateLocation()
        resetFunc()
        ReDim prodArray(itemCode.prodCode, 0)
        txbProdSN.Focus()
        modeSwitch = False
        invEnable()
    End Sub

    Private Sub packFormSetting()
        btnChange.Text = "전표코드"
        gbPacking.Enabled = True
        gbPacking.Visible = True
        packLocation()
        resetFunc()
        ReDim prodArray(itemCode.prodCode, 0)
        cboPacking.Focus()
        modeSwitch = True
        invEnable()
    End Sub

    Private Sub packLocation()
        gbProdSN.Location = New Point(873, 4)
        gbProdSN.Size = New Size(659, 106)
        txbProdSN.Location = New Point(90, 24)
        txbProdSN.Size = New Size(448, 74)
        btnOK.Location = New Point(541, 28)
        btnOK.Size = New Size(110, 64)
    End Sub

    Private Sub stateLocation()
        gbProdSN.Location = New Point(459, 4)
        gbProdSN.Size = New Size(1073, 106)
        txbProdSN.Location = New Point(90, 24)
        txbProdSN.Size = New Size(863, 74)
        btnOK.Location = New Point(956, 29)
        btnOK.Size = New Size(110, 64)
    End Sub

    Private Sub lbPCNum_DoubleClick(sender As Object, e As EventArgs) Handles lbPCNum.DoubleClick
        If txbPCNum.Enabled = True Then
            txbPCNum.Enabled = False
        Else
            loginForm.loginMode = False
            loginForm.ShowDialog()
            If loginForm.runSwitch = True Then
                txbPCNum.Enabled = True
            End If
        End If
    End Sub

    Private Sub optionSetting()
        pnMain.Visible = False
        pnOption.Location = New Point(0, 0)
        pnOption.Size = New Size(1920, 1040)
        pnOption.Visible = True
    End Sub

    Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
        weightSum = 50
        weightForm.ShowDialog()
    End Sub

    Private Sub rdbMode1_CheckedChanged(sender As Object, e As EventArgs) Handles rdbMode1.CheckedChanged
        If rdbMode1.Checked = True Then
            gbAuto.Enabled = False
            gbMass.Enabled = False
        End If
    End Sub

    Private Sub rdbMode2_CheckedChanged(sender As Object, e As EventArgs) Handles rdbMode2.CheckedChanged
        If rdbMode2.Checked = True Then
            gbAuto.Enabled = True
            gbMass.Enabled = True
        End If
    End Sub

    Private Sub modeSetting(modeSet As Boolean, sender As Object, e As EventArgs)  '' true : 1 / false : 2
        If modeSet = True Then
            btnLoginTest.Enabled = True
            gbMESId.Enabled = True
            gbInv.Enabled = True

            gbAutoMode.Visible = False
            gbAutoMode.Enabled = False

            btnLoginTest.Visible = True
            gbMESId.Visible = True
            gbInv.Visible = True

            lbPacking.Text = "출고코드"
            txbPacking.Text = "패킹 코드"
            txbPacking.Enabled = True
            btnChange.Enabled = True

            lbProdCountB.Text = "구매수량"

            If modeSwitch = False Then
                btnChange.Text = "패킹코드"
                packFormSetting()
            Else
                btnChange.Text = "전표코드"
                stateFormSetting()
            End If

        Else
            logOff()

            btnChange.Enabled = False

            lbProdCountB.Text = "요청수량"

            gbAutoMode.Visible = True
            gbAutoMode.Enabled = True

            btnLoginTest.Visible = False
            btnLoginTest.Enabled = False

            gbMESId.Visible = False
            gbMESId.Enabled = False

            gbInv.Visible = False
            gbInv.Enabled = False

            If rdbNew.Checked = True Then
                stateFormSetting()

                modeSwitch = True

                pnMassCount.Enabled = True
                pnMassCount.Visible = True
                pnPacking.Enabled = False
                pnPacking.Visible = False

                pnTimer.Enabled = True
                pnTimer.Visible = True
                pn_image.Enabled = False
                pn_image.Visible = False

                MassValueReset()
            Else

                packFormSetting()

                pnPacking.Enabled = True
                pnPacking.Visible = True
                pnMassCount.Enabled = False
                pnMassCount.Visible = False

                pnTimer.Enabled = False
                pnTimer.Visible = False
                pn_image.Enabled = True
                pn_image.Visible = True

                btnChange.Text = "수량" & vbCrLf & "불러오기"
                lbPacking.Text = "제한수량"
                txbPacking.Text = Val(txbAutoCount.Text)
                txbPacking.Enabled = False
                autoCountReady = True
            End If

        End If
    End Sub

    Private Sub MassValueReset()
        RequestUpdate(0)
        WorkUpdate(0)
        LeftOverUpdate(0)
        StartUpdate(TimeSpan.Zero)
        EndUpdate(TimeSpan.Zero)
        UseUpdate(TimeSpan.Zero)
        AverageUpdate(TimeSpan.Zero)
        StartSwitch = True
        WorkSwitch = True
        tgtFullCount = 0
        nowFullCount = 0
        nowFullCountBack = 0
        SaveOrderName = String.Empty

    End Sub

    Private Sub StartUpdate(settime As TimeSpan)
        StartTime = settime
        lbTimeStart.Text = StartTime.ToString("hh\:mm\:ss")
        lbTimeStart.Refresh()
    End Sub

    Private Sub EndUpdate(settime As TimeSpan)
        EndTime = settime
        lbTimeEnd.Text = EndTime.ToString("hh\:mm\:ss")
        lbTimeEnd.Refresh()
    End Sub

    Private Sub UseUpdate(settime As TimeSpan)
        UseTime = settime
        lbTimeTotal.Text = UseTime.ToString("hh\:mm\:ss")
        lbTimeTotal.Refresh()
    End Sub

    Private Sub AverageUpdate(settime As TimeSpan)
        AverTime = settime
        lbTimeAver.Text = AverTime.ToString("hh\:mm\:ss")
        lbTimeAver.Refresh()
    End Sub

    Private Sub RequestUpdate(value As Integer)
        RequestCount = value
        txbRequest.Text = RequestCount
        txbRequest.Refresh()
    End Sub

    Private Sub WorkUpdate(value As Integer)
        WorkCount = value
        txbWork.Text = WorkCount
        txbWork.Refresh()
    End Sub

    Private Sub LeftOverUpdate(value As Integer)
        LeftOverCount = value
        txbLeftOver.Text = LeftOverCount
        txbLeftOver.Refresh()
    End Sub

    Private Sub lbPacking_DoubleClick(sender As Object, e As EventArgs) Handles lbPacking.DoubleClick
        If rdbMode2.Checked = True Then
            If txbPacking.Enabled = False Then
                txbPacking.Enabled = True
                autoCountReady = False
            Else
                txbPacking.Enabled = False
                autoCount = Val(txbPacking.Text)
                autoCountReady = True
            End If
        End If

        txbProdSN.Focus()
    End Sub

    Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
        Dim Ivi(1) As String   '' No. 와 프린트명
        Dim printList As System.Collections.ArrayList = New System.Collections.ArrayList(System.Drawing.Printing.PrinterSettings.InstalledPrinters)

        printList.Sort()
        dgvPrint.Rows.Clear()

        For i = 0 To printList.Count - 1
            Ivi(0) = i + 1
            Ivi(1) = printList(i).ToString

            dgvPrint.Rows.Add(Ivi)
        Next
    End Sub

    Private Sub btnLabelChange_Click(sender As Object, e As EventArgs) Handles btnLabelChange.Click
        Dim fileAddress As String = openFile()

        If fileAddress <> "FAIL" Then
            txblabelAd.Text = fileAddress
            printChange = True
        End If
    End Sub

    Private Function openFile() As String
        Dim ofd As OpenFileDialog = New OpenFileDialog
        ofd.Title = "DUALSONIC Sales Packing Print Option 라벨 파일 불러오기"
        ofd.FileName = ""
        ofd.Filter = "라벨 파일(*.lbx)|*.lbx"

        Dim ofdResult As DialogResult = ofd.ShowDialog

        If ofdResult = DialogResult.OK Then
            Return ofd.FileName
        End If

        Return "FAIL"

    End Function

    Private Sub dgvPrint_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvPrint.CellDoubleClick
        Dim selNum As Integer = dgvPrint.SelectedRows(0).Index

        If InStr(dgvPrint.Rows(selNum).Cells(1).Value.ToString.ToLower, "zdesigner") > 0 Or InStr(dgvPrint.Rows(selNum).Cells(1).Value.ToString.ToLower, "brother") > 0 Then
            txbPrintName.Text = dgvPrint.Rows(selNum).Cells(1).Value
            printChange = True
            Exit Sub
        End If

        MsgBox("라벨 프린터가 아닙니다.", vbExclamation)

    End Sub

    Private Sub btnPrintSave_Click(sender As Object, e As EventArgs) Handles btnPrintSave.Click
        saveConfig(saveList.print)
        MsgBox("저장을 완료하였습니다.", vbInformation)
        printChange = False
    End Sub

    Private Sub txbBarValue_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txbBarValue.KeyPress, txbtxtValue.KeyPress
        printChange = True
    End Sub

    Private Function printPlay(packingcode As String) As Boolean
        Try
            If rdbMode2.Checked = True And rdbAuto2.Checked = True Then
                Return True
            End If

            If packingcode = orderCode Then
                Return True
            End If

            If ckbPrinter.Checked = True Then

                If txblaBro.Text.Replace(" ", "") <> "" Then
                    If txblaZeb.Text.Replace(" ", "") <> "" Then

                        If printerState() Then

                            If InStr(txbPrintName.Text.ToLower, txblaBro.Text) > 0 Then

                                If brotherPrintPlay() Then
                                    Return True
                                Else
                                    Return False
                                End If

                            ElseIf InStr(txbPrintName.Text.ToLower, txblaZeb.Text) > 0 Then

                                If zebraPrintPlay() Then
                                    Return True
                                Else
                                    Return False
                                End If

                            Else
                                errorOut("인쇄오류")
                                errorGen("잘못된 프린터가 설정되어 있습니다. 라벨 프린터로 설정하여 주십시오.")
                                Return False
                            End If

                        Else
                            errorOut("인쇄오류")
                            errorGen("프린터가 존재하지 않습니다. 프린터 연결을 확인하여 주십시오.")
                            Return False
                        End If

                    Else
                        errorOut("인쇄오류")
                        errorGen("Zebra 사 프린터의 구분 기준을 알 수 없습니다.")
                        Return False
                    End If
                Else
                    errorOut("인쇄오류")
                    errorGen("Brother 사 프린터의 구분 기준을 알 수 없습니다.")
                    Return False
                End If
            End If

            Return True

        Catch ex As Exception
            errorOut("인쇄오류")
            errorGen("바코드 인쇄 오류 :: " & ex.Message)
            Return False
        End Try
    End Function

    Private Function brotherPrintPlay() As Boolean
        If txblabelAd.Text.Replace(" ", "") <> "" Then
            If txbBarValue.Text.Replace(" ", "") <> "" Then
                If txbtxtValue.Text.Replace(" ", "") <> "" Then

                    Dim doc As bpac.Document = New bpac.Document
                    doc.Open(txblabelAd.Text)
                    Dim usePrinter As Boolean = doc.SetPrinter(txbPrintName.Text, True)

                    If usePrinter = False Then
                        errorOut("인쇄오류")
                        errorGen("프린터가 인쇄할 준비를 하지 못했습니다.")
                        Return False
                    End If

                    For i = 0 To printSerial.Length - 1
                        doc.GetObject(txbBarValue.Text).Text = printSerial(i)
                        doc.GetObject(txbtxtValue.Text).Text = printSerial(i)

                        doc.StartPrint("", bpac.PrintOptionConstants.bpoDefault)
                        doc.PrintOut(1, bpac.PrintOptionConstants.bpoDefault)
                        doc.EndPrint()
                    Next

                    doc.Close()

                    Return True
                Else
                    errorOut("인쇄오류")
                    errorGen("라벨 텍스트를 담당하는 변수를 알 수 없습니다.")
                    Return False
                End If
            Else
                errorOut("인쇄오류")
                errorGen("라벨 바코드를 담당하는 변수를 알 수 없습니다.")
                Return False
            End If

        Else
            errorOut("인쇄오류")
            errorGen("인쇄할 라벨 파일을 알 수 없습니다. 라벨 파일을 확인하여 주십시오.")
            Return False
        End If
    End Function

    Private Function zebraPrintCode(serialCode As String) As String
        Dim zplCode As String = String.Empty
        If rdbPaper30.Checked = True Then
            zplCode = "^XA" + vbCrLf + "^FO100,70^BY2" + vbCrLf + "^BCR,120,Y,N,N,A" + vbCrLf + "^FD" & serialCode & "^FS" + vbCrLf + "^XZ"  ''시작 선언
        Else
            'zplCode = "^XA" + vbCrLf + "^FO70,30^BY2" + vbCrLf + "^BCN,90,Y,N,N,A" + vbCrLf + "^FD" & serialCode & "^FS" + vbCrLf + "^XZ"  ''시작 선언
            zplCode = "^XA" + vbCrLf + "^LH70,30" + vbCrLf + "^FO0,5^BY2" + vbCrLf + "^PRC" + vbCrLf + "^BCN,90,Y,N,N,A" + vbCrLf + "^FD" + serialCode + vbCrLf + "^FS" + vbCrLf + "^XZ"
        End If

        Return zplCode
    End Function

    Private Function zebraPrintPlay() As Boolean
        Dim pd As PrintDialog = New PrintDialog
        pd.PrinterSettings = New Printing.PrinterSettings

        For i = 0 To printSerial.Length - 1
            Dim zplCode As String = zebraPrintCode(printSerial(i))

            If Not zebraPrinterClass.SendStringToPrinter(txbPrintName.Text, zplCode) Then
                errorOut("인쇄오류")
                errorGen("제브라 프린터 사용중 오류가 발생하였습니다.")
                Return False
            End If
        Next

        Return True
    End Function

    Private Function printerState() As Boolean
        Dim scope As ManagementScope = New ManagementScope("\root\cimv2")
        scope.Connect()
        Dim searcher As ManagementObjectSearcher = New ManagementObjectSearcher("SELECT * FROM Win32_Printer")

        Dim printName As String = ""

        For Each printobj As ManagementObject In searcher.Get
            printName = printobj("Name").ToString
            If printName.Equals(txbPrintName.Text) Then
                If printobj("WorkOffline").ToString.ToLower.Equals("true") Then
                    Return False
                Else
                    Return True
                End If
            End If
        Next

        Return False
    End Function

    Private Sub autotitleUpdate()
        If rdbAuto1.Checked = True Then
            lbAutoMode.Text = "제품 등록 공정"
            pnbotWeight.Visible = False
            pnbotWeight.Enabled = False

            pnBtn.Visible = True
            pnBtn.Enabled = True
        Else
            lbAutoMode.Text = "무게 측정 공정"
            pnbotWeight.Visible = True
            pnbotWeight.Enabled = True

            pnBtn.Visible = False
            pnBtn.Enabled = False
        End If
    End Sub

    Private Sub txbProdSN_focus(sender As Object, e As EventArgs) Handles txbProdSN.GotFocus
        txbProdSN.Select(txbProdSN.Text.Length, 0)
    End Sub

    Private Sub txbPacking_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txbPacking.KeyPress, txbAutoCount.KeyPress, txbEvCount.KeyPress
        If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
            e.Handled = True
        End If
    End Sub

    Private Sub txbPacking_KeyDown(sender As Object, e As KeyEventArgs) Handles txbPacking.KeyDown
        If e.KeyCode = Keys.Return Then
            txbPacking.Enabled = False
            autoCount = Val(txbPacking.Text)
            autoCountReady = True

            txbProdSN.Focus()
        End If
    End Sub

    Private Sub successTimer_Tick(sender As Object, e As EventArgs) Handles successTimer.Tick
        If autoSuccess = False Then
            autoSuccess = True
        Else
            txbResult.Text = "대기중"
            txbResult.BackColor = Color.LemonChiffon
            successTimer.Enabled = False
        End If
    End Sub

    Private Sub txbResult_gotFocus(sender As Object, e As EventArgs) Handles txbResult.GotFocus, txbMmodel.GotFocus, txbMdevSN.GotFocus, txbMdevShot.GotFocus, txbMfaceSN.GotFocus, txbMfaceShot.GotFocus, txbMeyeSN.GotFocus, txbMeyeShot.GotFocus, txbMagent.GotFocus, txbCmodel.GotFocus, txbCfaceSN.GotFocus, txbCfaceShot.GotFocus, txbCeyeSN.GotFocus, txbCeyeShot.GotFocus, txbCbodySN.GotFocus, txbCbodyShot.GotFocus, txbCnt.GotFocus, txbCagent.GotFocus, txbCount.GotFocus, txbProSet.GotFocus, txbProFace.GotFocus, txbProEye.GotFocus, txbProBody.GotFocus, txbLuxSet.GotFocus, txbLuxFace.GotFocus, txbLuxEye.GotFocus, txbLuxBody.GotFocus, txbMAX.GotFocus, txbGel.GotFocus, txbAmp.GotFocus
        txbProdSN.Focus()
    End Sub

    Private Sub ckbInv_CheckedChanged(sender As Object, e As EventArgs) Handles ckbInv.CheckedChanged
        txbProdSN.Focus()
    End Sub

    Private Sub txbPacking_gotFocus(sender As Object, e As EventArgs) Handles txbPacking.GotFocus
        If autoCountReady = True Then
            txbProdSN.Focus()
        End If
    End Sub

    Private Sub btndgvReset_Click(sender As Object, e As EventArgs) Handles btndgvReset.Click
        If dgvRefresh() Then
            dgvEvent.Refresh()
        Else
            MsgBox("불러오는 데이터의 규격이 맞지 않습니다", vbCritical)
        End If
    End Sub

    Private Function dgvRefresh() As Boolean
        Dim runCount As Integer = 0
        Const dgvRowCount As Int16 = 10

        dgvEvent.Rows.Clear()

        DBCmd = "SELECT a.Number, a.EventName,a.ItemCode,b.ItemName,a.ItemCount,b.FaceShot,b.EyeShot,b.ProdCode,if(b.FaceShot is NULL,'1','0'),a.LimitCount FROM " & applyPackEvent & " AS a INNER JOIN (SELECT un.ItemCode, un.ProdCode, un.ItemName,pd.FaceShot,pd.EyeShot,if(pd.FaceShot is NULL,'1','0') FROM (SELECT ItemCode,ProdCode,ItemName FROM " & applyPlistDB & " UNION SELECT ItemCode,ProdCode,ItemName FROM " & applyClistDB & ") AS un LEFT join " & applyPlistDB & " AS pd ON pd.ItemCode = un.ItemCode) AS b ON a.ItemCode = b.ItemCode"
        If DBQueryReader(DBCmd) Then

            If sqlDataQuery.Length Mod dgvRowCount = 0 Then
                For i = 0 To (sqlDataQuery.Length / dgvRowCount) - 1
                    Dim dgvRowData(dgvRowCount - 1) As String

                    For cnt = 0 To dgvRowCount - 1
                        dgvRowData(cnt) = sqlDataQuery(runCount)
                        runCount += 1
                    Next

                    dgvEvent.Rows.Add(dgvRowData)

                Next
            Else
                Return False
            End If
        End If

        Return True
    End Function

    Private Sub txbWeightRg_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txbWeightPlus.KeyPress, txbWeightMinus.KeyPress, txbPCNum.KeyPress, txbIdenMES.KeyPress, txbIdenERP.KeyPress, txbAutoCount.KeyPress, txblaBro.KeyPress, txblaZeb.KeyPress
        textChange = True
    End Sub

    Private Sub rdbPaper30_CheckedChanged(sender As Object, e As EventArgs) Handles rdbPaper30.CheckedChanged, rdbPaper20.CheckedChanged
        printChange = True
    End Sub

    Private Sub ckbWeight_CheckedChanged(sender As Object, e As EventArgs) Handles ckbWeight.CheckedChanged
        If ckbWeight.Checked = True Then
            rdbWeightAuto.Enabled = True
            rdbWeightCAS.Enabled = True
            rdbWeightQW.Enabled = True

            rdbWeightAuto.Checked = True
            rdbWeightCAS.Checked = False
            rdbWeightQW.Checked = False
        Else
            rdbWeightAuto.Enabled = False
            rdbWeightCAS.Enabled = False
            rdbWeightQW.Enabled = False

            rdbWeightAuto.Checked = False
            rdbWeightCAS.Checked = False
            rdbWeightQW.Checked = False
        End If
    End Sub

    Private Sub ckbAPIuse_CheckedChanged(sender As Object, e As EventArgs) Handles ckbAPIuse.CheckedChanged
        If ckbAPIuse.Checked = True Then
            gbMesDb.Enabled = True
        Else
            gbMesDb.Enabled = False
        End If
    End Sub

    Private Sub txbProdSN_KeyDown(sender As Object, e As KeyEventArgs) Handles txbProdSN.KeyDown
        If chbUseBarcode.Checked = False Then
            If e.KeyCode = Keys.Return Then
                btnOK_Click(sender, New System.EventArgs)
            End If
        End If
    End Sub

    Private Sub mainSetting()
        pnOption.Visible = False
        pnMain.Location = New Point(0, 0)
        pnMain.Size = New Size(1920, 1040)
        pnMain.Visible = True
    End Sub

    Private Sub invEnable()
        If modeSwitch = False Then
            gbInv.Enabled = True
            ckbInv.Checked = True
        Else
            gbInv.Enabled = False
            ckbInv.Checked = False
        End If
    End Sub

End Class
