Imports Microsoft.Office.Interop.Excel

Public Class mainform
    Private Const RowCount As Byte = 3
    Private Const PKCodeCheck As String = "PK001"

    Private Sub mainform_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Me.Text = "DUALSONIC PK Code Register Program Ver 1.0.0"
    End Sub

    Private Sub txbop1_pk_KeyDown(sender As Object, e As KeyEventArgs) Handles txbop1_pk.KeyDown
        If e.KeyCode = Keys.Return Then
            btnop1_search_Click(sender, New System.EventArgs())
        End If
    End Sub

    Private Sub btnop1_search_Click(sender As Object, e As EventArgs) Handles btnop1_search.Click
        Dim UcaseText As String = UCase(txbop1_pk.Text)
        PKCode_Search(UcaseText)
    End Sub

    Private Sub PKCode_Search(searchtxt As String)
        dgvop1_data.Rows.Clear()

        Dim DBCmd As String = "SELECT * FROM " & PKCodeDB & " WHERE PKCode = '" & searchtxt & "'"
        Dim QueryCount As Byte = DBQueryReader(DBCmd)
        Dim SearchCount As Byte = 0

        If QueryCount Then

            Dim ColListCount As Byte = RowCount - 1
            Dim RowListCount As Byte = (QueryCount / RowCount) - 1

            For i = 0 To RowListCount

                Dim DataSearch(ColListCount) As String

                For n = 0 To ColListCount

                    DataSearch(n) = sqlDataQuery(SearchCount)

                    SearchCount += 1

                Next

                dgvop1_data.Rows.Add(DataSearch)

            Next

            dgvop1_data.ClearSelection()
            dgvop1_data.Rows(0).Selected = True
            txbop1_pk.Text = String.Empty

        Else
            MsgBox("존재하는 PK코드가 존재하지 않습니다. 먼저 등록하여 주십시오.", vbExclamation)
        End If
    End Sub

    Private Sub btnop1_del1_Click(sender As Object, e As EventArgs) Handles btnop1_del1.Click

        If dgvop1_data.SelectedRows.Count > 0 Then
            If MsgBox("선택한 행을 삭제하시겠습니까?", vbExclamation + vbOKCancel) = MsgBoxResult.Ok Then
                PKCode_RowDel()
            End If
        Else
            MsgBox("선택한 행이 없습니다.", vbExclamation)
        End If
    End Sub

    Private Sub PKCode_RowDel()
        Dim DBCmd As String = "DELETE FROM " & PKCodeDB & " WHERE PKCode = '" & dgvop1_data.SelectedRows(0).Cells(0).Value.ToString & "' AND ProdCode = '" & dgvop1_data.SelectedRows(0).Cells(1).Value.ToString & "'"

        If DBCommand(DBCmd) Then
            dgvop1_data.Rows.RemoveAt(dgvop1_data.CurrentCell.RowIndex)
            MsgBox("데이터를 삭제하였습니다.", vbInformation)
        Else
            MsgBox("데이터를 삭제하지 못하였습니다.", vbCritical)
        End If
    End Sub

    Private Sub btnop1_del2_Click(sender As Object, e As EventArgs) Handles btnop1_del2.Click

        If dgvop1_data.SelectedRows.Count > 0 Then
            If MsgBox("해당 코드 번호를 전체 삭제하시겠습니까?", vbExclamation + vbOKCancel) = MsgBoxResult.Ok Then
                If MsgBox("정말 삭제하시겠습니까?", vbCritical + vbOKCancel) = MsgBoxResult.Ok Then
                    PKCode_AllDel()
                End If
            End If
        Else
            MsgBox("선택한 행이 없습니다.", vbExclamation)
        End If

    End Sub

    Private Sub PKCode_AllDel()
        Dim DBCmd As String = "DELETE FROM " & PKCodeDB & " WHERE PKCode = '" & dgvop1_data.SelectedRows(0).Cells(0).Value.ToString & "'"

        If DBCommand(DBCmd) Then
            dgvop1_data.Rows.Clear()
            MsgBox("데이터를 삭제하였습니다.", vbInformation)
        Else
            MsgBox("데이터를 삭제하지 못하였습니다.", vbCritical)
        End If

    End Sub

    Private Sub btnop1_reg_Click(sender As Object, e As EventArgs) Handles btnop1_reg.Click
        If String.IsNullOrWhiteSpace(txbop1_regpk.Text) Or String.IsNullOrWhiteSpace(txbop1_regpd.Text) Or String.IsNullOrWhiteSpace(nudop1_regct.Text) Then

            MsgBox("비어있는 칸이 존재합니다. 값을 입력해주세요.", vbCritical)
            Exit Sub

        Else

            If Mid(txbop1_regpk.Text, 1, 5) = PKCodeCheck Then
                PKCode_Register()
            Else
                MsgBox("PK 코드 양식에 맞지 않는 코드 번호입니다. PK 코드는 앞자리가 ""PK001"" 로 시작됩니다.", vbExclamation)
            End If
        End If
    End Sub

    Private Sub PKCode_Register()
        Dim DBCmd As String = "INSERT INTO " & PKCodeDB & " VALUES ('" & txbop1_regpk.Text & "','" & txbop1_regpd.Text & "'," & nudop1_regct.Value & ")"

        If DBCommand(DBCmd) Then
            txbop1_regpk.Text = String.Empty
            txbop1_regpd.Text = String.Empty
            nudop1_regct.Value = 1

            MsgBox("등록 완료하였습니다.", vbInformation)
        Else
            MsgBox("PK 코드를 등록하지 못했습니다.", vbCritical)
        End If

    End Sub

    Private Sub btnop_reset_Click(sender As Object, e As EventArgs) Handles btnop_reset.Click
        dgvop1_data.Rows.Clear()
        txbop1_pk.Text = String.Empty
        txbop1_regpk.Text = String.Empty
        txbop1_regpd.Text = String.Empty
        nudop1_regct.Text = String.Empty

        txbop1_pk.Focus()
    End Sub

    Private Sub btnop1_load_Click(sender As Object, e As EventArgs) Handles btnop1_load.Click

        Dim OfdExcel As New OpenFileDialog()
        OfdExcel.Filter = "Excel Files|*.xls;*.xlsx"
        OfdExcel.Title = "엑셀 파일 불러오기"
        OfdExcel.Multiselect = False

        If OfdExcel.ShowDialog() = DialogResult.OK Then
            Dim filePath As String = OfdExcel.FileName
            ExcelLoad(filePath)

            MsgBox("불러오기 완료!", vbInformation)
        End If

    End Sub

    Private Sub ExcelLoad(filePath As String)
        Dim excelApp As New Application()
        Dim workBook As Workbook = Nothing
        Dim workSheet As Worksheet = Nothing

        Try
            workBook = excelApp.Workbooks.Open(filePath)
            workSheet = CType(workBook.Sheets(1), Worksheet)

            dgvop1_data.Rows.Clear()
            Dim rowNum As Integer = 3

            Do While workSheet.Range("D" & rowNum).Value IsNot Nothing
                Dim setCode As String = workSheet.Range("D" & rowNum).Value.ToString

                Dim colNum As Byte = 7
                Dim dgvData(RowCount - 1)

                For i = 0 To 7

                    Dim cellValue As String = workSheet.Cells(rowNum, colNum).Value

                    If Not String.IsNullOrEmpty(cellValue) Then
                        dgvData(0) = setCode.Replace(" ", "").Replace(vbTab, "")
                        dgvData(1) = workSheet.Cells(rowNum, colNum).Value.ToString.Replace(" ", "").Replace(vbTab, "")
                        dgvData(2) = workSheet.Cells(rowNum, colNum + 2).Value.ToString.Trim.Replace(" ", "").Replace(vbTab, "")
                    Else
                        Exit For
                    End If

                    dgvop1_data.Rows.Add(dgvData)
                    colNum += 3
                Next

                rowNum += 1
            Loop


        Catch ex As Exception
            MsgBox("오류 발생: " & ex.Message, vbCritical)

        Finally

            workBook.Close(False)
            excelApp.Quit()
            ReleaseObject(workSheet)
            ReleaseObject(workBook)
            ReleaseObject(excelApp)

        End Try

    End Sub

    Private Sub ReleaseObject(ByVal obj As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub

    Private CheckBol As Boolean = False
    Private CheckStr As String = String.Empty

    Private Sub btnop1_save_Click(sender As Object, e As EventArgs) Handles btnop1_save.Click
        For i = 0 To dgvop1_data.RowCount - 2
            Dim setCode As String = dgvop1_data.Rows(i).Cells(0).Value

            If setCode <> CheckStr Then
                CheckStr = setCode
                If PKCodeCompare(setCode) Then
                    CheckBol = True
                Else
                    CheckBol = False
                End If

            End If

            If CheckBol = True Then
                If PKCode_ExcelSave(i) Then
                    Exit For
                End If

                dgvop1_data.Rows(i).DefaultCellStyle.BackColor = Color.Green
            Else
                dgvop1_data.Rows(i).DefaultCellStyle.BackColor = Color.Red
            End If

        Next
    End Sub

    Private Function PKCode_ExcelSave(n As Integer) As Boolean
        Dim DBCmd As String = "INSERT INTO " & PKCodeDB & " VALUES ('" & dgvop1_data.Rows(n).Cells(0).Value & "','" & dgvop1_data.Rows(n).Cells(1).Value & "'," & dgvop1_data.Rows(n).Cells(2).Value & ")"

        If DBCommand(DBCmd) = False Then
            MsgBox("PK 코드를 등록하지 못했습니다.", vbCritical)
            Return True
        End If

        Return False
    End Function

    Private Function PKCodeCompare(setCode As String) As Boolean
        Dim DBCmd As String = "SELECT 1 FROM " & PKCodeDB & " WHERE PKCode = '" & setCode & "' LIMIT 1"
        Dim dbResult As String = DBQueryScalar(DBCmd)

        If String.IsNullOrWhiteSpace(dbResult) Then
            Return True
        Else
            Return False
        End If
    End Function
End Class
