Imports System.IO
Imports System.IO.Ports
Imports System.Math
Imports System.Text
Imports System.Threading
Imports Microsoft.VisualBasic.ApplicationServices

Public Class MainForm
    Private Const TDMaxLength As Int16 = 10
    Private Const TDMinLength As Int16 = 9
    Private Const InputCntVal As Int16 = 10
    Private Const LimitWhile As Int16 = 5

    Private TDSNHead1 As String = "DIT"
    Private TDSNHead2 As String = "J"

    Const oldSearchLength As Int16 = 12
    Const newSearchLength As Int16 = 16

    Private DBCmd As String
    Private tmpCmdMessage As String
    Private rxMessage, cmdMessage As String

    Private ThreadStop As Boolean = False

    Private SerialNum As String
    Private NowDate As String
    Private NowTime As String
    Private OptionChange As Boolean = False
    Private IDName As String = String.Empty

    Private ModelCode As String
    Private TypeCode As String
    Private ColorCode As String
    Private ClassCode As String
    Private VersionCode As String
    Private ProdCode As String
    Private TDUseCompare As Boolean = False

    Private RegNumber() As Integer

    Private InputCnt As Int16

    Private TrayData(0, 0) As Integer

    Private Enum TrayDataList
        NumData
        State
        maxList
    End Enum

    Private Enum SearchList
        TestStep
        Power
        Depth
        Serial
        InputDate
        Frequency
        TestDate
        Capacitor_FW
        Grede

        maxList
    End Enum
    Private TDData(SearchList.maxList - 1) As String
    Private TDDataTxb(SearchList.maxList - 1) As TextBox

    Private Enum ModeList
        Prod_Input
        TDRecycle
    End Enum
    Private NowMode As Int16

    Private Enum SaveList
        Info
        Config
        Print
        MaxSave
    End Enum
    Private SaveName(SaveList.MaxSave) As String

    Private Enum CountList
        Total
        Success
        Fail

        maxCount
    End Enum
    Private CountSelect(CountList.maxCount - 1) As Integer
    Private ErrorData As Boolean = False

    Private Enum ClassList
        Domestic_Set
        Domestic_AS
        Domestic_shop
        OverSeas_Set
        OverSeas_AS
        Experience
        MaxClass
    End Enum
    Private ClassNumber(ClassList.MaxClass - 1) As Int16

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

    Private Delegate Sub SerialDelegate()
    Private SerialDelegateFunc As SerialDelegate

    Private Runthread As Thread = New Thread(AddressOf ThreadPlay)
    Private ThreadSwitch As Boolean = True

    Private Sub ScanTimer_Tick(sender As Object, e As EventArgs) Handles ScanTimer.Tick
        If InputCnt Then
            InputCnt -= 1
        Else
            ScanTimer.Enabled = False
            If txbPVSN.Text.Replace(" ", "") <> "" Or chbAutoMeasure.Checked Then

                Select Case NowMode
                    Case ModeList.Prod_Input
                        If InStr(txbPVSN.Text, "[START]") > 0 Or txbPVSN.Text.Length = oldSearchLength Or txbPVSN.Text.Length = newSearchLength Then
                            btnEnter_Click(sender, e)
                        End If
                    Case ModeList.TDRecycle
                        If InStr(txbPVSN.Text, TDSNHead1) > 0 Or InStr(txbPVSN.Text, TDSNHead2) > 0 Then
                            btnEnter_Click(sender, e)
                        End If
                    Case Else
                        MsgBox("잘못된 접근입니다.", vbCritical)
                End Select

                txbPVSN.Focus()
            Else
                btnEnter.Focus()
            End If
            txbPVSN.Refresh()
            btnEnter.Refresh()
        End If
    End Sub

    Private Sub txbPVSN_TextChanged(sender As Object, e As EventArgs) Handles txbPVSN.TextChanged
        Dim TmpStr As String
        If txbPVSN.Enabled = True Then
            If InputCnt = 0 And chbUseBarcode.Checked = True Then
                TmpStr = txbPVSN.Text
                If (Len(TmpStr) > 1) Then
                    TmpStr = Mid(TmpStr, Len(TmpStr), 1)
                    txbPVSN.Clear()
                    txbPVSN.AppendText(TmpStr)
                End If
                SetInputCnt()
            End If
        End If
    End Sub

    Private Sub DataSetting()
        Select Case NowMode
            Case ModeList.Prod_Input
                TDDataTxb(SearchList.TestStep) = txbTDStep
                TDDataTxb(SearchList.Frequency) = txbTDFreq
                TDDataTxb(SearchList.Grede) = txbTDGrade
                TDDataTxb(SearchList.Serial) = txbTDNum
                TDDataTxb(SearchList.InputDate) = txbTDIDate
                TDDataTxb(SearchList.Depth) = txbTDDepth
                TDDataTxb(SearchList.TestDate) = txbReTest
                TDDataTxb(SearchList.Power) = txbTDPower
                TDDataTxb(SearchList.Capacitor_FW) = txbPDVersion ''제외
            Case ModeList.TDRecycle
                TDDataTxb(SearchList.TestStep) = txbReOrder
                TDDataTxb(SearchList.Capacitor_FW) = txbReCValue
                TDDataTxb(SearchList.Frequency) = txbReFreq
                TDDataTxb(SearchList.Grede) = txbReGrade
                TDDataTxb(SearchList.Serial) = txbReSerial
                TDDataTxb(SearchList.InputDate) = txbReInput
                TDDataTxb(SearchList.Depth) = txbReMotor
                TDDataTxb(SearchList.TestDate) = txbReTest
                TDDataTxb(SearchList.Power) = txbRePower
        End Select
    End Sub

    Private Sub DefaultSetting()
        PrintUseCkb(PrintList.BoxCode) = ckbBoxPnt
        PrintUseCkb(PrintList.Warranty) = ckbWarPnt
        PrintUseCkb(PrintList.ProdLabel) = ckbProdPnt
        PrintUseTxb(PrintList.BoxCode) = txbPtBox_Name
        PrintUseTxb(PrintList.Warranty) = txbPtWar_Name
        PrintUseTxb(PrintList.ProdLabel) = txbPtProd_Name
        PrintUseZip(PrintList.BoxCode) = txbPtBox_Label
        PrintUseZip(PrintList.Warranty) = txbPtWar_Label
        PrintUseZip(PrintList.ProdLabel) = txbPtProd_Label
        SaveName(SaveList.Info) = "InfoList"
        SaveName(SaveList.Config) = "Config"
        SaveName(SaveList.Print) = "Print"
        ClassNumber(ClassList.Domestic_Set) = "1"
        ClassNumber(ClassList.Domestic_AS) = "2"
        ClassNumber(ClassList.Domestic_shop) = "3"
        ClassNumber(ClassList.OverSeas_Set) = "5"
        ClassNumber(ClassList.OverSeas_AS) = "6"
        ClassNumber(ClassList.Experience) = "7"
    End Sub

    Private Sub RegCboSetting()
        ModelCboSetting()
        ClassCboSetting()
        VersionCboSetting()
        cboClear()
    End Sub

    Private Sub ClassCboSetting()
        cboRegClass.DisplayMember = "Key"
        cboRegClass.ValueMember = "Value"

        cboRegClass.Items.Clear()
        cboRegClass.Items.Add(New DictionaryEntry("국내-세트", 1))
        cboRegClass.Items.Add(New DictionaryEntry("국내-A/S", 2))
        cboRegClass.Items.Add(New DictionaryEntry("국내-샵용", 3))
        cboRegClass.Items.Add(New DictionaryEntry("해외-세트", 5))
        cboRegClass.Items.Add(New DictionaryEntry("해외-A/S", 6))
        cboRegClass.Items.Add(New DictionaryEntry("체험단", 7))
    End Sub

    Private Sub VersionCboSetting()
        cboRegVersion.DisplayMember = "Key"
        cboRegVersion.ValueMember = "Value"

        cboRegVersion.Items.Clear()
        cboRegVersion.Items.Add(New DictionaryEntry("V1", 0))
        cboRegVersion.Items.Add(New DictionaryEntry("V2", 1))
        cboRegVersion.Items.Add(New DictionaryEntry("V3", 2))
        cboRegVersion.Items.Add(New DictionaryEntry("V4", 3))
        cboRegVersion.Items.Add(New DictionaryEntry("V5", 4))
        cboRegVersion.Items.Add(New DictionaryEntry("V6", 5))
        cboRegVersion.Items.Add(New DictionaryEntry("V7", 6))
        cboRegVersion.Items.Add(New DictionaryEntry("V8", 7))
        cboRegVersion.Items.Add(New DictionaryEntry("V9", 8))
    End Sub

    Private Sub ModelCboSetting()
        cboRegModel.Items.Clear()

        DBCmd = "SELECT ModelName FROM " & ApplyModelInfoDB & " WHERE DeviceTypeCode = 'A' GROUP BY ModelName"
        If DBQueryReader(DBCmd) Then
            For i = 0 To sqlDataQuery.Length - 1
                cboRegModel.Items.Add(sqlDataQuery(i))
            Next
        End If
    End Sub

    Private Sub cboRegModel_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboRegModel.SelectedIndexChanged
        If cboRegModel.SelectedIndex > -1 Then
            cboRegType.Items.Clear()

            DBCmd = "SELECT CartTypeName FROM " & ApplyModelInfoDB & " WHERE ModelName = '" & cboRegModel.SelectedItem & "' GROUP BY CartTypeCode ORDER BY CartTypeCode ASC"
            If DBQueryReader(DBCmd) Then
                For i = 0 To sqlDataQuery.Length - 1
                    cboRegType.Items.Add(sqlDataQuery(i))
                Next
            End If

            cboRegType.SelectedIndex = -1
            cboRegType.Text = "SELECT!"
            pnRegType.Enabled = True
        End If
    End Sub

    Private Sub cboRegType_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboRegType.SelectedIndexChanged
        If cboRegType.SelectedIndex > -1 Then
            cboRegColor.Items.Clear()

            DBCmd = "SELECT ColorName FROM " & ApplyModelInfoDB & " WHERE ModelName = '" & cboRegModel.SelectedItem & "' AND CartTypeName = '" & cboRegType.SelectedItem & "' ORDER BY ColorCode ASC"
            If DBQueryReader(DBCmd) Then
                For i = 0 To sqlDataQuery.Length - 1
                    cboRegColor.Items.Add(sqlDataQuery(i))
                Next
            End If

            cboRegColor.SelectedIndex = -1
            cboRegColor.Text = "SELECT!"
            pnRegColor.Enabled = True
        End If
    End Sub

    Private Function ColorSet(cboSelect As Integer) As Boolean
        Dim modelName As String = dgvDataSet.Rows(cboSelect).Cells(1).Value
        Dim cartTypeName As String = dgvDataSet.Rows(cboSelect).Cells(2).Value
        Dim colorName As String = dgvDataSet.Rows(cboSelect).Cells(5).Value

        DBCmd = "SELECT ModelCode, CartTypeCode, ColorCode, TDUseYn FROM " & ApplyModelInfoDB & " WHERE ModelName = '" & modelName & "' AND CartTypeName = '" & cartTypeName & "' AND  ColorName = '" & colorName & "'"

        If DBQueryReader(DBCmd) Then
            ModelCode = sqlDataQuery(0)
            TypeCode = sqlDataQuery(1)
            ColorCode = sqlDataQuery(2)
            If sqlDataQuery(3) <> "Y" Then
                TDUseCompare = False
            Else
                TDUseCompare = True
            End If
        End If

        Return False
    End Function

    Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        FormSetting()
        DefaultSetting()
        ModeEnable()
        DataSetting()

        ComboBoxSetting()
        txtManufactureDate.ReadOnly = True
        txtManufactureDate.BackColor = Color.Lavender
        UpdateDateTextBox()

        For i = SaveList.Info To SaveList.MaxSave - 1
            OptionLoad(i)
        Next

        Print_Activate()
        RegCboSetting()
        StartCountSetting()
        NowRegCheck()
        txbPVSN.Focus()
    End Sub

    Private Sub ComboBoxSetting()

        ' 년도 콤보박스 (예: 2020~2030)
        For i As Integer = 2020 To 2030
            cmbYear.Items.Add(i.ToString())
        Next

        ' 월 콤보박스 (1~12)
        For i As Integer = 1 To 12
            cmbMonth.Items.Add(i.ToString("00"))
        Next

        ' 일 콤보박스 (1~31)
        For i As Integer = 1 To 31
            cmbDay.Items.Add(i.ToString("00"))
        Next

        ' 기본값 설정 (오늘 날짜)
        cmbYear.Text = DateTime.Now.Year.ToString()
        cmbMonth.Text = DateTime.Now.Month.ToString("00")
        cmbDay.Text = DateTime.Now.Day.ToString("00")

    End Sub

    Private Sub UpdateDateTextBox()
        If cmbYear.Text <> "" And cmbMonth.Text <> "" And cmbDay.Text <> "" Then
            txtManufactureDate.Text = cmbYear.Text & "-" & cmbMonth.Text.PadLeft(2, "0"c) & "-" & cmbDay.Text.PadLeft(2, "0"c)
        Else
            txtManufactureDate.Text = ""
        End If
    End Sub

    Private Sub cmbYear_SelectedIndexChanged() Handles cmbYear.SelectedIndexChanged
        UpdateDateTextBox()
    End Sub

    Private Sub cmbMonth_SelectedIndexChanged() Handles cmbMonth.SelectedIndexChanged
        UpdateDateTextBox()
    End Sub

    Private Sub cmbDay_SelectedIndexChanged() Handles cmbDay.SelectedIndexChanged
        UpdateDateTextBox()
    End Sub

    Private Sub MainForm_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        If UserLogOut() Then
            End
        Else
            e.Cancel = True
        End If
    End Sub

    Private Function UserLogOut() As Boolean
        DBCmd = "UPDATE " & LoginDB & " SET NowState = '0' WHERE UserID = '" & IDName & "'"
        If DBCommand(DBCmd) Then
            Return True
        Else
            Return False
        End If
    End Function

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

        If Runthread.IsAlive = True Then
            Runthread.Abort()
        End If

        If UserLogOut() Then
            End
        Else
            MsgBox("LogOut Fail!", vbCritical)
        End If
    End Sub

    Private Sub FormSetting()
        Const ProgramName As String = "Product Program Ver_"
        Const VersionNum As String = "2.0.3"

        Me.Text = ProgramName & VersionNum
        Me.Size = New Size(1920, 1050)
        Me.WindowState = FormWindowState.Maximized

        IDName = LoginForm.UserInfo.UserID

        dgvPrinter.DefaultCellStyle.Font = New Font("함초롱바탕", 12)

        NowTimer.Enabled = True
    End Sub

    Private Sub ModeEnable()
        rdbCSearch.Enabled = False
        rdbPD1.Enabled = False
        rdbPD2.Enabled = True
        rdbCheck.Enabled = False
        rdbManager.Enabled = False
        rdbRecycle.Enabled = True
    End Sub

    Private Sub ConfigSetting()

        chbUseBarcode.Location = New Point(45, 20)
        chbAutoMeasure.Location = New Point(45, 50)
        ckbPrintUse.Location = New Point(200, 20)
        ckbAutoFunc.Location = New Point(200, 50)

        If rdbRecycle.Checked = True Then
            ckbAutoFunc.Text = "자동삭제"
            ckbAutoFunc.Checked = True
        Else
            ckbAutoFunc.Text = "자동생성"
            ckbAutoFunc.Checked = True
        End If

    End Sub

    Private Sub chbUseBarcode_CheckedChanged(sender As Object, e As EventArgs) Handles chbUseBarcode.CheckedChanged
        If chbUseBarcode.Checked = True Then
            chbAutoMeasure.Checked = True
            chbAutoMeasure.Enabled = True
            lbPVSN.Location = New Point(265, 28)
            txbPVSN.Location = New Point(760, 25)
            btnEnter.Enabled = False
            btnEnter.Visible = False
        Else
            chbAutoMeasure.Checked = False
            chbAutoMeasure.Enabled = False
            lbPVSN.Location = New Point(155, 28)
            txbPVSN.Location = New Point(650, 25)
            btnEnter.Enabled = True
            btnEnter.Visible = True
        End If

        txbPVSN.Focus()
    End Sub

    Private Sub rdbRecycle_CheckedChanged(sender As Object, e As EventArgs) Handles rdbRecycle.CheckedChanged
        If rdbRecycle.Checked = True Then
            NowMode = ModeList.TDRecycle
            OptionSave(SaveList.Config)
            ModeChange()
        End If
    End Sub

    Private Sub rdbPD2_CheckedChanged(sender As Object, e As EventArgs) Handles rdbPD2.CheckedChanged
        If rdbPD2.Checked = True Then
            NowMode = ModeList.Prod_Input
            OptionSave(SaveList.Config)
            ModeChange()
        End If
    End Sub

    Private Sub ModeChange()
        TimerFalse()
        ConfigSetting()

        gbSerial.Enabled = False
        lbState.Visible = False

        pnMaxInput.Enabled = False
        pnMaxInput.Visible = False
        pnRecycle.Enabled = False
        pnRecycle.Visible = False

        Select Case NowMode
            Case ModeList.Prod_Input
                pnMaxInput.Enabled = True
                pnMaxInput.Visible = True
                gbSerial.Enabled = True
                lbState.Visible = True
            Case ModeList.TDRecycle
                pnRecycle.Enabled = True
                pnRecycle.Visible = True
            Case Else
                MsgBox("알 수 없는 동작 모드입니다. 관리자에게 문의해주세요.", vbCritical)
        End Select

        DataReset()
    End Sub

    Private Sub StartCountSetting()
        NowDate = Format(Now, "yyyy-MM-dd")

        If TodayCountCreate() Then
            MsgBox("수량 카운터를 생성하는 도중 오류가 발생하였습니다.", vbCritical)
            Exit Sub
        End If

        If cboPDInfo.SelectedIndex = -1 Then
            ModelCode = 3
        End If

        If TodayCountLoad() Then
            MsgBox("수량 카운터를 불러오는 도중 오류가 발생하였습니다.", vbCritical)
            Exit Sub
        End If

        CountSetting()
    End Sub

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

    Private Sub cmdSerial_Click(sender As Object, e As EventArgs) Handles cmdSerial.Click
        TimerFalse()

        If cmdSerial.Text = "스캔" Then
            cboComPort.Text = "SELECT!"
            LoadComportName()
            cmdSerial.Text = "연결"
        Else
            PortSerial.Close()

            If PortSerial.IsOpen = True Then
                PortSerial.Close()
                SerialStateOFF()
            End If

            Dim PortName As String = cboComPort.SelectedItem
            If OpenSerial(PortName) = False Then
                SerialStateOFF()
            Else
                OptionSave(SaveList.Config)
            End If
            cmdSerial.Text = "스캔"
        End If

        txbPVSN.Focus()
    End Sub

    Private Sub SerialStateOn()
        txbState.BackColor = Color.Green
        lbState.BackColor = Color.Green
        lbState.Text = "ON"
        lbState.Location = New Point(389, 40)
    End Sub

    Private Sub SerialStateOFF()
        txbState.BackColor = Color.Red
        lbState.BackColor = Color.Red
        lbState.Text = "OFF"
        lbState.Location = New Point(385, 40)
    End Sub

    Private Sub LoadComportName()
        Dim PortName() As String
        Dim i As Integer
        Try
            cboComPort.Items.Clear()
            PortName = SerialPort.GetPortNames

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

            cboComPort.Text = "PRESS!"

        Catch ex As Exception
            MsgBox("Port Load ERROR !!" & vbCrLf & ex.Message, vbCritical)
        End Try
    End Sub

    Private Function OpenSerial(SerialName As String) As Boolean
        Try
            If SerialName <> "" Then
                If PortSerial.IsOpen = False Then
                    With PortSerial
                        .PortName = SerialName
                        .BaudRate = 230400
                        .DataBits = 8
                        .Parity = IO.Ports.Parity.None
                        .StopBits = IO.Ports.StopBits.One
                        .Handshake = IO.Ports.Handshake.None
                    End With
                    PortSerial.Open()
                    SerialStateOn()
                End If

                Return True
            Else
                MsgBox("시리얼포트를 설정해주세요!" & vbCrLf & "", vbCritical, "DUALSONIC T/D Selecter Tester Manager")
                Return False
            End If
        Catch ex As Exception
            MsgBox("COM 포트 연결 ERROR !!" & vbCrLf & ex.Message, vbCritical)
            Return False
        End Try
    End Function

    Private Sub btnEnter_Click(sender As Object, e As EventArgs) Handles btnEnter.Click
        Dim SearchData As String = txbPVSN.Text

        If SearchData.Replace(" ", "") = "" Then
            MsgBox("검색할 TD 번호를 입력하여 주십시오.", vbExclamation)
            GoTo FailFunc
        End If

        Select Case NowMode
            Case ModeList.Prod_Input
                TimerFalse()
                ProdInputFunc(sender, e, SearchData)
            Case ModeList.TDRecycle
                TDRecycleFunc(sender, e, SearchData)
            Case Else
                MsgBox("잘못된 루트입니다.", vbCritical)
        End Select

        Exit Sub
