Imports System.Data.Common
Imports System.IO
Imports System.Net
Imports System.Text
Imports UTS_Core.Database
Imports UTS_Core.Security
Imports UTS_Core.UTSModule.DbTableModel.Customer
Imports UTS_Core.UTSModule.DbTableModel.LocalPrivate
Imports UTS_Core.UTSModule.DbTableModel.Manage
Imports UTS_Core.UTSModule.Production
Imports UTS_Core.UTSModule.Station
Imports UTS_Core.UTSModule.Test


Namespace UTSModule.DbConnect
    ''' <summary>
    ''' 测试数据入库类
    ''' </summary>
    Public Class DbConnector

#Region "通用执行"

        ''' <summary>
        ''' 是否能够连接远程网络
        ''' </summary>
        ''' <returns></returns>
        Public Shared Function CanConnectToRemote() As Boolean
            Return My.Computer.Network.IsAvailable
        End Function

        Public Shared Sub Update(db As DbExecutor, dbName As String, tbName As String, field As Dictionary(Of String, String), condition As String)

            Dim cmdText As String = db.CmdHelper.DbUpdate(dbName, tbName, field, condition)
            db.ExecuteNonQuery(cmdText) '执行语句
        End Sub

        Public Shared Sub Insert(db As DbExecutor, dbName As String, tbName As String, field As Dictionary(Of String, String))
            Dim cmdText As String = db.CmdHelper.DbInsert(dbName, tbName, field)
            db.ExecuteNonQuery(cmdText) '执行语句
        End Sub


        Public Shared Sub InsetOrUpdate(db As DbExecutor, dbName As String, tbName As String, field As Dictionary(Of String, String), condition As String)
            If CInt(db.ExecuteScalar(db.CmdHelper.DbSearchCount(dbName, tbName, condition))) > 0 Then
                Update(db, dbName, tbName, field, condition)
            Else
                Insert(db, dbName, tbName, field)
            End If
        End Sub

        Public Shared Function SearchRowCount(db As DbExecutor, tbName As String, Optional condition As String = "") As Integer

            Return CInt(db.ExecuteScalar(db.CmdHelper.SearchCount(tbName, condition)))
        End Function


        ''' <summary>
        ''' 创建本地测试记录表
        ''' 由于同步数据不会下载测试记录表,所以本地测试记录表需要手动创建
        ''' <param name="projectIndex">项目索引</param>
        ''' <param name="stationIndex">工艺站索引</param>
        ''' </summary>
        Public Shared Sub UtsCreateTestLogTableToLocal(projectIndex As Integer, stationIndex As Integer)
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                db.ExecuteNonQuery(TestLogTable.CreateTableString(String.Empty, TestLogTable.TableName(projectIndex, stationIndex), db.DatabaseType))

                db.Close()
            End Using
        End Sub

        ''' <summary>
        ''' 创建本地测试记录表
        ''' 由于同步数据不会下载测试记录表,所以本地测试记录表需要手动创建
        ''' </summary>
        ''' <param name="tbName">测试记录表名</param>
        Public Shared Sub UtsCreateTestLogTableToLocal(tbName As String)
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                db.ExecuteNonQuery(TestLogTable.CreateTableString(String.Empty, tbName, db.DatabaseType))

                db.Close()
            End Using
        End Sub

        Public Shared Sub UtsCreateTestLogTableToLocal(db As DbExecutor, tbName As String)
            db.ExecuteNonQuery(TestLogTable.CreateTableString(String.Empty, tbName, db.DatabaseType))
        End Sub

        ''' <summary>
        ''' 获取指定表中未存在的数据列集合
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        '''  <param name="dbName">需要查询的数据库名</param>
        ''' <param name="tbName">需要查询的数据表名</param>
        ''' <param name="fieldName">需要查询的字段名集合</param>
        ''' <returns></returns>
        Public Shared Function GetUnExistsColList(db As DbExecutor, dbName As String, tbName As String, fieldName As List(Of String)) As List(Of String)
            Dim colList As New List(Of String)
            Dim dtCol As DataTable = db.ExecuteDataTable(db.CmdHelper.DbSearchAll(dbName, tbName, "1 = 0"))

            For Each colName As String In fieldName
                If String.IsNullOrWhiteSpace(colName) Then Continue For '剔除无效数据库字段名

                If dtCol.Columns.Contains(colName) = False Then '当前数据表是否已经存在对应列信息
                    colList.Add(colName)
                End If
            Next

            Return colList
        End Function


        ''' <summary>
        ''' 检测测试记录字段名是否存在远端数据库，如果不存在则新增，存在则检测字段长度是否需要加长
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="dbName">数据库名</param>
        ''' <param name="tbName">数据表名</param>
        ''' <param name="field">测试记录字段集合</param>
        Public Shared Sub CheckTestLogFiledToRemote(db As DbExecutor, dbName As String, tbName As String, field As Dictionary(Of String, String))
            Dim dtCol As DataTable = db.ExecuteDataTable(db.CmdHelper.DbSearchAll(dbName, tbName, "1 = 0"))

            Dim fieldName As List(Of String) = field.Keys.ToList
            Dim typeString As String
            Dim length As Integer
            For Each colName As String In fieldName
                If String.IsNullOrWhiteSpace(colName) Then Continue For '剔除无效数据库字段名

                If dtCol.Columns.Contains(colName) Then '当前数据表是否已经存在对应列信息
                    Select Case dtCol.Columns(colName).DataType.Name
                        Case "String" '仅处理VarChar类型
                            If field(colName).Length > dtCol.Columns(colName).MaxLength Then
                                length = GetFiledLength(field(colName).Length)
                                If length = -1 Then
                                    Throw New Exception($"字段[{colName}] 超过最大长度2048的限制,无法入库!")
                                Else
                                    typeString = $"varchar({length})"
                                End If

                                '修改列字段长度
                                db.ExecuteNonQuery($"Call `{dbName}`.`AlterTestLogFiled`('{dbName}','{tbName}','{colName}','{length}')")
                            End If
                        Case Else
                            Console.WriteLine(colName & ":" & dtCol.Columns(colName).DataType.Name)
                    End Select
                Else
                    length = GetFiledLength(field(colName).Length)
                    If length = -1 Then
                        Throw New Exception($"字段[{colName}] 超过最大长度4096的限制,无法入库!")
                    Else
                        typeString = $"varchar({length})"
                    End If

                    '插入字段语句
                    db.ExecuteNonQuery($"Call `{dbName}`.`AlterTestLogFiled`('{dbName}','{tbName}','{colName}','{length}')")
                End If
            Next
        End Sub

        ''' <summary>
        ''' 检测测试记录字段名是否存在远端数据库，如果不存在则新增，存在则检测字段长度是否需要加长
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="dbName">数据库名</param>
        ''' <param name="tbName">数据表名</param>
        ''' <param name="field">测试记录字段集合</param>
        Public Shared Sub CheckTestLogFiledToLocal(db As DbExecutor, dbName As String, tbName As String, field As Dictionary(Of String, String), Optional saveCache As Boolean = True)
            Dim dtCol As DataTable = db.ExecuteDataTable(db.CmdHelper.DbSearchAll(dbName, tbName, "1 = 0"))

            Dim fieldName As List(Of String) = field.Keys.ToList
            Dim typeString As String
            Dim length As Integer
            For Each colName As String In fieldName
                If String.IsNullOrWhiteSpace(colName) Then Continue For '剔除无效数据库字段名

                length = GetFiledLength(field(colName).Length)
                If length = -1 Then
                    Throw New Exception($"字段[{colName}] 超过最大长度2048的限制,无法入库!")
                Else
                    typeString = $"varchar({length})"
                End If

                If dtCol.Columns.Contains(colName) Then '当前数据表是否已经存在对应列信息
                    Select Case dtCol.Columns(colName).DataType.Name
                        Case "String" '仅处理VarChar类型
                            If field(colName).Length > dtCol.Columns(colName).MaxLength Then
                                '修改字段语句
                                If db.DatabaseType = DbExecutor.DbTypeEnum.Sqlite Then
                                    '由于sqlite的特殊性，varchar类型不需要修改长度
                                Else
                                    Throw New Exception($"暂未支持[{db.DatabaseType}]该类型数据库，请联系管理员添加支持！")
                                End If

                                If saveCache Then
                                    Dim cmdText As String = $"Call `{UtsDb.RemotePrivateDb}`.`AlterTestLogFiled`('{UtsDb.RemotePrivateDb}','{tbName}','{colName}','{length}')"
                                    SaveCmdStringToCacheTable(db, cmdText) '执行命令入缓存库
                                End If
                            End If
                        Case Else
                            Console.WriteLine("Other ColName - " & colName & ":" & dtCol.Columns(colName).DataType.Name)
                    End Select
                Else
                    '插入字段语句
                    db.ExecuteNonQuery(db.CmdHelper.DbAddCol(dbName, tbName, colName, typeString))

                    If saveCache Then
                        Dim cmdText As String = $"Call `{UtsDb.RemotePrivateDb}`.`AlterTestLogFiled`('{UtsDb.RemotePrivateDb}','{tbName}','{colName}','{length}')"
                        SaveCmdStringToCacheTable(db, cmdText) '执行命令入缓存库
                    End If
                End If
            Next
        End Sub

        Private Shared Function GetFiledLength(len As Integer) As Integer
            Dim result As Integer
            If len = 0 Then
                result = 8
            ElseIf len <= 2048 Then
                If len Mod 8 = 0 Then
                    result = len
                Else
                    result = ((len \ 8) + 1) * 8
                End If
            Else
                result = -1
            End If
            Return result
        End Function
#End Region

