Imports MySql.Data.MySqlClient
Imports Renci.SshNet

Module mySQLModule
    '' MySQL 접속 정보
    Private Const LocalHostIP As String = "192.168.0.250"
    Private Const UserName As String = "root"
    Private Const UserPasswrod As String = "JOMT1646db!!"
    Private DataBaseName As String = "jomtOrderTestDB"

    Private Conn As String = "Server=" + LocalHostIP + ";DataBase=" + DataBaseName + ";user=" + UserName + ";password=" + UserPasswrod + ";"

    Private sqlCon As New MySqlConnection(Conn)
    Private sqlCmd As New MySqlCommand()
    Private sqlData As MySqlDataReader           '' SQL Server와 연결을 유지한 상태에서 한번에 한 레코드(One Row)씩 데이타를 가져오는데 사용된다

    Public sqlDataQuery() As Object

    Public Const SaleDB As String = "jomtTesterDB.jomtSalesPackingTbl"
    Public Const NonTDDB As String = "jomtTesterDB.jomtNonTDTbl"
    Public Const CartTDDB As String = "jomtTesterDB.jomtCartridgeTbl"
    Public Const OrderDB As String = "jomtOrderDB.jomtOrderTbl"
    Public Const PlistDB As String = "jomtTesterDB.jomtProdList"

    Public Function GetDBConn() As MySqlConnection
        Try
            If sqlCon.State <> ConnectionState.Open Then
                sqlCon.Open()
            End If
            Return sqlCon
        Catch ex As Exception
            MsgBox("MySQL Command Error:" + vbCrLf + Err.Description)
            Return Nothing
        End Try
    End Function

    Public Function FindSerialsByDate(targetDate As Date) As ValueTuple(Of List(Of String), List(Of String))
        Using conn As MySqlConnection = GetDBConn()
            Dim getSerialCmd As New MySqlCommand("SELECT Serial_Number FROM jomtOrderDB.jomtOrderTbl 
                                         WHERE Invoice_Number IS NOT NULL 
                                           AND Serial_Number IS NOT NULL 
                                           AND LENGTH(Serial_Number) > 11
                                           AND LEFT(Serial_Number, 1) < '8'
                                           AND Shipment_Date = @date", conn)

            getSerialCmd.Parameters.AddWithValue("@date", targetDate)

            Dim serials As New List(Of String)
            Dim unmatchedSerials As New List(Of String)

            Using reader As MySqlDataReader = getSerialCmd.ExecuteReader()
                While reader.Read()
                    Dim raw = reader("Serial_Number").ToString().Trim()
                    If raw.Contains("/") Then
                        serials.AddRange(raw.Split("/"c).Select(Function(s) s.Trim()).Where(Function(s) s.Length > 0))
                        unmatchedSerials.Add(raw.Split("/"c).Select(Function(s) s.Trim()).FirstOrDefault(Function(s) s.Length > 0))
                    ElseIf raw.Length > 0 Then
                        serials.Add(raw)
                    End If
                End While
            End Using

            Return (serials.ToList(), unmatchedSerials.ToList())
        End Using

    End Function

    Public Sub FillFromOrderTblByLike(dtoMap As Dictionary(Of String, GenuineProductDto), likeClauses As List(Of String))
        Using conn As MySqlConnection = GetDBConn()
            For Each clause In likeClauses
                Dim query As String =
                "SELECT Serial_Number, Item_Code, Item_Name, Invoice_Number, Packing_Code, DATE_FORMAT(Shipment_Date, '%Y-%m-%d') AS Shipment_Date, " &
                "Account_Name, Order_Code, Orderer_Name, Receiver_Name, Phone_Number, Address, Refer " &
                "FROM jomtOrderDB.jomtOrderTbl " &
                "WHERE " & clause

                Using cmd As New MySqlCommand(query, conn)
                    Using reader = cmd.ExecuteReader()
                        While reader.Read()
                            Dim serialRaw = reader("Serial_Number").ToString().Trim()
                            Dim serials = serialRaw.Split("/"c)

                            For Each sn In serials
                                Dim key = sn.Trim()
                                If dtoMap.ContainsKey(key) Then
                                    Dim dto = dtoMap(key)

                                    dto.ModelCode = reader("Item_Code").ToString()
                                    dto.Model = reader("Item_Name").ToString()
                                    dto.InvoiceNumber = reader("Invoice_Number").ToString()
                                    dto.PackingSn = reader("Packing_Code").ToString()
                                    dto.BuyDate = reader("Shipment_Date").ToString()
                                    dto.SalesStore = reader("Account_Name").ToString()
                                    dto.SalesOrderNo = reader("Order_Code").ToString()
                                    dto.OrderName = reader("Orderer_Name").ToString()
                                    dto.RecipientName = reader("Receiver_Name").ToString()
                                    dto.OrderHp = reader("Phone_Number").ToString()
                                    dto.OrderAddress = reader("Address").ToString()
                                    dto.Note = reader("Refer").ToString()
                                End If
                            Next
                        End While
                    End Using
                End Using
            Next
        End Using
    End Sub

    Public Sub FillFromOrderTblByIn(dtoMap As Dictionary(Of String, GenuineProductDto), inClauses As List(Of String))
        Dim serials = dtoMap.Keys.ToList()
        Dim missingItemCodeSNs As New List(Of String)

        Using conn As MySqlConnection = GetDBConn()
            For Each clause In inClauses
                Dim query As String =
                "SELECT Serial_Number, Item_Code, Item_Name, Invoice_Number, Packing_Code, DATE_FORMAT(Shipment_Date, '%Y-%m-%d') AS Shipment_Date, " &
                "Account_Name, Order_Code, Orderer_Name, Receiver_Name, Phone_Number, Address, Refer " &
                "FROM jomtOrderDB.jomtOrderTbl " &
                "WHERE Serial_Number IN " & clause

                Using cmd As New MySqlCommand(query, conn)
                    Using reader = cmd.ExecuteReader()
                        While reader.Read()
                            Dim sn = reader("Serial_Number").ToString().Trim()
                            If dtoMap.ContainsKey(sn) Then
                                Dim dto = dtoMap(sn)

                                dto.ModelCode = reader("Item_Code").ToString()
                                dto.Model = reader("Item_Name").ToString()
                                dto.InvoiceNumber = reader("Invoice_Number").ToString()
                                dto.PackingSn = reader("Packing_Code").ToString()
                                dto.BuyDate = reader("Shipment_Date").ToString()
                                dto.SalesStore = reader("Account_Name").ToString()
                                dto.SalesOrderNo = reader("Order_Code").ToString()
                                dto.OrderName = reader("Orderer_Name").ToString()
                                dto.RecipientName = reader("Receiver_Name").ToString()
                                dto.OrderHp = reader("Phone_Number").ToString()
                                dto.OrderAddress = reader("Address").ToString()
                                dto.Note = reader("Refer").ToString()
                            End If
                        End While
                    End Using
                End Using
            Next
        End Using
    End Sub

    Public Sub FillFromProductTbl(dtoMap As Dictionary(Of String, GenuineProductDto), inClauses As List(Of String))
        Dim serials = dtoMap.Keys.ToList()

        Using conn As MySqlConnection = GetDBConn()
            For Each clause In inClauses
                Dim query As String =
                "SELECT Product_SN, FaceCart_SN, EyeCart_SN " &
                "FROM jomtTesterDB.jomtProductTbl " &
                "WHERE Product_SN IN " & clause

                Using cmd As New MySqlCommand(query, conn)
                    Using reader = cmd.ExecuteReader()
                        While reader.Read()
                            Dim sn = reader("Product_SN").ToString()
                            If dtoMap.ContainsKey(sn) Then
                                dtoMap(sn).FaceSn = reader("FaceCart_SN").ToString()
                                dtoMap(sn).EyeSn = reader("EyeCart_SN").ToString()
                            End If
                        End While
                    End Using
                End Using
            Next
        End Using
    End Sub

    Public Sub FillFromProdData(dtoMap As Dictionary(Of String, GenuineProductDto), inClauses As List(Of String))
        Dim serials = dtoMap.Keys.ToList()

        Using conn As MySqlConnection = GetDBConn()
            For Each clause In inClauses
                Dim query As String =
                "SELECT Product_SN, Ct_Abroad AS Country, DATE_FORMAT(P3_DateTime, '%Y-%m-%d') AS MfgDate " &
                "FROM jomtTesterDB.jomtCartridgeTbl WHERE Product_SN IN " & clause &
                "UNION ALL " &
                "SELECT Product_SN, Abroad AS Country, DATE_FORMAT(DateTime, '%Y-%m-%d') AS MfgDate " &
                "FROM jomtTesterDB.jomtDeviceTbl WHERE Product_SN IN " & clause &
                "UNION ALL " &
                "SELECT Product_SN, Ct_Abroad AS Country, DATE_FORMAT(P3_DateTime, '%Y-%m-%d') AS MfgDate " &
                "FROM jomtTesterDB.jomtNonTDTbl WHERE Product_SN IN " & clause

                Using cmd As New MySqlCommand(query, conn)
                    Using reader = cmd.ExecuteReader()
                        While reader.Read()
                            Dim sn = reader("Product_SN").ToString()
                            If dtoMap.ContainsKey(sn) AndAlso String.IsNullOrEmpty(dtoMap(sn).CountryCode) Then
                                dtoMap(sn).CountryCode = reader("Country").ToString()
                                dtoMap(sn).ManufactureDate = reader("MfgDate").ToString()
                            End If
                        End While
                    End Using
                End Using
            Next
        End Using
    End Sub
End Module