FailFunc:
        txbPVSN.BackColor = Color.Red
        txbPVSN.Text = String.Empty
        txbPVSN.Focus()
    End Sub

    Private Function SerialUseCheck() As Boolean
        If txbNowNum.Text = "" Or txbNowNum.Text = "0" Or txbNowNum.Text = String.Empty Then
            MsgBox("시리얼 번호를 불러올 수 없습니다.", vbCritical)
            Return True
        Else
            ProdCode = txbNowNum.Text
        End If

        If ModelCode.Length = 2 Then    '16자리 시리얼번호
            Dim Serial As String = ProdCode.PadLeft(6, "0"c)
            SerialNum = ModelCode & ColorCode & Format(Now, "yyMM") & Serial & ClassCode & TypeCode & VersionCode
        Else                            '12자리 시리얼번호
            Dim FrontSerial As String = Mid(ProdCode, 1, 3)
            Dim BackSerial As String = Mid(ProdCode, 4, 3)
            SerialNum = ModelCode & TypeCode & Format(Now, "yyMM") & BackSerial & FrontSerial
        End If

        If DBSerialCheck() Then
            Return False
        Else
            MsgBox("생성 할 시리얼 번호 " & SerialNum & "은 이미 존재 합니다.", vbCritical)
            Return True
        End If
    End Function

    'Private Function SerialUseCheck() As Boolean
    '    Const ReGen As Int16 = 5
    '    Dim SearchData As String = ClassCode & ColorCode
    '    RichTextBox1.AppendText("SearchData :" & SearchData & vbCrLf)
    '    Dim rdNum As Random = New Random

    '    For i = 1 To ReGen
    '        If SerialCompare(SearchData) Then
    '            ProdCode = NextSerialCheck(SearchData)

    '            If ProdCode = "0" Then
    '                MsgBox("시리얼 번호 확인 중 오류가 발생하였습니다.", vbCritical)
    '                Return True
    '            End If

    '        Else
    '            ProdCode = SearchData & "0000"
    '        End If

    '        ProdCode = Val(ProdCode) + i
    '        RichTextBox1.AppendText("ProdCode :" & ProdCode & vbCrLf)

    '        Dim FrontSerial As String = Mid(ProdCode, 1, 3)
    '        RichTextBox1.AppendText("FrontSerial :" & FrontSerial & vbCrLf)

    '        Dim BackSerial As String = Mid(ProdCode, 4, 3)
    '        RichTextBox1.AppendText("BackSerial :" & BackSerial & vbCrLf)

    '        SerialNum = ModelCode & TypeCode & Format(Now, "yyMM") & BackSerial & FrontSerial
    '        RichTextBox1.AppendText("SerialNum :" & SerialNum & vbCrLf)

    '        Dim NumUse As Boolean = False

    '        For chk = 0 To 2
    '            If DBSerialCheck() Then
    '                NumUse = True
    '            Else
    '                NumUse = False
    '                Exit For
    '            End If
    '            Thread.Sleep(rdNum.Next(50, 100))
    '        Next

    '        If NumUse = True Then
    '            If DBPreemptSet() Then
    '                Return False
    '            End If
    '        End If

    '    Next

    '    MsgBox("시리얼 번호를 설정할 수 없습니다.", vbCritical)
    '    Return True

    'End Function

    'Private Function DBPreemptSet() As Boolean
    '    DBCmd = "UPDATE " & ApplyCartDB & " SET Product_SN = '" & SerialNum & "', Ct_SN = '" & ProdCode & "' WHERE PV_SN = '" & TDData(SearchList.Serial) & "'"
    '    If DBCommand(DBCmd) Then
    '        Return True
    '    Else
    '        Return False
    '    End If
    'End Function

    Private Function DBSerialCheck() As Boolean
        If TDUseCompare = True Then
            DBCmd = "SELECT COUNT(NUMBER) FROM " & ApplyCartDB & " WHERE Product_SN = '" & SerialNum & "'"
        Else
            DBCmd = "SELECT COUNT(NUMBER) FROM " & ApplyNonTDDB & " WHERE Product_SN = '" & SerialNum & "'"
        End If

        Dim UseCheck As Integer = DBQueryScalar(DBCmd)

        If UseCheck = 0 Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Function SerialCompare(FrontCode As String) As Boolean
        DBCmd = "SELECT COUNT(Ct_SN) FROM " & ApplyCartDB & " WHERE Ct_Manufacture_Year = " & Format(Now, "yy") & " AND Ct_Manufacture_Month = " & Format(Now, "MM") & " AND Ct_SN IS not NULL AND Product_SN LIKE '" & ModelCode & TypeCode & "%' AND Ct_SN LIKE '" & FrontCode & "%'"
        RichTextBox1.AppendText("DBCmd FULL :" & DBCmd & vbCrLf)

        Dim SerialUse As Integer = DBQueryScalar(DBCmd)
        RichTextBox1.AppendText("SerialUse :" & SerialUse & vbCrLf)

        If SerialUse = 0 Then
            Return False
        Else
            Return True
        End If
    End Function

    'Private Function NextSerialCheck(FrontCode As String) As String
    '    Dim UseSerial As String = String.Empty
    '    Dim NewSerialUse As Boolean = True
    '    Dim NowNumber As String = String.Empty

    '    DBCmd = "SELECT b.Ct_SN FROM (SELECT Ct_SN FROM " & ApplyCartDB & " WHERE Ct_Manufacture_Year = " & Format(Now, "yy") & " AND Ct_Manufacture_Month = " & Format(Now, "MM") & " AND Ct_SN IS not NULL AND Product_SN LIKE '" & ModelCode & TypeCode & "%' AND Ct_SN LIKE '" & FrontCode & "%' ORDER BY Ct_SN DESC LIMIT 5) AS b ORDER BY b.Ct_SN ASC LIMIT 5"
    '    RichTextBox1.AppendText("DBCmd FULL :" & DBCmd & vbCrLf)

    '    If DBQueryReader(DBCmd) Then

    '        For i = 0 To sqlDataQuery.Length - 1
    '            UseSerial = sqlDataQuery(i)

    '            If i = 0 Then
    '                NowNumber = UseSerial
    '            Else
    '                Dim CheckData As String = UseSerial - NowNumber

    '                If CheckData <> 1 Then
    '                    Exit For
    '                Else
    '                    NowNumber = UseSerial
    '                End If

    '            End If
    '        Next

    '        Return NowNumber

    '    Else
    '        Return "NULL"
    '    End If

    'End Function


    Private Sub ProdInputFunc(sender As Object, e As EventArgs, SearchData As String)
        Dim userID As String = ""

        StepReset()
        ValueReset()

        If cboPDInfo.SelectedIndex = -1 Then
            MsgBox("제품 설정을 선택하지 않았습니다. 선택하여 주십시오.", vbExclamation)
            GoTo FailFunc
        End If

        If PortSerial.IsOpen = False Then
            MsgBox("통신 포트를 설정하지 않았습니다. 연결하여 주십시오.", vbExclamation)
            GoTo FailFunc
        End If

        If ckbAutoFunc.Checked = True Then

            If SearchData <> "[START]" Then
                MsgBox("잘못된 시작 코드입니다. 확인하여 주십시오.", vbExclamation)
                GoTo FailFunc
            End If

            TraySerialSetting()

        Else
            If SearchData.Length <> oldSearchLength And SearchData.Length <> newSearchLength Then
                MsgBox("잘못된 제품 코드입니다. 확인하여 주십시오.", vbExclamation)
                GoTo FailFunc
            End If

            txbPDNum.Text = SearchData
            SerialNum = SearchData

            If DBSerialCheck() = False Then
                If RePrintCheck() Then
                    Print_Activate()

                    Dim RePrForm As RePrintForm = New RePrintForm
                    RePrForm.Visible = False

                    RePrForm.ShowDialog()

                    GoTo RePrintOk
                End If
            End If

        End If

        RunStateFunc("제품 연결 대기", Color.Orange)

        ThreadStop = False
        Runthread = New Thread(AddressOf ThreadPlay)
        Runthread.IsBackground = True
        Runthread.Start()

        Exit Sub

