Imports System.Security.Cryptography
Imports System.Windows.Forms.AxHost
Imports Newtonsoft.Json.Linq

Public Class frm_Main

    Public programName As String = "PackingInvoiceMapper Ver. "
    Private programVer As String = "3.0.0"

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

    '--------------------------검색 및 패킹 등 기능 종류---------------
    Private Enum funcList
        search
        mapstate
        mappack
        msstate
        mspack
    End Enum
    Private setPanel(funcList.mspack) As Panel

    '--------------------------로그인 관련-----------------------------
    Private loginState As Boolean = False

    '------------------------------------------------------------------

    Private Const stateLength As Int16 = 13
    Private Const oldProdCodeLength As Int16 = 12    '12자리 제품시리얼번호
    Private Const newProdCodeLength As Int16 = 16    '16자리 제품시리얼번호

    Private DBCmd As String
    Private txbArrayList(,) As TextBox

    '-------------------------패킹관련------------------------
    Private mapStateOK As Boolean = True
    Private mapPackOk As Boolean = True
    Private mapInvOk As Boolean = True
    Private stateFullCount As Integer = 0
    Private packFullCount As Integer = 0

    Private TDUseCompare As Boolean = False

    Const invLimitCount As Int16 = 6
    Const StoreLimitCount As Int16 = 10
    Const StoreLimitMax As Int16 = 14

    '-------------------------검색 관련-------------------------

    Private ModifySwitch As Boolean = False '' 수정 더블클릭 시 온오프
    Private ModifyListSwitch As Boolean = False '' 수정 완료 시 리스트 새로고침 기능 온오프

    Private DelFuncSwitch As Boolean = False

    Private Enum itemInfoList
        code
        name
        count
        face
        eye
        id_Serial  '' 전표 : api id 코드, 맵핑 : 제품 시리얼 번호
        invoice_number
        packing_code
        pk_Type   '' 전표 : pk 코드, 맵핑 : 물품 타입(완제품 혹은 구성품)

        type  '' 정보 종합 시 물품 타입 저장
        serial '' 정보 종합 시 제품 시리얼 번호 저장
        nowcount
    End Enum

    Private chkItem(itemInfoList.pk_Type) As String

    Private Enum directData
        state
        code
        name
        count
        id
    End Enum

    Private ChkItemSet(,) As String   '' 전표 데이터
    Private packItemSet(,) As String  '' 패킹 데이터
    Private apiItemSet(,) As String  '' api 등록용 데이터 백업 배열
    Private mapping_list As New List(Of Object)

    Private btnArrayList(,) As Button

    Const btnCount As Int16 = 2

    '' 수정 및 삭제 관련
    Const indexDefault As Int16 = 16
    Const indexRange As Int16 = 6

    '' 패킹맵핑진행 - 텍스트 박스 및 버튼 위치 데이터
    Const prodMapStartCol As Int16 = 3
    Const prodMapHeight As Int16 = 39
    Const maplocplus As Int16 = 5

    ''출하내용확인 - 텍스트 박스 및 버튼 위치 데이터
    Private prodInfoWidth(txbList.Remove), prodInfoRow(txbList.Remove) As Int16
    Const locplus As Int16 = 10  ''출하내용확인 텍스트박스 간격
    Const prodInfoHeight As Int16 = 49   '' 텍스트박스, 버튼 세로 사이즈
    Const prodInfoStartCol As Int16 = 57  '' 텍스트박스 시작 부분 세로 위치

    Private Enum firstStateList
        ERP
        MES
    End Enum
    Private firstState(firstStateList.MES) As String

    Private Enum typeList
        prodSet
        prodFace
        prodEye
        prodBody
    End Enum

    Private Enum txbList
        Name
        Count
        Face
        Eye
        Modify
        Remove
    End Enum
    Private txbSetName(txbList.Remove) As String

    Private Enum ProdList
        OrderCode
        BuyDate
        AccountCode '' mes 때문에 적용 혹시 모르니 나중에 사용할 수도 있음
        AccountName
        OrdererCode
        OrdererName
        phone   '' mes 때문에 적용 혹시 모르니 나중에 사용할 수도 있음
        zip
        Address
        Refer
    End Enum
    Private ProdSelect(ProdList.Refer) As String

    '' mes 관련
    Private mesDate As DateTime

    '' 바코드 관련
    Public InputCnt As Long
    Public InputCntVal As Integer = 13

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

    ''세트코드 관련
    Private setCodeUse As Boolean = False

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

    Private Enum invList
        cj2 = 3
        hanjin = 4
        hanjin2 = 5
        cj = 6
    End Enum

    Private query_product As String
    Private query_component As String

    Private Sub frm_Main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        DataSetting()
        formSetting()
        funcSetting()

        txbStateRead.Focus()
    End Sub

    Private Sub funcSetting()
        rdbState.Checked = True
        ckbBarcode.Checked = 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 ckbBarcode.Checked Then
                btnSearch_Click(sender, e)
            Else
                txbStateRead.Focus()
                txbStateRead.Refresh()
            End If
        End If
    End Sub

    Private Sub txbStateRead_TextChanged(sender As Object, e As EventArgs) Handles txbStateRead.TextChanged, txbStateRead.Click
        If txbStateRead.Enabled = True Then
            Dim tmpStr As String
            txbStateRead.BackColor = Color.White

            If InputCnt = 0 And ckbBarcode.Checked = True Then
                If txbStateRead.Text <> String.Empty Then
                    tmpStr = txbStateRead.Text
                    If (Len(tmpStr) > 1) Then
                        tmpStr = Mid(tmpStr, Len(tmpStr), 1)
                        txbStateRead.Clear()
                        txbStateRead.AppendText(tmpStr)
                    End If
                    SetInputCnt()
                End If
            End If
        End If
    End Sub

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

    Private Sub formSetting()
        Me.Text = programName & programVer
        Me.Size = New Drawing.Size(1920, 1060)
    End Sub

    Private Sub DataSetting()
        txbNameValue(funcList.search)

        prodInfoWidth(txbList.Modify) = "95"
        prodInfoWidth(txbList.Remove) = "95"

        prodInfoRow(txbList.Modify) = "1029"
        prodInfoRow(txbList.Remove) = "1131"

        txbSetName(txbList.Modify) = "btnModify"
        txbSetName(txbList.Remove) = "btnRemove"

        firstState(firstStateList.ERP) = "E040221"
        firstState(firstStateList.MES) = "ORD"

        setPanel(funcList.search) = pnProdInfo
        setPanel(funcList.mapstate) = pnMapStProd
        setPanel(funcList.mappack) = pnMapPkProd
        setPanel(funcList.msstate) = pnMsStProd
        setPanel(funcList.mspack) = pnMsPkProd

        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.address) = "receiverAddress"
        apiCommand(parsingCode.item) = "Item"
        apiCommand(parsingCode.state) = "state"

        DBCmd = "SELECT MAX(ProdCode) FROM " & applyPlistDB & ";"
        If DBQueryReader(DBCmd) Then
            item_product_max_index = sqlDataQuery(0)
            ReDim item_product_list(item_product_max_index)
        End If

        '제품 ProdCode는 1부터 시작하며, ProSet(1),LuxSet(2)는 같은 컬럼을 사용하고 있어 중복되기 때문에 2부터 조회
        DBCmd = "SELECT CAST(ProdCode AS CHAR), SalesPackingCntColNm, SalesPackingSerialColNm FROM " & applyPlistDB & " WHERE ProdCode > 1 GROUP BY ProdCode ORDER BY ProdCode asc;"
        If DBQueryReader(DBCmd) Then
            Dim RowCount As Int16 = (sqlDataQuery.Length / 3)
            Dim dataSetCount As Int32 = 0
            Dim item_data As item_info

            For row = 1 To RowCount
                item_data.item_type = "P"
                For col = 0 To 2
                    If col = 0 Then
                        item_data.prod_code = sqlDataQuery(dataSetCount)
                    ElseIf col = 1 Then
                        item_data.sales_packing_cnt_col_nm = sqlDataQuery(dataSetCount)
                    ElseIf col = 2 Then
                        item_data.sales_packing_serial_col_nm = sqlDataQuery(dataSetCount)
                    End If
                    dataSetCount += 1
                Next
                item_product_list(item_data.prod_code) = item_data
            Next
        End If

        DBCmd = "SELECT MAX(ProdCode) FROM " & applyClistDB & ";"
        If DBQueryReader(DBCmd) Then
            item_component_max_index = sqlDataQuery(0)
            ReDim item_component_list(item_component_max_index)
        End If

        DBCmd = "SELECT CAST(ProdCode AS CHAR), SalesPackingCntColNm FROM " & applyClistDB & " GROUP BY ProdCode ORDER BY ProdCode asc;"
        If DBQueryReader(DBCmd) Then
            Dim RowCount As Int16 = (sqlDataQuery.Length / 2) - 1
            Dim dataSetCount As Int32 = 0
            Dim item_data As item_info

            For row = 0 To RowCount
                item_data.item_type = "C"
                For col = 0 To 1
                    If col = 0 Then
                        item_data.prod_code = sqlDataQuery(dataSetCount)
                    ElseIf col = 1 Then
                        item_data.sales_packing_cnt_col_nm = sqlDataQuery(dataSetCount)
                    End If
                    dataSetCount += 1
                Next
                item_component_list(item_data.prod_code) = item_data
            Next
        End If

        '제품 정보 조회 쿼리 생성
        'item_product_list 에 index (2)부터 등록되어 있기에 (2)부터 조회
        query_product = Nothing
        For i = 2 To item_product_max_index
            If query_product = Nothing Then
                query_product = "IFNULL(" & item_product_list(i).sales_packing_serial_col_nm & ",'NULL'), IFNULL(" & item_product_list(i).sales_packing_cnt_col_nm & ",'0')"
            Else
                query_product = query_product & ", IFNULL(" & item_product_list(i).sales_packing_serial_col_nm & ",'NULL'), IFNULL(" & item_product_list(i).sales_packing_cnt_col_nm & ",'0')"
            End If
        Next

        '구성품 정보 조회 쿼리 생성
        query_component = Nothing
        For i = 0 To item_component_max_index
            '구성품 중 ProdCode는 있으나 품목이 없는 경우가 있기에 NULL 체크 필요
            If item_component_list(i).sales_packing_cnt_col_nm <> Nothing Then
                If query_component = Nothing Then
                    query_component = "IFNULL(" & item_component_list(i).sales_packing_cnt_col_nm & ",'0')"
                Else
                    query_component = query_component & ", IFNULL(" & item_component_list(i).sales_packing_cnt_col_nm & ",'0')"
                End If
            Else
                If query_component = Nothing Then
                    query_component = "'0'"
                Else
                    query_component = query_component & ", '0'"
                End If
            End If
        Next

    End Sub

    Private Sub txbNameValue(valueType As Int16)  '' order 데이터 - true / packing 데이터 - false

        For i = 0 To txbList.Eye
            txbSetName(i) = String.Empty
            prodInfoWidth(i) = 0
            prodInfoRow(i) = 0
        Next

        Select Case valueType
            Case funcList.search

                txbSetName(txbList.Name) = "txbProdName"
                txbSetName(txbList.Count) = "txbProdCount"
                txbSetName(txbList.Face) = "txbProdFace"
                txbSetName(txbList.Eye) = "txbProdEye"

                prodInfoWidth(txbList.Name) = "660"
                prodInfoWidth(txbList.Count) = "80"
                prodInfoWidth(txbList.Face) = "118"
                prodInfoWidth(txbList.Eye) = "131"

                prodInfoRow(txbList.Name) = "20"
                prodInfoRow(txbList.Count) = "685"
                prodInfoRow(txbList.Face) = "769"
                prodInfoRow(txbList.Eye) = "891"

            Case funcList.mapstate

                txbSetName(txbList.Name) = "txbMapName"
                txbSetName(txbList.Count) = "txbMapCount"
                txbSetName(txbList.Face) = "txbMapFace"
                txbSetName(txbList.Eye) = "txbMapEye"

                prodInfoWidth(txbList.Name) = "564"
                prodInfoWidth(txbList.Count) = "106"
                prodInfoWidth(txbList.Face) = "110"
                prodInfoWidth(txbList.Eye) = "110"

                prodInfoRow(txbList.Name) = "15"
                prodInfoRow(txbList.Count) = "585"
                prodInfoRow(txbList.Face) = "695"
                prodInfoRow(txbList.Eye) = "810"

            Case funcList.mappack

                txbSetName(txbList.Name) = "txbPackName"
                txbSetName(txbList.Count) = "txbPackCount"
                txbSetName(txbList.Face) = "txbPackFace"
                txbSetName(txbList.Eye) = "txbPackEye"

                prodInfoWidth(txbList.Name) = "564"
                prodInfoWidth(txbList.Count) = "106"
                prodInfoWidth(txbList.Face) = "110"
                prodInfoWidth(txbList.Eye) = "110"

                prodInfoRow(txbList.Name) = "15"
                prodInfoRow(txbList.Count) = "585"
                prodInfoRow(txbList.Face) = "695"
                prodInfoRow(txbList.Eye) = "810"

            Case funcList.msstate

                txbSetName(txbList.Name) = "txbMsStName"
                txbSetName(txbList.Count) = "txbMsStCount"
                txbSetName(txbList.Face) = "txbMsStFace"
                txbSetName(txbList.Eye) = "txbMsStEye"

                prodInfoWidth(txbList.Name) = "564"
                prodInfoWidth(txbList.Count) = "106"
                prodInfoWidth(txbList.Face) = "110"
                prodInfoWidth(txbList.Eye) = "110"

                prodInfoRow(txbList.Name) = "15"
                prodInfoRow(txbList.Count) = "585"
                prodInfoRow(txbList.Face) = "695"
                prodInfoRow(txbList.Eye) = "810"

            Case funcList.mspack

                txbSetName(txbList.Name) = "txbMsPkName"
                txbSetName(txbList.Count) = "txbMsPkCount"
                txbSetName(txbList.Face) = "txbMsPkFace"
                txbSetName(txbList.Eye) = "txbMsPkEye"

                prodInfoWidth(txbList.Name) = "564"
                prodInfoWidth(txbList.Count) = "106"
                prodInfoWidth(txbList.Face) = "110"
                prodInfoWidth(txbList.Eye) = "110"

                prodInfoRow(txbList.Name) = "15"
                prodInfoRow(txbList.Count) = "585"
                prodInfoRow(txbList.Face) = "695"
                prodInfoRow(txbList.Eye) = "810"
        End Select

    End Sub

    Private Sub NowTimer_Tick(sender As Object, e As EventArgs) Handles NowTimer.Tick
        lblTime.Text = Now
    End Sub

    Private Sub btnSearch_Click(sender As Object, e As EventArgs) Handles btnSearch.Click

        If btnSearch.Text = "등 록" Then

            If rdbMass.Checked = True Then
                If compareSaveEx() Then
                    txbStateRead.BackColor = Color.Red
                Else
                    txbStateRead.BackColor = Color.Green
                End If
            Else
                If compareSave() Then
                    txbStateRead.BackColor = Color.Red
                Else
                    txbStateRead.BackColor = Color.Green
                End If
            End If

        Else

            If txbStateRead.Text.Replace(" ", "") = "" Then
                MsgBox("검색란이 비워져 있습니다. 검색하고자 하는 전표번호를 입력하여 주십시오.", vbExclamation)
                Exit Sub
            End If

            If rdbState.Checked = True Then

                compareClear()

                If orderSearch(txbStateRead.Text) Then
                    txbStateRead.BackColor = Color.Green
                Else
                    txbStateRead.BackColor = Color.Red
                End If

            ElseIf rdbMap.Checked = True Then

                If mappingRunning(txbStateRead.Text) Then
                    txbStateRead.BackColor = Color.Green
                Else
                    txbStateRead.BackColor = Color.Red
                End If

            Else

                If MassPacking_Ex2(txbStateRead.Text) Then
                    txbStateRead.BackColor = Color.Green
                Else
                    txbStateRead.BackColor = Color.Red
                End If

            End If

        End If

        txbStateRead.Focus()

    End Sub
    '-------------------------------대량 포장----------------------------------
    Private Sub MassTxbReset()
        gbMsInfo.BackColor = SystemColors.Control
        txbMsState.Text = "N/A"
        txbMsDate.Text = "N/A"
        txbMsOrder.Text = "N/A"
        txbMsAccount.Text = "N/A"
        txbMsRefer.Text = "N/A"

        gbMsPkInfo.BackColor = SystemColors.Control
        txbMsPacking.Text = "N/A"
        txbMsPkDate.Text = "N/A"

        'txbMsInv.Text = String.Empty

        txbMsState.Refresh()
        txbMsDate.Refresh()
        txbMsOrder.Refresh()
        txbMsAccount.Refresh()
        txbMsRefer.Refresh()

        txbMsPacking.Refresh()
        txbMsPkDate.Refresh()

        'txbMsInv.Refresh()
    End Sub

    Private Sub MassReset()
        StartFunc = True
        fullSuccess = False
        stateSuccess = False
        packSuccess = False
        invSuccess = False
        StateTxbClear(funcList.msstate)
        StateTxbClear(funcList.mspack)
        MassTxbReset()
        compareValueClean()
    End Sub

    Private Sub msPKTxbReset()
        gbMsPkInfo.BackColor = SystemColors.Control
        txbMsPacking.Text = "N/A"
        txbMsPkDate.Text = "N/A"

        txbMsPacking.Refresh()
        txbMsPkDate.Refresh()
    End Sub

    Private Sub StateReset()
        gbMsInfo.BackColor = SystemColors.Control
        txbMsState.Text = "N/A"
        txbMsDate.Text = "N/A"
        txbMsOrder.Text = "N/A"
        txbMsAccount.Text = "N/A"
        txbMsRefer.Text = "N/A"

        txbMsState.Refresh()
        txbMsDate.Refresh()
        txbMsOrder.Refresh()
        txbMsAccount.Refresh()
        txbMsRefer.Refresh()
    End Sub

    Private Sub PackReset()
        gbMsPkInfo.BackColor = SystemColors.Control
        txbMsPacking.Text = "N/A"
        txbMsPkDate.Text = "N/A"

        txbMsPacking.Refresh()
        txbMsPkDate.Refresh()
    End Sub

    Private StartFunc As Boolean = True
    Private invSuccess As Boolean = False
    Private packSuccess As Boolean = False
    Private stateSuccess As Boolean = False
    Private fullSuccess As Boolean = False

    Private RequestCount As Integer = 0  '' 요청수량
    Private WorkCount As Integer = 0  '' 작업 수량
    Private LeftOverCount As Integer = 0 '' 남은수량

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

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

    Private Sub MassResetEx()
        StateTxbClear(funcList.msstate)
        StateTxbClear(funcList.mspack)
        MassValueClear()
        MassTxbClear()
    End Sub

    Private Sub MassPackReset()
        StateTxbClear(funcList.mspack)
        ReDim packItemSet(0, 0)
        txbLabelCode.Text = String.Empty
        txbLabelCode.BackColor = Color.White
    End Sub

    Private Sub MassValueClear()
        stateSuccess = False
        packSuccess = False
        fullSuccess = False
        StartFunc = False
        invSuccess = False

        StartTime = TimeSpan.Zero
        EndTime = TimeSpan.Zero
        UseTime = TimeSpan.Zero
        AverTime = TimeSpan.Zero

        SetPKCode = String.Empty
        ReDim SetIdCode(0)


    End Sub

    Private Sub MassTxbClear()
        txbMsState.Text = String.Empty
        txbMsDate.Text = String.Empty
        txbMsOrder.Text = String.Empty
        txbMsAccount.Text = String.Empty
        txbMsRefer.Text = String.Empty
        txbMsPacking.Text = String.Empty
        txbMsPkDate.Text = String.Empty
        txbLabelCode.Text = String.Empty

        RequestCount = 0
        txbRequest.Text = RequestCount
        txbRequest.ForeColor = Color.Black

        WorkCount = 0
        txbWork.Text = WorkCount
        txbWork.ForeColor = Color.Black

        LeftOverCount = 0
        txbLeftOver.Text = LeftOverCount
        txbLeftOver.ForeColor = Color.Black

        lbTimeStart.Text = StartTime.ToString("hh\:mm\:ss")
        lbTimeEnd.Text = EndTime.ToString("hh\:mm\:ss")
        lbTimeTotal.Text = UseTime.ToString("hh\:mm\:ss")
        lbTimeAver.Text = AverTime.ToString("hh\:mm\:ss")

    End Sub

    Private Function MassPacking_Ex2(codeData As String) As Boolean
        If StartFunc Then
            MassResetEx()
        End If

        If fullSuccess = True Then

            If codeData.Replace(" ", "") = "" Then
                MsgBox("라벨번호를 입력하지 않았습니다.", vbExclamation)
                Return False
            End If

            If codeData.Length < StoreLimitCount Or codeData.Length > StoreLimitMax Then
                MsgBox("양식에 맞지 않는 입고번호입니다.", vbExclamation)
                Return False
            End If

            If SerialCheck(codeData) Then  '' 중복 유무 확인
                MsgBox("패킹 번호는 송장 번호로 사용할 수 없습니다.", vbExclamation)
                Return False
            End If

            txbLabelCode.Text = codeData
            txbLabelCode.BackColor = Color.ForestGreen

            WorkCount += 1
            LeftOverCount -= 1
            txbWork.Text = WorkCount
            txbWork.ForeColor = Color.Blue
            txbLeftOver.Text = LeftOverCount
            txbLeftOver.ForeColor = Color.Red

            For i = 0 To packItemSet.GetLength(1) - 1
                packItemSet(itemInfoList.invoice_number, i) = codeData
                packItemSet(itemInfoList.packing_code, i) = txbMsPacking.Text
            Next

            mapping_list.Add(packItemSet)

            If RequestCount = WorkCount Then
                invSuccess = True
            Else
                fullSuccess = False
                invSuccess = False
                packSuccess = False
            End If

        Else
            If codeData.Length = oldProdCodeLength Or codeData.Length = newProdCodeLength Then
                MassPackReset()

                If stateSuccess = False Then
                    MsgBox("전표 데이터를 알 수 없습니다. 전표 데이터를 먼저 스캔하여 주십시오.", vbExclamation)
                    Return False
                End If

                If packingCompare(codeData) Then '' 패킹 내역 존재 유무
                    Return False
                End If

                If mappingComapare(codeData) Then '' 맵핑 유무 확인
                    Return False
                End If

                If SerialCheck(codeData) Then  '' 중복 유무 확인
                    Return False
                End If

                If packingSearch(codeData) Then
                    Return False
                End If

                If comSearch(codeData) Then
                    Return False
                End If

                If packDateSearch(codeData) Then
                    Return False
                End If

                txbMsPacking.Text = codeData

                If massListSetting(pnMsPkProd, funcList.mspack, False) Then
                    Return False
                End If

                gbMapPkInfo.BackColor = Color.ForestGreen

                packSuccess = True

            Else

                gbMsState.Text = "■ 출하지시서 정보"

                If Mid(codeData, 1, 7) = firstState(firstStateList.ERP) Or Mid(codeData, 1, 3) = firstState(firstStateList.MES) Then

                    setCodeUse = False
                    stateFullCount = 0
                    mapping_list.Clear()

                    If ckbAPIUse.Checked = True Then

                        If ExistApiCompare(codeData) Then
                            Return False
                        End If

                        If ckbPostgre.Checked = True Then

                            If useAPIDirect(codeData) Then
                                Return False
                            End If

                        Else

                            If mesRunning(codeData) Then
                                Return False
                            End If

                        End If

                    Else
                        If ExistDataCompare(codeData) Then
                            Return False
                        End If

                        If completeCompare(codeData) Then
                            Return False
                        End If

                        If orderer_Search(codeData) Then
                            Return False
                        End If

                        If Product_Search(codeData) Then
                            Return False
                        End If
                    End If

                    apiBackupData()

                    If PKCodeCheck() Then
                        Return False
                    End If

                    If PKCodeSearch() Then
                        Return False
                    End If

                    If massListSetting(pnMsStProd, funcList.msstate, True) Then
                        Return False
                    End If

                    txbMsState.Text = ProdSelect(ProdList.OrderCode)
                    txbMsDate.Text = ProdSelect(ProdList.BuyDate)
                    txbMsOrder.Text = ProdSelect(ProdList.OrdererName)
                    txbMsAccount.Text = ProdSelect(ProdList.AccountName)
                    txbMsRefer.Text = ProdSelect(ProdList.Refer)

                    gbMapStInfo.BackColor = Color.ForestGreen

                    StartTime = DateTime.Now.TimeOfDay
                    lbTimeStart.Text = StartTime.ToString("hh\:mm\:ss")

                    stateSuccess = True

                Else
                    MsgBox("번호 양식에 맞지 않는 번호입니다. 확인하여 주십시오.", vbExclamation)
                    Return False
                End If

            End If

            If packSuccess = True And stateSuccess = True Then

                If statePackmsCompare() Then
                    Return False
                End If

                fullSuccess = True
            End If
        End If

        If fullSuccess = True And invSuccess = True Then
            If ckbAuto.Checked = True Then
                If compareSaveEx() Then
                    Return False
                End If
            Else
                btnSearch.Text = "등 록"
            End If
        End If

        Return True
    End Function

    Private Function PKCodeSearch() As Boolean
        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 = '" & SetPKCode & "'"

        If DBQueryReader(DBCmd) Then
            Dim dataCount As Integer = 0
            Dim rowNum As Integer = (sqlDataQuery.Length / 5) - 1
            ReDim ChkItemSet(itemInfoList.id_Serial, rowNum)

            For i = 0 To rowNum
                For n = 0 To itemInfoList.eye
                    ChkItemSet(n, i) = sqlDataQuery(dataCount)

                    dataCount += 1
                Next
            Next

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

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

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

            SetIdCode(i) = ChkItemSet(itemInfoList.id_Serial, i)
        Next

        gbMsState.Text = "■ 출하지시서 정보 : " & SetPKCode
        RequestCount = ChkItemSet.GetLength(1)
        LeftOverCount = RequestCount
        txbRequest.Text = RequestCount
        txbWork.Text = WorkCount
        txbLeftOver.Text = LeftOverCount

        Return False
    End Function

    Private Function SerialCheck(codeData As String) As Boolean
        If stateSuccess = True Then
            For i = 0 To ChkItemSet.GetLength(1) - 1
                If InStr(ChkItemSet(itemInfoList.id_Serial, i), codeData) > 0 Then
                    MsgBox("중복값이 존재합니다.", vbExclamation)
                    Return True
                End If
            Next
        End If

        Return False
    End Function

    Private Function compareSaveEx() As Boolean

        txbStateRead.Enabled = False
        txbStateRead.Text = "등록중"
        txbStateRead.BackColor = Color.Yellow

        Dim nowToday As String = Format(Now, "yyyy") & "-" & Format(Now, "MM") & "-" & Format(Now, "dd")

        If ckbAPIUse.Checked = True Then

            If rdbMass.Checked = True Then
                If apiMassSave() Then
                    failForm()
                    Return True
                End If

                'If apiSerialSave() Then
                '    failForm()
                '    Return True
                'End If
            Else
                apiSerialData()

                If mesDataReg() Then
                    failForm()
                    Return True
                End If

                If mesDBOrderReg(nowToday) Then
                    failForm()
                    Return True
                End If
            End If

        Else

            If rdbStateInv.Checked = True Then
                If dbSaveInv(nowToday) Then
                    failForm()
                    Return True
                End If
            Else
                If dbSave(nowToday) Then
                    failForm()
                    Return True
                End If
            End If

        End If

        txbStateRead.Text = "등록완료"
        StartFunc = True

        EndTime = DateTime.Now.TimeOfDay
        lbTimeEnd.Text = EndTime.ToString("hh\:mm\:ss")
        lbTimeEnd.Refresh()

        UseTime = EndTime - StartTime
        lbTimeTotal.Text = UseTime.ToString("hh\:mm\:ss")
        lbTimeTotal.Refresh()

        Dim AverResult As Integer = CInt(UseTime.TotalSeconds)
        AverResult = AverResult / RequestCount

        AverTime = TimeSpan.FromSeconds(AverResult)
        lbTimeAver.Text = AverTime.ToString("hh\:mm\:ss")
        lbTimeAver.Refresh()

        gbMapStInfo.BackColor = SystemColors.Control
        gbMapPkInfo.BackColor = SystemColors.Control
        btnSearch.Text = "검 색"
        txbInv.Enabled = False

        txbStateRead.Enabled = True

        txbStateRead.SelectionStart = txbStateRead.TextLength
        txbStateRead.ScrollToCaret()
        Return False
    End Function

    Private Function msProduct_Search(DataCode As String) As Boolean
        Dim QueryCount As Integer = 0

        DBCmd = "SELECT Item_Code,Item_Name,Item_Count,Apply_Face,Apply_Eye FROM " & applyOrderDB & " WHERE Order_Code = '" & DataCode & "'"
        If DBQueryReader(DBCmd) Then
            Dim DataCount As Integer = sqlDataQuery.Length

            If rdbState.Checked = True Then
                ReDim ChkItemSet(itemInfoList.eye, (DataCount / (itemInfoList.eye + 1)) - 1)
            Else
                ReDim ChkItemSet(itemInfoList.nowcount, (DataCount / (itemInfoList.eye + 1)) - 1)
            End If

            For row = 0 To ChkItemSet.GetLength(1) - 1
                For col = 0 To itemInfoList.eye
                    ChkItemSet(col, row) = sqlDataQuery(QueryCount)
                    QueryCount += 1
                Next
            Next

            Return False
        Else
            Return True
        End If
    End Function

    Private Function massListSetting(pntype As Panel, valueType As Int16, type As Boolean) As Boolean   '' 전표번호 : true / 패킹번호 : false
        Try
            Dim RowDataCount As Integer
            Dim txbCount As Int16

            If type = True Then
                RowDataCount = ChkItemSet.GetLength(1) - 1
                StateTxbClear(funcList.msstate)
                txbCount = txbList.Eye
                ReDim txbArrayList(RowDataCount, txbList.Eye)
            Else
                RowDataCount = packItemSet.GetLength(1) - 1
                StateTxbClear(funcList.mspack)
                txbCount = txbList.Eye

            End If

            Dim prodMapCol As Integer = 0

            For cnt = 0 To RowDataCount
                For i = 0 To txbCount
                    Dim txtBox As TextBox = New TextBox

                    If cnt = 0 Then
                        prodMapCol = prodMapStartCol
                    Else
                        If i = txbList.Name Then
                            prodMapCol = prodMapCol + prodMapHeight + maplocplus
                        End If
                    End If

                    txtBox.Name = txbSetName(i) & cnt
                    pntype.Controls.Add(txtBox)
                    txtBox.Font = New Font("함초롱바탕", 18, FontStyle.Bold)
                    txtBox.Size = New Drawing.Size(prodInfoWidth(i), prodMapHeight)
                    txtBox.Location = New Point(prodInfoRow(i), prodMapCol)

                    If type = True Then
                        txtBox.Text = ChkItemSet(i + 1, cnt)
                        txbArrayList(cnt, i) = txtBox

                        If i = txbList.Count + 1 Then
                            stateFullCount += ChkItemSet(itemInfoList.count, cnt)
                        End If
                    Else
                        txtBox.Text = packItemSet(i + 1, cnt)

                        If i = txbList.Count + 1 Then
                            packFullCount += packItemSet(itemInfoList.count, cnt)
                        End If
                    End If

                    txtBox.ReadOnly = True
                    txtBox.BackColor = Color.White
                Next
            Next

            Return False
        Catch ex As Exception
            MsgBox("리스트를 생성하는 도중 오류가 발생하였습니다. :: " & ex.Message, vbCritical)
            Return True
        End Try
    End Function

    Private Function statePackmsCompare() As Boolean

        If ChkItemSet.GetLength(1) = packItemSet.GetLength(1) Then
            For pack = 0 To packItemSet.GetLength(1) - 1
                Dim checkOk As Boolean = False
                For chkState = 0 To ChkItemSet.GetLength(1) - 1

                    Dim packCodeData As String
                    Dim packCode As String = packItemSet(itemInfoList.code, pack)
                    Dim codeNum As Int16 = UBound(Split(packItemSet(itemInfoList.code, pack), "/"))

                    For i = 0 To codeNum
                        If i = codeNum Then
                            packCodeData = Mid(packCode, 1, packCode.Length)
                        Else
                            packCodeData = Mid(packCode, 1, InStr(packCode, "/") - 1)
                            packCode = Mid(packCode, InStr(packCode, "/") + 1, packCode.Length)
                        End If

                        If packCodeData = ChkItemSet(itemInfoList.code, chkState) Then
                            If ChkItemSet(itemInfoList.count, chkState) = packItemSet(itemInfoList.count, pack) Then
                                If ChkItemSet(itemInfoList.face, chkState) = packItemSet(itemInfoList.face, pack) Then
                                    If ChkItemSet(itemInfoList.eye, chkState) = packItemSet(itemInfoList.eye, pack) Then

                                        If ChkItemSet(itemInfoList.id_Serial, chkState) = String.Empty Then
                                            ChkItemSet(itemInfoList.id_Serial, chkState) = packItemSet(itemInfoList.id_Serial, pack)
                                        Else
                                            ChkItemSet(itemInfoList.id_Serial, chkState) = ChkItemSet(itemInfoList.id_Serial, chkState) & "/" & packItemSet(itemInfoList.id_Serial, pack)
                                        End If

                                        checkOk = True
                                        Exit For
                                    End If
                                End If
                            End If
                        End If

                    Next

                    If checkOk = True Then
                        Exit For
                    End If

                Next

                If checkOk = False Then
                    For i = 0 To txbList.Eye
                        txbArrayList(pack, i).BackColor = Color.Red
                    Next
                    gbMapPkInfo.BackColor = Color.Red
                    MsgBox("맞지 않는 제품이 포장되어 있습니다. 확인하여 주십시오.", vbCritical)
                    Return True
                End If

            Next

            Return False
        Else
            For i = 0 To packItemSet.GetLength(1) - 1
                txbArrayList(i, txbList.Count).BackColor = Color.Red
            Next

            gbMapPkInfo.BackColor = Color.Red
            MsgBox("항목 개수가 맞지 않습니다.", vbCritical)
            Return True
        End If

    End Function

    '-------------------------------출하 검색----------------------------------

    Private Function orderSearch(codeData As String) As Boolean

        If codeData.Length = oldProdCodeLength Or codeData.Length = newProdCodeLength Then

            If packingCompare(codeData) Then
                Return False
            End If

            Dim orderPackCode As String = orderPackingCompare(codeData)

            If orderPackCode = "FAIL" Then
                Return False
            End If

            If orderPackCode = "NOLINK" Then
                nolinkOutput()
            Else
                If orderer_Search(orderPackCode) Then
                    Return False
                End If
            End If

            If packingSearch(codeData) Then
                Return False
            End If

            If comSearch(codeData) Then
                Return False
            End If

            If ListSetting(True) Then
                MsgBox("제품 리스트 생성 중 오류가 발생하였습니다.", vbCritical)
                Return False
            End If

        Else
            If Mid(codeData, 1, 7) = firstState(firstStateList.ERP) Or Mid(codeData, 1, 3) = firstState(firstStateList.MES) Then

                If ckbAPIUse.Checked = True Then
                    If mesRunning(codeData) Then
                        Return False
                    End If
                Else
                    If ExistDataCompare(codeData) Then
                        Return False
                    End If

                    If orderer_Search(codeData) Then
                        Return False
                    End If

                    If Product_Search(codeData) Then
                        MsgBox("해당 전표코드의 제품 데이터가 존재하지 않습니다.", vbCritical)
                        Return False
                    End If
                End If

                If ListSetting(True) Then
                    Return False
                End If

            Else
                MsgBox("전표번호 양식과 맞지 않습니다. 전표번호를 확인하여 주십시오.", vbExclamation)
                Return False
            End If
        End If

        txbChkState.Text = ProdSelect(ProdList.OrderCode)
        txbChkCode.Text = ProdSelect(ProdList.OrdererCode)
        txbChkOrderer.Text = ProdSelect(ProdList.OrdererName)
        txbChkAcc.Text = ProdSelect(ProdList.AccountName)
        txbChkDate.Text = ProdSelect(ProdList.BuyDate)
        txbChkRefer.Text = ProdSelect(ProdList.Refer)
        txbChkAD.Text = ProdSelect(ProdList.Address)

        Return True

    End Function

    Private Function mesRunning(codeData As String) As Boolean
        mesDate = Nothing

        If mesDateSet(codeData) Then
            MsgBox("MES 형식과 맞지 않는 코드 번호입니다.", vbExclamation)
            Return True
        End If

        Dim searchData As String = "createdAtFrom=" & mesDate & "&createdAtTo=" & mesDate.AddDays(1) & ""

        Dim apiResult As String = apiRequest_GET(apiItemOutURL, searchData)

        If apiResult = "-1" Then
            MsgBox("등록된 데이터가 존재하지 않습니다.", vbExclamation)
            Return True
        End If

        If mesParsing(apiResult, codeData) Then
            Return True
        End If

        mesShotSearch()
        ProdSelect(ProdList.OrderCode) = codeData
        Return False
    End Function

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

    Private Function mesParsing(pData As String, codeData As String) As Boolean
        Try
            Dim dataCount As Int16 = 0
            Dim codeExist As Boolean = False

            If rdbState.Checked = True Then
                ReDim ChkItemSet(itemInfoList.id_Serial, 0)
            ElseIf rdbMap.Checked = True Then
                ReDim ChkItemSet(itemInfoList.serial, 0)
            Else
                ReDim ChkItemSet(itemInfoList.nowcount, 0)
            End If

            ReDim ProdSelect(ProdList.Refer)

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

            If pData <> "SUCCESS" Then
                MsgBox("Data를 불러오는데 실패하였습니다.", vbCritical)
                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
                MsgBox("MES에 존재하지 않은 데이터입니다.", vbExclamation)
                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 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 = codeData Then

                        Dim NowState As String = jsArray(cnt)(apiCommand(parsingCode.state)).ToString

                        If NowState <> "canceled" Then

                            If rdbState.Checked = True Then
                                ReDim Preserve ChkItemSet(itemInfoList.id_Serial, dataCount)
                            ElseIf rdbMap.Checked = True Then
                                ReDim Preserve ChkItemSet(itemInfoList.serial, dataCount)
                            Else
                                ReDim Preserve ChkItemSet(itemInfoList.nowcount, dataCount)
                            End If

                            ChkItemSet(itemInfoList.id_Serial, dataCount) = jsArray(cnt)(apiCommand(parsingCode.id)).ToString

                            ProdSelect(ProdList.OrdererCode) = jQuery.SelectToken(apiCommand(parsingCode.ordererCode)).ToString
                            ProdSelect(ProdList.OrdererName) = jQuery.SelectToken(apiCommand(parsingCode.ordererName)).ToString
                            ProdSelect(ProdList.phone) = jQuery.SelectToken(apiCommand(parsingCode.phone)).ToString
                            ProdSelect(ProdList.zip) = jQuery.SelectToken(apiCommand(parsingCode.zip)).ToString
                            ProdSelect(ProdList.Address) = jQuery.SelectToken(apiCommand(parsingCode.address)).ToString

                            ChkItemSet(itemInfoList.count, dataCount) = jsArray(cnt)(apiCommand(parsingCode.itemcount)).ToString

                            ProdSelect(ProdList.BuyDate) = jsArray(cnt)(apiCommand(parsingCode.regDate)).ToString

                            Dim parterInfo As String = jsArray(cnt)(apiCommand(parsingCode.accuount)).ToString
                            If parterInfo <> Nothing Then
                                jQuery = JObject.Parse(parterInfo)
                                ProdSelect(ProdList.AccountCode) = jQuery.SelectToken(apiCommand(parsingCode.code)).ToString
                                ProdSelect(ProdList.AccountName) = jQuery.SelectToken(apiCommand(parsingCode.name)).ToString
                            Else
                                ProdSelect(ProdList.AccountCode) = String.Empty
                                ProdSelect(ProdList.AccountName) = String.Empty
                            End If


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

                            dataCount += 1
                            codeExist = False

                        End If

                    Else
                        If ChkItemSet(itemInfoList.code, 0) = "" Then
                            codeExist = True
                        End If
                    End If
                End If
            Next

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

    End Function

    Private Function mesDateSet(codeData As String) As Boolean
        Const yearFront As Int16 = 20
        Const dateLength As Int16 = 6
        If UBound(Split(codeData, firstState(firstStateList.MES))) > 0 Then
            If UBound(Split(codeData, "-")) > 0 Then
                Dim useDate As String = Mid(codeData, InStr(codeData, firstState(firstStateList.MES)) + firstState(firstStateList.MES).Length, InStr(codeData, "-") - firstState(firstStateList.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 Function comSearch(codeData As String) As Boolean

        If comSearchCount(codeData) Then
            If comSearchOut() Then
                Return False
            Else
                Return True
            End If
        Else
            Return True
        End If

    End Function

    Private Function comSearchOut() As Boolean
        Try
            Const rowCount As Int16 = 2
            Dim itemCode As String = Nothing
            Dim itemName As String = Nothing

            For i = 0 To item_component_max_index
                itemCode = Nothing
                itemName = Nothing
                If item_component_list(i).cnt <> 0 Then
                    DBCmd = "SELECT ItemCode,ItemName FROM " & applyClistDB & " WHERE ProdCode = '" & i & "'"

                    If DBQueryReader(DBCmd) Then
                        For cnt = 0 To sqlDataQuery.Length - 1
                            If cnt Mod rowCount = 0 Then
                                If itemCode = Nothing Then
                                    itemCode = sqlDataQuery(cnt)
                                Else
                                    itemCode = itemCode & "/" & sqlDataQuery(cnt)
                                End If
                            Else
                                If itemName = Nothing Then
                                    itemName = sqlDataQuery(cnt)
                                Else
                                    If itemName.Length > sqlDataQuery(cnt).ToString.Length Then
                                        itemName = sqlDataQuery(cnt)
                                    End If
                                End If
                            End If
                        Next

                        Const firstDataNum As Int16 = 0

                        If rdbState.Checked = True Then
                            If ChkItemSet(0, 0) = Nothing Then
                                ReDim ChkItemSet(itemInfoList.pk_Type, firstDataNum)
                                ChkItemSet(itemInfoList.code, firstDataNum) = itemCode
                                ChkItemSet(itemInfoList.name, firstDataNum) = itemName
                                ChkItemSet(itemInfoList.count, firstDataNum) = item_component_list(i).cnt
                                ChkItemSet(itemInfoList.face, firstDataNum) = 0
                                ChkItemSet(itemInfoList.eye, firstDataNum) = 0
                                ChkItemSet(itemInfoList.pk_Type, firstDataNum) = 1
                            Else
                                Dim chkCount As Int16 = ChkItemSet.GetLength(1)
                                ReDim Preserve ChkItemSet(itemInfoList.pk_Type, chkCount)
                                ChkItemSet(itemInfoList.code, chkCount) = itemCode
                                ChkItemSet(itemInfoList.name, chkCount) = itemName
                                ChkItemSet(itemInfoList.count, chkCount) = item_component_list(i).cnt
                                ChkItemSet(itemInfoList.face, chkCount) = 0
                                ChkItemSet(itemInfoList.eye, chkCount) = 0
                                ChkItemSet(itemInfoList.pk_Type, chkCount) = 1
                            End If
                        Else
                            If packItemSet(0, 0) = Nothing Then
                                ReDim packItemSet(itemInfoList.pk_Type, firstDataNum)
                                packItemSet(itemInfoList.code, firstDataNum) = itemCode
                                packItemSet(itemInfoList.name, firstDataNum) = itemName
                                packItemSet(itemInfoList.count, firstDataNum) = item_component_list(i).cnt
                                packItemSet(itemInfoList.face, firstDataNum) = 0
                                packItemSet(itemInfoList.eye, firstDataNum) = 0
                                packItemSet(itemInfoList.pk_Type, firstDataNum) = 1
                            Else
                                Dim chkCount As Int16 = packItemSet.GetLength(1)
                                ReDim Preserve packItemSet(itemInfoList.pk_Type, chkCount)
                                packItemSet(itemInfoList.code, chkCount) = itemCode
                                packItemSet(itemInfoList.name, chkCount) = itemName
                                packItemSet(itemInfoList.count, chkCount) = item_component_list(i).cnt
                                packItemSet(itemInfoList.face, chkCount) = 0
                                packItemSet(itemInfoList.eye, chkCount) = 0
                                packItemSet(itemInfoList.pk_Type, chkCount) = 1
                            End If
                        End If

                    Else
                        MsgBox("존재하지 않은 소모품 항목이 존재합니다.", vbExclamation)
                        Return False
                    End If
                End If
            Next

            Return True

        Catch ex As Exception
            MsgBox("소모품 항목을 불러오는 도중 오류가 발생하였습니다. :: " & ex.Message, vbCritical)
            Return False
        End Try

    End Function

    Private Function comSearchCount(codeData As String) As Boolean
        DBCmd = "SELECT " & query_component & " FROM " & applySalesDB & " WHERE PackingCode = '" & codeData & "'"

        If DBQueryReader(DBCmd) Then
            'query_component로 구성품 개수만큼 조회했기에 item_component_max_index(=sqlDataQuery.Length - 1)까지 조회
            For i = 0 To item_component_max_index
                item_component_list(i).cnt = sqlDataQuery(i)
            Next

            Return True
        Else
            MsgBox("소모품 관련 데이터를 확인할 수 없습니다.", vbExclamation)
            Return False
        End If
    End Function

    Private Function packingSearch(codeData As String) As Boolean
        If serialPacking(codeData) Then
            If serialDivision() Then
                Return False
            Else
                Return True
            End If
        Else
            Return True
        End If
    End Function

    Private Function serialDivision() As Boolean
        Dim slashNum As Int16
        'item_product_list 에 index (2)부터 등록되어 있기에 (2)부터 조회
        For i = 2 To item_product_max_index
            If item_product_list(i).cnt > 0 Then
                Dim restData As String = item_product_list(i).serial
                slashNum = UBound(Split(restData, "/"))

                For slash = 0 To slashNum
                    Dim serialData As String
                    If slash = slashNum Then
                        serialData = restData
                    Else
                        serialData = Mid(restData, 1, InStr(restData, "/") - 1)    '' 302308110335
                        restData = Mid(restData, InStr(restData, "/") + 1, restData.Length)
                    End If

                    For chk = 0 To itemInfoList.pk_Type
                        chkItem(chk) = Nothing
                    Next

                    If serialSearch(serialData) = False Then
                        Return False
                    End If

                Next
            End If
        Next

        Return True
    End Function

    Private Function serialSearch(serialData As String) As Boolean
        Dim modelNumber As String = Nothing
        Dim typeNumber As String = Nothing
        Dim deviceTypeCode As String = Nothing
        Dim sqlResult As String

        If serialData.Length = oldProdCodeLength Then      '12자리 제품시리얼번호
            modelNumber = Mid(serialData, 1, 1)
            typeNumber = Mid(serialData, 2, 1)
        ElseIf serialData.Length = newProdCodeLength Then  '16자리 제품시리얼번호
            modelNumber = Mid(serialData, 1, 2)
            typeNumber = Mid(serialData, 15, 1)
        End If

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

            If sqlDataQuery(1) = "Y" Then
                TDUseCompare = True
            Else
                TDUseCompare = False
            End If
        Else
            TDUseCompare = False
            MsgBox("존재하지 않는 모델 번호입니다.", vbExclamation)
            Return False
        End If

        If deviceTypeCode = "D" Then    '분리형 디바이스 : PRO, LUX, ALPHA
            If typeNumber = typeList.prodSet Then
                DBCmd = "SELECT Ct_Max_ShotCnt from " & applyCartDB & " where Product_SN = (SELECT FaceCart_SN FROM " & applyProdDB & " WHERE Product_SN = '" & serialData & "') OR Product_SN = (SELECT EyeCart_SN FROM " & applyProdDB & " WHERE Product_SN = '" & serialData & "')"
                If DBQueryReader(DBCmd) Then
                    chkItem(itemInfoList.face) = sqlDataQuery(0)
                    chkItem(itemInfoList.eye) = sqlDataQuery(1)
                Else
                    MsgBox("세트 제품의 샷 수를 알 수 없습니다.", vbExclamation)
                    Return False
                End If
            Else

                sqlResult = singleCartShot(serialData)

                If sqlResult = "FAIL" Then
                    Return False
                End If

                If typeNumber = typeList.prodFace Or typeNumber = typeList.prodBody Then
                    chkItem(itemInfoList.face) = sqlResult
                    chkItem(itemInfoList.eye) = "0"
                ElseIf typeNumber = typeList.prodEye Then
                    chkItem(itemInfoList.face) = "0"
                    chkItem(itemInfoList.eye) = sqlResult
                Else
                    MsgBox("형식에 맞지 않은 바코드가 존재합니다.", vbCritical)
                    Return False
                End If

            End If
        Else
            sqlResult = singleCartShot(serialData)

            If sqlResult = "FAIL" Then
                Return False
            End If

            chkItem(itemInfoList.face) = sqlResult
            chkItem(itemInfoList.eye) = sqlResult
        End If

        If prodListSet(modelNumber, typeNumber, serialData) Then
            Return True
        Else
            Return False
        End If

    End Function

    Private Function singleCartShot(serialData As String) As String
        If TDUseCompare = True Then
            DBCmd = "SELECT Ct_Max_ShotCnt FROM " & applyCartDB & " WHERE Product_SN = '" & serialData & "'"

            Dim sqlResult As String = DBQueryScalar(DBCmd)
            If sqlResult = "False" Then
                MsgBox("단일 제품의 샷 수를 알 수 없습니다.", vbExclamation)
                Return "FAIL"
            End If

            Return sqlResult

        Else
            Return "0"
        End If
    End Function

    Private Function prodListSet(modelNumber As String, typeNumber As String, serialData As String) As Boolean
        Try
            Dim tempFaceShot As String = Nothing
            Dim tempEyeShot As String = Nothing
            Dim successSwitch As Boolean = False

            DBCmd = "SELECT count(ItemCode) FROM " & applyPlistDB & " WHERE FaceShot = '" & chkItem(itemInfoList.face) & "' AND EyeShot = '" & chkItem(itemInfoList.eye) & "'"
            Dim resultCount As String = DBQueryScalar(DBCmd)

            If resultCount = "False" Then
                MsgBox("샷 수에 따른 제품 코드를 검색하는 과정에서 오류가 발생하였습니다.", vbCritical)
                Return False
            ElseIf resultCount = "0" Then
                MsgBox("샷 수에 해당하는 제품이 없습니다.", vbCritical)
                Return False
            Else
                tempFaceShot = chkItem(itemInfoList.face)
                tempEyeShot = chkItem(itemInfoList.eye)
            End If

            Const rowCount As Int16 = 2
            Dim colorNumber As String = Nothing

            If serialData.Length = oldProdCodeLength Then      '12자리 제품시리얼번호
                colorNumber = Mid(serialData, 11, 1)
            ElseIf serialData.Length = newProdCodeLength Then  '16자리 제품시리얼번호
                colorNumber = Mid(serialData, 3, 1)
            End If

            DBCmd = "SELECT ItemCode,ItemName FROM " & applyPlistDB & " WHERE ModelNum = '" & modelNumber & "' AND TypeNum = '" & typeNumber & "' AND FaceShot = '" & tempFaceShot & "' AND EyeShot = '" & tempEyeShot & "' AND ColorNum = '" & colorNumber & "'" & " AND ItemName NOT LIKE '%체험%' LIMIT 1"

            If DBQueryReader(DBCmd) Then
                For i = 0 To sqlDataQuery.Length - 1
                    If i Mod rowCount = 0 Then
                        If chkItem(itemInfoList.code) = Nothing Then
                            chkItem(itemInfoList.code) = sqlDataQuery(i)
                        Else
                            chkItem(itemInfoList.code) = chkItem(itemInfoList.code) & "/" & sqlDataQuery(i)
                        End If
                    Else
                        If chkItem(itemInfoList.name) = Nothing Then
                            chkItem(itemInfoList.name) = sqlDataQuery(i)
                        Else
                            If chkItem(itemInfoList.name).Length > sqlDataQuery(i).ToString.Length Then
                                chkItem(itemInfoList.name) = sqlDataQuery(i)
                            End If
                        End If
                    End If
                Next

                chkItem(itemInfoList.id_Serial) = serialData
                chkItem(itemInfoList.pk_Type) = 0
            Else
                MsgBox("등록되지 않은 제품이 존재합니다.", vbExclamation)
                Return False
            End If

            If rdbState.Checked = True Then
                If ChkItemSet(0, 0) = Nothing Then
                    ReDim ChkItemSet(itemInfoList.pk_Type, 0)

                    For i = 0 To itemInfoList.pk_Type
                        If i = itemInfoList.count Then
                            ChkItemSet(i, 0) += 1
                        Else
                            ChkItemSet(i, 0) = chkItem(i)
                        End If
                    Next

                Else
                    For i = 0 To ChkItemSet.GetLength(1) - 1
                        If ChkItemSet(itemInfoList.code, i) = chkItem(itemInfoList.code) And ChkItemSet(itemInfoList.face, i) = chkItem(itemInfoList.face) And ChkItemSet(itemInfoList.eye, i) = chkItem(itemInfoList.eye) Then
                            ChkItemSet(itemInfoList.count, i) += 1
                            ChkItemSet(itemInfoList.id_Serial, i) = ChkItemSet(itemInfoList.id_Serial, i) & "/" & chkItem(itemInfoList.id_Serial)
                            successSwitch = True
                            Exit For
                        End If
                    Next

                    If successSwitch = False Then
                        Dim chkLength As Int16 = ChkItemSet.GetLength(1)
                        ReDim Preserve ChkItemSet(itemInfoList.pk_Type, chkLength)
                        For i = 0 To itemInfoList.pk_Type
                            If i = itemInfoList.count Then
                                ChkItemSet(i, chkLength) += 1
                            Else
                                ChkItemSet(i, chkLength) = chkItem(i)
                            End If
                        Next
                    End If

                End If
            Else

                If packItemSet(0, 0) = Nothing Then
                    ReDim packItemSet(itemInfoList.pk_Type, 0)

                    For i = 0 To itemInfoList.pk_Type
                        If i = itemInfoList.count Then
                            packItemSet(i, 0) += 1
                        Else
                            packItemSet(i, 0) = chkItem(i)
                        End If
                    Next
                Else
                    For i = 0 To packItemSet.GetLength(1) - 1
                        If packItemSet(itemInfoList.code, i) = chkItem(itemInfoList.code) And packItemSet(itemInfoList.face, i) = chkItem(itemInfoList.face) And packItemSet(itemInfoList.eye, i) = chkItem(itemInfoList.eye) Then
                            packItemSet(itemInfoList.count, i) += 1
                            packItemSet(itemInfoList.id_Serial, i) = packItemSet(itemInfoList.id_Serial, i) & "/" & chkItem(itemInfoList.id_Serial)
                            successSwitch = True
                            Exit For
                        End If
                    Next

                    If successSwitch = False Then
                        Dim chkLength As Int16 = packItemSet.GetLength(1)
                        ReDim Preserve packItemSet(itemInfoList.pk_Type, chkLength)
                        For i = 0 To itemInfoList.pk_Type
                            If i = itemInfoList.count Then
                                packItemSet(i, chkLength) += 1
                            Else
                                packItemSet(i, chkLength) = chkItem(i)
                            End If
                        Next
                    End If

                End If
            End If

            Return True
        Catch ex As Exception
            MsgBox("제품 검색 도중 오류가 발생하였습니다. :: " & ex.Message)
            Return False
        End Try

    End Function

    Private Function serialPacking(codeData As String) As Boolean
        DBCmd = "SELECT " & query_product & " FROM " & applySalesDB & " WHERE PackingCode = '" & codeData & "'"
        If DBQueryReader(DBCmd) Then
            Dim dataSetCount As Int32 = 0

            'query_product가 ProdCode = 2부터 생성되었기에 (2)부터 조회
            For i = 2 To item_product_max_index
                For col = 0 To 1
                    If col = 0 Then
                        item_product_list(i).serial = sqlDataQuery(dataSetCount)
                    ElseIf col = 1 Then
                        item_product_list(i).cnt = sqlDataQuery(dataSetCount)
                    End If
                    dataSetCount += 1
                Next
            Next
        Else
            MsgBox("패킹 시리얼 번호를 검색하는 도중 오류가 발생하였습니다.")
            Return False
        End If

        Return True
    End Function

    Private Function mappingComapare(codeData As String) As Boolean
        DBCmd = "SELECT COUNT(Order_Code) FROM " & applyOrderDB & " WHERE Packing_Code = '" & codeData & "'"
        Dim sqlResult As String = DBQueryScalar(DBCmd)

        If sqlResult = "False" Then
            MsgBox("해당 데이터를 데이터베이스로 확인할 수 없습니다.", vbCritical)
            Return True
        End If

        If Val(sqlResult) > 0 Then
            MsgBox("이미 고객과 연결된 제품입니다.", vbExclamation)
            Return True
        End If

        Return False
    End Function

    Private Function orderPackingCompare(codeData As String) As String
        Const sqlLength As Int16 = 1
        Dim orderCode As String

        DBCmd = "SELECT Order_Code FROM " & applyOrderDB & " WHERE Packing_Code = '" & codeData & "' GROUP BY Order_Code"
        If DBQueryReader(DBCmd) Then
            If sqlDataQuery.Length = sqlLength Then
                orderCode = sqlDataQuery(sqlLength - 1)
                Return orderCode
            Else
                MsgBox("중복 맵핑된 고객이 존재합니다. 데이터를 확인하여 주십시오.", vbExclamation)
                Return "FAIL"
            End If
        Else
            Return "NOLINK"
        End If
    End Function

    Private Function packingCompare(codeData As String) As Boolean
        DBCmd = "SELECT COUNT(PackingCode) FROM " & applySalesDB & " WHERE PackingCode = '" & codeData & "'"
        Dim result As String = DBQueryScalar(DBCmd)

        If result = "False" Then
            MsgBox("패킹 데이터를 불러오는 도중 오류가 발생하였습니다.")
            Return True
        End If

        If result = 0 Then
            MsgBox("패킹 내역이 존재하지 않습니다.", vbExclamation)
            Return True
        Else
            Return False
        End If
    End Function

    Private Function packListSetting(pntype As Panel, valueType As Int16, type As Boolean) As Boolean   '' 전표번호 : true / 패킹번호 : false
        Try
            Dim RowDataCount As Integer

            If type = True Then
                RowDataCount = ChkItemSet.GetLength(1) - 1
                StateTxbClear(funcList.mapstate)
            Else
                RowDataCount = packItemSet.GetLength(1) - 1
                StateTxbClear(funcList.mappack)
                ReDim txbArrayList(RowDataCount, txbList.Eye)
            End If

            Dim prodMapCol As Integer = 0

            For cnt = 0 To RowDataCount
                For i = 0 To txbList.Eye
                    Dim txtBox As TextBox = New TextBox

                    If cnt = 0 Then
                        prodMapCol = prodMapStartCol
                    Else
                        If i = txbList.Name Then
                            prodMapCol = prodMapCol + prodMapHeight + maplocplus
                        End If
                    End If

                    txtBox.Name = txbSetName(i) & cnt
                    pntype.Controls.Add(txtBox)
                    txtBox.Font = New Font("함초롱바탕", 18, FontStyle.Bold)
                    txtBox.Size = New Drawing.Size(prodInfoWidth(i), prodMapHeight)
                    txtBox.Location = New Point(prodInfoRow(i), prodMapCol)

                    If type = True Then
                        txtBox.Text = ChkItemSet(i + 1, cnt)
                        If i = txbList.Count + 1 Then
                            stateFullCount += ChkItemSet(itemInfoList.count, cnt)
                        End If
                    Else

                        txtBox.Text = packItemSet(i + 1, cnt)
                        txbArrayList(cnt, i) = txtBox

                        If i = txbList.Count + 1 Then
                            packFullCount += packItemSet(itemInfoList.count, cnt)
                        End If
                    End If

                    txtBox.ReadOnly = True
                    txtBox.BackColor = Color.White
                Next
            Next

            Return False
        Catch ex As Exception
            MsgBox("리스트를 생성하는 도중 오류가 발생하였습니다. :: " & ex.Message, vbCritical)
            Return True
        End Try
    End Function

    Private Function setCodeParsing() As Boolean
        Const colCount As Int16 = 5
        Dim pkAddSwitch As Boolean = False
        Try
            For i = 0 To ChkItemSet.GetLength(1) - 1
                If InStr(ChkItemSet(itemInfoList.code, i), "PK") > 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 = '" & ChkItemSet(itemInfoList.code, i) & "'"

                    If DBQueryReader(DBCmd) Then
                        Dim dataSetCount As Int16 = 0
                        Dim RowCount As Int16 = (sqlDataQuery.Length / colCount) - 1
                        Dim setCodeArray(itemInfoList.eye)

                        For row = 0 To RowCount
                            existSwitch = False

                            For col = 0 To colCount - 1

                                setCodeArray(col) = sqlDataQuery(dataSetCount)

                                If col = itemInfoList.count Then
                                    setCodeArray(itemInfoList.count) = setCodeArray(itemInfoList.count) * ChkItemSet(itemInfoList.count, i)
                                End If

                                dataSetCount += 1
                            Next

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

                                    If ChkItemSet(itemInfoList.pk_Type, chk) = String.Empty Then
                                        ChkItemSet(itemInfoList.pk_Type, chk) = ChkItemSet(itemInfoList.code, i)
                                    Else
                                        ChkItemSet(itemInfoList.pk_Type, chk) = ChkItemSet(itemInfoList.pk_Type, chk) & "/" & ChkItemSet(itemInfoList.code, i)
                                    End If

                                    If ChkItemSet(itemInfoList.id_Serial, i) <> String.Empty Then
                                        If ChkItemSet(itemInfoList.id_Serial, chk) = String.Empty Then
                                            ChkItemSet(itemInfoList.id_Serial, chk) = ChkItemSet(itemInfoList.id_Serial, i)
                                        Else
                                            ChkItemSet(itemInfoList.id_Serial, chk) = ChkItemSet(itemInfoList.id_Serial, chk) & "/" & ChkItemSet(itemInfoList.id_Serial, i)
                                        End If
                                    End If

                                    existSwitch = True
                                    Exit For
                                End If
                            Next

                            If existSwitch = False Then
                                Dim chkRowNum As Int16 = ChkItemSet.GetLength(1)

                                If rdbMap.Checked = True Then
                                    ReDim Preserve ChkItemSet(itemInfoList.serial, chkRowNum)
                                Else
                                    ReDim Preserve ChkItemSet(itemInfoList.nowcount, chkRowNum)
                                End If

                                For svd = 0 To itemInfoList.eye
                                    ChkItemSet(svd, chkRowNum) = setCodeArray(svd)
                                Next
                                ChkItemSet(itemInfoList.pk_Type, chkRowNum) = ChkItemSet(itemInfoList.code, i)

                                If ChkItemSet(itemInfoList.id_Serial, i) <> String.Empty Then
                                    ChkItemSet(itemInfoList.id_Serial, chkRowNum) = ChkItemSet(itemInfoList.id_Serial, i)
                                End If

                                pkAddSwitch = True
                            End If

                        Next

                    Else
                        MsgBox("존재하지 않는 세트코드가 존재합니다. 데이터를 확인 후 없을 시 요청하여 주십시오.", vbCritical)
                        Return False
                    End If

                    For del = 0 To itemInfoList.serial
                        ChkItemSet(del, i) = String.Empty
                    Next
                End If
            Next

            If pkAddSwitch = True Then
                pkAddSwitch = False
                Dim nowRow As Int16 = 0

                For rc = 0 To ChkItemSet.GetLength(1) - 1
                    If ChkItemSet(itemInfoList.code, rc) <> String.Empty Then
                        For cc = 0 To itemInfoList.serial
                            ChkItemSet(cc, nowRow) = ChkItemSet(cc, rc)
                        Next
                        pkAddSwitch = True
                        nowRow += 1
                    End If
                Next

                If pkAddSwitch = True Then
                    setCodeUse = True

                    If rdbMap.Checked = True Then
                        ReDim Preserve ChkItemSet(itemInfoList.serial, nowRow - 1)
                    Else
                        ReDim Preserve ChkItemSet(itemInfoList.nowcount, nowRow - 1)
                    End If

                End If

            End If

            Return False

        Catch ex As Exception
            MsgBox("세트 코드 관련 오류 발생!! :: " + ex.Message, vbCritical)
            Return True
        End Try

    End Function

    Private Sub apiBackupData()
        If ckbAPIUse.Checked = True Then
            ReDim apiItemSet(itemInfoList.serial, ChkItemSet.GetLength(1) - 1)
            For i = 0 To ChkItemSet.GetLength(1) - 1
                For n = 0 To itemInfoList.serial
                    apiItemSet(n, i) = ChkItemSet(n, i)
                Next
            Next
        End If
    End Sub

    Private Function ListSetting(type As Boolean) As Boolean
        Try

            StateTxbClear(funcList.search)
            txbNameValue(funcList.search)

            Dim prodInfoCol As Integer = 0
            Dim RowDataCount As Integer = ChkItemSet.GetLength(1) - 1
            ReDim txbArrayList(RowDataCount, txbList.Eye)
            ReDim btnArrayList(RowDataCount, btnCount - 1)

            For cnt = 0 To RowDataCount
                For i = 0 To txbList.Remove
                    Dim txtBox As TextBox = New TextBox
                    Dim btnBox As Button = New Button

                    If cnt = 0 Then
                        prodInfoCol = prodInfoStartCol
                    Else
                        If i = txbList.Name Then
                            prodInfoCol = prodInfoCol + prodInfoHeight + locplus
                        End If
                    End If

                    If i >= txbList.Name And i <= txbList.Eye Then

                        txtBox.Name = txbSetName(i) & cnt
                        pnProdInfo.Controls.Add(txtBox)

                        txbArrayList(cnt, i) = txtBox

                        txtBox.Font = New Font("함초롱바탕", 24, FontStyle.Bold)
                        txtBox.Size = New Drawing.Size(prodInfoWidth(i), prodInfoHeight)
                        txtBox.Location = New Point(prodInfoRow(i), prodInfoCol)

                        txtBox.Text = ChkItemSet(i + 1, cnt)

                        txtBox.ReadOnly = True
                        txtBox.BackColor = Color.White

                    Else

                        If ModifyListSwitch = False Then
                            btnBox.Name = txbSetName(i) & cnt

                            If i = txbList.Modify Then
                                btnBox.Text = "수정"
                                AddHandler btnBox.Click, AddressOf ModifyClick
                            Else
                                btnBox.Text = "제거"
                                AddHandler btnBox.Click, AddressOf DeleteClick
                            End If


                            pnProdInfo.Controls.Add(btnBox)

                            btnArrayList(cnt, i - (txbList.Eye + 1)) = btnBox

                            btnBox.Font = New Font("함초롱바탕", 18, FontStyle.Bold)
                            btnBox.Size = New Drawing.Size(prodInfoWidth(i), prodInfoHeight)
                            btnBox.Location = New Point(prodInfoRow(i), prodInfoCol - 3)

                            btnBox.Enabled = False
                        End If

                    End If

                Next
            Next

            Return False

        Catch ex As Exception
            MsgBox("리스트를 생성하는 도중 오류가 발생하였습니다. :: " & ex.Message, vbCritical)
            Return True
        End Try
    End Function

    Private Function packDateSearch(DataCode As String) As Boolean
        DBCmd = "SELECT `Data` FROM " & applySalesDB & " WHERE PackingCode = '" & DataCode & "'"
        Dim sqlResult As String = DBQueryScalar(DBCmd)

        If sqlResult = "False" Then
            MsgBox("해당 데이터를 데이터베이스에서 찾을 수 없습니다.", vbCritical)
            Return True
        End If

        If rdbMap.Checked = True Then
            txbMapPkDate.Text = sqlResult
        Else
            txbMsPkDate.Text = sqlResult
        End If

        Return False
    End Function

    Private Function Product_Search(DataCode As String) As Boolean
        Dim QueryCount As Integer = 0

        DBCmd = "SELECT Item_Code,Item_Name,Item_Count,Apply_Face,Apply_Eye FROM " & applyOrderDB & " WHERE Order_Code = '" & DataCode & "'"
        If DBQueryReader(DBCmd) Then
            Dim DataCount As Integer = sqlDataQuery.Length

            If rdbState.Checked = True Then
                ReDim ChkItemSet(itemInfoList.eye, (DataCount / (itemInfoList.eye + 1)) - 1)
            Else
                ReDim ChkItemSet(itemInfoList.serial, (DataCount / (itemInfoList.eye + 1)) - 1)
            End If

            For row = 0 To ChkItemSet.GetLength(1) - 1
                For col = 0 To itemInfoList.eye
                    ChkItemSet(col, row) = sqlDataQuery(QueryCount)
                    QueryCount += 1
                Next
            Next
            Return False
        Else
            Return True
        End If
    End Function

    Private Function orderer_Search(DataCode As String) As Boolean
        DBCmd = "SELECT distinct Order_Code,Date,Account_Code,Account_Name,Orderer_Code,Orderer_Name,Phone_Number,ZipCode,Address,Refer FROM " & applyOrderDB & " WHERE Order_Code = '" & DataCode & "'"
        If DBQueryReader(DBCmd) Then
            ProdSelect(ProdList.OrderCode) = sqlDataQuery(ProdList.OrderCode)
            ProdSelect(ProdList.BuyDate) = sqlDataQuery(ProdList.BuyDate)
            ProdSelect(ProdList.AccountCode) = sqlDataQuery(ProdList.AccountCode)
            ProdSelect(ProdList.AccountName) = sqlDataQuery(ProdList.AccountName)
            ProdSelect(ProdList.OrdererCode) = sqlDataQuery(ProdList.OrdererCode)
            ProdSelect(ProdList.OrdererName) = sqlDataQuery(ProdList.OrdererName)
            ProdSelect(ProdList.phone) = sqlDataQuery(ProdList.phone)
            ProdSelect(ProdList.zip) = sqlDataQuery(ProdList.zip)
            ProdSelect(ProdList.Address) = sqlDataQuery(ProdList.Address)
            ProdSelect(ProdList.Refer) = sqlDataQuery(ProdList.Refer)
            gb_map_state.BackColor = SystemColors.Control
            Return False
        Else
            nolinkOutput()
            MsgBox("해당 전표코드에 대한 데이터가 존재하지 않습니다.", vbCritical)
            Return True
        End If
    End Function

    Private Sub nolinkOutput()
        ProdSelect(ProdList.OrderCode) = "N/A"
        ProdSelect(ProdList.BuyDate) = "N/A"
        ProdSelect(ProdList.AccountCode) = "N/A"
        ProdSelect(ProdList.AccountName) = "N/A"
        ProdSelect(ProdList.OrdererCode) = "N/A"
        ProdSelect(ProdList.OrdererName) = "N/A"
        ProdSelect(ProdList.phone) = "N/A"
        ProdSelect(ProdList.zip) = "N/A"
        ProdSelect(ProdList.Address) = "N/A"
        ProdSelect(ProdList.Refer) = "N/A"
        gb_map_state.BackColor = Color.Red
    End Sub

    Private Function releaseDataCompare(DataCode As String) As Boolean


        If DBQueryScalar(DBCmd) = 0 Then
            MsgBox("데이터가 존재하지 않습니다. 데이터를 확인하여 주십시오.", vbExclamation)
            Return True
        End If

        Return False
    End Function

    Private Function completeCompare(DataCode As String) As Boolean
        Dim dupSwitch As Boolean = False
        DBCmd = "SELECT Invoice_Number FROM " & applyOrderDB & " WHERE Order_Code = '" & DataCode & "'"
        If DBQueryReader(DBCmd) Then
            For i = 0 To sqlDataQuery.Length - 1
                If sqlDataQuery(i) <> 0 Then
                    dupSwitch = True
                End If
            Next
        End If

        If dupSwitch = True Then
            MsgBox("이미 송장 등록이 되어있는 제품이 존재합니다.", vbExclamation)
            Return True
        End If

        Return False
    End Function

    Private Function ExistApiCompare(DataCode As String) As Boolean
        DBCmd = "SELECT COUNT(Order_Code) FROM " & applyOrderDB & " WHERE Order_Code = '" & DataCode & "'"
        Dim dbResult As String = DBQueryScalar(DBCmd)

        If dbResult = "False" Then
            MsgBox("데이터를 찾는 도중 오류가 발생하였습니다.", vbCritical)
            Return True
        End If

        If dbResult > 0 Then
            MsgBox("해당 번호는 처리된 번호입니다.", vbExclamation)
            Return True
        End If

        Return False
    End Function

    Private Function ExistDataCompare(DataCode As String) As Boolean

        If rdbMap.Checked = True And rdbStateInv.Checked = True Then
            DBCmd = "SELECT COUNT(distinct Order_Code) FROM " & applyOrderDB & " WHERE Order_Code = '" & DataCode & "' AND release_state = 'release'"
        ElseIf rdbMap.Checked = True And rdbStatePack.Checked = True Then
            DBCmd = "SELECT COUNT(distinct Order_Code) FROM " & applyOrderDB & " WHERE Order_Code = '" & DataCode & "' AND release_state IS null"
        Else
            DBCmd = "SELECT COUNT(distinct Order_Code) FROM " & applyOrderDB & " WHERE Order_Code = '" & DataCode & "'"
        End If

        Dim dbResult As String = DBQueryScalar(DBCmd)

        If dbResult = "False" Then
            MsgBox("데이터를 찾는 도중 오류가 발생하였습니다.", vbCritical)
            Return True
        End If

        If dbResult = 0 Then

            DBCmd = "SELECT COUNT(Order_Code) FROM " & applyOrderDB & " WHERE Order_Code = '" & DataCode & "'"

            dbResult = DBQueryScalar(DBCmd)

            If dbResult = "False" Then
                MsgBox("데이터를 찾는 도중 오류가 발생하였습니다.", vbCritical)
                Return True
            End If

            If dbResult = 0 Then
                MsgBox("데이터가 존재하지 않습니다. 데이터를 확인하여 주십시오.", vbExclamation)
                Return True
            Else
                MsgBox("이미 등록 완료된 데이터 입니다.", vbExclamation)
                Return True
            End If


        End If

        Return False
    End Function

    Private Function delOrder_Search(ordCode As String) As Boolean
        DBCmd = "SELECT COUNT(Order_Code) FROM " & applyOrderDB & " WHERE Order_Code = '" & ordCode & "'"
        Dim scResult As String = DBQueryScalar(DBCmd)

        If scResult = "0" Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Sub lbProdRmv_DoubleClick(sender As Object, e As EventArgs) Handles lbProdRmv.DoubleClick

        If txbChkState.Text = "N/A" Then
            MsgBox("패킹 번호는 수정이 불가능 합니다.", vbExclamation)
            Exit Sub
        End If

        Const ctrlCount As Int16 = 6
        Dim txbCount As Integer = (pnProdInfo.Controls.Count - ctrlCount) / ctrlCount

        DelFuncSwitch = Not DelFuncSwitch

        If DelFuncSwitch = True Then
            For i = txbCount - 1 To 0 Step -1
                pnProdInfo.Controls(txbSetName(txbList.Remove) & i).Enabled = True
            Next
        Else
            For i = txbCount - 1 To 0 Step -1
                pnProdInfo.Controls(txbSetName(txbList.Remove) & i).Enabled = False
            Next
        End If
    End Sub

    Private Sub lbProdMdf_DoubleClick(sender As Object, e As EventArgs) Handles lbProdMdf.DoubleClick

        If txbChkState.Text = "N/A" Then
            MsgBox("패킹 번호는 수정이 불가능 합니다.", vbExclamation)
            Exit Sub
        End If

        Const ctrlCount As Int16 = 6
        Dim txbCount As Integer = (pnProdInfo.Controls.Count - ctrlCount) / ctrlCount

        ModifySwitch = Not ModifySwitch

        If ModifySwitch = True Then
            For i = txbCount - 1 To 0 Step -1
                txbArrayList(i, txbList.Count).ReadOnly = False
                txbArrayList(i, txbList.Face).ReadOnly = False
                txbArrayList(i, txbList.Eye).ReadOnly = False
                pnProdInfo.Controls(txbSetName(txbList.Modify) & i).Enabled = True
            Next
        Else
            For i = txbCount - 1 To 0 Step -1
                txbArrayList(i, txbList.Count).ReadOnly = True
                txbArrayList(i, txbList.Face).ReadOnly = True
                txbArrayList(i, txbList.Eye).ReadOnly = True
                pnProdInfo.Controls(txbSetName(txbList.Modify) & i).Enabled = False
            Next

            If ModifyListSwitch = True Then
                ListSetting(True)
            End If
        End If

    End Sub

    Private Sub DeleteClick(sender As Object, e As EventArgs)
        Dim btnIndex As Int16 = CType(sender, Button).TabIndex - indexDefault
        btnIndex = btnIndex / indexRange

        DBCmd = "SELECT Packing_Code FROM " & applyOrderDB & " WHERE Order_Code = '" & txbChkState.Text & "' AND Item_Code = '" & ChkItemSet(itemInfoList.code, btnIndex) & "'"
        Dim dbResult As String = DBQueryScalar(DBCmd)

        If dbResult.Replace(" ", "") = "" Or dbResult = String.Empty Then

            DBCmd = "UPDATE " & applyOrderDB & " SET Order_Code = 'null_" & txbChkState.Text & "' WHERE Order_Code = '" & txbChkState.Text & "' AND Item_Code = '" & ChkItemSet(itemInfoList.code, btnIndex) & "'"

            If DBCommand(DBCmd) Then

                If modifyResetList(txbChkState.Text) Then
                    MsgBox("데이터 불러오기 실패, 관리자 문의", vbCritical)
                    Exit Sub
                End If

                MsgBox("삭제 완료", vbInformation)
                Exit Sub
            End If

            MsgBox("삭제 실패", vbExclamation)
        Else
            MsgBox("이미 등록 완료된 데이터는 삭제할 수 없습니다.", vbExclamation)
        End If

    End Sub

    Private Function modifyResetList(codeData As String) As Boolean

        If delOrder_Search(codeData) Then
            StateTxbClear(funcList.search)
            Return False
        End If

        If orderer_Search(codeData) Then
            MsgBox("해당 전표코드의 고객 데이터가 존재하지 않습니다.", vbCritical)
            Return True
        End If

        If Product_Search(codeData) Then
            MsgBox("해당 전표코드의 제품 데이터가 존재하지 않습니다.", vbCritical)
            Return True
        End If

        If ListSetting(True) Then
            MsgBox("전표 데이터 리스트화 진행중 오류가 발생하였습니다.", vbCritical)
            Return True
        End If

        Return False
    End Function

    Private Sub ModifyClick(sender As Object, e As EventArgs)
        Dim btnIndex As Int16 = CType(sender, Button).TabIndex - indexDefault
        btnIndex = btnIndex / indexRange

        DBCmd = "UPDATE " & applyOrderDB & " SET Item_Count = '" & txbArrayList(btnIndex, txbList.Count).Text & "', Apply_Face = '" & txbArrayList(btnIndex, txbList.Face).Text & "', Apply_Eye = '" & txbArrayList(btnIndex, txbList.Eye).Text & "' WHERE Order_Code = '" & txbChkState.Text & "' AND Item_Code = '" & ChkItemSet(itemInfoList.code, btnIndex) & "'"

        If DBCommand(DBCmd) Then
            MsgBox("수정 완료", vbInformation)
            Exit Sub
        End If

        MsgBox("수정 실패", vbExclamation)
        Exit Sub

    End Sub

    '-------------------------------패킹 관련----------------------------------
    Private Sub mappingReset()
        mapStateOK = False
        mapPackOk = False
        mapInvOk = False
        StateTxbClear(funcList.mapstate)
        StateTxbClear(funcList.mappack)
        topInfoClear()

        compareValueClean()

        ReDim ChkItemSet(0, 0)
        ReDim packItemSet(0, 0)
        setCodeUse = False

        txbInv.BackColor = SystemColors.Window
        txbInv.Text = String.Empty
    End Sub

    Private Sub topInfoClear()
        gbMapStInfo.BackColor = SystemColors.Control
        txbMapState.Text = "N/A"
        txbMapDate.Text = "N/A"
        txbMapOrder.Text = "N/A"
        txbMapAccount.Text = "N/A"
        txbMapRefer.Text = "N/A"

        gbMapPkInfo.BackColor = SystemColors.Control
        txbMapPacking.Text = "N/A"
        txbMapPkDate.Text = "N/A"

        txbMapState.Refresh()
        txbMapDate.Refresh()
        txbMapOrder.Refresh()
        txbMapAccount.Refresh()
        txbMapRefer.Refresh()
        txbMapPacking.Refresh()
        txbMapPkDate.Refresh()
    End Sub

    Private Function mappingRunning(codeData As String) As Boolean

        If mapStateOK = True And mapPackOk = True And mapInvOk = True Then
            mappingReset()
        End If

        If rdbStateInv.Checked = True Then
            mapPackOk = True
        End If

        If mapStateOK = True And mapPackOk = True Then
            txbInv.BackColor = Color.White
            txbInv.Text = codeData

            If txbInv.Text.Replace(" ", "") = "" Then
                txbInv.BackColor = Color.Red
                MsgBox("송장번호를 입력하지 않았습니다.", vbExclamation)
                Return False
            End If

            'If IsNumeric(txbInv.Text) = False Then
            '    txbInv.BackColor = Color.Red
            '    MsgBox("양식에 맞지 않는 송장번호입니다.", vbExclamation)
            '    Return False
            'End If

            If txbInv.Text.Length < invLimitCount Then
                txbInv.BackColor = Color.Red
                MsgBox("양식에 맞지 않는 송장번호입니다.", vbExclamation)
                Return False
            End If

            If txbInv.Text = txbMapState.Text Or txbInv.Text = txbMapPacking.Text Then
                txbInv.BackColor = Color.Red
                MsgBox("패킹 번호 혹은 전표 번호는 송장 번호로 사용할 수 없습니다.", vbExclamation)
                Return False
            End If

            Dim InvoiceNum As Int16 = Val(Mid(txbInv.Text, 1, 1))

            If InvoiceNum <> invList.hanjin And InvoiceNum <> invList.cj And InvoiceNum <> invList.hanjin2 And InvoiceNum <> invList.cj2 Then
                txbInv.BackColor = Color.Red
                MsgBox("형식에 맞는 택배사가 존재하지 않습니다.", vbExclamation)
                Return False
            End If

            txbInv.BackColor = Color.ForestGreen
            mapInvOk = True

        Else
            If codeData.Length = oldProdCodeLength Or codeData.Length = newProdCodeLength Then

                packFullCount = 0

                If rdbStateInv.Checked = True Then
                    MsgBox("해당 기능은 제품 패킹 번호를 필요로 하지 않습니다.", vbExclamation)
                    Return False
                Else
                    If packingCompare(codeData) Then
                        Return False
                    End If

                    If mappingComapare(codeData) Then
                        Return False
                    End If

                    If packingSearch(codeData) Then
                        Return False
                    End If

                    If comSearch(codeData) Then
                        Return False
                    End If

                    If packDateSearch(codeData) Then
                        Return False
                    End If

                    txbMapPacking.Text = codeData

                    If packListSetting(pnMapPkProd, funcList.mappack, False) Then
                        Return False
                    End If

                    gbMapPkInfo.BackColor = Color.ForestGreen
                    mapPackOk = True
                End If

            Else

                If Mid(codeData, 1, 7) = firstState(firstStateList.ERP) Or Mid(codeData, 1, 3) = firstState(firstStateList.MES) Then

                    setCodeUse = False
                    stateFullCount = 0

                    If ckbAPIUse.Checked = True Then

                        If ExistApiCompare(codeData) Then
                            Return False
                        End If

                        If ckbPostgre.Checked = True Then

                            If useAPIDirect(codeData) Then
                                Return False
                            End If

                        Else

                            If mesRunning(codeData) Then
                                Return False
                            End If

                        End If

                    Else
                        If ExistDataCompare(codeData) Then
                            Return False
                        End If

                        If completeCompare(codeData) Then
                            Return False
                        End If

                        If orderer_Search(codeData) Then
                            Return False
                        End If

                        If Product_Search(codeData) Then
                            Return False
                        End If
                    End If

                    apiBackupData()

                    If setCodeParsing() Then
                        Return False
                    End If

                    If packListSetting(pnMapStProd, funcList.mapstate, True) Then
                        Return False
                    End If

                Else
                    MsgBox("해당 번호의 데이터를 찾을 수 없습니다. 번호를 확인하여 주십시오.", vbExclamation)
                    Return False
                End If

                txbMapState.Text = ProdSelect(ProdList.OrderCode)
                txbMapDate.Text = ProdSelect(ProdList.BuyDate)
                txbMapOrder.Text = ProdSelect(ProdList.OrdererName)
                txbMapAccount.Text = ProdSelect(ProdList.AccountName)
                txbMapRefer.Text = ProdSelect(ProdList.Refer)

                gbMapStInfo.BackColor = Color.ForestGreen
                mapStateOK = True

            End If

            If mapStateOK = True And mapPackOk = True Then

                If statePackCompare() Then
                    mapPackOk = False
                    Return False
                End If

                txbInv.Enabled = True

            End If

        End If

        If mapStateOK = True And mapPackOk = True And mapInvOk = True Then
            If ckbAuto.Checked = True Then
                If compareSave() Then
                    Return False
                End If
            Else
                btnSearch.Text = "등 록"
            End If

        End If

        Return True
    End Function

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

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

    Private Function stateinfoRun_API(CodeData As String) 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,os.receiver_address,io.description 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 = '" & CodeData & "' and od.deleted_at is null;"

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

                ProdSelect(ProdList.OrderCode) = CodeData

                If ProdSelect(ProdList.Refer) = "0" Then
                    ProdSelect(ProdList.Refer) = String.Empty
                End If

                Return True

            Else

                MsgBox("고객 데이터가 존재하지 않습니다. 데이터를 확인하여 주십시오.", vbCritical)
                Return False

            End If

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

    Private Function stateCodeRun_API(CodeData As String) As Boolean
        Try
            Const colCount As Int16 = 5

            DBCmd = "select io.state,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 = '" & CodeData & "' and od.deleted_at is null;"
            If pgDBQueryReader(DBCmd) Then
                Dim RowCount As Int16 = (pgDataQuery.Length / colCount) - 1
                Dim dataSetCount As Int32 = 0

                If rdbState.Checked = True Then
                    ReDim ChkItemSet(itemInfoList.id_Serial, RowCount)
                Else
                    ReDim ChkItemSet(itemInfoList.serial, RowCount)
                End If


                For row = 0 To RowCount
                    For col = 0 To colCount - 1
                        Select Case col
                            Case directData.state
                                If pgDataQuery(dataSetCount) <> "registered" Then
                                    dataSetCount += 5
                                    Exit For
                                End If
                            Case directData.code
                                ChkItemSet(itemInfoList.code, row) = pgDataQuery(dataSetCount)
                            Case directData.name
                                ChkItemSet(itemInfoList.name, row) = pgDataQuery(dataSetCount)
                            Case directData.count
                                ChkItemSet(itemInfoList.count, row) = pgDataQuery(dataSetCount)
                            Case directData.id
                                ChkItemSet(itemInfoList.id_Serial, row) = pgDataQuery(dataSetCount)
                            Case Else
                                MsgBox("잘못된 경로 개입입니다. useAPIDirect !", vbCritical)
                                Return False
                        End Select

                        dataSetCount += 1
                    Next

                    ChkItemSet(itemInfoList.serial, row) = Nothing

                Next

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

    End Function

    Private Function compareSave() As Boolean

        txbStateRead.Enabled = False
        txbStateRead.Text = "등록중"
        txbStateRead.BackColor = Color.Yellow

        Dim nowToday As String = Format(Now, "yyyy") & "-" & Format(Now, "MM") & "-" & Format(Now, "dd")

        If ckbAPIUse.Checked = True Then

            apiSerialData()

            If mesDataReg() Then
                failForm()
                Return True
            End If

            If mesDBOrderReg(nowToday) Then
                failForm()
                Return True
            End If
        Else
            If rdbStateInv.Checked = True Then
                If dbSaveInv(nowToday) Then
                    failForm()
                    Return True
                End If
            Else
                If dbSave(nowToday) Then
                    failForm()
                    Return True
                End If
            End If
        End If

        txbStateRead.Text = "등록완료"
        StartFunc = True

        gbMapStInfo.BackColor = SystemColors.Control
        gbMapPkInfo.BackColor = SystemColors.Control
        btnSearch.Text = "검 색"
        txbInv.Enabled = False

        txbStateRead.Enabled = True

        txbStateRead.SelectionStart = txbStateRead.TextLength
        txbStateRead.ScrollToCaret()
        Return False
    End Function

    Private Sub failForm()
        txbStateRead.Text = "등록실패"

        gbMapStInfo.BackColor = SystemColors.Control
        gbMapPkInfo.BackColor = SystemColors.Control
        txbInv.BackColor = Color.Red

        btnSearch.Text = "검 색"
        txbInv.Enabled = False
        txbStateRead.Enabled = True

        txbStateRead.SelectionStart = txbStateRead.TextLength
        txbStateRead.ScrollToCaret()
    End Sub

    Private Function mesDBOrderReg(nowToday As String) As Boolean

        Dim buydateParsing As String = Mid(ProdSelect(ProdList.BuyDate), 1, InStr(ProdSelect(ProdList.BuyDate), " ") - 1)
        Dim serialParsing, accCode, accName, address As String

        If ProdSelect(ProdList.AccountCode) = Nothing Then
            accCode = "NULL"
        Else
            accCode = Chr(39) & ProdSelect(ProdList.AccountCode) & Chr(39)
        End If

        If ProdSelect(ProdList.AccountName) = Nothing Then
            accName = "NULL"
        Else
            accName = Chr(39) & ProdSelect(ProdList.AccountName) & Chr(39)
        End If

        If UBound(Split(ProdSelect(ProdList.Address), "'")) > 0 Then
            address = ProdSelect(ProdList.Address).Insert(InStr(ProdSelect(ProdList.Address), "'"), "'")
        End If

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

            If ChkItemSet(itemInfoList.serial, i) = Nothing Then
                serialParsing = "NULL"
            Else
                serialParsing = Chr(39) & ChkItemSet(itemInfoList.serial, i) & Chr(39)
            End If

            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(),'" & txbMapState.Text & "','" & buydateParsing & "'," & accCode & "," & accName & ",'" & ProdSelect(ProdList.OrdererCode) & "','" & ProdSelect(ProdList.OrdererName) & "','" & ProdSelect(ProdList.OrdererName) & "','" & ProdSelect(ProdList.phone) & "','" & ProdSelect(ProdList.zip) & "','" & ProdSelect(ProdList.Address) & "','" & nowToday & "','" & ChkItemSet(itemInfoList.code, i) & "','" & ChkItemSet(itemInfoList.name, i) & "','" & ChkItemSet(itemInfoList.count, i) & "','" & ChkItemSet(itemInfoList.face, i) & "','" & ChkItemSet(itemInfoList.eye, i) & "','" & txbInv.Text & "','" & txbMapPacking.Text & "'," & serialParsing & ",'release')"
            If DBCommand(DBCmd) = False Then
                Return True
            End If
        Next

        Return False
    End Function

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

        If rdbMap.Checked = True Or rdbMass.Checked = True Then
            If setCodeUse = True Then
                For i = 0 To apiItemSet.GetLength(1) - 1
                    If rdbStateInv.Checked = True Then
                        jsonData = "{""expectedOutCount"":" & apiItemSet(itemInfoList.count, i) & ",""invoiceNumber"":""" & txbInv.Text & """}"
                    Else
                        If apiItemSet(itemInfoList.type, i) = 0 Then
                            jsonData = "{""expectedOutCount"":" & apiItemSet(itemInfoList.count, i) & ",""serialNumber"":""" & apiItemSet(itemInfoList.serial, i) & """,""invoiceNumber"":""" & txbInv.Text & """}"
                        Else
                            jsonData = "{""expectedOutCount"":" & apiItemSet(itemInfoList.count, i) & ",""invoiceNumber"":""" & txbInv.Text & """}"
                        End If
                    End If

                    apiResult = apiRequest_PUT(jsonData, apiItemSet(itemInfoList.id_Serial, i))

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

                Next
            Else

                For i = 0 To ChkItemSet.GetLength(1) - 1
                    If rdbStateInv.Checked = True Then
                        jsonData = "{""expectedOutCount"":" & ChkItemSet(itemInfoList.count, i) & ",""invoiceNumber"":""" & txbInv.Text & """}"
                    Else
                        If ChkItemSet(itemInfoList.type, i) = 0 Then
                            jsonData = "{""expectedOutCount"":" & ChkItemSet(itemInfoList.count, i) & ",""serialNumber"":""" & ChkItemSet(itemInfoList.serial, i) & """,""invoiceNumber"":""" & txbInv.Text & """}"
                        Else
                            jsonData = "{""expectedOutCount"":" & ChkItemSet(itemInfoList.count, i) & ",""invoiceNumber"":""" & txbInv.Text & """}"
                        End If
                    End If

                    apiResult = apiRequest_PUT(jsonData, ChkItemSet(itemInfoList.id_Serial, i))

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

                Next

            End If
        End If

        Return False
    End Function


    Private Function apiMassSave() As Boolean
        Dim jsonData As String
        Dim apiResult As String

        For i = 0 To mapping_list.Count - 1
            Dim packItemSet(,) As String = mapping_list(i)
            Dim serial_number As String = ""
            Dim order_code As String = ProdSelect(ProdList.OrderCode) & "/" & i + 1
            Dim buy_date As String = Mid(ProdSelect(ProdList.BuyDate), 1, InStr(ProdSelect(ProdList.BuyDate), " ") - 1)
            Dim nowToday As String = Format(Now, "yyyy") & "-" & Format(Now, "MM") & "-" & Format(Now, "dd")

            For j = 0 To packItemSet.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() " &
                                                        ", '" & order_code & "'" &
                                                        ", '" & buy_date & "'" &
                                                        ", '" & ProdSelect(ProdList.AccountCode) & "'" &
                                                        ", '" & ProdSelect(ProdList.AccountName) & "'" &
                                                        ", '" & ProdSelect(ProdList.OrdererCode) & "'" &
                                                        ", '" & ProdSelect(ProdList.OrdererName) & "'" &
                                                        ", '" & ProdSelect(ProdList.OrdererName) & "'" &
                                                        ", '" & ProdSelect(ProdList.phone) & "'" &
                                                        ", '" & ProdSelect(ProdList.zip) & "'" &
                                                        ", '" & ProdSelect(ProdList.Address) & "'" &
                                                        ", '" & nowToday & "'" &
                                                        ", '" & packItemSet(itemInfoList.code, j) & "'" &
                                                        ", '" & packItemSet(itemInfoList.name, j) & "'" &
                                                        ", '" & packItemSet(itemInfoList.count, j) & "'" &
                                                        ", '" & packItemSet(itemInfoList.face, j) & "'" &
                                                        ", '" & packItemSet(itemInfoList.eye, j) & "'" &
                                                        ", '" & packItemSet(itemInfoList.invoice_number, 0) & "'" &
                                                        ", '" & packItemSet(itemInfoList.packing_code, 0) & "'" &
                                                        ", '" & packItemSet(itemInfoList.id_Serial, j) & "'" &
                                                        ", 'release'" &
                                                        ")"
                If DBCommand(DBCmd) = False Then
                    'errorOut("등록오류")
                    MsgBox("전표 데이터 등록 도중 오류가 발생하였습니다.", vbExclamation)
                    Return False
                End If

                If packItemSet(itemInfoList.id_Serial, j) <> Nothing And packItemSet(itemInfoList.id_Serial, j) <> "" Then
                    If serial_number = "" Then
                        serial_number = packItemSet(itemInfoList.id_Serial, j)
                    Else
                        serial_number = serial_number & "/" & packItemSet(itemInfoList.id_Serial, j)
                    End If
                End If
            Next

            jsonData = "{""expectedOutCount"": 1,""serialNumber"":""" & serial_number & """,""invoiceNumber"":""" & packItemSet(itemInfoList.invoice_number, 0) & """}"

            apiResult = apiRequest_PUT(jsonData, SetIdCode(i))

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

        Next

        Return False
    End Function


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

        If rdbMap.Checked = True Then
            If setCodeUse = True Then
                For i = 0 To ChkItemSet.GetLength(1) - 1
                    If ChkItemSet(itemInfoList.serial, i) <> String.Empty Then
                        Dim idSave As String = ChkItemSet(itemInfoList.id_Serial, i)
                        Dim pkSave As String = ChkItemSet(itemInfoList.pk_Type, i)
                        Dim serialSave As String = ChkItemSet(itemInfoList.serial, i)
                        Dim runInt As Integer = UBound(Split(idSave, "/"))

                        For n = 0 To runInt
                            Dim nowid As String
                            Dim nowSerial As String

                            If n < runInt Then
                                nowid = Mid(idSave, 1, InStr(idSave, "/") - 1)
                                nowSerial = Mid(serialSave, 1, InStr(serialSave, "/") - 1)

                                idSave = Mid(idSave, InStr(idSave, "/") + 1, idSave.Length)
                                serialSave = Mid(serialSave, InStr(serialSave, "/") + 1, serialSave.Length)
                            Else
                                nowid = Mid(idSave, 1, idSave.Length)
                                nowSerial = Mid(serialSave, 1, serialSave.Length)
                            End If

                            jsonData = "{""expectedOutCount"": 1,""serialNumber"":""" & nowSerial & """,""invoiceNumber"":""" & txbLabelCode.Text & """}"

                            apiResult = apiRequest_PUT(jsonData, nowid)

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

                        Next
                    End If
                Next
            End If
        End If

        Return True
    End Function

    Private Sub apiSerialData()
        Dim serialArr(ChkItemSet.GetLength(1) - 1) As String

        For i = 0 To ChkItemSet.GetLength(1) - 1
            serialArr(i) = ChkItemSet(itemInfoList.serial, i)    '' SerialArr 배열에 ChkItemSet 시리얼 번호 저장
        Next

        For api = 0 To apiItemSet.GetLength(1) - 1

            For chk = 0 To ChkItemSet.GetLength(1) - 1

                If apiItemSet(itemInfoList.code, api) = ChkItemSet(itemInfoList.code, chk) Then
                    serialArr(chk) = apiItemReg(serialArr(chk), chk, api)
                Else
                    If InStr(ChkItemSet(itemInfoList.pk_Type, chk), apiItemSet(itemInfoList.code, api)) > 0 Then
                        If ChkItemSet(itemInfoList.type, chk) = 0 Then
                            serialArr(chk) = apiItemReg(serialArr(chk), chk, api)
                        End If
                    End If
                End If

            Next

        Next

    End Sub

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

                    If apiItemSet(itemInfoList.serial, apiNum) = String.Empty Then
                        apiItemSet(itemInfoList.serial, apiNum) = serialData
                    Else
                        apiItemSet(itemInfoList.serial, apiNum) = apiItemSet(itemInfoList.serial, apiNum) & "/" & serialData
                    End If
                End If
            Next
        Else
            apiItemSet(itemInfoList.type, apiNum) = 1
        End If

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

        Return serStr
    End Function

    Private Function dbSaveInv(nowToday As String) As Boolean

        For i = 0 To ChkItemSet.GetLength(1) - 1
            DBCmd = "UPDATE " & applyOrderDB & " SET Shipment_Date = '" & nowToday & "', Invoice_Number = '" & txbInv.Text & "', release_state = 'release' WHERE Order_Code = '" & txbMapState.Text & "' AND Item_Code = '" & ChkItemSet(itemInfoList.code, i) & "'"
            If DBCommand(DBCmd) = False Then
                MsgBox("데이터베이스에 없는 제품이 포함되어 있습니다.", vbCritical)
                Return True
            End If
        Next

            Return False
    End Function

    Private Function dbSave(nowToday As String) As Boolean
        Dim packSerial As String

        If setCodeUse = True Then
            If setCodeInsert() Then

                For i = 0 To ChkItemSet.GetLength(1) - 1
                    DBCmd = "SELECT COUNT(Order_Code) FROM " & applyOrderDB & " WHERE Order_Code = '" & txbMapState.Text & "' AND Item_Code = '" & ChkItemSet(itemInfoList.code, i) & "'"

                    Dim rowStr As String = DBQueryScalar(DBCmd)

                    If rowStr = "False" Then
                        MsgBox("세트 데이터를 저장하는 도중 오류가 발생하였습니다.", vbCritical)
                        Return True
                    End If

                    If ChkItemSet(itemInfoList.serial, i) = Nothing Then
                        packSerial = "NULL"
                    Else
                        packSerial = Chr(39) & ChkItemSet(itemInfoList.serial, i) & Chr(39)
                    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(),'" & txbMapState.Text & "'," & 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 & "','" & ChkItemSet(itemInfoList.code, i) & "','" & ChkItemSet(itemInfoList.name, i) & "','" & ChkItemSet(itemInfoList.count, i) & "','" & ChkItemSet(itemInfoList.face, i) & "','" & ChkItemSet(itemInfoList.eye, i) & "','" & txbInv.Text & "','" & txbMapPacking.Text & "'," & packSerial & ",'release')"
                    Else
                        DBCmd = "UPDATE " & applyOrderDB & " SET Shipment_Date = '" & nowToday & "', Item_Count = '" & ChkItemSet(itemInfoList.count, i) & "', Invoice_Number = '" & txbInv.Text & "', Packing_Code= '" & txbMapPacking.Text & "',Serial_Number= " & packSerial & ",release_state='release' WHERE Order_Code = '" & txbMapState.Text & "' AND Item_Code = '" & ChkItemSet(itemInfoList.code, i) & "'"
                    End If

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

                Next

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

            Else
                Return True
            End If
        Else
            For i = 0 To ChkItemSet.GetLength(1) - 1

                If ChkItemSet(itemInfoList.serial, i) = Nothing Then
                    packSerial = "NULL"
                Else
                    packSerial = Chr(39) & ChkItemSet(itemInfoList.serial, i) & Chr(39)
                End If

                DBCmd = "UPDATE " & applyOrderDB & " SET Shipment_Date = '" & nowToday & "', Invoice_Number = '" & txbInv.Text & "', Packing_Code = '" & txbMapPacking.Text & "', Serial_Number = " & packSerial & ", release_state = 'release' WHERE Order_Code = '" & txbMapState.Text & "' AND Item_Code = '" & ChkItemSet(itemInfoList.code, i) & "'"
                If DBCommand(DBCmd) = False Then
                    MsgBox("데이터베이스에 없는 제품이 포함되어 있습니다.", vbCritical)
                    Return True
                End If
            Next
        End If

        Return False
    End Function

    Private Function setCodeDelete() As Boolean
        DBCmd = "DELETE FROM " & applyOrderDB & " WHERE Order_Code = '" & txbMapState.Text & "' AND Item_Code LIKE 'PK%'"
        If DBCommand(DBCmd) Then
            Return True
        Else
            MsgBox("세트 코드를 삭제하는 과정에서 오류가 발생하였습니다.", vbCritical)
            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 = '" & txbMapState.Text & "' 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
            MsgBox("구매 고객에 대한 데이터가 존재하지 않습니다.", vbCritical)
            Return False
        End If
    End Function

    Private Function statePackCompare() As Boolean
        If ChkItemSet.GetLength(1) = packItemSet.GetLength(1) Then
            If stateFullCount = packFullCount Then
                For pack = 0 To packItemSet.GetLength(1) - 1
                    Dim checkOk As Boolean = False
                    For chkState = 0 To ChkItemSet.GetLength(1) - 1

                        Dim packCodeData As String
                        Dim packCode As String = packItemSet(itemInfoList.code, pack)
                        Dim codeNum As Int16 = UBound(Split(packItemSet(itemInfoList.code, pack), "/"))

                        For i = 0 To codeNum
                            If i = codeNum Then
                                packCodeData = Mid(packCode, 1, packCode.Length)
                            Else
                                packCodeData = Mid(packCode, 1, InStr(packCode, "/") - 1)
                                packCode = Mid(packCode, InStr(packCode, "/") + 1, packCode.Length)
                            End If

                            If packCodeData = ChkItemSet(itemInfoList.code, chkState) Then
                                If ChkItemSet(itemInfoList.count, chkState) = packItemSet(itemInfoList.count, pack) Then
                                    If ChkItemSet(itemInfoList.face, chkState) = packItemSet(itemInfoList.face, pack) Then
                                        If ChkItemSet(itemInfoList.eye, chkState) = packItemSet(itemInfoList.eye, pack) Then
                                            ChkItemSet(itemInfoList.type, chkState) = packItemSet(itemInfoList.pk_Type, pack)
                                            ChkItemSet(itemInfoList.serial, chkState) = packItemSet(itemInfoList.id_Serial, pack)
                                            checkOk = True
                                            Exit For
                                        End If
                                    End If
                                End If
                            End If

                        Next

                        If checkOk = True Then
                            Exit For
                        End If

                    Next

                    If checkOk = False Then
                        For i = 0 To txbList.Eye
                            txbArrayList(pack, i).BackColor = Color.Red
                        Next
                        gbMapPkInfo.BackColor = Color.Red
                        MsgBox("맞지 않는 제품이 포장되어 있습니다. 확인하여 주십시오.", vbCritical)
                        Return True
                    End If

                Next

                Return False
            Else
                For i = 0 To packItemSet.GetLength(1) - 1
                    txbArrayList(i, txbList.Count).BackColor = Color.Red
                Next

                gbMapPkInfo.BackColor = Color.Red
                MsgBox("전체 수량이 맞지 않습니다.", vbCritical)
                Return True
            End If
        Else
            For i = 0 To packItemSet.GetLength(1) - 1
                txbArrayList(i, txbList.Count).BackColor = Color.Red
            Next

            gbMapPkInfo.BackColor = Color.Red
            MsgBox("항목 개수가 맞지 않습니다.", vbCritical)
            Return True
        End If

    End Function


    '---------------------------초기화------------------------------------------

    Private Sub StateTxbClear(i As Int16)
        Dim FuncSwitch As Boolean = False
        Dim ctrlCount As Int16 = 0
        Dim NowTxbCount As Integer = 0

        txbNameValue(i)

        If i = funcList.search Then
            ctrlCount = txbList.Remove + 1
            NowTxbCount = (setPanel(i).Controls.Count - ctrlCount) / ctrlCount
        Else
            ctrlCount = txbList.Eye + 1
            NowTxbCount = setPanel(i).Controls.Count / ctrlCount
        End If

        If NowTxbCount <> 0 Then
            FuncSwitch = True
        Else
            FuncSwitch = False
        End If

        If FuncSwitch = True Then
            TxbClearFunc(i, setPanel(i), NowTxbCount)
        End If

    End Sub

    Private Sub TxbClearFunc(setType As Int16, setpanel As Panel, txbCount As Integer)
        For i = txbCount - 1 To 0 Step -1

            If setType = funcList.search Then
                setpanel.Controls(txbSetName(txbList.Name) & i).Dispose()
                setpanel.Controls(txbSetName(txbList.Count) & i).Dispose()
                setpanel.Controls(txbSetName(txbList.Face) & i).Dispose()
                setpanel.Controls(txbSetName(txbList.Eye) & i).Dispose()
                setpanel.Controls(txbSetName(txbList.Modify) & i).Dispose()
                setpanel.Controls(txbSetName(txbList.Remove) & i).Dispose()
            Else
                setpanel.Controls(txbSetName(txbList.Name) & i).Dispose()
                setpanel.Controls(txbSetName(txbList.Count) & i).Dispose()
                setpanel.Controls(txbSetName(txbList.Face) & i).Dispose()
                setpanel.Controls(txbSetName(txbList.Eye) & i).Dispose()
            End If
        Next
    End Sub


    Private Sub compareClear()
        compareValueClean()
        compareTxbClean()
        compareTxbRefresh()
    End Sub

    Private Sub compareTxbRefresh()
        txbChkState.Refresh()
        txbChkCode.Refresh()
        txbChkOrderer.Refresh()
        txbChkAcc.Refresh()
        txbChkDate.Refresh()
        txbChkRefer.Refresh()
        txbChkAD.Refresh()
    End Sub

    Private Sub compareTxbClean()
        txbChkState.Text = Nothing
        txbChkCode.Text = Nothing
        txbChkOrderer.Text = Nothing
        txbChkAcc.Text = Nothing
        txbChkDate.Text = Nothing
        txbChkRefer.Text = Nothing
        txbChkAD.Text = Nothing
    End Sub

    Private Sub compareValueClean()

        If rdbState.Checked = True Then
            ReDim ChkItemSet(0, 0)
            ReDim packItemSet(0, 0)
            ReDim apiItemSet(0, 0)
        Else
            ReDim ChkItemSet(0, 0)
            ReDim packItemSet(0, 0)
            setCodeUse = False
            txbInv.BackColor = SystemColors.Window
            txbInv.Text = String.Empty
        End If

        stateFullCount = 0
        packFullCount = 0
        setCodeUse = False

        For i = 0 To ProdSelect.Length - 1
            ProdSelect(i) = Nothing
        Next

        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

        For i = 0 To chkItem.Length - 1
            chkItem(i) = Nothing
        Next
    End Sub

    '-------------------api 로그인------------------------------

    Private Sub btnLogin_Click(sender As Object, e As EventArgs) Handles btnLogin.Click
        If loginState = False Then
            If loginForm.ShowDialog = DialogResult.OK Then
                loginState = True
                ckbAPIUse.Checked = True
                ckbAPIUse.Enabled = True
                lbAPIUse.Text = "ON"
                btnLogin.Text = "LogOut"
            Else
                loginState = False
            End If
        Else
            loginState = False
            ckbAPIUse.Checked = False
            ckbAPIUse.Enabled = False
            lbAPIUse.Text = "OFF"
            btnLogin.Text = "Login"
        End If
        resetFunc()

        txbStateRead.Focus()
    End Sub


    '-----------------상단 버튼류 기능----------------------

    Private Sub rdbState_CheckedChanged(sender As Object, e As EventArgs) Handles rdbState.CheckedChanged
        If rdbState.Checked = True Then
            pnOrderCheck.Visible = True
            pnOrderCheck.Location = New Point(2, 196)
            pnPacking.Visible = False
            gbMapOption.Visible = False
            pnMass.Visible = False
            gb_map_state.BackColor = SystemColors.Control
            rdbStatePack.Checked = False
        End If

        resetFunc()

        txbStateRead.Focus()
    End Sub

    Private Sub rdbMap_CheckedChanged(sender As Object, e As EventArgs) Handles rdbMap.CheckedChanged
        If rdbMap.Checked = True Then
            pnOrderCheck.Visible = False
            pnPacking.Visible = True
            pnPacking.Location = New Point(2, 196)
            pnMass.Visible = False
            gbMapOption.Visible = True
            rdbStatePack.Checked = True
        End If

        resetFunc()

        txbStateRead.Focus()
    End Sub

    Private Sub rdbMass_CheckedChanged(sender As Object, e As EventArgs) Handles rdbMass.CheckedChanged
        If rdbMass.Checked = True Then
            pnOrderCheck.Visible = False
            pnPacking.Visible = False
            pnMass.Location = New Point(2, 196)
            pnMass.Visible = True
            gbMapOption.Visible = False
            rdbStatePack.Checked = False
        End If

        ckbBarcode.Checked = False
        ckbBarcode.Checked = True

        MassReset()

        txbStateRead.Focus()
    End Sub

    Private Sub ckbBarcode_CheckedChanged(sender As Object, e As EventArgs) Handles ckbBarcode.CheckedChanged
        If ckbBarcode.Checked = True Then
            ckbAuto.Checked = True
            ckbAuto.Enabled = True
        Else
            ckbAuto.Checked = False
            ckbAuto.Enabled = False
        End If

        txbStateRead.Focus()
    End Sub

    Private Sub ckbAuto_CheckedChanged(sender As Object, e As EventArgs) Handles ckbAuto.CheckedChanged


        If ckbAuto.Checked = True Then
            btnSearch.Visible = False
            btnSearch.Location = New Point(1365, 90)
            pnBarcode.Location = New Point(245, 80)
            btnReset.Location = New Point(1365, 90)
        Else
            btnSearch.Visible = True
            btnSearch.Location = New Point(1365, 90)
            pnBarcode.Location = New Point(245, 80)
            btnReset.Location = New Point(1555, 90)
        End If

        'If rdbMass.Checked = True Then
        '    If ckbAuto.Checked = True Then
        '        btnSearch.Visible = False
        '        btnSearch.Location = New Point(930, 90)
        '        pnBarcode.Location = New Point(0, 80)
        '        btnReset.Location = New Point(930, 90)
        '    Else
        '        btnSearch.Visible = True
        '        btnSearch.Location = New Point(930, 90)
        '        pnBarcode.Location = New Point(0, 80)
        '        btnReset.Location = New Point(1115, 90)
        '    End If
        'Else
        'End If

        txbStateRead.Focus()
    End Sub

    Private Sub rdbStateInv_CheckedChanged(sender As Object, e As EventArgs) Handles rdbStateInv.CheckedChanged
        If rdbStateInv.Checked = True Then
            gbMapPacking.Enabled = False
            ptbLogo.Location = New Point(954, 638)
            gbInvoice.Location = New Point(3, 622)
        End If

        resetFunc()
        txbStateRead.Focus()
    End Sub

    Private Sub rdbStatePack_CheckedChanged(sender As Object, e As EventArgs) Handles rdbStatePack.CheckedChanged
        If rdbStatePack.Checked = True Then
            gbMapPacking.Enabled = True
            ptbLogo.Location = New Point(3, 638)
            gbInvoice.Location = New Point(954, 622)
        End If

        resetFunc()
        txbStateRead.Focus()
    End Sub

    Private Sub resetFunc()
        txbStateRead.BackColor = SystemColors.Window
        txbStateRead.Text = String.Empty

        compareValueClean()
        compareClear()

        If rdbMass.Checked = True Then
            MassReset()
        Else
            mappingReset()
        End If

        For i = 0 To funcList.mappack
            StateTxbClear(i)
        Next

        txbStateRead.Focus()
    End Sub

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

    Private Sub txbChkState_GotFocus(sender As Object, e As EventArgs) Handles txbChkState.GotFocus, txbChkCode.GotFocus, txbChkOrderer.GotFocus, txbChkAcc.GotFocus, txbChkDate.GotFocus, txbChkRefer.GotFocus, txbChkAD.GotFocus, txbMapState.GotFocus, txbMapDate.GotFocus, txbMapOrder.GotFocus, txbMapAccount.GotFocus, txbMapRefer.GotFocus, txbMapPacking.GotFocus, txbMapPkDate.GotFocus, txbInv.GotFocus, txbMsState.GotFocus, txbMsDate.GotFocus, txbMsOrder.GotFocus, txbMsAccount.GotFocus, txbMsRefer.GotFocus, txbMsPacking.GotFocus, txbLabelCode.GotFocus, txbMsPkDate.GotFocus, txbRequest.GotFocus, txbWork.GotFocus, txbLeftOver.GotFocus
        txbStateRead.Focus()
    End Sub

    Private Sub ckbAPIUse_CheckedChanged(sender As Object, e As EventArgs) Handles ckbAPIUse.CheckedChanged
        txbStateRead.Focus()
    End Sub

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