#Region "远程执行"

        Public Shared Sub UtsInsetOrUpdateToRemote(dbName As String, tbName As String, field As Dictionary(Of String, String), condition As String)

            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()

                Dim remoteDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名

                CheckTestLogFiledToRemote(db, remoteDbName, tbName, field)

                InsetOrUpdate(db, remoteDbName, tbName, field, condition)

                db.Close()
            End Using
        End Sub


        Public Shared Sub UtsInsertToRemote(dbName As String, tbName As String, field As Dictionary(Of String, String))
            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()

                Dim remoteDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名

                CheckTestLogFiledToRemote(db, remoteDbName, tbName, field)

                Insert(db, remoteDbName, tbName, field)

                db.Close()
            End Using
        End Sub

        Public Shared Sub UtsInsertToRemote(db As DbExecutor, dbName As String, tbName As String, field As Dictionary(Of String, String))
            Dim remoteDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名

            CheckTestLogFiledToRemote(db, remoteDbName, tbName, field)

            Insert(db, remoteDbName, tbName, field)
        End Sub


        Public Shared Sub UtsUpdateToRemote(dbName As String, tbName As String, field As Dictionary(Of String, String), condition As String)
            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()

                Dim remoteDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名

                CheckTestLogFiledToRemote(db, remoteDbName, tbName, field)

                Update(db, remoteDbName, tbName, field, condition)

                db.Close()
            End Using
        End Sub
#End Region

#Region "本地执行"
        ''' <summary>
        ''' 在指定数据表中添加指定字段集合
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="tbName">需要查询的数据表名</param>
        ''' <param name="field">添加字段的键值对，键为字段名，值为列的修饰</param>
        ''' <param name="saveCache">是否将执行命令保存到缓存表中</param>
        Public Shared Sub UtsAddColsToLocal(db As DbExecutor, dbName As String, tbName As String, field As Dictionary(Of String, String), Optional saveCache As Boolean = True)
            Dim localDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名
            Dim remoteDbName As String = dbName

            For Each colName As KeyValuePair(Of String, String) In field
                db.ExecuteNonQuery(db.CmdHelper.DbAddCol(localDbName, tbName, colName.Key, colName.Value))

                If saveCache = False Then Continue For '执行命令不保存在缓冲区则退出执行

                Dim cmdHelper As DbCmdHelper = DbCmdHelper.CreateCmdHelper(UtsDb.RemoteDbType)
                SaveCmdStringToCacheTable(db, cmdHelper.DbAddCol(remoteDbName, tbName, colName.Key, colName.Value)) '执行命令入缓存库
            Next

        End Sub


        Public Shared Sub UtsInsetOrUpdateToLocal(dbName As String, tbName As String, field As Dictionary(Of String, String), condition As String, Optional saveCache As Boolean = True)
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                Dim localDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名
                Dim remoteDbName As String = dbName

                If CInt(db.ExecuteScalar(db.CmdHelper.DbSearchCount(localDbName, tbName, condition))) > 0 Then
                    UtsUpdateToLocal(db, remoteDbName, tbName, field, condition, saveCache)
                Else
                    UtsInsertToLocal(db, remoteDbName, tbName, field, saveCache)
                End If

                db.Close()
            End Using

        End Sub


        Public Shared Sub UtsInsertToLocal(dbName As String, tbName As String, field As Dictionary(Of String, String), Optional saveCache As Boolean = True)
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                UtsInsertToLocal(db, dbName, tbName, field, saveCache)

                db.Close()
            End Using
        End Sub


        Public Shared Sub UtsInsertToLocal(db As DbExecutor, dbName As String, tbName As String, field As Dictionary(Of String, String), Optional saveCache As Boolean = True)
            Dim localDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名
            Dim remoteDbName As String = dbName

            CheckTestLogFiledToLocal(db, localDbName, tbName, field， saveCache)

            Dim cmdText As String = db.CmdHelper.DbInsert(localDbName, tbName, field)
            db.ExecuteNonQuery(cmdText) '执行语句

            If saveCache = False Then Return '执行命令不保存在缓冲区则退出执行

            Dim cmdHelper As DbCmdHelper = DbCmdHelper.CreateCmdHelper(UtsDb.RemoteDbType)
            SaveCmdStringToCacheTable(db, cmdHelper.DbInsert(remoteDbName, tbName, field)) '执行命令入缓存库

        End Sub


        Public Shared Sub UtsUpdateToLocal(dbName As String, tbName As String, field As Dictionary(Of String, String), condition As String, Optional saveCache As Boolean = True)
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                UtsUpdateToLocal(db, dbName, tbName, field, condition, saveCache)

                db.Close()
            End Using
        End Sub


        ''' <summary>
        ''' 过滤数据库名，当前sqlite数据库不需要指定库名
        ''' </summary>
        ''' <param name="dbType"></param>
        ''' <param name="dbName"></param>
        ''' <returns></returns>
        Public Shared Function UtsFilterDbName(dbType As DbExecutor.DbTypeEnum, dbName As String) As String
            If dbType = DbExecutor.DbTypeEnum.Sqlite Then 'sqlite数据库不需要指定dbName
                Return String.Empty
            Else
                Return dbName
            End If
        End Function


        Public Shared Sub UtsUpdateToLocal(db As DbExecutor, dbName As String, tbName As String, field As Dictionary(Of String, String), condition As String, Optional saveCache As Boolean = True)
            Dim localDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名
            Dim remoteDbName As String = dbName

            CheckTestLogFiledToLocal(db, localDbName, tbName, field， saveCache)

            Dim cmdText As String = db.CmdHelper.DbUpdate(localDbName, tbName, field, condition)
            db.ExecuteNonQuery(cmdText) '执行语句

            If saveCache = False Then Return '执行命令不保存在缓冲区则退出执行

            Dim cmdHelper As DbCmdHelper = DbCmdHelper.CreateCmdHelper(UtsDb.RemoteDbType)
            SaveCmdStringToCacheTable(db, cmdHelper.DbUpdate(remoteDbName, tbName, field, condition)) '执行命令入缓存库
        End Sub

        ''' <summary>
        ''' 保存执行语句到缓存表中
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="commandText">Sql语句</param>
        Public Shared Sub SaveCmdStringToCacheTable(db As DbExecutor, commandText As String)
            'todo：更改入库方式
            Dim colName As String
            Dim colNames As New List(Of String)
            db.ClearDbParameter()

            colName = $"{CacheTable.ColNamesEnum.DateTime}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.DateTime, colName, $"{Now:yyyy-MM-dd HH:mm:ss}")

            colName = $"{CacheTable.ColNamesEnum.SqlCmd}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.AnsiString, colName, commandText)

            colName = $"{CacheTable.ColNamesEnum.IsUpload}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.Boolean, colName, False)

            Try
                db.ExecuteNonQuery(db.CmdHelper.InsertParam(CacheTable.TableName, colNames))
            Catch ex As Exception
                Console.WriteLine($"SaveCmdStringToCacheTable DbType:{db.DatabaseType} Error:{ex.Message}")
            End Try
        End Sub

        ''' <summary>
        ''' 保存执行语句到缓存表中
        ''' </summary>
        ''' <param name="commandText">Sql语句</param>
        Public Shared Sub SaveCmdStringToCacheTable(commandText As String)
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                SaveCmdStringToCacheTable(db, commandText)

                db.Close()
            End Using
        End Sub

#End Region

#Region "指定执行句柄特殊操作"
        ''' <summary>
        ''' 查询对应产品名的对应产品索引,指定执行器方式
        ''' </summary>
        ''' <param name="db"></param>
        ''' <param name="dbName"></param>
        ''' <param name="projectName"></param>
        ''' <returns></returns>
        Public Shared Function SearchProjectIndex(db As DbExecutor, dbName As String, projectName As String) As Integer
            Dim tbName As String = ProjectTable.TableName
            Dim colName As String = $"`{ProjectTable.ColNames.ID}`"
            Dim condition As String = $"`{ProjectTable.ColNames.ProjectName}` = '{projectName}'"
            Return CInt(db.ExecuteScalar(db.CmdHelper.DbSearch(dbName, colName, tbName, condition)))
        End Function

        Public Shared Function SearchStationIndex(db As DbExecutor, dbName As String, projectIndex As Integer, stationName As String) As Integer
            Dim tbName As String = StationListTable.TableName
            Dim colName As String = $"`{StationListTable.ColNames.ID}`"
            Dim condition As String = $"`{StationListTable.ColNames.ProjectID}` = {projectIndex} and `{StationListTable.ColNames.StationName}` = '{stationName}'"

            Return CInt(db.ExecuteScalar(db.CmdHelper.DbSearch(dbName, colName, tbName, condition)))
        End Function


        Public Shared Function SearchProjectIndex(db As DbExecutor, projectName As String) As Integer
            Dim tbName As String = ProjectTable.TableName
            Dim colName As String = $"`{ProjectTable.ColNames.ID}`"
            Dim condition As String = $"`{ProjectTable.ColNames.ProjectName}` = '{projectName}'"
            Return CInt(db.ExecuteScalar(db.CmdHelper.Search(colName, tbName, condition)))
        End Function

        Public Shared Function SearchStationIndex(db As DbExecutor, projectIndex As Integer, stationName As String) As Integer
            Dim tbName As String = StationListTable.TableName
            Dim colName As String = $"`{StationListTable.ColNames.ID}`"
            Dim condition As String = $"`{StationListTable.ColNames.ProjectID}` = {projectIndex} and `{StationListTable.ColNames.StationName}` = '{stationName}'"

            Return CInt(db.ExecuteScalar(db.CmdHelper.Search(colName, tbName, condition)))
        End Function

        Public Shared Function SearchStationIndex(db As DbExecutor, projectName As String, stationName As String) As Integer


            Return SearchStationIndex(db, SearchProjectIndex(db, projectName), stationName)
        End Function

#End Region

#Region "通用自动识别"
        ''' <summary>
        ''' 根据判断条件获取数据库是否存在数据，若存在则更新该数据，不存在则插入一条数据
        ''' </summary>
        ''' <param name="dbName">数据库名，账号操作多库时必填</param>
        ''' <param name="tbName">数据表名</param>
        ''' <param name="field">需要更新或插入的数据</param>
        ''' <param name="condition">判断条件,如 `Sn` = '1001'</param>
        Public Shared Sub UtsInsertOrUpdate(dbName As String, tbName As String, field As Dictionary(Of String, String), condition As String)

            If CanConnectToRemote() Then
                UtsInsetOrUpdateToRemote(dbName, tbName, field, condition)
                UtsInsetOrUpdateToLocal(dbName, tbName, field, condition, False)
            Else
                UtsInsetOrUpdateToLocal(dbName, tbName, field, condition, True)
            End If
        End Sub


        Public Shared Sub UtsInsert(dbName As String, tbName As String, field As Dictionary(Of String, String))
            If CanConnectToRemote() Then
                UtsInsertToRemote(dbName, tbName, field)
                UtsInsertToLocal(dbName, tbName, field, False)
            Else
                UtsInsertToLocal(dbName, tbName, field, True)
            End If

        End Sub


        Public Shared Sub UtsUpdate(dbName As String, tbName As String, field As Dictionary(Of String, String), condition As String)
            If CanConnectToRemote() Then
                UtsUpdateToRemote(dbName, tbName, field, condition)
                UtsUpdateToLocal(dbName, tbName, field, condition, False)
            Else
                UtsUpdateToLocal(dbName, tbName, field, condition, True)
            End If

        End Sub