RePrintOk:
        RunStateFunc("재인쇄 완료", Color.Green)
        Exit Sub

FailFunc:
        RunStateFunc("실 패", Color.Red)
    End Sub

    Private Function RePrintCheck() As Boolean

        If TDUseCompare = True Then
            DBCmd = "SELECT TestStep FROM " & ApplyCartDB & " WHERE Product_SN = '" & SerialNum & "'"
        Else
            DBCmd = "SELECT TestStep FROM " & ApplyNonTDDB & " WHERE Product_SN = '" & SerialNum & "'"
        End If

        Dim StepCheck As String = DBQueryScalar(DBCmd)

        If StepCheck = "False" Then
            Return False
        End If

        If StepCheck = "31" Then
            Return True
        End If

        Return False
    End Function

    Private Sub ValueReset()
        ProdCode = String.Empty
        SerialNum = String.Empty
        ThreadSwitch = True
        ErrorData = False
    End Sub

    Private Sub ThreadPlay()
        Const RunLimitMax As Int16 = 10
        Dim RunLimit As Int16 = 0
        Dim LimitFail As Boolean = False
        SerialDelegateFunc = New SerialDelegate(AddressOf ThreadFunc)

        While ThreadSwitch

            If ThreadStop = True Then   '' 초기화 누를 시 강제 탈출하도록
                ThreadSwitch = False
                Exit While
            End If

            If RunLimit = RunLimitMax Then
                ThreadSwitch = False
                LimitFail = True
                Exit While
            End If

            Me.Invoke(SerialDelegateFunc)

            Thread.Sleep(1000)
            RunLimit += 1
        End While

        If LimitFail = True Then
            SerialDelegateFunc = New SerialDelegate(AddressOf ThreadStateFunc)
            Me.Invoke(SerialDelegateFunc)
        End If

    End Sub

    Private Sub ThreadStateFunc()
        RunStateFunc("시간 초과", Color.Red)
    End Sub

    Private Sub ThreadFunc()
        Select Case NowMode
            Case ModeList.Prod_Input
                If IsNumeric(ShotSearch()) Then

                    If ckbOpAlto.Checked = False Then

                        Dim SerialCode As String = TDCodeSearch()

                        If SerialCode = "1" Then
                            MsgBox("제품과의 연결이 올바르지 않습니다. 다시 시도하여 주십시오.", vbCritical)
                            GoTo ComErr
                        ElseIf SerialCode = "0" Then
                            MsgBox("TD 시리얼 번호가 존재하지 않습니다. TD 시리얼 번호를 등록하여 주십시오.", vbCritical)
                            ErrorData = True
                            GoTo DataErr
                        End If

                        If TDExist(SerialCode) Then
                            ErrorData = True
                            GoTo DataErr
                        End If

                        If TDUseCompare = True Then
                            If TDSearch(SerialCode) Then
                                ErrorData = True
                                GoTo DataErr
                            End If

                            For i = SearchList.TestStep To SearchList.maxList - 1
                                If i = SearchList.TestStep Then
                                    TDDataTxb(i).Text = TestStepParsing()

                                    If TDDataTxb(i).Text = "NULL" Then
                                        TDDataTxb(i).BackColor = Color.Red
                                    Else
                                        TDDataTxb(i).BackColor = Color.Green
                                    End If

                                Else
                                    TDDataTxb(i).Text = TDData(i)
                                End If
                            Next
                        Else
                            TDData(SearchList.Serial) = SerialCode

                            DBCmd = "SELECT TestStep FROM " & ApplyNonTDDB & " WHERE PV_SN = '" & TDData(SearchList.Serial) & "'"
                            TDData(SearchList.TestStep) = DBQueryScalar(DBCmd)
                            TDDataTxb(SearchList.TestStep).Text = TestStepParsing()

                            For i = SearchList.TestStep To SearchList.maxList - 1
                                If i <> SearchList.Serial Then
                                    TDDataTxb(i).Text = "확인"
                                Else
                                    TDDataTxb(i).Text = TDData(SearchList.Serial)
                                End If
                            Next

                        End If
                    Else
                        TDData(SearchList.Serial) = txbTDNum.Text

                        For i = SearchList.TestStep To SearchList.maxList - 1
                            If i <> SearchList.Serial Then
                                TDDataTxb(i).Text = "확인"
                            Else
                                TDDataTxb(i).Text = TDData(SearchList.Serial)
                            End If
                        Next

                    End If

                    RunTimer.Enabled = True
                    GoTo FinishFunc
                End If
        End Select

        Exit Sub
DataErr:
        RunStateFunc("데이터 에러", Color.Red)

        If ErrorData = True Then
            If TodayCountSet(False) Then
                RunStateFunc("D 수량 에러", Color.Red)
            End If
        End If

        GoTo FinishFunc
ComErr:
        RunStateFunc("통신 에러", Color.Red)
FinishFunc:
        ThreadSwitch = False
    End Sub

    Private Function CheckRfUse() As Boolean
        DBCmd = "SELECT RfUseYn FROM " & ApplyModelInfoDB & " WHERE ModelCode = '" & ModelCode & "' AND CartTypeCode = '" & TypeCode & "' AND ColorCode = '" & ColorCode & "'"

        If DBQueryReader(DBCmd) Then
            If sqlDataQuery(0) = "Y" Then
                Return True
            End If
        End If

        Return False
    End Function


    Private Sub RunTimer_Tick(sender As Object, e As EventArgs) Handles RunTimer.Tick
        Dim ConfigStr As String

        If ThreadSwitch = False Then
            RunTimer.Enabled = False

            If ckbOpAlto.Checked = False Then
                If txbTDNum.Text.Length = TDMaxLength Then
                    If Not (CheckRfUse() = False And (Val(TDData(SearchList.TestStep)) = 21 Or Val(TDData(SearchList.TestStep)) = 25)) Then
                        If Val(TDData(SearchList.TestStep)) <> 23 And Val(TDData(SearchList.TestStep)) <> 27 And Val(TDData(SearchList.TestStep)) <> 30 And Val(TDData(SearchList.TestStep)) <> 32 And Val(TDData(SearchList.TestStep)) <> 41 Then
                            If Val(TDData(SearchList.TestStep)) > 29 Then
                                RunStateFunc("중복 처리", Color.Red)
                                ErrorData = True
                                GoTo FinishFunc
                            Else
                                RunStateFunc("공정 순서 불량", Color.Red)
                                ErrorData = True
                                GoTo FinishFunc
                            End If
                        End If
                    End If

                    If TDUseCompare = True Then

                        ConfigStr = FreqPowerSearch()

                        If ConfigStr = "NULL" Or ConfigStr = "FAIL" Then
                            FreqPowerReg(TDData(SearchList.Frequency), TDData(SearchList.Power))
                            ConfigStr = FreqPowerSearch()
                        End If

                        If ConfigStr = "NULL" Then
                            ErrorData = True
                            MsgBox("잘못된 주파수가 입력되어 있습니다. 주파수 값을 확인하여 주십시오.", vbExclamation)
                            GoTo DataFail
                        ElseIf ConfigStr = "FAIL" Then
                            MsgBox("주파수를 읽어오지 못했습니다. 연결을 확인하여 주십시오.", vbExclamation)
                            GoTo DataFail
                        End If

                        If FreqCompare(ConfigStr) Then
                            FreqPowerReg(TDData(SearchList.Frequency), TDData(SearchList.Power))
                        End If

                        If FreqCompare(ConfigStr) Then
                            ErrorData = True
                            GoTo LoadFail
                        End If

                        TDDataTxb(SearchList.Frequency).BackColor = Color.Green
                        TDDataTxb(SearchList.Power).BackColor = Color.Green

                    End If

                    ConfigStr = FirmWareCheck()

                    If ConfigStr = "NULL" Then
                        MsgBox("잘못된 펌웨어가 입력되어 있습니다. 값을 확인하여 주십시오.", vbExclamation)
                        ErrorData = True
                        GoTo LoadFail
                    ElseIf ConfigStr = "FAIL" Then
                        MsgBox("펌웨어를 읽어오지 못했습니다. 연결을 확인하여 주십시오.", vbExclamation)
                        GoTo LoadFail
                    Else
                        txbPDVersion.Text = ConfigStr
                    End If

                    RunStateFunc("정보 입력중", Color.Lime)

                    If ckbAutoFunc.Checked = True Then
                        If SerialUseCheck() Then
                            GoTo LoadFail
                        End If
                        txbPDNum.Text = SerialNum
                    Else
                        SerialNum = txbPDNum.Text
                        If SerialNum.Length = oldSearchLength Then      '12자리 시리얼번호
                            Dim FrontSetSerial As String = Mid(SerialNum, 7, 3)
                            Dim BackSetSerial As String = Mid(SerialNum, 10, 3)
                            ProdCode = BackSetSerial & FrontSetSerial
                        ElseIf SerialNum.Length = newSearchLength Then  '16자리 시리얼번호
                            ProdCode = Mid(SerialNum, 8, 6)
                        End If
                    End If

                    PrintFunc()

                    If ProdRegData(txbPDCP.Text, txbPDCC.Text, txbPDAgency.Text) Then
                        If ShotReg(0) Then
                            If ShotSearch() = "0" Then 'If ShotSearch() = "False" Then 'hjw test
                                If DBProdReg(txbPDCP.Text, txbPDCC.Text, txbPDAgency.Text, 0) Then
                                    If TraySuccess() Then

                                        If TodayCountSet(True) Then
                                            MsgBox("데이터베이스 수량 카운트 도중 오류가 발생하였습니다.", vbCritical)
                                            GoTo LoadFail
                                        End If

                                        RunStateFunc("입력 완료", Color.Green)
                                        GoTo FinishFunc

                                    Else
                                        MsgBox("데이터베이스에 Tray 내용을 등록하는 도중 오류가 발생하였습니다.", vbCritical)
                                        GoTo LoadFail
                                    End If

                                Else
                                    MsgBox("데이터베이스에 등록하는 도중 오류가 발생하였습니다.", vbCritical)
                                    GoTo LoadFail
                                End If
                            Else
                                MsgBox("샷 수 정보 확인 실패!", vbCritical)
                                MsgBox("통신 포트 연결을 확인하세요", vbExclamation, "포트 연결 확인")
                                GoTo LoadFail
                            End If
                        Else
                            MsgBox("샷 정보 입력 실패 !", vbCritical)
                            GoTo LoadFail
                        End If
                    Else
                        MsgBox("시리얼 정보 입력 실패 !", vbCritical)
                        GoTo LoadFail
                    End If

                Else
                    txbTDNum.BackColor = Color.Red
                    MsgBox("잘못된 TD 번호가 입력되어 있습니다. TD 번호를 재입력하여 주십시오.", vbExclamation)
                    GoTo FinishFunc
                End If

            Else
                RunStateFunc("정보 입력중", Color.Lime)
                PrintFunc()
                If ProdRegData(txbPDCP.Text, txbPDCC.Text, txbPDAgency.Text) Then
                    If DBProdRegAlto(txbPDNum.Text, txbPDCP.Text, txbPDCC.Text, txbPDAgency.Text, 0) Then

                        If TodayCountSet(True) Then
                            MsgBox("데이터베이스 수량 카운트 도중 오류가 발생하였습니다.", vbCritical)
                            GoTo LoadFail
                        End If

                        RunStateFunc("입력 완료", Color.Green)
                        GoTo FinishFunc
                    Else
                        MsgBox("데이터베이스에 등록하는 도중 오류가 발생하였습니다.", vbCritical)
                        GoTo LoadFail
                    End If
                Else
                    MsgBox("시리얼 정보 입력 실패 !", vbCritical)
                    GoTo LoadFail
                End If

            End If

            GoTo FinishFunc

        End If

        Exit Sub
DataFail:
        TDDataTxb(SearchList.Frequency).BackColor = Color.Red
        TDDataTxb(SearchList.Power).BackColor = Color.Red

LoadFail:
        RunStateFunc("입력 실패", Color.Red)

        If ErrorData = True Then
            If TodayCountSet(False) Then
                If DBProdFailReg() Then
                    RunStateFunc("T 수량 에러", Color.Red)
                End If
            End If
        End If
