Imports System.IO
Imports Newtonsoft.Json

Imports UTS_Core.Database
Imports UTS_Core.UTSModule.DbConnect

Public Class JsonFileListen

    ''' <summary>
    ''' 读取文件并将内容保存在本地数据库中
    ''' </summary>
    ''' <param name="path"></param>
    ''' <returns></returns>
    Public Function ReadFile(db As DbExecutor, path As String) As Boolean
        ServiceLog.WriteInfoLog($"FileListen Begin ReadFile!")

        If File.Exists(path) = False Then
            Throw New Exception($"{path}不存在！")
        End If

        ServiceLog.WriteInfoLog($"FileListen Get fileLength!")

        Dim fileInfo As New FileInfo(path) '获取文件大小
        If fileInfo.Length = 0 Then Return True

        ServiceLog.WriteInfoLog($"FileListen Begin Read Text String!")

        Using reader As New StreamReader(path)
            While reader.Peek() <> -1
                Dim line As String = reader.ReadLine()
                If String.IsNullOrWhiteSpace(line) Then Continue While '过滤信息
                line = line.Replace("\", "\\") '处理转义字符

                Dim tmpField As Dictionary(Of String, String)
                Try
                    tmpField = CType(JsonConvert.DeserializeObject(line, GetType(Dictionary(Of String, String))), Dictionary(Of String, String))
                Catch ex As Exception
                    ServiceLog.WriteErrorLog($"FileListen JsonConvertToKeyValue Error:{ex.Message};JsonString:{line}")
                    Continue While
                End Try

                ServiceLog.WriteInfoLog($"FileListen Filter Text String!")

                ''过滤缺失字段字符串
                If tmpField.ContainsKey("ProjectName") = False OrElse tmpField.ContainsKey("StationName") = False Then
                    ServiceLog.WriteErrorLog($"FileListen Unexist ProjectName Or StationName Filed,JsonString:{line}")
                    Continue While
                End If

                ServiceLog.WriteInfoLog($"FileListen Filter Text String Success!")

                '数据处理，根据表名进行分类，增删必要字段
                Dim tableName As String
                Try
                    Dim projectIndex As Integer = DbConnector.SearchProjectIndex(db, tmpField("ProjectName"))
                    Dim stationIndex As Integer = DbConnector.SearchStationIndex(db, projectIndex, tmpField("StationName"))
                    tableName = UTS_Core.UTSModule.DbTableModel.Customer.TestLogTable.TableName(projectIndex, stationIndex)
                Catch ex As Exception
                    ServiceLog.WriteErrorLog($"FileListen GetTestLogTableName Error:{ex.Message};ProjectName:{tmpField("ProjectName")};StationName:{tmpField("StationName")}")
                    Continue While
                End Try

                ServiceLog.WriteInfoLog($"FileListen Begin CreateTestLogTable!")

                Try '本地表格新建
                    DbConnector.UtsCreateTestLogTableToLocal(db, tableName)
                Catch ex As Exception
                    ServiceLog.WriteErrorLog($"FileListen CreateTestLogTable Error:{ex.Message}")
                    Continue While
                End Try

                ServiceLog.WriteInfoLog($"FileListen Begin CreateTestLogTable Success!")


                ServiceLog.WriteInfoLog($"FileListen Begin Filter Db Filed!")


                Dim fields As New Dictionary(Of String, String) '入库字段
                For Each valuePair As KeyValuePair(Of String, String) In tmpField
                    If String.IsNullOrWhiteSpace(valuePair.Key) Then Continue For
                    If String.Compare(valuePair.Key, "ProjectName", True) = 0 Then Continue For
                    If String.Compare(valuePair.Key, "StationName", True) = 0 Then Continue For

                    If String.Compare(valuePair.Key, "ProductionLineID", True) = 0 Then
                        If String.IsNullOrWhiteSpace(valuePair.Value) Then Continue For
                    End If

                    If String.Compare(valuePair.Key, "OrderID", True) = 0 Then
                        If String.IsNullOrWhiteSpace(valuePair.Value) Then Continue For
                    End If

                    If String.Compare(valuePair.Key, "ServiceID", True) = 0 Then
                        If String.IsNullOrWhiteSpace(valuePair.Value) Then Continue For
                    End If

                    If String.Compare(valuePair.Key, "UserID", True) = 0 Then
                        If String.IsNullOrWhiteSpace(valuePair.Value) Then Continue For
                    End If

                    fields.Add(valuePair.Key, valuePair.Value) '过滤字段，保留有效字段
                Next

                ServiceLog.WriteInfoLog($"FileListen Begin Filter Db Filed Success!")

                ServiceLog.WriteInfoLog($"FileListen SaveTestRecord!")
                Try '存储
                    DbConnector.UtsInsertToLocal(db, UTS_Core.UTSModule.UtsDb.RemotePrivateDb, tableName, fields)
                Catch ex As Exception
                    ServiceLog.WriteErrorLog($"FileListen SaveTestRecord Error:{ex.Message}")
                    Continue While
                End Try

                ServiceLog.WriteInfoLog($"FileListen SaveTestRecord Success!")
            End While

            reader.Close()
        End Using

        ServiceLog.WriteInfoLog($"FileListen Begin Clear!")

        File.WriteAllText(path, String.Empty) '清空文件内容,由于多地同时写的原因，有可能会失败

        ServiceLog.WriteInfoLog($"FileListen Success!")

        Return True
    End Function
End Class