#End Region

#Region "特殊自动识别"
        ''' <summary>
        ''' 获取匹配的用户信息
        ''' </summary>
        ''' <param name="userAccount">用户账号</param>
        ''' <param name="userPassword">用户密码</param>
        ''' <returns></returns>
        Public Shared Function UtsGetUserInfo(userAccount As String, userPassword As String) As DataTable
            Dim dtUser As DataTable

            Dim tbName As String = UserListTable.TableName

            'Momo 2022-09-23 修正SQL_Lite 查询语句拼接问题 (在CMJ发现断网登录无法通过本地数据库登录 --- 已修正)
            'Dim condition As String = $"`{UserListTable.ColNamesEnum.UserName}` = @user and `{UserListTable.ColNamesEnum.Password}` = @pwd"
            Dim md5Password As String = Md5.GetStringMd5(Md5.GetStringMd5(userPassword))
            Dim condition As String = "UserName" & " = '" & userAccount & "' And " &
                                      "Password" & " = '" & md5Password & "'"


            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                db.AddDbParameter(DbType.AnsiString, "user", userAccount)
                db.AddDbParameter(DbType.AnsiString, "pwd", Md5.GetStringMd5(Md5.GetStringMd5(userPassword)))

                dtUser = db.ExecuteDataTable(db.CmdHelper.SearchAll(tbName, condition))

                db.Close()
            End Using

            'todo:厂商校验

            '本地查询到匹配用户信息
            If dtUser.Rows.Count <> 0 Then Return dtUser

            '本地未查询到用户,从云端查询
            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()

                db.AddDbParameter(DbType.AnsiString, "user", userAccount)
                db.AddDbParameter(DbType.AnsiString, "pwd", Md5.GetStringMd5(Md5.GetStringMd5(userPassword)))

                dtUser = db.ExecuteDataTable(db.CmdHelper.DbSearchAll(UtsDb.RemotePublicDb, tbName, condition))

                db.Close()
            End Using

            Return dtUser
        End Function


        ''' <summary>
        ''' 保存指定字段得测试记录至指定表格中。
        ''' 直接执行保存操作，未检测表格是否存在。
        ''' 保存失败则会抛出异常。
        ''' </summary>
        ''' <param name="tbName">数据表名</param>
        ''' <param name="field">字段内容</param>
        Public Shared Sub SaveTestRecord(tbName As String, field As Dictionary(Of String, String))

            If CanConnectToRemote() Then
                UtsInsertToRemote(UtsDb.RemotePrivateDb, tbName, field)

                UtsInsertToLocal(UtsDb.RemotePrivateDb, tbName, field, False)
            Else
                UtsInsertToLocal(UtsDb.RemotePrivateDb, tbName, field, True)
            End If
        End Sub

        ''' <summary>
        ''' 新增SN至云端总表，仅针对产品条码生成方式为测试录入的类型
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="dbName">数据库名</param>
        ''' <param name="station">站位信息</param>
        ''' <param name="result">测试结果</param>
        Public Shared Sub InsertBarcodeToRemote(db As DbExecutor, dbName As String, station As ProcessStation, result As TestResult)
            If station.SnType <> ProcessStation.SnTypeEnum.Test Then Return

            Dim condition As String = $"`{SnListTable.ColNames.BarCode}` = '{result.DUT_SN}' and `{SnListTable.ColNames.SnType}` = " & ProcessStation.SnTypeEnum.Test
            Dim cmd As String = db.CmdHelper.DbSearchCount(dbName, SnListTable.TableName, condition)
            If CInt(db.ExecuteScalar(cmd)) > 0 Then Return

            'Momo 2022-09-05 SnType由文本转换为数字，否则调用数据库存储过程出错
            Dim tmpSnTypeVale As String = "0"
            Select Case station.SnType
                Case ProcessStation.SnTypeEnum.None
                    tmpSnTypeVale = "0"
                Case ProcessStation.SnTypeEnum.Auto
                    tmpSnTypeVale = "1"
                Case ProcessStation.SnTypeEnum.Test
                    tmpSnTypeVale = "2"
                Case ProcessStation.SnTypeEnum.Excel
                    tmpSnTypeVale = "3"
                Case Else
                    tmpSnTypeVale = "0"
            End Select

            '采用存储过程
            'cmd = $"Call {dbName}.AlterSnListBarcode(-1,-1,{station.ParentProject.Index},'{result.DUT_SN}',{station.SnType})"
            cmd = $"Call {dbName}.AlterSnListBarcode(-1,-1,{station.ParentProject.Index},'{result.DUT_SN}','{tmpSnTypeVale}')"
            db.ExecuteNonQuery(cmd)
        End Sub

        ''' <summary>
        ''' 新增SN至本地总表，仅针对产品条码生成方式为测试录入的类型
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="dbName">数据库名</param>
        ''' <param name="station">站位信息</param>
        ''' <param name="result">测试结果</param>
        ''' <param name="saveCache">是否将结果保存至本地缓存表</param>
        Public Shared Sub InsertBarcodeToLocal(db As DbExecutor, dbName As String, station As ProcessStation, result As TestResult, Optional saveCache As Boolean = True)
            If station.SnType <> ProcessStation.SnTypeEnum.Test Then Return

            'Momo 2022-09-05 SnType由文本转换为数字，否则调用数据库存储过程出错
            Dim tmpSnTypeVale As String = "0"
            Select Case station.SnType
                Case ProcessStation.SnTypeEnum.None
                    tmpSnTypeVale = "0"
                Case ProcessStation.SnTypeEnum.Auto
                    tmpSnTypeVale = "1"
                Case ProcessStation.SnTypeEnum.Test
                    tmpSnTypeVale = "2"
                Case ProcessStation.SnTypeEnum.Excel
                    tmpSnTypeVale = "3"
                Case Else
                    tmpSnTypeVale = "0"
            End Select

            ' 注意单引号，SnType必须是数字
            'Dim condition As String = $"`{SnListTable.ColNames.BarCode}` = '{result.DUT_SN}' and `{SnListTable.ColNames.SnType}` = " & ProcessStation.SnTypeEnum.Test
            Dim condition As String = $"'{SnListTable.ColNames.BarCode}' = '{result.DUT_SN}' and '{SnListTable.ColNames.SnType}' = '{tmpSnTypeVale}'"

            '注意不要加数据库名
            'Dim cmdText As String = db.CmdHelper.DbSearchCount(dbName, SnListTable.TableName, condition
            Dim cmdText As String = db.CmdHelper.DbSearchCount("", SnListTable.TableName, condition)

            If CInt(db.ExecuteScalar(cmdText)) > 0 Then Return




            'Dim filed As New Dictionary(Of String, String) From {
            '    {$"{SnListTable.ColNames.ProductID}", station.ParentProject.Index.ToString},
            '    {$"{SnListTable.ColNames.BarCode}", result.DUT_SN},
            '    {$"{SnListTable.ColNames.SnType}", station.SnType.ToString},
            '    {$"{SnListTable.ColNames.OrderID}", "-1"},
            '    {$"{SnListTable.ColNames.OrderInternalID}", "-1"}

            'CreateTime不能为空
            Dim filed As New Dictionary(Of String, String) From {
                {$"{SnListTable.ColNames.ProductID}", station.ParentProject.Index.ToString},
                {$"{SnListTable.ColNames.BarCode}", result.DUT_SN},
                {$"{SnListTable.ColNames.CreateTime}", $"{Now:yyyy-MM-dd HH:mm:ss}"},
                {$"{SnListTable.ColNames.UpdateTime}", $"{Now:yyyy-MM-dd HH:mm:ss}"},
                {$"{SnListTable.ColNames.SnType}", tmpSnTypeVale},
                {$"{SnListTable.ColNames.OrderID}", "-1"},
                {$"{SnListTable.ColNames.OrderInternalID}", "-1"}
            }


            '注意不要加数据库名
            'cmdText = db.CmdHelper.DbInsert(dbName, SnListTable.TableName, filed)
            cmdText = db.CmdHelper.DbInsert("", SnListTable.TableName, filed)

            db.ExecuteNonQuery(cmdText)

            If saveCache Then
                '采用存储过程
                'cmdText = $"Call {UtsDb.RemotePrivateDb}.AlterSnListBarcode(-1,-1,{station.ParentProject.Index},'{result.DUT_SN}',{station.SnType})"
                cmdText = $"Call {UtsDb.RemotePrivateDb}.AlterSnListBarcode(-1,-1,{station.ParentProject.Index},'{result.DUT_SN}','{tmpSnTypeVale}')"
                SaveCmdStringToCacheTable(db, cmdText)
            End If
        End Sub


        ''' <summary>
        ''' 更新Sn总表内容至远端数据库
        ''' </summary>
        ''' <param name="db">DB执行器</param>
        ''' <param name="dbName">数据库名</param>
        ''' <param name="station">当前站位信息</param>
        ''' <param name="result">当前测试结果</param>
        Public Shared Sub UpdateSnListTableToRemote(db As DbExecutor, dbName As String, station As ProcessStation, result As TestResult)
            Dim timeString As String = $"{result.StartTime:yyyy-MM-dd HH:mm:ss}"
            Dim logResult As Integer = CInt(IIf(result.TestResult = TestResult.TestResultEnum.Pass, 1, 0))
            Dim a1String As String = ""
            Dim MoId As String = "-1"
            'A类型站额外更新组装字段
            If station.StationType = ProcessStation.StationTypeEnum.Assem Then
                a1String = result.CustomRecord("AssemblySn")
            End If

            'Dim sqlText As String = $"Call `{dbName}`.`UpdateSnListBarcode`('{result.DUT_SN}','{station.SnListOrder},'{timeString}',{logResult},'{a1String}');" '‘错误的格式’
            'Momo 2023-11-10 修正格式
            'Dim sqlText As String = $"Call `{dbName}`.`UpdateSnListBarcode`('{result.DUT_SN}',{station.SnListOrder},'{timeString}',{logResult},'{a1String}',{MoId});"
            'Momo 2024-05-10 修正：存储过程 UpdateSnListBarcode 不带 MoID，存储过程 UpdateSnListBarcode_MO 带MoID
            Dim sqlText As String = $"Call `{dbName}`.`UpdateSnListBarcode`('{result.DUT_SN}',{station.SnListOrder},'{timeString}',{logResult},'{a1String}');"


            'CZH 2023 06 07 增加SN_list MoId 
            If result.CustomRecord.ContainsKey("InternalNo") And result.TestResult = TestResult.TestResultEnum.Pass Then
                MoId = result.CustomRecord("OrderID")
                sqlText = $"Call `{dbName}`.`UpdateSnListBarcode_MO`('{result.DUT_SN}',{station.SnListOrder},'{timeString}',{logResult},'{a1String}',{MoId});"
            End If
            ''''''''''''''''''
            db.ExecuteNonQuery(sqlText)

            '发送广播通知局域网其他设备
            Dim app As UtsAppForm = UtsAppForm.CreateSingleton
            Dim fileds As New Dictionary(Of String, String)
            fileds.Add("DB", dbName) '用于区分是否同一厂商
            fileds.Add("Barcode", result.DUT_SN)
            fileds.Add("SnListOrder", station.SnListOrder.ToString)
            fileds.Add("StartTime", timeString)
            fileds.Add("Result", logResult.ToString)
            fileds.Add("A1String", a1String)
            app.SendAppMsg(Service.TaskJsonParam.AppMsgTypes.SnListChanged, fileds)
        End Sub

        Public Shared Sub UpdateSnListTableToLocal(db As DbExecutor, dbName As String, station As ProcessStation, result As TestResult, Optional saveCache As Boolean = True)
            Dim timeString As String = $"{result.StartTime:yyyy-MM-dd HH:mm:ss}"
            Dim logResult As Integer = CInt(IIf(result.TestResult = TestResult.TestResultEnum.Pass, 1, 0))
            Dim a1String As String = ""

            Dim localDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名
            Dim updateString As String = $"`S{station.SnListOrder}` = '{timeString}',`Result{station.SnListOrder}` = {logResult}"
            Dim MoId As String = "-1"
            'A类型站额外更新组装字段
            If station.StationType = ProcessStation.StationTypeEnum.Assem Then
                'a1String = result.CustomRecord("AssemblySn")
                updateString &= $",`{SnListTable.ColNames.AssemblySn}` = '{a1String}',`{SnListTable.ColNames.AssemblyTime}` = '{timeString}'"
            End If

            Dim condition As String = $"`{SnListTable.ColNames.ProductID}` = '{station.ParentProject.Index}' and `{SnListTable.ColNames.BarCode}` = '{result.DUT_SN}'"
            Dim cmdText As String = db.CmdHelper.DbUpdate(localDbName, SnListTable.TableName, updateString, condition)
            db.ExecuteNonQuery(cmdText)

            If saveCache Then
                cmdText = $"Call `{UtsDb.RemotePrivateDb}`.`UpdateSnListBarcode`('{result.DUT_SN}',{station.SnListOrder},'{timeString}',{logResult},'{a1String}');"
                'CZH 2023 06 07 增加SN_list MoId 
                If result.CustomRecord.ContainsKey("OrderID") Then
                    MoId = result.CustomRecord("OrderID")
                    cmdText = $"Call `{dbName}`.`UpdateSnListBarcode_MO`('{result.DUT_SN}',{station.SnListOrder},'{timeString}',{logResult},'{a1String}',{MoId});"
                End If
                ''''''''''''''''''

                SaveCmdStringToCacheTable(db, cmdText)

                '发送广播通知局域网其他设备
                Dim app As UtsAppForm = UtsAppForm.CreateSingleton
                Dim fileds As New Dictionary(Of String, String)
                fileds.Add("DB", dbName) '用于区分是否同一厂商
                fileds.Add("Barcode", result.DUT_SN)
                fileds.Add("SnListOrder", station.SnListOrder.ToString)
                fileds.Add("StartTime", timeString)
                fileds.Add("Result", logResult.ToString)
                fileds.Add("A1String", a1String)
                app.SendAppMsg(Service.TaskJsonParam.AppMsgTypes.SnListChanged, fileds)
            End If
        End Sub

        ''' <summary>
        ''' 更新SNList表指定字段名称的值
        ''' </summary>
        ''' <param name="db"></param>
        ''' <param name="dbName"></param>
        ''' <param name="filedNames"></param>
        ''' <param name="filedValues"></param>
        ''' <param name="saveCache"></param>
        Public Shared Sub UpdateSnListTableToLocal(db As DbExecutor, dbName As String, filedNames As List(Of String), filedValues As List(Of String), Optional saveCache As Boolean = True)
            'Dim timeString As String = $"{result.StartTime:yyyy-MM-dd HH:mm:ss}"
            'Dim logResult As Integer = CInt(IIf(result.TestResult = TestResult.TestResultEnum.Pass, 1, 0))
            'Dim a1String As String = ""

            'Dim localDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名
            'Dim updateString As String = $"`S{Station.SnListOrder}` = '{timeString}',`Result{Station.SnListOrder}` = {logResult}"
            'Dim MoId As String = "-1"
            ''A类型站额外更新组装字段
            'If Station.StationType = ProcessStation.StationTypeEnum.Assem Then
            '    'a1String = result.CustomRecord("AssemblySn")
            '    updateString &= $",`{SnListTable.ColNames.AssemblySn}` = '{a1String}',`{SnListTable.ColNames.AssemblyTime}` = '{timeString}'"
            'End If

            'Dim condition As String = $"`{SnListTable.ColNames.ProductID}` = '{Station.ParentProject.Index}' and `{SnListTable.ColNames.BarCode}` = '{result.DUT_SN}'"
            'Dim cmdText As String = db.CmdHelper.DbUpdate(localDbName, SnListTable.TableName, updateString, condition)
            'db.ExecuteNonQuery(cmdText)

            'If saveCache Then
            '    cmdText = $"Call `{UtsDb.RemotePrivateDb}`.`UpdateSnListBarcode`('{result.DUT_SN}',{Station.SnListOrder},'{timeString}',{logResult},'{a1String}');"
            '    'CZH 2023 06 07 增加SN_list MoId 
            '    If result.CustomRecord.ContainsKey("OrderID") Then
            '        MoId = result.CustomRecord("OrderID")
            '        cmdText = $"Call `{dbName}`.`UpdateSnListBarcode_MO`('{result.DUT_SN}',{Station.SnListOrder},'{timeString}',{logResult},'{a1String}',{MoId});"
            '    End If
            '    ''''''''''''''''''

            '    SaveCmdStringToCacheTable(db, cmdText)
            'End If
        End Sub


        ''' <summary>
        ''' 更新本地SN总表的测试记录(用于处理组播写入Sn总表操作)
        ''' </summary>
        ''' <param name="barcode">测试条码</param>
        ''' <param name="snListOrder">对应总表站位顺序</param>
        ''' <param name="timeString">测试时间</param>
        ''' <param name="result">测试结果</param>
        ''' <param name="a1String">A1站对应条码</param>
        Public Shared Sub UpdateLocalSnList(barcode As String, snListOrder As String, timeString As String, result As String, a1String As String)
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                Dim updateString As String = $"`S{snListOrder}` = '{timeString}',`Result{snListOrder}` = {result}"
                If String.IsNullOrEmpty(a1String) = False Then
                    updateString &= $",`{SnListTable.ColNames.AssemblySn}` = '{a1String}',`{SnListTable.ColNames.AssemblyTime}` = '{timeString}'"
                End If
                Dim condition As String = $"`{SnListTable.ColNames.BarCode}` = '{barcode}'"
                Dim cmdText As String = db.CmdHelper.DbUpdate("", SnListTable.TableName, updateString, condition)

                db.ExecuteNonQuery(cmdText)

                db.Close()
            End Using
        End Sub

        ''' <summary>
        ''' 更新远程订单表订单状态
        ''' </summary>
        ''' <param name="db">数据库句柄</param>
        ''' <param name="dbName">数据库名</param>
        ''' <param name="station">站位信息</param>
        ''' <param name="result">测试结果</param>
        Public Shared Sub UpdateInternalOrderTableToRemote(db As DbExecutor, dbName As String, station As ProcessStation, result As TestResult)
            If result.OrderID = -1 Then Return

            Dim order As InternalOrderManager = InternalOrderManager.CreateManager()
            If order.ID <> result.OrderID Then order.Initialize(result.OrderID)

            Dim cmdText As String
            Dim filed As New Dictionary(Of String, String)
            Dim condition As String = $"`{OrderInternalTable.ColNames.ID}` = {result.OrderID}"
            If station.ArtworkOrder = 1 Then
                '仅在订单状态为3时，更新状态为4

                If order.OrderStatus > 3 Then Return
                filed.Add($"{OrderInternalTable.ColNames.OrderStatus}", "4")

                cmdText = db.CmdHelper.DbUpdate(dbName, OrderInternalTable.TableName, filed, condition)
                db.ExecuteNonQuery(cmdText)

                order.OrderStatus = 4

                Try
                    GetData("http://uts-data.com/api/Common/ClearCache")
                Catch ex As Exception
                    Console.WriteLine($"更新缓存数据失败,{ex.Message}")
                End Try
            End If

        End Sub

        ''' <summary>
        ''' 更新本地订单表订单状态
        ''' </summary>
        ''' <param name="db">数据库句柄</param>
        ''' <param name="dbName">数据库名</param>
        ''' <param name="station">站位信息</param>
        ''' <param name="result">测试结果</param>
        ''' <param name="saveCache">是否将执行命令保存到缓存表中</param>
        Public Shared Sub UpdateInternalOrderTableToLocal(db As DbExecutor, dbName As String, station As ProcessStation, result As TestResult, Optional saveCache As Boolean = True)
            If result.OrderID = -1 Then Return

            Dim order As InternalOrderManager = InternalOrderManager.CreateManager()
            If order.ID <> result.OrderID Then order.Initialize(result.OrderID)

            Dim localDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名
            Dim remoteDbName As String = dbName

            Dim cmdText As String
            Dim filed As New Dictionary(Of String, String)
            Dim condition As String = $"`{OrderInternalTable.ColNames.ID}` = {result.OrderID}"

            If station.ArtworkOrder = 1 Then
                '仅在订单状态为3时，更新状态为4

                If order.OrderStatus > 3 Then Return
                filed.Add($"{OrderInternalTable.ColNames.OrderStatus}", "4")

                cmdText = db.CmdHelper.DbUpdate(localDbName, OrderInternalTable.TableName, filed, condition)
                db.ExecuteNonQuery(cmdText)

                order.OrderStatus = 4

                If saveCache Then
                    Dim cmdHelper As DbCmdHelper = DbCmdHelper.CreateCmdHelper(UtsDb.RemoteDbType)
                    cmdText = cmdHelper.DbUpdate(remoteDbName, OrderInternalTable.TableName, filed, condition)
                    SaveCmdStringToCacheTable(db, cmdText)
                End If
            End If


            'If station.ArtworkOrder = station.ParentProject.Station.Count Then
            '    '仅在订单状态为4且生产数量与目标产品匹配，更新状态为5
            '    If order.OrderStatus > 4 Then Return

            '    '查询订单数量
            '    cmdText = db.CmdHelper.DbSearchCount(localDbName, $"{SnListTable.TableName}", $" `{SnListTable.ColNames.OrderInternalID}` = {order.ID} and `{SnListTable.ColNames.ProductID}` = {order.ProductID} and `Result{station.SnListOrder}` = 1")
            '    Dim total As Integer = CInt(db.ExecuteScalar(cmdText))
            '    If total < order.ObjectiveYield Then Return

            '    '达到目标产能则更换订单状态
            '    filed.Add($"{OrderInternalTable.ColNames.OrderStatus}", "5")
            '    cmdText = db.CmdHelper.DbUpdate(localDbName, OrderInternalTable.TableName, filed, condition)
            '    db.ExecuteNonQuery(cmdText)

            '    order.OrderStatus = 5

            '    If saveCache Then
            '        Dim cmdHelper As DbCmdHelper = DbCmdHelper.CreateCmdHelper(UtsDb.RemoteDbType)
            '        cmdText = cmdHelper.DbUpdate(remoteDbName, OrderInternalTable.TableName, filed, condition)
            '        SaveCmdStringToCacheTable(db, cmdText)
            '    End If
            'End If
        End Sub

        Public Shared Sub UpdateUniqueTestLogToRemote(db As DbExecutor, dbName As String, tbName As String, result As TestResult)
            Dim field As Dictionary(Of String, String) = result.ToStringDictionary()

            '新增不存在的字段
            CheckTestLogFiledToRemote(db, dbName, tbName, field)

            '删除并插入一行数据,实现存在则更新不存在则删除
            Dim condition As String = $"`{TestLogTable.ColNames.DUT_SN}` = '{result.DUT_SN}'"
            Dim cmdText As String = db.CmdHelper.DbDeleteRows(dbName, tbName, condition)
            cmdText &= db.CmdHelper.DbInsert(dbName, tbName, field)
            db.ExecuteNonQuery(cmdText)
        End Sub


        Public Shared Sub UpdateTestLogToRemote(db As DbExecutor, dbName As String, tbName As String, result As TestResult)
            Dim field As Dictionary(Of String, String) = result.ToStringDictionary()

            '新增不存在的字段
            CheckTestLogFiledToRemote(db, dbName, tbName, field)

            '添加测试记录
            Dim cmdText As String = db.CmdHelper.DbInsert(dbName, tbName, field)
            db.ExecuteNonQuery(cmdText)
        End Sub





        ''' <summary>
        ''' 更新本地数据库测试记录，若存在相同条码号的记录则删除后添加
        ''' </summary>
        ''' <param name="db"></param>
        ''' <param name="dbName"></param>
        ''' <param name="tbName"></param>
        ''' <param name="result"></param>
        ''' <param name="saveCache"></param>
        Public Shared Sub UpdateUniqueTestLogToLocal(db As DbExecutor, dbName As String, tbName As String, result As TestResult, Optional saveCache As Boolean = True)
            Dim field As Dictionary(Of String, String) = result.ToStringDictionary()
            Dim localDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名
            Dim remoteDbName As String = dbName

            '增加列
            CheckTestLogFiledToLocal(db, localDbName, tbName, field， saveCache)

            '删除并插入一行数据,实现存在则更新不存在则删除
            Dim condition As String = $"`{TestLogTable.ColNames.DUT_SN}` = '{result.DUT_SN}'"
            Dim cmdText As String = db.CmdHelper.DbDeleteRows(localDbName, tbName, condition)
            cmdText &= db.CmdHelper.DbInsert(localDbName, tbName, field)
            db.ExecuteNonQuery(cmdText)

            '执行命令不保存在缓冲区则退出执行
            If saveCache Then
                Dim cmdHelper As DbCmdHelper = DbCmdHelper.CreateCmdHelper(UtsDb.RemoteDbType)
                cmdText = cmdHelper.DbDeleteRows(remoteDbName, tbName, condition)
                cmdText &= cmdHelper.DbInsert(remoteDbName, tbName, field)
                SaveCmdStringToCacheTable(db, cmdText)
            End If
        End Sub

        ''' <summary>
        ''' 更新本地数据库测试记录
        ''' </summary>
        ''' <param name="db"></param>
        ''' <param name="dbName"></param>
        ''' <param name="tbName"></param>
        ''' <param name="result"></param>
        ''' <param name="saveCache"></param>
        Public Shared Sub UpdateTestLogToLocal(db As DbExecutor, dbName As String, tbName As String, result As TestResult, Optional saveCache As Boolean = True)
            Dim field As Dictionary(Of String, String) = result.ToStringDictionary()

            Dim localDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名
            Dim remoteDbName As String = dbName

            '增加不存在的列
            CheckTestLogFiledToLocal(db, localDbName, tbName, field， saveCache)

            '执行保存操作
            Dim cmdText As String = db.CmdHelper.DbInsert(localDbName, tbName, field)
            db.ExecuteNonQuery(cmdText)

            '执行命令不保存在缓冲区则退出执行
            If saveCache Then
                Dim cmdHelper As DbCmdHelper = DbCmdHelper.CreateCmdHelper(UtsDb.RemoteDbType)
                cmdText = cmdHelper.DbInsert(remoteDbName, tbName, field)
                SaveCmdStringToCacheTable(db, cmdText) '执行命令入缓存库
            End If
        End Sub


        ''' <summary>
        ''' 保存测试记录至云端数据库
        ''' </summary>
        ''' <param name="dbName"></param>
        ''' <param name="tbName"></param>
        ''' <param name="station"></param>
        ''' <param name="result"></param>
        ''' <returns></returns>
        Public Shared Function SaveTestLogToRemote(dbName As String, tbName As String, station As ProcessStation, result As TestResult) As Boolean
            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                Try
                    db.Open()
                Catch ex As Exception
                    Console.WriteLine($"Open remote db error,{ex.Message}")
                    Return False
                End Try

                Dim dbTran As DbTransaction = db.BeginTransaction()

                Try
                    '保存测试记录
                    UpdateTestLogToRemote(db, dbName, tbName, result)

                    '无序列模式，仅保存测试记录
                    If station.SnType <> ProcessStation.SnTypeEnum.None Then
                        '检测是否需要新增Sn，仅当产品sntype为test的时候
                        InsertBarcodeToRemote(db, dbName, station, result)

                        '更新Sn列表
                        UpdateSnListTableToRemote(db, dbName, station, result)

                        '更新内部订单表
                        UpdateInternalOrderTableToRemote(db, dbName, station, result)
                    End If
                Catch ex As Exception
                    Console.WriteLine($"save remote db error,{ex.Message}")

                    dbTran.Rollback() '失败则回滚
                    db.Close()

                    Return False
                End Try

                dbTran.Commit()
                db.Close()
            End Using

            Return True
        End Function

        ''' <summary>
        ''' 保存唯一测试日志至云端数据库,若存在相同条码号的记录则覆盖
        ''' </summary>
        ''' <param name="dbName"></param>
        ''' <param name="tbName"></param>
        ''' <param name="station"></param>
        ''' <param name="result"></param>
        ''' <returns></returns>
        Public Shared Function SaveUniqueTestLogToRemote(dbName As String, tbName As String, station As ProcessStation, result As TestResult) As Boolean
            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                Try
                    db.Open()
                Catch ex As Exception
                    Console.WriteLine($"Open remote db error,{ex.Message}")
                    Return False
                End Try

                Dim remoteDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名
                Dim dbTran As DbTransaction = db.BeginTransaction()
                Try
                    '保存测试记录
                    UpdateUniqueTestLogToRemote(db, remoteDbName, tbName, result)

                    '无序列模式，仅保存测试记录
                    If station.SnType <> ProcessStation.SnTypeEnum.None Then
                        '检测是否需要新增Sn，仅当产品sntype为test的时候
                        InsertBarcodeToRemote(db, dbName, station, result)

                        '更新Sn列表
                        UpdateSnListTableToRemote(db, remoteDbName, station, result)

                        '更新内部订单表
                        UpdateInternalOrderTableToRemote(db, dbName, station, result)
                    End If
                Catch ex As Exception
                    Console.WriteLine($"Save unique remote db error,{ex.Message}")

                    dbTran.Rollback() '失败则回滚
                    db.Close()
                    Return False
                End Try

                dbTran.Commit()
                db.Close()
            End Using

            Return True
        End Function

        ''' <summary>
        ''' 保存测试记录至本地数据库
        ''' </summary>
        ''' <param name="dbName"></param>
        ''' <param name="tbName"></param>
        ''' <param name="station"></param>
        ''' <param name="result"></param>
        ''' <param name="saveCache"></param>
        Public Shared Sub SaveTestLogToLocal(dbName As String, tbName As String, station As ProcessStation, result As TestResult, Optional saveCache As Boolean = True)
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                Try
                    db.Open()
                Catch ex As Exception
                    Throw New Exception($"Open local db error,{ex.Message}")
                End Try


                Dim dbTran As DbTransaction = db.BeginTransaction()

                Try
                    '保存测试记录
                    UpdateTestLogToLocal(db, dbName, tbName, result, saveCache)

                    '无序列模式，仅保存测试记录
                    If station.SnType <> ProcessStation.SnTypeEnum.None Then
                        '检测是否新增Sn至Sn总表
                        InsertBarcodeToLocal(db, dbName, station, result, saveCache)

                        '更新Sn列表测试时间
                        UpdateSnListTableToLocal(db, dbName, station, result, saveCache)

                        '更新内部订单表
                        UpdateInternalOrderTableToLocal(db, dbName, station, result, saveCache)
                    End If
                Catch ex As Exception
                    Try
                        dbTran.Rollback() '失败则回滚
                        db.Close()
                    Catch ex2 As Exception

                    End Try

                    Throw New Exception($"Save test log error,{ex.Message}")
                End Try

                dbTran.Commit()
                db.Close()
            End Using
        End Sub

        ''' <summary>
        ''' 保存唯一测试记录至本地数据库,若存在相同条码号的记录则覆盖
        ''' </summary>
        ''' <param name="dbName"></param>
        ''' <param name="tbName"></param>
        ''' <param name="station"></param>
        ''' <param name="result"></param>
        ''' <param name="saveCache"></param>
        Public Shared Sub SaveUniqueTestLogToLocal(dbName As String, tbName As String, station As ProcessStation, result As TestResult, Optional saveCache As Boolean = True)
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                Try
                    db.Open()
                Catch ex As Exception
                    Throw New Exception($"Open local db error,{ex.Message}")
                End Try

                Dim dbTran As DbTransaction = db.BeginTransaction()
                Try
                    '保存测试记录
                    UpdateUniqueTestLogToLocal(db, dbName, tbName, result, saveCache)

                    '无序列模式，仅保存测试记录
                    If station.SnType <> ProcessStation.SnTypeEnum.None Then
                        '检测是否新增Sn至Sn总表
                        InsertBarcodeToLocal(db, dbName, station, result, saveCache)

                        '更新Sn列表测试时间与结果
                        UpdateSnListTableToLocal(db, dbName, station, result, saveCache)

                        '更新内部订单表
                        UpdateInternalOrderTableToLocal(db, dbName, station, result, saveCache)
                    End If
                Catch ex As Exception
                    Try
                        dbTran.Rollback() '失败则回滚
                        db.Close()
                    Catch ex2 As Exception

                    End Try

                    Throw New Exception($"Save unique test log error,{ex.Message}")
                End Try

                dbTran.Commit()
                db.Close()
            End Using
        End Sub


        ''' <summary>
        ''' 保存唯一测试记录至数据库，若存在相同条码号的记录则覆盖
        ''' </summary>
        ''' <param name="tbName"></param>
        ''' <param name="station"></param>
        ''' <param name="result"></param>
        Public Shared Sub SaveUniqueTestLog(tbName As String, station As ProcessStation, result As TestResult)
            If String.IsNullOrWhiteSpace(result.DUT_SN) Then
                Return
            End If

            Dim saveCache As Boolean
            If CanConnectToRemote() Then
                Try
                    saveCache = SaveUniqueTestLogToRemote(UtsDb.RemotePrivateDb, tbName, station, result) = False
                Catch ex As Exception
                    saveCache = True
                    Console.WriteLine($"SaveUniqueTestLogToRemote Error:{ex.Message}")
                End Try

                SaveUniqueTestLogToLocal(UtsDb.RemotePrivateDb, tbName, station, result, saveCache)
            Else
                saveCache = True
                SaveUniqueTestLogToLocal(UtsDb.RemotePrivateDb, tbName, station, result, saveCache)
            End If
        End Sub


        ''' <summary>
        ''' 保存测试记录至数据库。
        ''' </summary>
        ''' <param name="tbName"></param>
        ''' <param name="station"></param>
        ''' <param name="result"></param>
        Public Shared Sub SaveTestLog(tbName As String, station As ProcessStation, result As TestResult)
            If String.IsNullOrWhiteSpace(result.DUT_SN) Then Return

            Dim saveCache As Boolean
            If CanConnectToRemote() Then
                Try
                    saveCache = SaveTestLogToRemote(UtsDb.RemotePrivateDb, tbName, station, result) = False
                Catch ex As Exception
                    Console.WriteLine($"Save TestLogToRemote Error:{ex.Message}")
                    saveCache = True
                End Try

                SaveTestLogToLocal(UtsDb.RemotePrivateDb, tbName, station, result, saveCache)
            Else
                saveCache = True
                SaveTestLogToLocal(UtsDb.RemotePrivateDb, tbName, station, result, saveCache)
            End If
        End Sub

        Public Shared Function SaveOtherSnToLocal(station As ProcessStation, result As TestResult, Optional saveCache As Boolean = True) As Boolean

            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                Try
                    db.Open()
                Catch ex As Exception
                    Console.WriteLine($"Open local db error,{ex.Message}")
                    Return False
                End Try


                '添加测试记录
                Dim cmdText As String = db.CmdHelper.Insert(TestLogTable.TableName(station.ParentProject.Index, station.StationID), result.ToStringDictionary)

                Try
                    db.ExecuteNonQuery(cmdText)
                Catch ex As Exception
                    Return False
                End Try

                '检测是否新增Sn至Sn总表
                Try
                    InsertBarcodeToLocal(db, "", station, result, saveCache)
                Catch ex As Exception
                    Return False
                End Try

                '更新Sn总表对应站信息
                Dim updateString As String = $"`S{station.SnListOrder}` = '{result.StartTime:yyyy-MM-dd HH:mm:ss}',`Result{station.SnListOrder}` = {IIf(result.TestResult = TestResult.TestResultEnum.Pass, 1, 0)}"

                Dim condition As String = $"`{SnListTable.ColNames.ProductID}` = '{station.ParentProject.Index}' and `{SnListTable.ColNames.BarCode}` = '{result.DUT_SN}'"

                Dim sqlText As String = db.CmdHelper.Update(SnListTable.TableName, updateString, condition)

                Try
                    db.ExecuteNonQuery(sqlText)
                Catch ex As Exception
                    Return False
                End Try

                '执行命令不保存在缓冲区则退出执行
                If saveCache Then
                    Dim cmdHelper As DbCmdHelper = DbCmdHelper.CreateCmdHelper(UtsDb.RemoteDbType)
                    cmdText = cmdHelper.DbInsert(UtsDb.RemotePrivateDb, TestLogTable.TableName(station.ParentProject.Index, station.StationID), result.ToStringDictionary)
                    SaveCmdStringToCacheTable(db, cmdText) '执行命令入缓存库

                    cmdText = cmdHelper.DbUpdate(UtsDb.RemotePrivateDb, SnListTable.TableName, updateString, condition)
                    SaveCmdStringToCacheTable(db, cmdText) '执行命令入缓存库
                End If

                db.Close()
            End Using

            Return True

        End Function


        Public Shared Function SaveOtherSnToRemote(dbName As String, station As ProcessStation, result As TestResult) As Boolean

            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                Try
                    db.Open()
                Catch ex As Exception
                    Console.WriteLine($"Open remote db error,{ex.Message}")
                    Return False
                End Try

                '添加测试记录
                Dim cmdText As String = db.CmdHelper.DbInsert(dbName, TestLogTable.TableName(station.ParentProject.Index, station.StationID), result.ToStringDictionary)
                Try
                    db.ExecuteNonQuery(cmdText)
                Catch ex As Exception
                    Return False
                End Try

                '增加条码检测
                Try
                    InsertBarcodeToRemote(db, dbName, station, result)
                Catch ex As Exception
                    Return False
                End Try

                '更新Sn总表对应站信息
                Dim updateString As String = $"`S{station.SnListOrder}` = '{result.StartTime:yyyy-MM-dd HH:mm:ss}',`Result{station.SnListOrder}` = {IIf(result.TestResult = TestResult.TestResultEnum.Pass, 1, 0)}"

                Dim condition As String = $"`{SnListTable.ColNames.ProductID}` = '{station.ParentProject.Index}' and `{SnListTable.ColNames.BarCode}` = '{result.DUT_SN}'"

                Dim sqlText As String = db.CmdHelper.DbUpdate(dbName, SnListTable.TableName, updateString, condition)

                Try
                    db.ExecuteNonQuery(sqlText)
                Catch ex As Exception
                    Return False
                End Try

                db.Close()
            End Using

            Return True
        End Function

        ''' <summary>
        ''' 更新组装站所有条码中与主条码产品相同的条码的测试信息(除主条码)
        ''' </summary>
        ''' <param name="snLst"></param>
        ''' <param name="station"></param>
        ''' <param name="result"></param>
        Public Shared Sub SaveOtherSn(snLst As List(Of String), station As ProcessStation, result As TestResult)

            Dim dbName As String = UtsDb.RemotePrivateDb

            '0位置存放主条码,从1位置开始
            For i As Integer = 1 To snLst.Count - 1
                '其他类型
                result.DUT_SN = snLst(i)
                result.TestResult = TestResult.TestResultEnum.Pass

                '自定义字段
                result.AddCustomRecord("AssemblySn", String.Empty)

                '查询条码所在的产品ID'与当前产品id符合则新增一条测试记录，并更新序号总表中的站位测试时间
                Dim pid As Integer = SearchProjectIndex(result.DUT_SN)

                If pid = -1 Then
                    If station.SnType = ProcessStation.SnTypeEnum.Test Then
                        Dim saveCache As Boolean
                        If CanConnectToRemote() Then
                            saveCache = SaveOtherSnToRemote(dbName, station, result) = False
                            SaveOtherSnToLocal(station, result, saveCache)
                        Else
                            saveCache = True
                            SaveOtherSnToLocal(station, result, saveCache)
                        End If
                    End If
                ElseIf pid = station.ParentProject.Index Then
                    Dim saveCache As Boolean
                    If CanConnectToRemote() Then
                        saveCache = SaveOtherSnToRemote(dbName, station, result) = False
                        SaveOtherSnToLocal(station, result, saveCache)
                    Else
                        saveCache = True
                        SaveOtherSnToLocal(station, result, saveCache)
                    End If

                End If
            Next

        End Sub


        Public Shared Function AddTestLogColsToRemote(dbName As String, tbName As String, field As Dictionary(Of String, String)) As Boolean

            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                Try
                    db.Open()
                Catch ex As Exception
                    Throw New Exception($"Open remote db error,{ex.Message}")
                End Try


                Dim dbTran As DbTransaction = db.BeginTransaction()

                Try
                    Dim remoteDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名
                    Dim colList As List(Of String) = GetUnExistsColList(db, remoteDbName, tbName, field.Keys.ToList())

                    For Each colName As String In colList
                        db.ExecuteNonQuery(db.CmdHelper.DbAddCol(dbName, tbName, colName, field(colName)))
                    Next

                Catch ex As Exception
                    dbTran.Rollback() '失败则回滚
                    db.Close()

                    Return False
                End Try

                dbTran.Commit()
                db.Close()
            End Using

            Return True
        End Function

        Public Shared Sub AddTestLogColsToLocal(dbName As String, tbName As String, field As Dictionary(Of String, String), Optional saveCache As Boolean = True)
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                Try
                    db.Open()
                Catch ex As Exception
                    Throw New Exception($"Open local db error,{ex.Message}")
                End Try

                Dim dbTran As DbTransaction = db.BeginTransaction()

                Try
                    Dim remoteDbName As String = UtsFilterDbName(db.DatabaseType, dbName) '过滤库名
                    Dim colList As List(Of String) = GetUnExistsColList(db, remoteDbName, tbName, field.Keys.ToList())
                    Dim destField As New Dictionary(Of String, String)

                    For Each colName As String In colList
                        destField.Add(colName, field(colName))
                    Next

                    UtsAddColsToLocal(db, dbName, tbName, destField, saveCache)
                Catch ex As Exception
                    dbTran.Rollback() '失败则回滚
                    db.Close()

                    Throw New Exception($"Add test log cols error,{ex.Message}")
                End Try

                dbTran.Commit()
                db.Close()

            End Using
        End Sub

        ''' <summary>
        ''' 添加指定字段到测试记录表中
        ''' </summary>
        ''' <param name="tbName">测试记录表明</param>
        ''' <param name="field">字段键值对,键为字段名，值为字段描述</param>
        Public Shared Sub AddTestLogCols(tbName As String, field As Dictionary(Of String, String))
            Dim saveCache As Boolean
            If CanConnectToRemote() Then
                saveCache = AddTestLogColsToRemote(UtsDb.RemotePrivateDb, tbName, field) = False
                AddTestLogColsToLocal(UtsDb.RemotePrivateDb, tbName, field, saveCache)
            Else
                saveCache = True
                AddTestLogColsToLocal(UtsDb.RemotePrivateDb, tbName, field, saveCache)
            End If
        End Sub



        ''' <summary>
        ''' 从数据表中查询对应客户订单号的内部订单信息
        ''' </summary>
        ''' <param name="orderID">客户订单索引</param>
        ''' <returns></returns>
        Public Shared Function GetInternalOrder(orderID As Integer) As DataTable
            Dim dtTable As DataTable

            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                Dim colNames As New List(Of String) From {
                        $"{OrderInternalTable.ColNames.ID}",
                        $"{OrderInternalTable.ColNames.OrderID}",
                        $"{OrderInternalTable.ColNames.OrderStatus}",
                        $"{OrderInternalTable.ColNames.CompanyID}",
                        $"{OrderInternalTable.ColNames.ProductID}",
                        $"{OrderInternalTable.ColNames.ProductTypeID}",
                        $"{OrderInternalTable.ColNames.CreateTime}",
                        $"{OrderInternalTable.ColNames.DeliveryTime}",
                        $"{OrderInternalTable.ColNames.InternalNo}",
                        $"{OrderInternalTable.ColNames.ObjectiveYield}",
                        $"{OrderInternalTable.ColNames.ObjectiveYieldTotal}"
                        }

                Dim condition As New StringBuilder
                condition.Append($"`{OrderInternalTable.ColNames.ID}` = {orderID}")

                Dim cmdText As String = db.CmdHelper.Search(colNames, OrderInternalTable.TableName, condition.ToString())

                dtTable = db.ExecuteDataTable(cmdText)

                db.Close()
            End Using

            Return dtTable
        End Function


        ''' <summary>
        ''' 从数据表中查询对应客户订单号的客户订单信息
        ''' </summary>
        ''' <param name="id">客户订单索引</param>
        ''' <returns></returns>
        Public Shared Function SearchCustomerOrder(id As Integer) As CustomerOrderManager
            Dim order As New CustomerOrderManager

            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                Dim colNames As New List(Of String) From {
                        $"{OrdersTable.ColNames.CompanyID}",
                        $"{OrdersTable.ColNames.CostPrice}",
                        $"{OrdersTable.ColNames.TransactPrice}",
                        $"{OrdersTable.ColNames.CreateTime}",
                        $"{OrdersTable.ColNames.DeliveryTime}",
                        $"{OrdersTable.ColNames.OrderCount}",
                        $"{OrdersTable.ColNames.OrderNo}",
                        $"{OrdersTable.ColNames.OrderStatus}",
                        $"{OrdersTable.ColNames.ProductID}"
                        }

                Dim condition As New StringBuilder
                condition.Append($"`{OrdersTable.ColNames.ID}` = {id}")

                Dim cmdText As String = db.CmdHelper.Search(colNames, OrdersTable.TableName, condition.ToString())

                Using dtReader As DbDataReader = db.ExecuteReader(cmdText)
                    While dtReader.Read()

                        If System.Enum.TryParse(CStr(dtReader($"{OrdersTable.ColNames.OrderStatus}")), order.OrderStatus) = False Then
                            Throw New Exception($"Invalid OrderStatus :{dtReader($"{OrdersTable.ColNames.OrderStatus}")}.")
                        End If

                        order.OrderID = id

                        order.CompanyID = CInt(dtReader($"{OrdersTable.ColNames.CompanyID}"))
                        order.OrderCount = CInt(dtReader($"{OrdersTable.ColNames.OrderCount}"))

                        order.ProductID = CInt(dtReader($"{OrdersTable.ColNames.ProductID}"))

                        order.CostPrice = CDbl(dtReader($"{OrdersTable.ColNames.CostPrice}"))
                        order.TransactPrice = CDbl(dtReader($"{OrdersTable.ColNames.TransactPrice}"))

                        order.CreateTime = CDate(dtReader($"{OrdersTable.ColNames.CreateTime}"))
                        order.DeliveryTime = CDate(dtReader($"{OrdersTable.ColNames.DeliveryTime}"))

                        order.OrderNo = CStr(dtReader($"{OrdersTable.ColNames.OrderNo}"))

                        Exit While
                    End While

                End Using

                db.Close()
            End Using

            Return order
        End Function


        ''' <summary>
        ''' 通过项目(产品)索引与条码查询客户订单号
        ''' </summary>
        ''' <param name="projectIndex"></param>
        ''' <param name="barcode"></param>
        ''' <returns></returns>
        Public Shared Function SearchOrderID(projectIndex As Integer, barcode As String) As Integer
            Dim orderID As Integer = -1
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                Dim cmd As String = db.CmdHelper.Search(SnListTable.ColNames.OrderInternalID.ToString(), SnListTable.TableName, $"`{SnListTable.ColNames.ProductID}` = {projectIndex} and `{SnListTable.ColNames.BarCode}` = '{barcode}' Order by `{SnListTable.ColNames.ID}` Desc limit 1")

                'Momo 2023-03-24 取消msgbox
                'MsgBox($"UtsDb.LocalDbType:{UtsDb.LocalDbType}{vbCrLf }UtsDb.LocalConnString:{UtsDb.LocalConnString}{vbCrLf }Cmd:{cmd}")

                Dim obj As Object = db.ExecuteScalar(cmd)

                If IsNothing(obj) = False Then
                    orderID = CInt(obj)
                End If

                db.Close()
            End Using
            Return orderID
        End Function

        ''' <summary>
        ''' 查询所有MO的名称与索引,优先云端，其次本地
        ''' </summary>
        ''' <returns></returns>
        Public Shared Function SearchMoTable() As DataTable
            Dim dt As DataTable = Nothing
            Try
                Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                    db.Open()

                    Dim colName As New List(Of String) From {OrderInternalTable.ColNames.ID.ToString, OrderInternalTable.ColNames.InternalNo.ToString}
                    dt = db.ExecuteDataTable(db.CmdHelper.DbSearch(UtsDb.RemotePrivateDb, colName, OrderInternalTable.TableName))

                    db.Close()
                End Using
                Return dt
            Catch ex As Exception
                Console.WriteLine($"Search Remote MoTable Error:{ex.Message}")
            End Try

            Try
                Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                    db.Open()

                    Dim colName As New List(Of String) From {OrderInternalTable.ColNames.ID.ToString, OrderInternalTable.ColNames.InternalNo.ToString}
                    dt = db.ExecuteDataTable(db.CmdHelper.Search(colName, OrderInternalTable.TableName))

                    db.Close()
                End Using
                Return dt
            Catch ex As Exception
                Console.WriteLine($"Search MoTable Error:{ex.Message}")
            End Try

            Return dt
        End Function

        ''' <summary>
        ''' 查询对应条码的对应产品索引,本地查询方式
        ''' </summary>
        ''' <param name="barcode"></param>
        ''' <returns></returns>
        Public Shared Function SearchProjectIndex(barcode As String) As Integer
            Dim pid As Integer = -1
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                Dim cmd As String = db.CmdHelper.Search(SnListTable.ColNames.ProductID.ToString(), SnListTable.TableName, $"`{SnListTable.ColNames.BarCode}` = '{barcode}'")

                Dim obj As Object = db.ExecuteScalar(cmd)

                If IsNothing(obj) = False Then
                    pid = CInt(obj)
                End If

                db.Close()
            End Using
            Return pid
        End Function

        ''' <summary>
        ''' 查询对应条码的对应产品索引,本地查询方式
        ''' </summary>
        ''' <param name="barcode"></param>
        ''' <returns></returns>
        Public Shared Function SearchBarcodeExists(barcode As String) As Boolean
            Dim result As Boolean = False
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()
                Dim cmd As String = db.CmdHelper.SearchCount(SnListTable.TableName, $"`{SnListTable.ColNames.BarCode}` = '{barcode}'")

                Try
                    Dim obj As Object = db.ExecuteScalar(cmd)
                    If CInt(obj) = 0 Then result = True
                Catch ex As Exception
                    result = False
                End Try

                db.Close()
            End Using
            Return result
        End Function


        ''' <summary>
        ''' 查询所有的错误代码，返回数据表
        ''' </summary>
        ''' <returns></returns>
        Public Shared Function GetAllErrCode() As DataTable
            Dim dtTable As DataTable
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                Dim cmd As String = db.CmdHelper.SearchAll(ErrCodeTable.TableName)
                dtTable = db.ExecuteDataTable(cmd)

                db.Close()
            End Using
            Return dtTable
        End Function

        ''' <summary>
        ''' 查询所有的产品类相关，返回数据表
        ''' </summary>
        ''' <returns></returns>
        Public Shared Function GetAllProductTypes() As DataTable
            Dim dtTable As DataTable
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                Dim cmd As String = db.CmdHelper.SearchAll(ProductTypesTable.TableName)
                dtTable = db.ExecuteDataTable(cmd)

                db.Close()
            End Using
            Return dtTable
        End Function

        ''' <summary>
        ''' 获取当前的测试记录数据表
        ''' </summary>
        ''' <param name="pid">项目索引</param>
        ''' <param name="sid">站位索引</param>
        ''' <returns></returns>
        Public Shared Function GetTodayTestResult(pid As Integer, sid As Integer) As DataTable
            Dim dtTable As DataTable

            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                Dim tbName As String = TestLogTable.TableName(pid, sid)
                Dim condition As String = $"`{TestLogTable.ColNames.StartTime}` like '{Now:yyyy-MM-dd}%'"
                Dim cols As New List(Of String) From {
                    $"{TestLogTable.ColNames.StartTime}",
                    $"{TestLogTable.ColNames.DUT_SN}",
                    $"{TestLogTable.ColNames.TestResult}",
                    $"{TestLogTable.ColNames.ErrCode}"
                }

                Dim cmd As String = db.CmdHelper.Search(cols, tbName, condition)

                dtTable = db.ExecuteDataTable(cmd, False)

                db.Close()
            End Using

            Return dtTable
        End Function


        ''' <summary>
        ''' 获取当前的条码指定站位的测试记录数据
        ''' </summary>
        ''' <param name="pid">项目索引</param>
        ''' <param name="sid">站位索引</param>
        ''' <returns></returns>
        Public Shared Function GetTestResult(pid As Integer, sid As Integer, barcode As String) As DataTable
            Dim dtTable As DataTable

            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()

                Dim tbName As String = TestLogTable.TableName(pid, sid)
                Dim condition As String = $"`{TestLogTable.ColNames.DUT_SN}` = '{barcode}'"

                Dim cmd As String = db.CmdHelper.DbSearchAll(UtsDb.RemotePrivateDb, tbName, condition)

                dtTable = db.ExecuteDataTable(cmd)

                db.Close()
            End Using

            Return dtTable
        End Function


        ''' <summary>
        ''' 从远程条码总表中获取条码信息
        ''' </summary>
        ''' <param name="barcode"></param>
        ''' <returns></returns>
        Public Shared Function GetRemoteBarcode(barcode As String) As DataTable
            Dim dtTable As DataTable

            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()

                Dim tbName As String = SnListTable.TableName
                Dim condition As String = $"`{SnListTable.ColNames.BarCode}` = '{barcode}'"

                Dim cmd As String = db.CmdHelper.DbSearchAll(UtsDb.RemotePrivateDb, tbName, condition)

                dtTable = db.ExecuteDataTable(cmd)

                db.Close()
            End Using

            Return dtTable
        End Function


        ''' <summary>
        ''' 从本地条码总表中获取条码信息
        ''' </summary>
        ''' <param name="barcode"></param>
        ''' <returns></returns>
        Public Shared Function GetLocalBarcode(barcode As String) As DataTable
            Dim dtTable As DataTable

            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()

                Dim tbName As String = SnListTable.TableName
                Dim condition As String = $"`{SnListTable.ColNames.BarCode}` = '{barcode}'"

                Dim cmd As String = db.CmdHelper.SearchAll(tbName, condition)

                dtTable = db.ExecuteDataTable(cmd)

                db.Close()
            End Using

            Return dtTable
        End Function


        ''' <summary>
        ''' 更新数据库服务表中的信息
        ''' </summary>
        ''' <param name="dsIndex">服务索引</param>
        ''' <param name="filed">更新字段值及内容</param>
        Public Shared Sub UpdateServiceTable(dsIndex As String, filed As Dictionary(Of String, String))
            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()

                Dim tableName As String = $"{DataServiceListTable.TableName}"
                Dim condition As String = $"{DataServiceListTable.ColNames.ID} = {dsIndex}"
                db.ExecuteNonQuery(db.CmdHelper.DbUpdate(UtsDb.RemotePublicDb, tableName, filed, condition))

                db.Close()
            End Using
        End Sub

        Public Shared Function GetBarcodeRepairLog(barcode As String) As DataTable
            Dim dtTable As DataTable

            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()

                Dim tbName As String = RepairLogTable.TableName
                Dim condition As String = $"`{RepairLogTable.ColNames.DUT_SN}` = '{barcode}'"

                Dim cmd As String = db.CmdHelper.DbSearchAll(UtsDb.RemotePrivateDb, tbName, condition)

                dtTable = db.ExecuteDataTable(cmd)

                db.Close()
            End Using

            Return dtTable
        End Function

        ''' <summary>
        ''' 更新缓存
        ''' </summary>
        ''' <param name="url"></param>
        ''' <returns></returns>
        Public Shared Function GetData(url As String) As String
            Dim request As HttpWebRequest = CType(WebRequest.Create(url & "?" & $"cmd=UP&dbName={""}"), HttpWebRequest)
            request.Accept = "text/html,application/xhtml+xml,*/*"
            request.ContentType = "application/json"
            request.Method = "GET"

            Dim sr As New StreamReader(request.GetResponse().GetResponseStream)
            Return sr.ReadToEnd
        End Function
#End Region

    End Class
End Namespace