FinishFunc:
        NowRegCheck()
    End Sub

    Private Function TraySuccess() As Boolean
        Dim TrayOkNg As Boolean = False
        For i = 0 To TrayData.GetLength(1) - 1
            If TrayData(TrayDataList.NumData, i) = txbNowNum.Text Then
                Dim DBNum As Int16 = i + 1

                DBCmd = "UPDATE " & InfoRegStateDB & " SET Tray" & DBNum & "State = '" & Abs(Val(True)) & "' WHERE UserID = '" & IDName & "' AND ModelNum = '" & ModelCode & "' AND TypeNum = '" & TypeCode & "' AND ColorNum = '" & ColorCode & "' AND UsageNum = '" & ClassCode & "' AND CreateYear = '" & Format(Now, "yy") & "' AND CreateMonth = '" & Format(Now, "MM") & "'"

                If DBCommand(DBCmd) Then
                    Return True
                End If

            End If
        Next

        Return False
    End Function

    Public Sub PrintFunc()

        If ckbPrintUse.Checked = True Then

            Dim PrintThread As Thread = New Thread(New ParameterizedThreadStart(AddressOf PrintRun))
            PrintThread.IsBackground = True
            PrintThread.Start(SerialNum)

        End If

    End Sub

    Private Function DBProdReg(Factory As String, Country As String, Agency As String, ShotCount As String) As Boolean
        Dim DBCheck As String = String.Empty

        If TDData(SearchList.TestStep) = "41" Then

            If TDUseCompare = True Then
                DBCmd = "SELECT PV_SN FROM " & ApplyCartDB & " WHERE Product_SN = '" & SerialNum & "'"
            Else
                DBCmd = "SELECT PV_SN FROM " & ApplyNonTDDB & " WHERE Product_SN = '" & SerialNum & "'"
            End If

            Dim PVSN As String = DBQueryScalar(DBCmd)

            If PVSN = "False" Then
                MsgBox("제품 시리얼 번호에 등록된 TD 시리얼 번호를 검색하는 도중 오류가 발생하였습니다.", vbCritical)
                Return True
            End If

            If PVSN <> TDData(SearchList.Serial) Then
                MsgBox("제품 시리얼 번호에 등록된 TD 시리얼 번호가 저장된 시리얼 번호와 다릅니다.", vbCritical)
                Return True
            End If

            DBCmd = "UPDATE " & ApplyReturnDB & " SET DataRegDate = '" & Format(Now, "yyyy-MM-dd") & "', DataRegTime = '" & Format(Now, "HH:mm:ss") & "' WHERE Product_SN = '" & SerialNum & "' AND ReturnCount = (SELECT MAX(ReturnCount) FROM " & ApplyReturnDB & " WHERE Product_SN = '" & SerialNum & "')"

            If DBCommand(DBCmd) = False Then
                Return True
            End If

        End If

        If TDUseCompare = True Then
            DBCheck = "UPDATE " & ApplyCartDB & " SET Product_SN = null WHERE PV_SN = '" & txbTDNum.Text & "'"
            DBCmd = "UPDATE " & ApplyCartDB & " SET TestStep = '31', Product_SN = '" & SerialNum & "', Ct_Manufacture_Name='" & Factory & "', Ct_Manufacture_Year='" & Format(Now, "yy") & "', Ct_Manufacture_Month='" & Format(Now, "MM") & "', Ct_SN='" & ProdCode & "', Ct_Model='" & txbPDModel.Text & "', Ct_Type='" & txbPDType.Text & "', Ct_Abroad='" & Country & "', Ct_Agency='" & Agency & "',Ct_Max_ShotCnt = '" & ShotCount & "', Ct_Remain_ShotCnt = '" & ShotCount & "', P3_DateTime = '" & Format(Now, "yyyy-MM-dd HH:mm:ss") & "', Manufacture_Date ='" & txtManufactureDate.Text & "' WHERE PV_SN = '" & txbTDNum.Text & "'"
        Else
            DBCheck = "UPDATE " & ApplyNonTDDB & " SET Product_SN = null WHERE PV_SN = '" & txbTDNum.Text & "'"
            DBCmd = "UPDATE " & ApplyNonTDDB & " SET TestStep = '31', Product_SN = '" & SerialNum & "', Ct_Manufacture_Name='" & Factory & "', Ct_Manufacture_Year='" & Format(Now, "yy") & "', Ct_Manufacture_Month='" & Format(Now, "MM") & "', Ct_SN='" & ProdCode & "', Ct_Model='" & txbPDModel.Text & "', Ct_Type='" & txbPDType.Text & "', Ct_Abroad='" & Country & "', Ct_Agency='" & Agency & "', P3_DateTime = '" & Format(Now, "yyyy-MM-dd HH:mm:ss") & "', Manufacture_Date ='" & txtManufactureDate.Text & "' WHERE PV_SN = '" & txbTDNum.Text & "'"
        End If

        If DBCommand(DBCheck) Then
            If DBCommand(DBCmd) Then
                If TDUseCompare = True Then
                    DBCmd = "SELECT TestStep FROM " & ApplyCartDB & " Where Product_SN = '" & SerialNum & "'"
                Else
                    DBCmd = "SELECT TestStep FROM " & ApplyNonTDDB & " Where Product_SN = '" & SerialNum & "'"
                End If

                If DBQueryScalar(DBCmd) = "31" Then
                    Return True
                End If
            Else
                MsgBox("DB Update 도중 오류 발생 !", vbCritical)
                Return True
            End If
        Else
            MsgBox("DB NULL 변경 오류 발생 !", vbCritical)
            Return True
        End If

        Return False
    End Function

    Private Function DBProdRegAlto(ProdSerial As String, Factory As String, Country As String, Agency As String, ShotCount As String) As Boolean
        Dim DBSerial As String = Mid(ProdSerial, 10, 3) & Mid(ProdSerial, 7, 3)
        DBCmd = "INSERT INTO " & ApplyNonTDDB & "(TestStep,Product_SN,Ct_Manufacture_Name,Ct_Manufacture_Year,Ct_Manufacture_Month,Ct_SN,Ct_Model,Ct_Type,Ct_Abroad,Ct_Agency,P3_DateTime) VALUES('31','" & ProdSerial & "','" & Factory & "','" & Format(Now, "yy") & "','" & Format(Now, "MM") & "','" & DBSerial & "','" & txbPDModel.Text & "','" & txbPDType.Text & "','" & Country & "','" & Agency & "','" & Format(Now, "yyyy-MM-dd HH:mm:ss") & "')"
        If DBCommand(DBCmd) Then
            DBCmd = "SELECT TestStep FROM " & ApplyNonTDDB & " Where Product_SN = '" & ProdSerial & "'"
            If DBQueryScalar(DBCmd) = "31" Then
                Return True
            End If
        End If
        Return False
    End Function

    Private Function DBProdFailReg() As Boolean
        DBCmd = "UPDATE " & ApplyCartDB & " SET TestStep = '30',Product_SN = NULL, Ct_SN = null, P3_DateTime = '" & Format(Now, "yyyy-MM-dd HH:mm:ss") & "' WHERE PV_SN = '" & txbTDNum.Text & "'"
        If DBCommand(DBCmd) Then
            DBCmd = "SELECT TestStep FROM " & ApplyCartDB & " Where PV_SN = '" & txbTDNum.Text & "'"
            If DBQueryScalar(DBCmd) = "30" Then
                Return True
            End If
        End If
        Return False
    End Function

    Private Function CreateSerialCompare(SerialNum As String) As Boolean
        DBCmd = "SELECT COUNT(NUMBER) FROM " & ApplyCartDB & " WHERE Product_SN = '" & SerialNum & "'"
        Dim CompareData As Integer = DBQueryScalar(DBCmd)
        If CompareData > 0 Then
            Return False
        End If

        Return True
    End Function

    Private Function SerialNumberSet() As String
        Const SearchLength As Int16 = 2
        Const SerialLength As Int16 = 6
        Dim SearchData As String = ClassCode & ColorCode

        If SearchData.Length <> SearchLength Then
            MsgBox("잘못된 시리얼번호 타입입니다.", vbCritical)
            Return "FAIL"
        End If

        DBCmd = "SELECT Ct_SN FROM " & ApplyCartDB & " WHERE Ct_Manufacture_Year = " & Format(Now, "yy") & " AND Ct_Manufacture_Month = " & Format(Now, "MM") & " AND Ct_SN IS not NULL AND Ct_SN LIKE '" & SearchData & "%' ORDER BY Ct_SN DESC LIMIT 1"
        Dim ScalarData = DBQueryScalar(DBCmd)

        If ScalarData = "False" Then
            Return "FAIL"
        End If

        If ScalarData = "" Or ScalarData.Length <> SerialLength Then
            ScalarData = SearchData & "0000"
        End If

        Return ScalarData
    End Function

    Private Function TDStepCheck(TDName As String) As String
        If TDUseCompare = True Then
            DBCmd = "SELECT TestStep FROM " & ApplyCartDB & " WHERE PV_SN = '" & TDName & "'"
        Else
            DBCmd = "SELECT TestStep FROM " & ApplyNonTDDB & " WHERE PV_SN = '" & TDName & "'"
        End If

        Return DBQueryScalar(DBCmd)
    End Function

    Private Function ProdRegData(Factory As String, Country As String, Agency As String) As Boolean
        Const Commander As String = "wrsconf1"
        Dim retVal As String

        If ModelCode.Length = 2 Then    '16자리 시리얼번호
            Dim Model As String = Mid(SerialNum, 1, 2)
            Dim ModelOpt As String = Mid(SerialNum, 3, 1)
            Dim BoardSN As String = Mid(SerialNum, 4, 10)
            Dim QcOpt As String = Mid(SerialNum, 14, 3)

            tmpCmdMessage = "[" & Commander & " " & Factory & "," & BoardSN & "," & Model & "," & ModelOpt & "," & QcOpt & "," & Country & "," & Agency & "]" + vbCrLf

            If SendData(tmpCmdMessage) Then
                Return False
            End If

            retVal = PollingReceiveData(2000)

            If retVal <> Factory & "," & BoardSN & "," & Model & "," & ModelOpt & "," & QcOpt & "," & Country & "," & Agency Then
                Return False
            End If
        Else                            '12자리 시리얼번호
            Dim ProdCode As String = Mid(SerialNum, 1, 2)
            Dim ProdDate As String = Mid(SerialNum, 3, 4)
            Dim FrontSetSerial As String = Mid(SerialNum, 7, 3)
            Dim BackSetSerial As String = Mid(SerialNum, 10, 3)
            Dim UseSerial As String = ProdDate & BackSetSerial & FrontSetSerial

            tmpCmdMessage = "[" & Commander & " " & Factory & "," & UseSerial & "," & ProdCode & "," & Country & "," & Agency & "]" + vbCrLf

            If SendData(tmpCmdMessage) Then
                Return False
            End If

            retVal = PollingReceiveData(2000)

            If retVal <> Factory.ToLower & "," & UseSerial & "," & ProdCode & "," & Country & "," & Agency Then
                Return False
            End If
        End If

        Return True
    End Function

    Private Function FirmWareCheck() As String
        Const Commander As String = "dsfwver"
        Dim retval As String

        tmpCmdMessage = "[" & Commander & "]" + vbCrLf
        If SendData(tmpCmdMessage) Then
            Return "FAIL"
        End If

        retval = PollingReceiveData(1000)

        If InStr(1, retval, ".") > 0 Then
            Return retval
        Else
            Return "NULL"
        End If
    End Function

    Private Function FreqCompare(FreqData As String) As Boolean
        If UBound(Split(FreqData, ",")) = 1 Then
            Dim FreqValue As String = Mid(FreqData, 1, InStr(FreqData, ",") - 1)
            Dim PowerValue As String = Mid(FreqData, InStr(FreqData, ",") + 1, FreqData.Length)

            If FreqValue = TDData(SearchList.Frequency) Then
                If PowerValue = TDData(SearchList.Power) Then
                    Return False
                End If
            End If

            Return True

        Else
            MsgBox("잘못된 형식의 주파수 값입니다. 연결을 확인하여 주십시오.", vbExclamation)
            Return True
        End If
    End Function

    Private Function TDCodeSearch() As String
        Dim retVal As String
        tmpCmdMessage = "settdsn"
        cmdMessage = "[" & tmpCmdMessage & "]" + vbCrLf
        If SendData(cmdMessage) Then
            Return "1"
        End If

        retVal = PollingReceiveData(500)

        If retVal.Length = TDMaxLength Then
            Return retVal
        Else
            Return "0"
        End If
    End Function

    Private Function FreqPowerReg(Freq As String, Power As String) As String
        Const Commander As String = "settdcnf"
        Dim Retval As String

        tmpCmdMessage = "[" & Commander & " " & Freq & "," & Power & "]" + vbCrLf
        If SendData(tmpCmdMessage) Then
            Return "FAIL"
        End If

        Retval = PollingReceiveData(500)

        If InStr(1, Retval, ",") > 0 Then
            Return Retval

        Else
            Return "NULL"
        End If

    End Function

    Private Function FreqPowerSearch() As String
        Const Commander As String = "settdcnf"
        Dim Retval As String

        tmpCmdMessage = "[" & Commander & "]" + vbCrLf
        If SendData(tmpCmdMessage) Then
            Return "FAIL"
        End If

        Retval = PollingReceiveData(500)

        If InStr(1, Retval, ",") > 0 Then
            Return Retval

        Else
            Return "NULL"
        End If

    End Function

    Private Function ShotReg(shot As Integer) As String
        Const Commander As String = "shotconf"
        Dim retval As String

        tmpCmdMessage = "[" & Commander & " " & shot & "]" + vbCrLf

        If SendData(tmpCmdMessage) Then
            Return False
        End If

        retval = PollingReceiveData(1000)

        If retval = shot.ToString Then
            Return True
        End If

        Return False

    End Function

    Private Function ShotSearch() As String
        Const Commander As String = "shotconf"
        Dim RetVal As String = "-1"

        tmpCmdMessage = "[" & Commander & "]" + vbCrLf

        If SendData(tmpCmdMessage) Then
            Return "False"
        End If

        RetVal = PollingReceiveData(1500)
        Return RetVal

    End Function

    Private Function PollingReceiveData(RdTimeout As Long) As String
        Try
            rxMessage = ""
            If PortSerial.IsOpen = True Then
                PortSerial.ReadTimeout = RdTimeout
                rxMessage = PortSerial.ReadLine()
                Return ParsingData(False)
            Else
                ThreadSwitch = False
                MsgBox("통신 포트가 열리지 않았습니다.", vbCritical)
                Return True
            End If
        Catch ex As Exception
            Return Err.Description
        End Try
    End Function

    Private Function ParsingData(CmdInclude As Boolean) As String
        Dim cmdStr As String
        Dim cmdVal(0 To 8) As String
        Dim i As Integer

        Try
            cmdStr = "0"

            If rxMessage <> "" Then
                cmdMessage = ""

                If Mid(rxMessage, 1, 1) = "[" Then
                    cmdMessage = Mid(rxMessage, 2, Len(rxMessage))

                    cmdStr = Mid(cmdMessage, 1, (InStr(rxMessage, " ") - 2))
                    cmdMessage = Mid(rxMessage, InStr(rxMessage, " ") + 1, Len(cmdMessage))

                    For i = 1 To 7
                        If InStr(cmdMessage, ",") <> 0 Then
                            cmdVal(i) = Mid(cmdMessage, 1, InStr(cmdMessage, ",") - 1)
                            cmdMessage = Mid(cmdMessage, InStr(cmdMessage, ",") + 1, Len(cmdMessage))
                        ElseIf InStr(cmdMessage, "]") <> 0 Then
                            cmdVal(i) = Mid(cmdMessage, 1, InStr(cmdMessage, "]") - 1)
                        Else
                            Exit For
                        End If
                    Next i
                    rxMessage = ""

                    Select Case cmdStr

                        Case "dsfwver"
                            cmdStr = cmdVal(1)
                            Return cmdStr
                        Case "freqconf"
                            cmdStr = cmdVal(1)
                            Return cmdStr
                        Case "settdcnf"
                            cmdStr = (cmdVal(1) & "," & cmdVal(2))
                            Return cmdStr
                        Case "wrsconf1"
                            If ModelCode.Length = 2 Then    '16자리 시리얼번호
                                cmdStr = cmdVal(1) & "," & cmdVal(2) & "," & cmdVal(3) & "," & cmdVal(4) & "," & cmdVal(5) & "," & cmdVal(6) & "," & cmdVal(7)
                            Else                            '12자리 시리얼번호
                                cmdStr = cmdVal(1) & "," & cmdVal(2) & "," & cmdVal(3) & "," & cmdVal(4) & "," & cmdVal(5)
                            End If
                            Return cmdStr
                        Case "settdsn"
                            cmdStr = cmdVal(1)
                            Return cmdStr
                        Case "resetinf"
                            cmdStr = cmdVal(1)
                            Return cmdStr
                        Case "rdsconf1"
                            cmdStr = cmdVal(1) & "," & cmdVal(2) & "," & cmdVal(3) & "," & cmdVal(4) & "," & cmdVal(5)
                            Return cmdStr
                        Case "shotconf"
                            cmdStr = cmdVal(1)
                            Return cmdStr
                        Case "setdepth"
                            cmdStr = cmdVal(1)
                            Return cmdStr
                        Case "setmotor"
                            cmdStr = cmdVal(1) & "," & cmdVal(2) & "," & cmdVal(3) & "," & cmdVal(4) & "," & cmdVal(5)
                            Return cmdStr
                        Case Else
                            Return "Else"
                            rxMessage = ""
                    End Select
                End If
                rxMessage = ""
                Return True
            Else
                Return False
            End If

        Catch ex As Exception
            rxMessage = ""
            Return Err.Description
        End Try
    End Function

    Private Function SendData(SendMessage As String) As Boolean
        Try
            If PortSerial.IsOpen = True Then
                PortSerial.DiscardInBuffer()
                PortSerial.DiscardOutBuffer()
                If PortSerial.BytesToRead Then
                    PortSerial.DiscardInBuffer()
                End If
                PortSerial.WriteTimeout = -1
                PortSerial.WriteLine(SendMessage)
            Else
                ThreadSwitch = False
                MsgBox("통신 포트가 열리지 않았습니다.")
                Return True
            End If
        Catch ex As Exception
            Return True
        End Try
        Return False
    End Function

    Private Sub TDRecycleFunc(sender As Object, e As EventArgs, SearchData As String)
        DataReset()
        SerialNum = String.Empty
        TDUseCompare = True

        If SearchData.Length > TDMaxLength Or SearchData.Length < TDMinLength Then
            MsgBox("잘못된 TD 번호입니다. 인쇄된 번호를 확인하여 주십시오.", vbExclamation)
            GoTo FailFunc
        End If

        If TDExist(SearchData) Then
            MsgBox("TD 데이터가 존재하지 않습니다. 확인하여 주십시오.", vbExclamation)
            GoTo FailFunc
        End If

        If TDSearch(SearchData) Then
            GoTo FailFunc
        End If

        For i = SearchList.TestStep To SearchList.maxList - 1
            If i = SearchList.TestStep Then
                TDDataTxb(i).Text = TestStepParsing()

                If TDDataTxb(i).Text = "NULL" Then
                    TDDataTxb(i).BackColor = Color.Red
                Else
                    TDDataTxb(i).BackColor = Color.Green
                End If

            Else
                TDDataTxb(i).Text = TDData(i)
            End If
        Next

        SerialNum = SearchData

        If ckbAutoFunc.Checked = True Then
            btnReDel_Click(sender, e)
        Else
            RunStateFunc("성 공", Color.Green)
        End If

        Exit Sub
