Imports System.Management
Imports UTS_Core.Database
Imports UTS_Core.UTSModule
Imports UTS_Core.UTSModule.DbTableModel.Manage

Public Class ServiceRegister

    Private _serviceID As Integer

    Private _mac As String

    Private _cpuId As String

    Private _privateIP As String

    Private _publicIP As String

    Private _dsVersion As String

    Private _usVersion As String


    Sub New()
        _dsVersion = UtsRegistry.DataServiceVersion
        _usVersion = UtsRegistry.UpdateServiceVersion

        InitServiceIndex()

        InitMacAndLocalIP()

        _cpuId = GetProcessorId()
        If String.IsNullOrWhiteSpace(_cpuId) Then
            Throw New Exception("无效的CPU序列号")
        End If
    End Sub

    Public ReadOnly Property PrivateIP() As String
        Get
            Return _privateIP
        End Get
    End Property

    Public ReadOnly Property DsVersion() As String
        Get
            Return _dsVersion
        End Get
    End Property

    Public Property UsVersion() As String
        Get
            Return _usVersion
        End Get
        Set(value As String)
            _usVersion = value
        End Set
    End Property

    Public ReadOnly Property ServiceID() As Integer
        Get
            Return _serviceID
        End Get
    End Property

    Public Property LicenseID As String
    Public Property VendorName As String
    Public Property ExpirationDate As String
    Public Property TerminalAlias As String
    Public Property Group As String
    Public Property Roles As String

    Private Function InitServiceIndex() As Boolean
        Try
            _serviceID = CInt(UtsRegistry.DataServiceIndex)
            If _serviceID = -1 Then Return False
        Catch ex As Exception
            Throw New Exception($"RegisterService Error: {ex.Message}")
        End Try

        Return True
    End Function



    ''' <summary>
    ''' 注册服务返回注册服务的索引
    ''' Momo 2024-04-05 Service ID 由 ProcessorID + AlisaName 构成，从Service Controller 传参传过来
    ''' </summary>
    Public Sub RegisterService(Optional AlisaName As String = "")
        '增加服务记录
        'Momo 2024-04-05 Service ID 由 ProcessorID + AlisaName 构成，从Service Controller 传参传过来
        _cpuId = _cpuId & "-" & AlisaName

        Dim filed As New Dictionary(Of String, String) From {
            {$"{DataServiceListTable.ColNames.LicenseID}", LicenseID},
            {$"{DataServiceListTable.ColNames.CompanyName}", VendorName},
            {$"{DataServiceListTable.ColNames.LicenseValidDateTime}", ExpirationDate},
            {$"{DataServiceListTable.ColNames.TerminalType}", "Windows"},
            {$"{DataServiceListTable.ColNames.TerminalName}", Environment.MachineName},
            {$"{DataServiceListTable.ColNames.TerminalOS}", My.Computer.Info.OSFullName},
            {$"{DataServiceListTable.ColNames.TerminalAlias}", TerminalAlias},
            {$"{DataServiceListTable.ColNames.TerminalMAC}", _mac},
            {$"{DataServiceListTable.ColNames.ProcessorId}", _cpuId},
            {$"{DataServiceListTable.ColNames.ServiceVersion}", DsVersion},
            {$"{DataServiceListTable.ColNames.USVer}", UsVersion},
            {$"{DataServiceListTable.ColNames.BarnchNet}", Group},
            {$"{DataServiceListTable.ColNames.Roles}", Roles},
            {$"{DataServiceListTable.ColNames.ServiceRegisterDateTime}", Now.ToString("yyyy-MM-dd HH:mm:ss")},
            {$"{DataServiceListTable.ColNames.ServiceLastActiveDateTime}", Now.ToString("yyyy-MM-dd HH:mm:ss")}
        }

        Dim tableName As String = DataServiceListTable.TableName
        Dim colName As String = $"{DataServiceListTable.ColNames.ID}"

        Dim condition As String = $"`{DataServiceListTable.ColNames.ProcessorId}` = '{_cpuId}'"

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

            '检测本机是否有注册信息
            If _serviceID = -1 Then
                '根据CPUID获取索引
                Try
                    _serviceID = CInt(db.ExecuteScalar(db.CmdHelper.DbSearch(UtsDb.RemotePublicDb, colName, tableName, condition)))

                Catch ex As Exception
                    Throw New Exception($"Don't Find  Mac:{_mac} Register.")
                End Try

                If _serviceID > 0 Then '更新
                    '有索引则更新
                    condition = $"`{DataServiceListTable.ColNames.ID}` = {_serviceID}"
                    db.ExecuteNonQuery(db.CmdHelper.DbUpdate(UtsDb.RemotePublicDb, tableName, filed, condition))
                Else
                    '无索引则注册
                    db.ExecuteNonQuery(db.CmdHelper.DbInsert(UtsDb.RemotePublicDb, tableName, filed))
                    _serviceID = CInt(db.ExecuteScalar(db.CmdHelper.DbSearch(UtsDb.RemotePublicDb, colName, tableName, condition)))
                End If
            Else
                '根据CPUID获取索引              
                Try
                    sid = CInt(db.ExecuteScalar(db.CmdHelper.DbSearch(UtsDb.RemotePublicDb, colName, tableName, condition)))
                Catch ex As Exception
                    Throw New Exception($"Search Service ID Error:{ex.Message}")
                End Try

                If _serviceID = sid Then
                    '索引相同则更新
                    condition = $"`{DataServiceListTable.ColNames.ID}` = {_serviceID}"
                    db.ExecuteNonQuery(db.CmdHelper.DbUpdate(UtsDb.RemotePublicDb, tableName, filed, condition))
                ElseIf sid = 0 Then
                    '索引不相同但无CUPID则更新
                    condition = $"`{DataServiceListTable.ColNames.ID}` = {_serviceID}"
                    db.ExecuteNonQuery(db.CmdHelper.DbUpdate(UtsDb.RemotePublicDb, tableName, filed, condition))
                Else
                    '索引不同则异常
                    Throw New Exception($"设备索引异常，请联系管理员解决问题")
                End If
            End If

            db.Close()
        End Using

        UtsRegistry.DataServiceIndex = _serviceID.ToString
    End Sub

    Private Sub InitMacAndLocalIP()
        Dim searcher As New ManagementObjectSearcher("select * from win32_NetworkAdapterConfiguration")
        Dim moc2 As ManagementObjectCollection = searcher.Get()
        For Each mo As ManagementObject In moc2
            If CBool(mo("IPEnabled")) Then
                _mac = mo("MACAddress").ToString().ToUpper

                Dim a() As String = CType(mo("IpAddress"), String())
                _privateIP = a(0)

                Exit For
            End If
        Next
    End Sub

    Private Function GetProcessorId() As String
        Dim Wmis As New System.Management.ManagementObjectSearcher("SELECT * FROM Win32_Processor")
        Dim pid As String = ""

        For Each WmiObj As ManagementObject In Wmis.Get
            pid = CStr(WmiObj("ProcessorId")).ToUpper
            Exit For
        Next

        Return pid
    End Function
End Class