FailFunc:
        RunStateFunc("실 패", Color.Red)
    End Sub

    Private Function TDSearch(SearchData As String) As Boolean
        Try
            DBCmd = "SELECT TestStep,Ct_Power,Ct_Motor_Lv,PV_SN,PV_Date,PV_Frequency,QC_Date,QC_Capacitor,QC_Grade FROM " & ApplyCartDB & " WHERE PV_SN = '" & SearchData & "'"

            If DBQueryReader(DBCmd) Then
                For i = SearchList.TestStep To SearchList.maxList - 1
                    TDData(i) = sqlDataQuery(i)
                Next
            Else
                MsgBox("TD 데이터가 존재하지 않습니다.", vbExclamation)
                Return True
            End If

            Return False

        Catch ex As Exception
            MsgBox("TD 데이터를 불러오는 도중 오류가 발생하였습니다. :: " & vbCrLf & ex.Message, vbCritical)
            Return True
        End Try

    End Function

    Private Function TDExist(SearchData As String) As Boolean
        Try
            If TDUseCompare = True Then
                DBCmd = "SELECT COUNT(NUMBER) FROM " & ApplyCartDB & " WHERE PV_SN = '" & SearchData & "'"
            Else
                DBCmd = "SELECT COUNT(NUMBER) FROM " & ApplyNonTDDB & " WHERE PV_SN = '" & SearchData & "'"
            End If


            Dim DataExist As Int16 = DBQueryScalar(DBCmd)

            If DataExist = 1 Then
                Return False
            Else
                Return True
            End If

        Catch ex As Exception
            MsgBox("TD 데이터 확인 중 오류가 발생하였습니다. :: " & vbCrLf & ex.Message, vbCritical)
            Return True
        End Try
    End Function

    Private Sub StepReset()
        For i = SearchList.TestStep To SearchList.maxList - 1
            TDData(i) = String.Empty

            With TDDataTxb(i)
                .Text = "대기"
                .BackColor = Color.White
            End With
        Next

        With txbPDNum
            .Text = "대기"
            .Font = New Font("함초롱바탕", 48, FontStyle.Bold)
            .ForeColor = Color.Black
        End With
    End Sub

    Private Sub DataReset()
        StepReset()

        If NowMode = ModeList.Prod_Input Then

            With txbPDModel
                .Text = "대기"
                .BackColor = Color.White
                .ForeColor = Color.Black
            End With

            With txbPDType
                .Text = "대기"
                .BackColor = Color.White
                .ForeColor = Color.Black
            End With

            With txbPDCC
                .Text = "대기"
                .BackColor = Color.White
                .ForeColor = Color.Black
            End With

            With txbPDAgency
                .Text = "대기"
                .BackColor = Color.White
                .ForeColor = Color.Black
            End With

            With txbPDCP
                .Text = "대기"
                .BackColor = Color.White
                .ForeColor = Color.Black
            End With

            With txbPDColor
                .Text = "대기"
                .BackColor = Color.White
                .ForeColor = Color.Black
            End With

            cboPDInfo.SelectedIndex = -1
            cboPDInfo.Text = "SELECT!"
        End If
    End Sub

    Private Function TestStepParsing() As String
        Select Case TDData(SearchList.TestStep)
            Case "11"
                Return "TD 검사 합격"
            Case "12"
                Return "TD 검사 불합격"
            Case "13"
                Return "TD 검사 재측정 합격"
            Case "14"
                Return "TD 검사 재측정 불합격"

            Case "15"
                Return "재사용 TD"

            Case "16"
                Return "납땜 합격"
            Case "17"
                Return "납땜 불합격"
            Case "18"
                Return "납땜 재측정 합격"
            Case "19"
                Return "납땜 재측정 불합격"

            Case "21"
                Return "HIFU 합격"
            Case "22"
                Return "HIFU 불합격"
            Case "23"
                Return "파형검사 합격"
            Case "24"
                Return "파형검사 불합격"
            Case "25"
                Return "HIFU 재측정 합격"
            Case "26"
                Return "HIFU 재측정 불합격"
            Case "27"
                Return "파형검사 재측정 합격"
            Case "28"
                Return "파형검사 재측정 불합격"
            Case "30"
                Return "정보 입력 불합격"
            Case "31"
                Return "양산 합격"
            Case "32"
                Return "양산 합격"
            Case "41"
                Return "반품 진행"
            Case Else
                Return "NULL"
        End Select
    End Function

    Private Sub btnReDel_Click(sender As Object, e As EventArgs) Handles btnReDel.Click
        NowDate = Format(Now, "yyyy-MM-dd")
        NowTime = Format(Now, "HH:mm:ss")

        If SerialNum = String.Empty Then
            MsgBox("삭제할 데이터가 존재하지 않습니다. TD 데이터를 검색하여 주십시오.", vbExclamation)
            GoTo FailFunc
        End If

        If TestDelete(ApplyHFTestDB) Then
            MsgBox("삭제 도중 문제가 발생했습니다.", vbCritical)
            GoTo FailFunc
        End If

        If TestDelete(ApplyRFTestDB) Then
            MsgBox("삭제 도중 문제가 발생했습니다.", vbCritical)
            GoTo FailFunc
        End If

        If DeleteData() Then
            MsgBox("삭제 도중 문제가 발생했습니다.", vbCritical)
            GoTo FailFunc
        End If

        If TDData(SearchList.TestStep) <> "15" Then
            If TodayCountSet(True) Then
                GoTo FailFunc
            End If
        End If

        txbPVSN.Enabled = False
        txbPVSN.Text = "삭제 성공"
        txbPVSN.BackColor = Color.Green
        txbPVSN.Enabled = True
        txbPVSN.Focus()

        Exit Sub
FailFunc:
        RunStateFunc("삭제 실패", Color.Red)
    End Sub

    Private Function TestDelete(DBTable As String) As Boolean
        DBCmd = "SELECT COUNT(PV_SN) FROM " & DBTable & " WHERE PV_SN = '" & SerialNum & "'"

        Dim DBResult As Int16 = DBQueryScalar(DBCmd)

        If DBResult > 0 Then

            DBCmd = "DELETE FROM " & DBTable & " WHERE PV_SN = '" & SerialNum & "' "

            If DBCommand(DBCmd) = False Then
                Return True
            End If

        End If

        Return False
    End Function

    Private Function DeleteData() As String
        DBCmd = "UPDATE " & ApplyCartDB & " SET TestStep = '15', Product_SN = NULL, Ct_Manufacture_Name = NULL, Ct_Manufacture_Year = NULL, Ct_Manufacture_Month = NULL, Ct_SN = NULL, Ct_Abroad = NULL, Ct_Agency = NULL, Ct_Frequency = NULL, Ct_Max_ShotCnt = NULL, Ct_Remain_ShotCnt = NULL, P0_Date = NULL, P0_Time = NULL, P0_Model = NULL, P0_Type = NULL, P1_Date = NULL, P1_Time = NULL, P1_Model = NULL, P1_CartType = NULL, P1_Frequency = NULL, P3_DateTime = NULL, LastQC_Date = NULL,LastQC_Time = NULL, Delete_Date = '" & NowDate & "', Delete_Time = '" & NowTime & "', Delete_TestStep = '" & TDData(SearchList.TestStep) & "' WHERE PV_SN = '" & SerialNum & "'"

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

    Private Function TodayCountUpdate() As Boolean

        Select Case NowMode
            Case ModeList.Prod_Input
                DBCmd = "SELECT InfoRegOkCntColumnName, InfoRegNgCntColumnName FROM " & ApplyModelInfoDB & " WHERE ModelCode = '" & ModelCode & "' LIMIT 1"

                If DBQueryReader(DBCmd) Then
                    Dim InfoRegOkCntColumnName As String = sqlDataQuery(0)
                    Dim InfoRegNgCntColumnName As String = sqlDataQuery(1)

                    DBCmd = "UPDATE " & ApplyPD1CntDB & " SET PD1_InfoTotalCnt = '" & CountSelect(CountList.Total) & "', " & InfoRegOkCntColumnName & " = '" & CountSelect(CountList.Success) & "', " & InfoRegNgCntColumnName & " = '" & CountSelect(CountList.Fail) & "' WHERE PD1_Date = '" & NowDate & "'"
                Else
                    MsgBox("수량 업데이트, 잘못된 경로입니다.", vbCritical)
                    Return True
                End If

            Case ModeList.TDRecycle
                DBCmd = "UPDATE " & ApplyPD1CntDB & " SET PD1_RecycleCnt = '" & CountSelect(CountList.Total) & "' WHERE PD1_Date = '" & NowDate & "'"
            Case Else
                MsgBox("수량 업데이트, 잘못된 경로입니다.", vbCritical)
                Return True
        End Select

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

    Private Function TodayCountLoad() As Boolean

        Select Case NowMode
            Case ModeList.Prod_Input
                DBCmd = "SELECT InfoRegOkCntColumnName, InfoRegNgCntColumnName FROM " & ApplyModelInfoDB & " WHERE ModelCode = '" & ModelCode & "' LIMIT 1"

                If DBQueryReader(DBCmd) Then
                    Dim InfoRegOkCntColumnName As String = sqlDataQuery(0)
                    Dim InfoRegNgCntColumnName As String = sqlDataQuery(1)

                    DBCmd = "SELECT PD1_InfoTotalCnt," & InfoRegOkCntColumnName & "," & InfoRegNgCntColumnName & " FROM " & ApplyPD1CntDB & " WHERE PD1_Date = '" & NowDate & "'"
                Else
                    MsgBox("수량 카운터 잘못된 경로입니다.", vbCritical)
                    Return True
                End If

            Case ModeList.TDRecycle
                DBCmd = "SELECT PD1_RecycleCnt,'0','0' FROM " & ApplyPD1CntDB & " WHERE PD1_Date = '" & NowDate & "'"
            Case Else
                MsgBox("수량 카운터 잘못된 경로입니다.", vbCritical)
                Return True
        End Select

        If DBQueryReader(DBCmd) Then
            For i = 0 To CountList.maxCount - 1
                CountSelect(i) = sqlDataQuery(i)
            Next
        Else
            Return True
        End If

        Return False
    End Function

    Private Function TodayCountCreate() As Boolean
        DBCmd = "SELECT COUNT(NUMBER) FROM " & ApplyPD1CntDB & " WHERE PD1_Date = '" & NowDate & "'"

        If DBQueryScalar(DBCmd) = 0 Then
            DBCmd = "INSERT INTO " & ApplyPD1CntDB & "(PD1_Date) VALUES('" & NowDate & "')"

            If DBCommand(DBCmd) = False Then
                Return True
            End If
        End If

        Return False
    End Function

    Private Sub RunStateFunc(OutputText As String, ApplyColor As Color)
        txbPVSN.Enabled = False
        txbPVSN.Text = OutputText
        txbPVSN.BackColor = ApplyColor
        txbPVSN.Enabled = True
        txbPVSN.Focus()
    End Sub

    Private Sub txbReFreq_GotFocus(sender As Object, e As EventArgs) Handles txbReFreq.GotFocus, txbReSerial.GotFocus, txbReCValue.GotFocus, txbReGrade.GotFocus, txbRePower.GotFocus, txbReMotor.GotFocus, txbReInput.GotFocus, txbReTest.GotFocus, txbReOrder.GotFocus, txbDayCount.GotFocus, txbTDNum.GotFocus, txbTDFreq.GotFocus, txbTDGrade.GotFocus, txbTDPower.GotFocus, txbTDDepth.GotFocus, txbTDIDate.GotFocus, txbTDStep.GotFocus, txbPDNum.GotFocus, txbPDModel.GotFocus, txbPDType.GotFocus, txbPDCC.GotFocus, txbPDAgency.GotFocus, txbPDCP.GotFocus, txbPDVersion.GotFocus, txbAllCount.GotFocus, txbSucCount.GotFocus, txbFailCount.GotFocus
        txbPVSN.Focus()
        txbPVSN.Select(txbPVSN.Text.Length, 0)
    End Sub

    Private Sub btnOption_Click(sender As Object, e As EventArgs) Handles btnOption.Click, btnOpExit.Click
        TimerFalse()

        If pnMain.Visible = True Then
            pnMain.Visible = False
            pnMain.Enabled = False
            pnOption.Visible = True
            pnOption.Enabled = True
            pnOption.Location = New Point(0, 0)
            pnMain.Location = New Point(1920, 0)

            btnPtRefresh_Click(sender, e)
        Else

            If OptionChange = True Then
                If MsgBox("변경된 설정이 존재합니다. 저장하시겠습니까?", vbOKCancel + vbExclamation) = MsgBoxResult.Ok Then
                    btnOpSave_Click(sender, e)
                End If
            End If

            Print_Activate()
            pnMain.Visible = True
            pnMain.Enabled = True
            pnOption.Visible = False
            pnOption.Enabled = False
            pnMain.Location = New Point(0, 0)
            pnOption.Location = New Point(1920, 0)
        End If

        txbPVSN.Focus()
    End Sub

    Private Sub LoadExitReset()
        TimerFalse()
        ModelCode = String.Empty
        TypeCode = String.Empty
        ColorCode = String.Empty
        ClassCode = String.Empty
        TDUseCompare = False

        cboPDInfo.SelectedIndex = -1
        cboPDInfo.Text = "SELECT!"

        With txbPDModel
            .Text = "대기"
            .Font = New Font("함초롱바탕", 26)
            .ForeColor = Color.Black
        End With

        With txbPDType
            .Text = "대기"
            .Font = New Font("함초롱바탕", 26)
            .ForeColor = Color.Black
        End With

        With txbPDCC
            .Text = "대기"
            .Font = New Font("함초롱바탕", 26)
            .ForeColor = Color.Black
        End With

        With txbPDAgency
            .Text = "대기"
            .Font = New Font("함초롱바탕", 26)
            .ForeColor = Color.Black
        End With

        With txbPDCP
            .Text = "대기"
            .Font = New Font("함초롱바탕", 26)
            .ForeColor = Color.Black
        End With

        With txbPDColor
            .Text = "대기"
            .Font = New Font("함초롱바탕", 26)
            .ForeColor = Color.Black
        End With

        With txbPDNum
            .Text = "대기"
            .Font = New Font("함초롱바탕", 48)
            .ForeColor = Color.Black
        End With
    End Sub


    Private Sub cboPDInfo_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboPDInfo.SelectedIndexChanged
        Dim SelectData As String = cboPDInfo.SelectedIndex
        TimerFalse()

        If dgvDataSet.Rows(SelectData).Cells(0).Value = "" Or dgvDataSet.Rows(SelectData).Cells(1).Value = "" Or dgvDataSet.Rows(SelectData).Cells(2).Value = "" Or dgvDataSet.Rows(SelectData).Cells(3).Value = "" Or dgvDataSet.Rows(SelectData).Cells(4).Value = "" Then
            MsgBox("존재하지 않는 데이터가 존재합니다. 설정에서 확인하여 주십시오.", vbCritical)
            Exit Sub
        End If

        If ColorSet(SelectData) Then
            MsgBox("잘못된 데이터를 불러왔습니다. 설정에서 확인하여 주십시오.", vbCritical)
            Exit Sub
        End If

        ClassCode = dgvDataSet.Rows(SelectData).Cells(6).Value
        VersionCode = dgvDataSet.Rows(SelectData).Cells(7).Value

        With txbPDModel
            .Text = dgvDataSet.Rows(SelectData).Cells(1).Value
            .Font = New Font("함초롱바탕", 26, FontStyle.Bold)
            .ForeColor = Color.Blue
        End With

        With txbPDType
            .Text = dgvDataSet.Rows(SelectData).Cells(2).Value
            .Font = New Font("함초롱바탕", 26, FontStyle.Bold)
            .ForeColor = Color.Blue
        End With

        With txbPDCC
            .Text = dgvDataSet.Rows(SelectData).Cells(3).Value
            .Font = New Font("함초롱바탕", 26, FontStyle.Bold)
            .ForeColor = Color.Blue
        End With

        With txbPDAgency
            .Text = dgvDataSet.Rows(SelectData).Cells(4).Value
            .Font = New Font("함초롱바탕", 26, FontStyle.Bold)
            .ForeColor = Color.Blue
        End With

        With txbPDCP
            .Text = txbOpCompany.Text
            .Font = New Font("함초롱바탕", 26, FontStyle.Bold)
            .ForeColor = Color.Blue
        End With

        With txbPDColor
            .Text = dgvDataSet.Rows(SelectData).Cells(5).Value
            .Font = New Font("함초롱바탕", 26, FontStyle.Bold)
            .ForeColor = Color.Blue
        End With

        With txbPDNum
            .Text = ClassCode
            .Font = New Font("함초롱바탕", 48, FontStyle.Bold)
            .ForeColor = Color.Black
        End With

        txbPVSN.Focus()
    End Sub

    Private Sub Print_Activate()
        For i = PrintList.BoxCode To PrintList.maxPrint - 1
            If PrintUseCkb(i).Checked = True Then
                PrintActive(i) = True
            Else
                PrintActive(i) = False
            End If
            PrintName(i) = PrintUseTxb(i).Text
            PrintAddress(i) = PrintUseZip(i).Text
        Next

        PrintUseCode(PrintList.BoxCode) = txbPtBox_Val1.Text
        PrintUseCode(PrintList.ProdLabel) = txbPtProd_Val1.Text

        PrintUseText(PrintList.BoxCode) = txbPtBox_Val2.Text
        PrintUseText(PrintList.Warranty) = txbPtWar_Val1.Text
        PrintUseText(PrintList.ProdLabel) = txbPtProd_Val2.Text

        PrintUseDate = txbPtProd_Date.Text

    End Sub

    Private Sub btnRegReset_Click(sender As Object, e As EventArgs) Handles btnRegReset.Click
        txbRegName.Text = String.Empty
        txbRegCountry.Text = String.Empty
        txbRegAgency.Text = String.Empty
        cboClear()
    End Sub

    Private Sub cboClear()
        cboRegModel.SelectedIndex = -1
        cboRegModel.Text = "SELECT!"
        cboRegType.SelectedIndex = -1
        cboRegType.Text = "SELECT!"
        cboRegColor.SelectedIndex = -1
        cboRegColor.Text = "SELECT!"
        cboRegClass.SelectedIndex = -1
        cboRegClass.Text = "SELECT!"
        cboRegVersion.SelectedIndex = -1
        cboRegVersion.Text = "SELECT!"
    End Sub

    Private Sub btnRegOK_Click(sender As Object, e As EventArgs) Handles btnRegOK.Click
        If txbRegName.Text = "" Then
            MsgBox("구분명을 입력하지 않으셨습니다. 확인하여 주십시오.", vbExclamation)
            txbRegName.Focus()
        Else
            If cboRegModel.SelectedIndex = -1 Then
                MsgBox("모델명을 선택하지 않으셨습니다. 확인하여 주십시오.", vbExclamation)
                cboRegModel.Focus()
            Else
                If cboRegType.SelectedIndex = -1 Then
                    MsgBox("타입명을 선택하지 않으셨습니다. 확인하여 주십시오.", vbExclamation)
                    cboRegType.Focus()
                Else
                    If cboRegColor.SelectedIndex = -1 Then
                        MsgBox("색상명을 선택하지 않으셨습니다. 확인하여 주십시오.", vbExclamation)
                        cboRegColor.Focus()
                    Else

                        If cboRegClass.SelectedIndex = -1 Then
                            MsgBox("분류명을 선택하지 않으셨습니다. 확인하여 주십시오.", vbExclamation)
                            cboRegClass.Focus()
                        Else
                            If txbRegCountry.Text = "" Then
                                MsgBox("국가코드를 입력하지 않으셨습니다. 확인하여 주십시오.", vbExclamation)
                                txbRegCountry.Focus()
                            Else
                                If txbRegAgency.Text = "" Then
                                    MsgBox("대리점코드를 입력하지 않으셨습니다. 확인하여 주십시오.", vbExclamation)
                                    txbRegAgency.Focus()
                                Else
                                    If cboRegVersion.SelectedIndex = -1 Then
                                        MsgBox("HW버전코드를 입력하지 않으셨습니다. 확인하여 주십시오.", vbExclamation)
                                        cboRegVersion.Focus()
                                    Else
                                        dgvDataSet.Rows.Add(txbRegName.Text, cboRegModel.SelectedItem, cboRegType.SelectedItem, txbRegCountry.Text, txbRegAgency.Text, cboRegColor.SelectedItem, cboRegClass.SelectedItem.Value, cboRegVersion.SelectedItem.Value.ToString)

                                        txbRegName.Text = String.Empty
                                        txbRegCountry.Text = String.Empty
                                        txbRegAgency.Text = String.Empty
                                        OptionChange = True
                                    End If
                                End If
                            End If
                        End If
                    End If
                End If
            End If
        End If
    End Sub

    Private Sub txbRegCountry_KeyPress(sender As Object, e As KeyPressEventArgs) Handles txbRegCountry.KeyPress, txbRegAgency.KeyPress

        If Not Char.IsDigit(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then
            e.Handled = True
        End If

    End Sub

    Private Sub btnRegDel_Click(sender As Object, e As EventArgs) Handles btnRegDel.Click
        Dim rowNum As Integer = dgvDataSet.SelectedCells(0).RowIndex
        dgvDataSet.Rows.RemoveAt(rowNum)
        OptionChange = True
    End Sub

    Private Sub btnRegADel_Click(sender As Object, e As EventArgs) Handles btnRegADel.Click
        If MsgBox("모든 행을 삭제하시겠습니까?", vbOKCancel + vbExclamation) = MsgBoxResult.Ok Then
            dgvDataSet.Rows.Clear()
            OptionChange = True
        End If
    End Sub

    Private Sub btnOpSave_Click(sender As Object, e As EventArgs) Handles btnOpSave.Click

        For i = SaveList.Info To SaveList.MaxSave - 1
            If OptionSave(i) Then
                OptionLoad(i)
            End If
        Next

        MsgBox("저장완료", vbInformation)
        OptionChange = False
    End Sub

    Private Function OptionSave(SaveType As Int16) As Boolean
        Try
            Dim SaveData As String = String.Empty
            Dim FilePath As String = System.AppDomain.CurrentDomain.BaseDirectory & "\Config"

            If Dir(FilePath, vbDirectory) = "" Then
                MkDir(FilePath)
            End If

            Dim FileName As String = FilePath & "\" & SaveName(SaveType) & ".ini"

            Select Case SaveType
                Case SaveList.Info
                    For i = 0 To dgvDataSet.Rows.Count - 2
                        Dim RowData As String = dgvDataSet.Rows(i).Cells(0).Value.ToString & "|" & dgvDataSet.Rows(i).Cells(1).Value.ToString & "|" & dgvDataSet.Rows(i).Cells(2).Value.ToString & "|" & dgvDataSet.Rows(i).Cells(3).Value.ToString & "|" & dgvDataSet.Rows(i).Cells(4).Value.ToString & "|" & dgvDataSet.Rows(i).Cells(5).Value.ToString & "|" & dgvDataSet.Rows(i).Cells(6).Value.ToString & "|" & dgvDataSet.Rows(i).Cells(7).Value.ToString & "|@"
                        SaveData = SaveData & RowData
                    Next

                Case SaveList.Config
                    SaveData = txbOpCompany.Text & "|" & nudPtCount.Value & "|" & cboComPort.SelectedItem & "|" & NowMode & "|" & ckbOpAlto.Checked & "|" & nudTray.Value & "|" & nudSerialCheck.Value & "|"

                Case SaveList.Print
                    SaveData = txbPtBox_Name.Text & "|" & txbPtBox_Label.Text & "|" & txbPtBox_Val1.Text & "|" & txbPtBox_Val2.Text & "|" & txbPtWar_Name.Text & "|" & txbPtWar_Label.Text & "|" & txbPtWar_Val1.Text & "|" & txbPtProd_Name.Text & "|" & txbPtProd_Label.Text & "|" & txbPtProd_Val1.Text & "|" & txbPtProd_Val2.Text & "|" & txbPtProd_Date.Text & "|"

                Case Else
                    MsgBox("잘못된 저장 데이터입니다.", vbCritical)
                    Return False
            End Select

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

            File.WriteAllText(FileName, SaveData, Encoding.UTF8)
            Return True
        Catch ex As Exception
            MsgBox("저장 도중 오류가 발생하였습니다." & vbCrLf & ex.Message, vbCritical)
            Return False
        End Try
    End Function

    Private Sub OptionLoad(LoadType As Int16)
        Try
            Dim ReadData As String = String.Empty
            Dim FilePath As String = System.AppDomain.CurrentDomain.BaseDirectory & "\Config"

            If Dir(FilePath, vbDirectory) = "" Then
                MkDir(FilePath)
            End If

            Dim FileName As String = FilePath & "\" & SaveName(LoadType) & ".ini"

            If File.Exists(FileName) Then
                ReadData = File.ReadAllText(FileName, Encoding.UTF8)

                If ReadData <> "" Then
                    Select Case LoadType
                        Case SaveList.Info
                            dgvDataSet.Rows.Clear()

                            For i = UBound(Split(ReadData, "@")) - 1 To 0 Step -1
                                Dim MdfData As String = Mid(ReadData, 1, InStr(ReadData, "@") - 1)
                                Dim InfoList(UBound(Split(MdfData, "|")) - 1)
                                ReadData = Mid(ReadData, InStr(ReadData, "@") + 1, ReadData.Length)

                                For cnt = 0 To UBound(Split(MdfData, "|")) - 1
                                    InfoList(cnt) = Mid(MdfData, 1, InStr(MdfData, "|") - 1)
                                    MdfData = Mid(MdfData, InStr(MdfData, "|") + 1, MdfData.Length)
                                Next

                                dgvDataSet.Rows.Add(InfoList)

                            Next

                            cboPDInfo.Items.Clear()

                            If dgvDataSet.Rows.Count - 2 <> -1 Then
                                For i = 0 To dgvDataSet.Rows.Count - 2
                                    cboPDInfo.Items.Add(dgvDataSet.Rows(i).Cells(0).Value.ToString)
                                Next

                                LoadExitReset()
                            End If

                        Case SaveList.Config
                            For i = 0 To UBound(Split(ReadData, "|")) - 1
                                Dim MdfData As String = Mid(ReadData, 1, InStr(ReadData, "|") - 1)
                                ReadData = Mid(ReadData, InStr(ReadData, "|") + 1, ReadData.Length)

                                Select Case i
                                    Case 0
                                        txbOpCompany.Text = MdfData
                                    Case 1
                                        If IsNumeric(MdfData) Then
                                            If MdfData < 4 And MdfData > 0 Then
                                                nudPtCount.Value = MdfData

                                            Else
                                                MsgBox("인쇄 수량 범위와 맞지 않습니다.", vbCritical)
                                            End If
                                        Else
                                            MsgBox("잘못된 인쇄 수량입니다.", vbCritical)
                                        End If

                                    Case 2
                                        LoadComportName()
                                        Dim RunSwitch As Boolean = False
                                        For cnt = 0 To cboComPort.Items.Count - 1
                                            cboComPort.SelectedIndex = cnt
                                            If MdfData = cboComPort.SelectedItem Then
                                                RunSwitch = True
                                                OpenSerial(MdfData)
                                                Exit For
                                            End If
                                        Next

                                        If RunSwitch = False Then
                                            cboComPort.SelectedIndex = -1
                                            cboComPort.Text = "SELECT!"
                                        End If

                                    Case 3
                                        Select Case MdfData
                                            Case ModeList.Prod_Input
                                                rdbPD2.Checked = True
                                            Case ModeList.TDRecycle
                                                rdbRecycle.Checked = True
                                            Case Else
                                                MsgBox("Mode Load, 잘못된 경로입니다.", vbCritical)
                                        End Select

                                    Case 4
                                        ckbOpAlto.Checked = MdfData

                                    Case 5
                                        If IsNumeric(MdfData) Then
                                            If MdfData < 13 And MdfData > 4 Then
                                                nudTray.Value = MdfData
                                                ReDim RegNumber(nudTray.Value - 1)

                                            Else
                                                MsgBox("Tray 수량 범위와 맞지 않습니다.", vbCritical)
                                            End If
                                        Else
                                            MsgBox("잘못된 Tray 수량입니다.", vbCritical)
                                        End If

                                    Case 6
                                        If IsNumeric(MdfData) Then
                                            If MdfData < 21 And MdfData > 0 Then
                                                nudTray.Value = MdfData
                                            Else
                                                MsgBox("Serial 확인 횟수에 대한 데이터가 맞지 않습니다.", vbCritical)
                                            End If
                                        Else
                                            MsgBox("잘못된 Serial 확인 횟수입니다.", vbCritical)
                                        End If

                                    Case Else
                                        MsgBox("불필요한 데이터가 존재합니다. 저장 내용을 확인하여 주십시오.", vbCritical)
                                        GoTo FailLoad
                                End Select
                            Next

                        Case SaveList.Print
                            For i = 0 To UBound(Split(ReadData, "|")) - 1
                                Dim MdfData As String = Mid(ReadData, 1, InStr(ReadData, "|") - 1)
                                ReadData = Mid(ReadData, InStr(ReadData, "|") + 1, ReadData.Length)

                                Select Case i
                                    Case 0
                                        txbPtBox_Name.Text = MdfData
                                    Case 1
                                        txbPtBox_Label.Text = MdfData
                                    Case 2
                                        txbPtBox_Val1.Text = MdfData
                                    Case 3
                                        txbPtBox_Val2.Text = MdfData
                                    Case 4
                                        txbPtWar_Name.Text = MdfData
                                    Case 5
                                        txbPtWar_Label.Text = MdfData
                                    Case 6
                                        txbPtWar_Val1.Text = MdfData
                                    Case 7
                                        txbPtProd_Name.Text = MdfData
                                    Case 8
                                        txbPtProd_Label.Text = MdfData
                                    Case 9
                                        txbPtProd_Val1.Text = MdfData
                                    Case 10
                                        txbPtProd_Val2.Text = MdfData
                                    Case 11
                                        txbPtProd_Date.Text = MdfData
                                    Case Else
                                        MsgBox("불필요한 데이터가 존재합니다. 저장 내용을 확인하여 주십시오.", vbCritical)
                                        GoTo FailLoad
                                End Select
                            Next
                        Case Else
                            MsgBox("잘못된 데이터가 존재합니다. 저장 내용을 확인하여 주십시오.", vbCritical)
                            GoTo FailLoad
                    End Select
                End If
            End If

            Exit Sub
        Catch ex As Exception
            MsgBox("불러오는 도중 오류가 발생하였습니다." & vbCrLf & ex.Message, vbCritical)
            GoTo FailLoad
        End Try

FailLoad:
    End Sub

    Private Sub rdbAllPnt_CheckedChanged(sender As Object, e As EventArgs) Handles rdbAllPnt.CheckedChanged, rdbEachPnt.CheckedChanged
        If rdbAllPnt.Checked = True Then
            gbPrintEach.Enabled = False

            ckbBoxPnt.Checked = True
            ckbWarPnt.Checked = True
            ckbProdPnt.Checked = True
        Else
            gbPrintEach.Enabled = True

            ckbBoxPnt.Checked = False
            ckbWarPnt.Checked = False
            ckbProdPnt.Checked = False
        End If
    End Sub

    Private Sub btnPtBox_Ch1_Click(sender As Object, e As EventArgs) Handles btnPtBox_Ch1.Click, btnPtWar_Ch1.Click, btnPtProd_Ch1.Click

        If dgvPrinter.Rows.Count - 2 = -1 Then
            MsgBox("연결된 프린터 항목을 알 수 없습니다." & vbCrLf & " 연결을 확인하여 주십시오.", vbCritical)
            Exit Sub
        End If

        Dim SelectRow As DataGridViewRow = dgvPrinter.SelectedRows(0)
        Dim PrintName As String = SelectRow.Cells(0).Value.ToString

        Dim NowButton As String = CType(sender, Button).Name

        Select Case NowButton
            Case "btnPtBox_Ch1"
                txbPtBox_Name.Text = PrintName
            Case "btnPtWar_Ch1"
                txbPtWar_Name.Text = PrintName
            Case "btnPtProd_Ch1"
                txbPtProd_Name.Text = PrintName
            Case Else
                MsgBox("잘못된 경로입니다.", vbCritical)
        End Select
    End Sub

    Private Sub btnPtBox_Ch2_Click(sender As Object, e As EventArgs) Handles btnPtBox_Ch2.Click, btnPtWar_Ch2.Click, btnPtProd_Ch2.Click
        Dim FileAddress As String = OpenFile()

        If FileAddress <> "fail" Then
            Dim NowButton As String = CType(sender, Button).Name
            Select Case NowButton
                Case "btnPtBox_Ch2"
                    txbPtBox_Label.Text = FileAddress
                Case "btnPtWar_Ch2"
                    txbPtWar_Label.Text = FileAddress
                Case "btnPtProd_Ch2"
                    txbPtProd_Label.Text = FileAddress
                Case Else
                    MsgBox("잘못된 경로입니다.", vbCritical)
            End Select
        End If
    End Sub

    Private Function OpenFile() As String
        Dim ofd As OpenFileDialog = New OpenFileDialog
        ofd.Title = "라벨 파일 주소 불러오기"
        ofd.FileName = ""
        ofd.Filter = "라벨 파일(*.lbx) | *.lbx"

        Dim dr As DialogResult = ofd.ShowDialog

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

        Return "fail"
    End Function

    Private Function TodayCountSet(OkNg As Boolean) As Boolean

        If TodayCountCreate() Then
            MsgBox("수량 카운터를 생성하는 도중 오류가 발생하였습니다.", vbCritical)
            Return True
        End If

        If TodayCountLoad() Then
            MsgBox("수량 카운터를 불러오는 도중 오류가 발생하였습니다.", vbCritical)
            Return True
        End If

        CountUpdate(OkNg)

        If TodayCountUpdate() Then
            MsgBox("수량 카운터를 업데이트하는 도중 오류가 발생하였습니다.", vbCritical)
            Return True
        End If

        CountSetting()

        Return False
    End Function

    Private Sub CountUpdate(OkNg)
        Select Case NowMode
            Case ModeList.Prod_Input

                CountSelect(CountList.Total) += 1

                If OkNg = True Then

                    If TDData(SearchList.TestStep) = "30" Then
                        CountSelect(CountList.Fail) -= 1
                    End If
                    CountSelect(CountList.Success) += 1
                Else
                    CountSelect(CountList.Fail) += 1
                End If

            Case ModeList.TDRecycle

                If OkNg = True Then
                    CountSelect(CountList.Total) += 1
                End If

            Case Else
                MsgBox("수량 카운터 출력 잘못된 경로입니다.", vbCritical)
        End Select
    End Sub

    Private Sub CountSetting()
        Select Case NowMode
            Case ModeList.Prod_Input
                txbAllCount.Text = CountSelect(CountList.Total)
                txbSucCount.Text = CountSelect(CountList.Success)
                txbFailCount.Text = CountSelect(CountList.Fail)
            Case ModeList.TDRecycle
                txbDayCount.Text = CountSelect(CountList.Total)
            Case Else
                MsgBox("수량 카운터 출력 잘못된 경로입니다.", vbCritical)
        End Select
    End Sub

    Private Sub NowRegCheck()
        Try
            Const LimitCheck As Int16 = 5
            Const RowCount As Int16 = 3
            dgvNowReg.Rows.Clear()

            DBCmd = "SELECT Product_SN,DATE_FORMAT(P3_DateTime,'%Y-%m-%d') AS d, DATE_FORMAT(P3_DateTime,'%H:%i:%s') AS t FROM " & ApplyCartDB & " WHERE TestStep > '30' ORDER BY P3_DateTime DESC LIMIT " & LimitCheck & ""
            If DBQueryReader(DBCmd) Then
                Dim RunCount As Int32 = 0
                Dim dgvData(RowCount - 1) As String
                For i = 0 To sqlDataQuery.Length - 1
                    dgvData(i Mod RowCount) = sqlDataQuery(RunCount)

                    If i Mod RowCount = RowCount - 1 Then
                        dgvNowReg.Rows.Add(dgvData)
                    End If

                    RunCount += 1
                Next

            End If
        Catch ex As Exception
            MsgBox("등록 현황 오류 발생 ! " & vbCrLf & ex.Message)
        End Try

    End Sub

    Private Sub btnPtRefresh_Click(sender As Object, e As EventArgs) Handles btnPtRefresh.Click
        List_Refreash(dgvPrinter)
    End Sub

    Private Sub MainForm_Click(sender As Object, e As EventArgs) Handles MyBase.Click
        txbPVSN.Focus()
    End Sub

    Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click
        btnReset.Enabled = False
        TimerFalse()
        StepReset()
        ValueReset()

        txbPDNum.Text = ClassCode
        txbPVSN.Text = ""
        txbPVSN.BackColor = Color.White

        NowRegCheck()
        StartCountSetting()
        btnReset.Enabled = True
    End Sub

    Private Sub TimerFalse()
        RunTimer.Enabled = False
        ThreadStop = True
    End Sub

    Private Sub txbPVSN_KeyDown(sender As Object, e As KeyEventArgs) Handles txbPVSN.KeyDown
        If chbAutoMeasure.Checked = False Then
            If e.KeyCode = Keys.Return Then
                btnEnter_Click(sender, New System.EventArgs)
            End If
        End If
    End Sub

    Private Sub ckbDBServer_CheckedChanged(sender As Object, e As EventArgs) Handles ckbDBServer.CheckedChanged
        ServerChanger(ckbDBServer.Checked)
    End Sub

    Private Sub TraySerialSetting()
        Dim NewData As Boolean = False
        Dim NowYear As Int16 = Format(Now, "yy")
        Dim NowMonth As Int16 = Format(Now, "MM")

        TrayDataReset()

        If BeforeTrayData(NowYear, NowMonth) Then
            If BeforeTrayLoad(NowYear, NowMonth) Then
                If BeforeTrayState() Then
                    NewData = False
                Else
                    NewData = True
                End If
            Else
                NewData = True
            End If
        Else

            If NewInfoRegData(NowYear, NowMonth) Then
                MsgBox("데이터베이스에 데이터를 생성할 수 없습니다.", vbCritical)
                Exit Sub
            End If

            NewData = True

        End If

        If NewData = True Then
            Dim MinResult As String = SerialMaxSearch(NowYear, NowMonth)

            If MinResult = "0" Then
                Dim CtMax As String = CtNumMaxSearch(NowYear, NowMonth)

                If CtMax = "NULL" Then
                    Exit Sub
                End If

                If CtMax = "0" Then
                    If ModelCode.Length = 2 Then    '16자리 시리얼번호
                        MinResult = "0"
                    Else                            '12자리 시리얼번호
                        MinResult = ClassCode & ColorCode & "0000"
                    End If
                Else
                    MinResult = CtMax
                End If

            End If

            MinResult = Val(MinResult) + 1

            If MAXResultSetting(MinResult, NowYear, NowMonth) Then
                Exit Sub
            End If

        End If

        TrayNowState()

    End Sub

    Private Sub TrayDataReset()
        txbTrayMax.Text = String.Empty
        txbTrayMin.Text = String.Empty
        txbNowNum.Text = String.Empty
    End Sub

    Private Function CtNumMaxSearch(NowYear As Int16, NowMonth As Int16) As String
        If TDUseCompare = True Then
            DBCmd = "SELECT IFNULL(max(Ct_SN),0) FROM " & ApplyCartDB & " WHERE Ct_Manufacture_Year = '" & NowYear & "' AND Ct_Manufacture_Month = '" & NowMonth & "' AND Ct_SN LIKE '" & ClassCode & ColorCode & "%' AND Ct_Model = '" & txbPDModel.Text & "' AND Ct_SN > 100000 AND (Ct_Type = '" & txbPDType.Text & "' OR Ct_Type = 'SET')"
        Else
            DBCmd = "SELECT IFNULL(max(Ct_SN),0) FROM " & ApplyNonTDDB & " WHERE Ct_Manufacture_Year = '" & NowYear & "' AND Ct_Manufacture_Month = '" & NowMonth & "' AND Ct_SN LIKE '" & ClassCode & ColorCode & "%' AND Ct_Model = '" & txbPDModel.Text & "' AND Ct_SN > 100000 AND (Ct_Type = '" & txbPDType.Text & "' OR Ct_Type = 'SET')"
        End If

        Dim CtMaxResult As String = DBQueryScalar(DBCmd)

        If CtMaxResult = "False" Then
            MsgBox("최대값을 불러올 수 없습니다.", vbCritical)
            Return "NULL"
        End If

        If CtMaxResult = "" Then
            Return "0"
        Else
            Return CtMaxResult
        End If
    End Function

    Private Function NewInfoRegData(NowYear As Int16, NowMonth As Int16) As Boolean
        DBCmd = "INSERT INTO " & InfoRegStateDB & "(UserID,ModelNum,TypeNum,ColorNum,UsageNum,CreateYear,CreateMonth) VALUES('" & IDName & "','" & ModelCode & "','" & TypeCode & "','" & ColorCode & "','" & ClassCode & "','" & NowYear & "','" & NowMonth & "')"
        If DBCommand(DBCmd) Then
            Return False
        Else
            Return True
        End If
    End Function

    Private Function MAXResultSetting(MinResult As String, NowYear As Int16, NowMonth As Int16) As Boolean
        Dim CheckOkNg As Boolean
        Dim RunCount As Int32 = nudTray.Value - 1
        Dim SearchYear As String = Format(Now, "yy")
        Dim SearchDate As String = Format(Now, "MM")
        ReDim TrayData(TrayDataList.State, RunCount)

        If ResetTrayData(NowYear, NowMonth) Then
            Return True
        End If

        For tay = 0 To RunCount
            CheckOkNg = False

            'For chk = 0 To nudSerialCheck.Value - 1
            '    DBCmd = "SELECT COUNT(Ct_SN) FROM " & ApplyCartDB & " WHERE Ct_Manufacture_Year = '" & SearchYear & "' AND Ct_Manufacture_Month = '" & SearchDate & "' and Ct_SN = '" & MinResult & "' AND Ct_Model = '" & txbPDModel.Text & "' AND Ct_Type = '" & txbPDType.Text & "'"
            '    Dim CtCount As String = DBQueryScalar(DBCmd)

            '    If CtCount = "False" Then
            '        MsgBox("시리얼 번호를 등록할 수 없습니다.", vbCritical)
            '        Return True
            '    End If

            '    If CtCount > 0 Then
            '        MinResult += 1
            '    Else
            '        TrayData(TrayDataList.NumData, tay) = MinResult
            '        TrayData(TrayDataList.State, tay) = "0"

            '        If TrayDataUpdate(tay) Then
            '            MsgBox("Tray Data를 입력하는 도중 오류가 발생하였습니다.", vbCritical)
            '            Return True
            '        End If

            '        CheckOkNg = True
            '        Exit For
            '    End If
            'Next

            'If CheckOkNg = False Then
            '    MsgBox("Serial Number 를 DB에 입력하지 못했습니다.", vbCritical)
            '    Return True
            'End If

            TrayData(TrayDataList.NumData, tay) = MinResult
            TrayData(TrayDataList.State, tay) = "0"

            If TrayDataUpdate(tay, NowYear, NowMonth) Then
                MsgBox("Tray Data를 입력하는 도중 오류가 발생하였습니다.", vbCritical)
                Return True
            End If

            If tay = RunCount Then
                If TrayMaxUpdate(tay, NowYear, NowMonth) Then
                    Return False
                Else
                    MsgBox("Serial Number 를 DB에 입력하지 못했습니다.", vbCritical)
                    Return True
                End If
            End If

            MinResult += 1

        Next

        MsgBox("Data를 전부 다 처리하지 못했습니다.", vbCritical)
        Return True
    End Function

    Private Function TrayMaxUpdate(TrayNumber As Int32, NowYear As Int16, NowMonth As Int16) As Boolean
        DBCmd = "UPDATE " & InfoRegStateDB & " SET MaxNum = '" & TrayData(TrayDataList.NumData, TrayNumber) & "' WHERE UserID = '" & IDName & "' AND ModelNum = '" & ModelCode & "' AND TypeNum = '" & TypeCode & "' AND ColorNum = '" & ColorCode & "' AND UsageNum = '" & ClassCode & "' AND CreateYear = '" & NowYear & "' AND CreateMonth = '" & NowMonth & "'"
        If DBCommand(DBCmd) Then
            Return True
        Else
            Return False
        End If
    End Function

    Private Function TrayDataUpdate(UpdateData As Int16, NowYear As Int16, NowMonth As Int16) As Boolean
        Dim DBUpdateCnt As String = UpdateData + 1
        Dim UpdateCmd As String = "Tray" & DBUpdateCnt & "Num = '" & TrayData(TrayDataList.NumData, UpdateData) & "', Tray" & DBUpdateCnt & "State = '" & TrayData(TrayDataList.State, UpdateData) & "'"

        DBCmd = "UPDATE " & InfoRegStateDB & " SET " & UpdateCmd & " WHERE UserID = '" & IDName & "' AND ModelNum = '" & ModelCode & "' AND TypeNum = '" & TypeCode & "' AND ColorNum = '" & ColorCode & "' AND UsageNum = '" & ClassCode & "' AND CreateYear = '" & NowYear & "' AND CreateMonth = '" & NowMonth & "'"
        If DBCommand(DBCmd) Then
            Return False
        Else
            Return True
        End If
    End Function

    Private Function ResetTrayData(NowYear As Int16, NowMonth As Int16) As Boolean
        DBCmd = "UPDATE " & InfoRegStateDB & " SET MaxNum = 0, Tray1Num = 0, Tray1State = 0, Tray2Num = 0, Tray2State = 0, Tray3Num = 0, Tray3State = 0, Tray4Num = 0, Tray4State = 0, Tray5Num = 0, Tray5State = 0, Tray6Num = 0, Tray6State = 0, Tray7Num = 0, Tray7State = 0, Tray8Num = 0, Tray8State = 0, Tray9Num = 0, Tray9State = 0, Tray10Num = 0, Tray10State = 0, Tray11Num = 0, Tray11State = 0, Tray12Num = 0, Tray12State = 0 WHERE UserID = '" & IDName & "' AND ModelNum = '" & ModelCode & "' AND TypeNum = '" & TypeCode & "' AND ColorNum = '" & ColorCode & "' AND UsageNum = '" & ClassCode & "' AND CreateYear = '" & NowYear & "' AND CreateMonth = '" & NowMonth & "'"
        If DBCommand(DBCmd) Then
            Return False
        Else
            Return True
        End If
    End Function

    Private Function SerialMaxSearch(NowYear As Int16, NowMonth As Int16) As String
        DBCmd = "SELECT ifnull(max(MaxNum),0) FROM " & InfoRegStateDB & " WHERE ModelNum = '" & ModelCode & "' AND TypeNum = '" & TypeCode & "' AND ColorNum = '" & ColorCode & "' AND UsageNum = '" & ClassCode & "' AND CreateYear = '" & NowYear & "' AND CreateMonth = '" & NowMonth & "'"
        Return DBQueryScalar(DBCmd)
    End Function

    Private Sub TrayNowState()
        txbTrayMin.Text = TrayData(TrayDataList.NumData, 0)
        txbTrayMax.Text = TrayData(TrayDataList.NumData, TrayData.GetLength(1) - 1)

        For c = 0 To TrayData.GetLength(1) - 1
            If TrayData(TrayDataList.State, c) = 0 Then
                txbNowNum.Text = TrayData(TrayDataList.NumData, c)
                txbNowNum.BackColor = Color.White
                txbNowNum.Refresh()
                Exit Sub
            End If
        Next

        txbNowNum.Text = "완료"
        txbNowNum.BackColor = Color.Green
        txbNowNum.Refresh()
    End Sub

    Private Function BeforeTrayState() As Boolean
        For i = 0 To TrayData.GetLength(1) - 1

            If TrayData(TrayDataList.NumData, i) = 0 Then
                Return False  '' 시리얼 번호가 0번일 시 신규 생성
            End If

            If TrayData(TrayDataList.State, i) = 0 Then
                Return True  '' 한 개라도 처리 안 한 제품이 있을 시
            End If

        Next

        Return False  '' 모두 처리 했을 경우
    End Function

    Private Function BeforeTrayLoad(NowYear As Int16, NowMonth As Int16) As Boolean

        BeforeTrayDBCmd(NowYear, NowMonth)

        If DBQueryReader(DBCmd) Then
            Dim DataCount As Integer = 0
            Dim RowData As Integer = (sqlDataQuery.Length / TrayDataList.maxList) - 1
            ReDim TrayData(TrayDataList.State, RowData)

            For c = 0 To RowData
                For r = 0 To TrayDataList.State
                    TrayData(r, c) = sqlDataQuery(DataCount)
                    DataCount += 1
                Next
            Next

            Return True  '' 데이터가 있을 경우
        Else
            Return False '' 데이터가 없을 경우
        End If
    End Function

    Private Sub BeforeTrayDBCmd(NowYear As Int16, NowMonth As Int16)
        DBCmd = String.Empty

        For i = nudTray.Value To 1 Step -1
            If i = 1 Then
                DBCmd = "Tray" & i & "Num,Tray" & i & "State" & DBCmd
            Else
                DBCmd = ",Tray" & i & "Num,Tray" & i & "State" & DBCmd
            End If
        Next

        DBCmd = "SELECT " & DBCmd & " FROM " & InfoRegStateDB & " WHERE UserID= '" & IDName & "' AND ModelNum = '" & ModelCode & "' AND TypeNum = '" & TypeCode & "' AND ColorNum = '" & ColorCode & "' AND UsageNum = '" & ClassCode & "' AND CreateYear = '" & NowYear & "' AND CreateMonth = '" & NowMonth & "'"
    End Sub

    Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        TraySerialSetting()
    End Sub

    Private Sub ckbManager_CheckedChanged(sender As Object, e As EventArgs) Handles ckbManager.CheckedChanged
        If ckbManager.Checked = True Then
            RichTextBox1.Visible = True
            Button1.Visible = True
            Button2.Visible = True

        Else
            RichTextBox1.Visible = False
            Button1.Visible = False
            Button2.Visible = False
        End If
    End Sub

    Private Sub ckbAutoFunc_CheckedChanged(sender As Object, e As EventArgs) Handles ckbAutoFunc.CheckedChanged
        If ckbAutoFunc.Checked = True Then
            btnTrayEnd.Enabled = True
        Else
            btnTrayEnd.Enabled = False
        End If

        txbPVSN.Focus()
    End Sub

    Private Sub TrayEndUpdate(NowYear As Int16, NowMonth As Int16)
        DBCmd = String.Empty

        For i = nudTray.Value To 1 Step -1
            If i = 1 Then
                DBCmd = "Tray" & i & "State = '1'" & DBCmd
            Else
                DBCmd = ",Tray" & i & "State = '1'" & DBCmd
            End If
        Next

        DBCmd = "UPDATE " & InfoRegStateDB & " SET " & DBCmd & " WHERE UserID= '" & IDName & "' AND ModelNum = '" & ModelCode & "' AND TypeNum = '" & TypeCode & "' AND ColorNum = '" & ColorCode & "' AND UsageNum = '" & ClassCode & "' AND CreateYear = '" & NowYear & "' AND CreateMonth = '" & NowMonth & "'"
    End Sub

    Private Sub btnTrayEnd_Click(sender As Object, e As EventArgs) Handles btnTrayEnd.Click
        Dim NowDate As String = Format(Now, "yy")
        Dim NowTime As String = Format(Now, "MM")

        If BeforeTrayData(NowDate, NowTime) Then
            TrayEndUpdate(NowDate, NowTime)
        End If
    End Sub

    Private Function BeforeTrayData(NowYear As Int16, NowMonth As Int16) As Boolean
        DBCmd = "SELECT COUNT(UserID) FROM " & InfoRegStateDB & " WHERE UserID= '" & IDName & "' AND ModelNum = '" & ModelCode & "' AND TypeNum = '" & TypeCode & "' AND ColorNum = '" & ColorCode & "' AND UsageNum = '" & ClassCode & "' AND CreateYear = '" & NowYear & "' AND CreateMonth = '" & NowMonth & "'"
        Dim BeforeData As Integer = DBQueryScalar(DBCmd)
        If BeforeData > 0 Then
            Return True  ''있을 경우
        Else
            Return False  '' 없을 경우
        End If
    End Function
End Class
