Imports System.Text
Imports UTS_Core.Database
Imports UTS_Core.UTSModule
Imports UTS_Core.UTSModule.DbTableModel.Customer
Imports UTS_Core.UTSModule.License
Imports UTS_Core.UTSModule.DbTableModel

Public Class FrmMain
    Private Sub BtnCommit_Click(sender As Object, e As EventArgs) Handles BtnCommit.Click
        UpdateInstallTip(0, "注册客户准备中")

        Try
            '更新License信息
            UpdateInstallTip(1, $"License信息更新中...")
            Dim lic As License = FillLicense()
            UpdateInstallTip(20, $"License信息更新完成！")

            '生成License文件
            UpdateInstallTip(21, $"License文件生成中...")
            CreateVendorLicense(lic)
            UpdateInstallTip(40, $"License文件生成完成！")

            '创建FTP文件夹
            UpdateInstallTip(41, $"Ftp文件夹生成中...")
            CreateFtpDic(lic)
            UpdateInstallTip(60, $"Ftp文件夹生成完成！")

            '创建数据库的数据表
            UpdateInstallTip(61, $"创建数据库结构中...")
            CreateVendorTables(lic)
            UpdateInstallTip(99, $"创建数据库结构完成！")

            UpdateInstallTip(100, $"注册客户完成")
        Catch ex As Exception
            Console.WriteLine($"Commit vendor error:{ex.Message}")
            UpdateInstallTip(100, $"注册客户失败,{ex.Message}")
        End Try
    End Sub


    Private Function FillLicense() As License
        '更新License缓存
        Dim lic As New License With {
            .ID = $"1",
            .VendorName = TxtVendorName.Text,
            .AuthorizationDate = $"{Now:yyyy-MM-dd HH:mm:ss}",
            .ExpirationDate = $"{DtpExpirationDate.Value:yyyy-MM-dd HH:mm:ss}",
            .DefaultUser = $"Admin",
            .DefaultPassword = $"Admin",
            .MysqlServer = TxtRemoteServer.Text,
            .MysqlPort = NudRemotePort.Value.ToString(),
            .MysqlUserID = TxtRemoteUser.Text,
            .MysqlPassword = TxtRemotePwd.Text,
            .MysqlDatabase = TxtRemotePrivateDb.Text,
            .PublicDb = TxtRemotePublicDb.Text,
            .SqliteDir = "LocalDB",
            .SqliteName = TxtLocalFileName.Text,
            .SqlitePassword = TxtLocalPwd.Text,
            .FtpHost = TxtFtpHost.Text,
            .FtpPort = NudFtpPort.Value.ToString(),
            .FtpUser = TxtFtpUser.Text,
            .FtpPwd = TxtFtpPwd.Text,
            .Mac = TxtMac.Text,
            .Remark = TxtRemard.Text,
            .UtsVersion = $"3",
            .Signature = $"this is a valid license data"
        }

        Return lic
    End Function

    ''' <summary>
    ''' 创建Ftp所需的文件夹
    ''' </summary>
    ''' <param name="lic"></param>
    Private Sub CreateFtpDic(lic As License)

        UtsFtp.InitConnectParams(CInt(lic.FtpPort), lic.FtpUser, lic.FtpPwd)
        Dim ftp As UtsFtp = UtsFtp.CreateObject()
        ftp.FtpHost = lic.FtpHost
        Try
            ftp.CreateDir($"/uts_Manager/AUTS/{lic.VendorName}/AOI", True) '拍摄站上传图像
            ftp.CreateDir($"/uts_Manager/AUTS/{lic.VendorName}/Package", True) '装箱站上传图像
            ftp.CreateDir($"/uts_Manager/AUTS/{lic.VendorName}/Product", True) '产品图像
            ftp.CreateDir($"/uts_Manager/AUTS/{lic.VendorName}/Repair", True) '维修站位图像
            ftp.CreateDir($"/uts_Manager/AUTS/{lic.VendorName}/Project", True) '测试站位流程
            ftp.CreateDir($"/uts_Manager/AUTS/{lic.VendorName}/Upload", True) '服务上传内容
        Catch ex As Exception
            Throw New Exception($"创建客户Ftp文件夹失败,{ex.Message}")
        End Try

    End Sub


    Private Sub CreateVendorLicense(lic As License)
        '获取License文件名
        Dim licensePath As String
        Using saveDlg As New SaveFileDialog
            saveDlg.Title = $"请选择鉴权License文件的保存路径"
            saveDlg.Filter = $"License文件(*.dat)|*.dat"
            saveDlg.AddExtension = True
            If saveDlg.ShowDialog() <> DialogResult.OK Then Return
            licensePath = saveDlg.FileName
        End Using

        UpdateInstallTip(30, $"License文件即将保存至{licensePath}.")
        '保存License文件
        lic.SaveLicenseFile(licensePath)
    End Sub


    Private Sub UpdateCompanyTable(db As DbExecutor, dbName As String, company As String)
        '更新公共库公司总表
        Dim tableName As String = $"{Manage.CustomerListTable.TableName}"
        Dim condition As String = $"`{Manage.CustomerListTable.ColNamesEnum.CustomerName}` = '{company}'"
        Dim cmdText As String = db.CmdHelper.DbSearch(dbName, "count(*)", tableName, condition)
        If CInt(db.ExecuteScalar(cmdText)) > 0 Then
            Return
        End If

        Dim field As New Dictionary(Of String, String) From
                {
                {$"{Manage.CustomerListTable.ColNamesEnum.CustomerName}", company}
                }

        cmdText = db.CmdHelper.DbInsert(dbName, tableName, field)
        db.ExecuteNonQuery(cmdText)
    End Sub

    Private Sub UpdateDatabaseTable(db As DbExecutor, dbName As String, company As String, userDb As String, user As String, pwd As String)
        ''更新公共库公司总表
        Dim tableName As String = $"{Manage.CustomerListTable.TableName}"
        Dim condition As String = $"`{Manage.CustomerListTable.ColNamesEnum.CustomerName}` = '{company}'"
        Dim colName As String = $"{Manage.CustomerListTable.ColNamesEnum.ID}"
        Dim cmdText As String = db.CmdHelper.DbSearch(dbName, colName, tableName, condition)
        Dim companyID As String = db.ExecuteScalar(cmdText).ToString()


        '更新公共库数据库总表
        tableName = Manage.DbListTable.TableName
        condition = $"`{Manage.DbListTable.ColNamesEnum.DatabaseName}` = '{userDb}'"
        cmdText = db.CmdHelper.DbSearch(dbName, "count(*)", tableName, condition)
        If CInt(db.ExecuteScalar(cmdText)) > 0 Then
            Return
        End If

        Dim field2 As New Dictionary(Of String, String) From
            {
                    {$"{Manage.DbListTable.ColNamesEnum.CompanyID}", companyID},
                    {$"{Manage.DbListTable.ColNamesEnum.DatabaseName}", userDb},
                    {$"{Manage.DbListTable.ColNamesEnum.DatabaseUser}", user},
                    {$"{Manage.DbListTable.ColNamesEnum.DatabasePassword}", pwd},
                    {$"{Manage.DbListTable.ColNamesEnum.DatabaseDesc}", ""}
            }

        cmdText = db.CmdHelper.DbInsert(dbName, tableName, field2)
        db.ExecuteNonQuery(cmdText)

    End Sub


    Private Sub CreateProcedure(db As DbExecutor, dbName As String)
        '修改测试记录表字段存储过程
        Dim sqlCmd As New StringBuilder
        sqlCmd.Append($"Drop Procedure If Exists `{dbName}`.`AlterTestLogFiled`;" & vbCrLf)
        sqlCmd.Append($"Create Procedure `{dbName}`.`AlterTestLogFiled`(in dbName varchar(32),in tbName varchar(32),in filed varchar(32),in len int)" & vbCrLf)
        sqlCmd.Append("begin" & vbCrLf)
        sqlCmd.Append("DECLARE l_int int default 0;" & vbCrLf)
        sqlCmd.Append("DECLARE l_len int default 0;" & vbCrLf)
        sqlCmd.Append("DECLARE l_type varchar(16) default '';" & vbCrLf)
        sqlCmd.Append("select count(*),`DATA_TYPE`,`CHARACTER_MAXIMUM_LENGTH` into l_int,l_type,l_len from  `information_schema`.`COLUMNS` WHERE TABLE_SCHEMA = dbName and TABLE_NAME = tbName and COLUMN_NAME = filed;" & vbCrLf)
        sqlCmd.Append("if l_int = 0 then" & vbCrLf)
        sqlCmd.Append("set @cmd = CONCAT('alter table ',dbName,'.',tbName,' add column ',filed,' varchar(',len,')');" & vbCrLf)
        sqlCmd.Append("PREPARE pre FROM @cmd;" & vbCrLf)
        sqlCmd.Append("EXECUTE pre;" & vbCrLf)
        sqlCmd.Append("deallocate prepare pre;" & vbCrLf)
        sqlCmd.Append("else" & vbCrLf)
        sqlCmd.Append("if l_type = 'varchar'  and  len > l_len then" & vbCrLf)
        sqlCmd.Append("set @cmd = CONCAT('alter table ',dbName,'.',tbName,' modify column ',filed,' varchar(',len,')');" & vbCrLf)
        sqlCmd.Append("PREPARE pre FROM @cmd;" & vbCrLf)
        sqlCmd.Append("EXECUTE pre;" & vbCrLf)
        sqlCmd.Append("deallocate prepare pre;" & vbCrLf)
        sqlCmd.Append("end if;" & vbCrLf)
        sqlCmd.Append("end if;" & vbCrLf)
        sqlCmd.Append("end" & vbCrLf)

        db.ExecuteNonQuery(sqlCmd.ToString)


        'Sn总表新增条码存储过程
        sqlCmd.Clear()
        sqlCmd.Append($"Drop Procedure If Exists `{dbName}`.`AlterSnListBarcode`;" & vbCrLf)
        sqlCmd.Append($"Create Procedure `{dbName}`.`AlterSnListBarcode`(in orderid int,in orderinternalid int,in pid int,in code varchar(32),in sntype int)" & vbCrLf)
        sqlCmd.Append("begin " & vbCrLf)
        sqlCmd.Append("DECLARE l_int int default 0; " & vbCrLf)
        sqlCmd.Append("select count(*) into l_int from  `TBL_SnList` WHERE `BarCode` = code; " & vbCrLf)
        sqlCmd.Append("if l_int = 0 then " & vbCrLf)
        sqlCmd.Append("set @cmd = CONCAT('Insert into TBL_SnList(OrderID,OrderInternalID,ProductID,BarCode,SnType) values(',orderid,',',orderinternalid,',',pid,',''',code,''',',sntype,')'); " & vbCrLf)
        sqlCmd.Append("PREPARE pre FROM @cmd; " & vbCrLf)
        sqlCmd.Append("EXECUTE pre; " & vbCrLf)
        sqlCmd.Append("deallocate prepare pre; " & vbCrLf)
        sqlCmd.Append("end if; " & vbCrLf)
        sqlCmd.Append("end " & vbCrLf)
        db.ExecuteNonQuery(sqlCmd.ToString)


        'Sn总表更新条码测试记录存储过程-有MO
        sqlCmd.Clear()
        sqlCmd.Append($"Drop Procedure If Exists `{dbName}`.`UpdateSnListBarcode_MO`;" & vbCrLf)

        '2023-06-07 add MO'''''''''''
        'sqlCmd.Append($"Create Procedure `{dbName}`.`UpdateSnListBarcode`(in code varchar(32),in snOrder int,in startTime datetime,in result int,in a1String varchar(254))," & vbCrLf)
        sqlCmd.Append($"Create Procedure `{dbName}`.`UpdateSnListBarcode_MO`(in code varchar(32),in snOrder int,in startTime datetime,in result int,in a1String varchar(254),in MoId int)" & vbCrLf)
        ''''''''''''''''''''''''''''''
        sqlCmd.Append("begin " & vbCrLf)
        sqlCmd.Append("DECLARE msg int default -1; " & vbCrLf)
        sqlCmd.Append("set @cmd = Concat('select S',snOrder,',count(1) into @l_tm,@l_ct from `TBL_SnList` where `BarCode` = ''',code,''''); " & vbCrLf)
        sqlCmd.Append("PREPARE pre FROM @cmd;" & vbCrLf)
        sqlCmd.Append("EXECUTE pre;" & vbCrLf)
        sqlCmd.Append("deallocate prepare pre;" & vbCrLf)
        sqlCmd.Append("if @l_ct = 0 then" & vbCrLf)
        sqlCmd.Append("set	msg = 0;" & vbCrLf)
        sqlCmd.Append("else" & vbCrLf)
        sqlCmd.Append("if  @l_tm is null then" & vbCrLf)
        sqlCmd.Append("if char_length(a1String) = 0 then " & vbCrLf)
        '2023-06-07 add MO'''''''''''
        'sqlCmd.Append("set @cmd = Concat('update `TBL_SnList` set S',snOrder,' = ''',startTime,''',Result',snOrder, ' = ',result,' where `BarCode` = ''',code,'''');" & vbCrLf)
        sqlCmd.Append("set @cmd = Concat('update `TBL_SnList` set OrderInternalID=''',MoId,''',S',snOrder,' = ''',startTime,''',Result',snOrder, ' = ',result,' where `BarCode` = ''',code,'''');" & vbCrLf)
        ''''''''''''''''''''''''''''''
        sqlCmd.Append("else" & vbCrLf)
        '2023-06-07 add MO'''''''''''
        'sqlCmd.Append("set @cmd = Concat('update `TBL_SnList` set S',snOrder,' = ''',startTime,''',Result',snOrder, ' = ',result,',AssemblySn = ''',a1String,''',AssemblyTime =''',startTime,''' where `BarCode` = ''',code,'''');	" & vbCrLf)
        sqlCmd.Append("set @cmd = Concat('update `TBL_SnList` set OrderInternalID=''',MoId,''',S',snOrder,' = ''',startTime,''',Result',snOrder, ' = ',result,',AssemblySn = ''',a1String,''',AssemblyTime =''',startTime,''' where `BarCode` = ''',code,'''');	" & vbCrLf)
        ''''''''''''''''''''''''''''''
        sqlCmd.Append("end if;" & vbCrLf)
        sqlCmd.Append("PREPARE pre FROM @cmd;" & vbCrLf)
        sqlCmd.Append("EXECUTE pre;" & vbCrLf)
        sqlCmd.Append("deallocate prepare pre;" & vbCrLf)
        sqlCmd.Append("set msg = 1;" & vbCrLf)
        sqlCmd.Append("else" & vbCrLf)
        sqlCmd.Append("if startTime >= @l_tm then" & vbCrLf)
        sqlCmd.Append("if char_length(a1String) = 0 then " & vbCrLf)
        '2023-06-07 add MO'''''''''''
        'sqlCmd.Append("set @cmd = Concat('update `TBL_SnList` set S',snOrder,' = ''',startTime,''',Result',snOrder, ' = ',result,' where `BarCode` = ''',code,'''');	" & vbCrLf)
        sqlCmd.Append("set @cmd = Concat('update `TBL_SnList` set OrderInternalID=''',MoId,''',S',snOrder,' = ''',startTime,''',Result',snOrder, ' = ',result,' where `BarCode` = ''',code,'''');	" & vbCrLf)
        ''''''''''''''''''''''''''''''
        sqlCmd.Append("else" & vbCrLf)
        '2023-06-07 add MO'''''''''''
        'sqlCmd.Append("set @cmd = Concat('update `TBL_SnList` set S',snOrder,' = ''',startTime,''',Result',snOrder, ' = ',result,',AssemblySn = ''',a1String,''',AssemblyTime =''',startTime,''' where `BarCode` = ''',code,'''');	" & vbCrLf)
        sqlCmd.Append("set @cmd = Concat('update `TBL_SnList` set OrderInternalID=''',MoId,''',S',snOrder,' = ''',startTime,''',Result',snOrder, ' = ',result,',AssemblySn = ''',a1String,''',AssemblyTime =''',startTime,''' where `BarCode` = ''',code,'''');	" & vbCrLf)
        ''''''''''''''''''''''''''''''
        sqlCmd.Append("end if;" & vbCrLf)
        sqlCmd.Append("PREPARE pre FROM @cmd;" & vbCrLf)
        sqlCmd.Append("EXECUTE pre;" & vbCrLf)
        sqlCmd.Append("deallocate prepare pre;" & vbCrLf)
        sqlCmd.Append("set msg = 1;" & vbCrLf)
        sqlCmd.Append("else" & vbCrLf)
        sqlCmd.Append("set msg = 2;" & vbCrLf)
        sqlCmd.Append("end if;" & vbCrLf)
        sqlCmd.Append("end if;" & vbCrLf)
        sqlCmd.Append("end if;" & vbCrLf)
        sqlCmd.Append("select msg;" & vbCrLf)
        sqlCmd.Append("end " & vbCrLf)
        db.ExecuteNonQuery(sqlCmd.ToString)

        'Sn总表更新条码测试记录存储过程:无MO
        sqlCmd.Clear()
        sqlCmd.Append($"Drop Procedure If Exists `{dbName}`.`UpdateSnListBarcode`;" & vbCrLf)

        sqlCmd.Append($"Create Procedure `{dbName}`.`UpdateSnListBarcode`(in code varchar(32),in snOrder int,in startTime datetime,in result int,in a1String varchar(254))" & vbCrLf)
        sqlCmd.Append("begin " & vbCrLf)
        sqlCmd.Append("DECLARE msg int default -1; " & vbCrLf)
        sqlCmd.Append("set @cmd = Concat('select S',snOrder,',count(1) into @l_tm,@l_ct from `TBL_SnList` where `BarCode` = ''',code,''''); " & vbCrLf)
        sqlCmd.Append("PREPARE pre FROM @cmd;" & vbCrLf)
        sqlCmd.Append("EXECUTE pre;" & vbCrLf)
        sqlCmd.Append("deallocate prepare pre;" & vbCrLf)
        sqlCmd.Append("if @l_ct = 0 then" & vbCrLf)
        sqlCmd.Append("set	msg = 0;" & vbCrLf)
        sqlCmd.Append("else" & vbCrLf)
        sqlCmd.Append("if  @l_tm is null then" & vbCrLf)
        sqlCmd.Append("if char_length(a1String) = 0 then " & vbCrLf)
        sqlCmd.Append("set @cmd = Concat('update `TBL_SnList` set S',snOrder,' = ''',startTime,''',Result',snOrder, ' = ',result,' where `BarCode` = ''',code,'''');" & vbCrLf)
        sqlCmd.Append("else" & vbCrLf)
        sqlCmd.Append("set @cmd = Concat('update `TBL_SnList` set S',snOrder,' = ''',startTime,''',Result',snOrder, ' = ',result,',AssemblySn = ''',a1String,''',AssemblyTime =''',startTime,''' where `BarCode` = ''',code,'''');	" & vbCrLf)
        sqlCmd.Append("end if;" & vbCrLf)
        sqlCmd.Append("PREPARE pre FROM @cmd;" & vbCrLf)
        sqlCmd.Append("EXECUTE pre;" & vbCrLf)
        sqlCmd.Append("deallocate prepare pre;" & vbCrLf)
        sqlCmd.Append("set msg = 1;" & vbCrLf)
        sqlCmd.Append("else" & vbCrLf)
        sqlCmd.Append("if startTime >= @l_tm then" & vbCrLf)
        sqlCmd.Append("if char_length(a1String) = 0 then " & vbCrLf)
        sqlCmd.Append("set @cmd = Concat('update `TBL_SnList` set S',snOrder,' = ''',startTime,''',Result',snOrder, ' = ',result,' where `BarCode` = ''',code,'''');	" & vbCrLf)
        sqlCmd.Append("else" & vbCrLf)
        sqlCmd.Append("set @cmd = Concat('update `TBL_SnList` set S',snOrder,' = ''',startTime,''',Result',snOrder, ' = ',result,',AssemblySn = ''',a1String,''',AssemblyTime =''',startTime,''' where `BarCode` = ''',code,'''');	" & vbCrLf)
        sqlCmd.Append("end if;" & vbCrLf)
        sqlCmd.Append("PREPARE pre FROM @cmd;" & vbCrLf)
        sqlCmd.Append("EXECUTE pre;" & vbCrLf)
        sqlCmd.Append("deallocate prepare pre;" & vbCrLf)
        sqlCmd.Append("set msg = 1;" & vbCrLf)
        sqlCmd.Append("else" & vbCrLf)
        sqlCmd.Append("set msg = 2;" & vbCrLf)
        sqlCmd.Append("end if;" & vbCrLf)
        sqlCmd.Append("end if;" & vbCrLf)
        sqlCmd.Append("end if;" & vbCrLf)
        sqlCmd.Append("select msg;" & vbCrLf)
        sqlCmd.Append("end " & vbCrLf)
        db.ExecuteNonQuery(sqlCmd.ToString)
    End Sub

    Private Sub CreateDatabase(db As DbExecutor, dbName As String)
        Dim sqlCmd As New StringBuilder
        Dim tableName As String

        '创建数据库
        UpdateInstallTip(55, $"创建数据库中...")
        sqlCmd.Clear()
        sqlCmd.Append($"CREATE DATABASE IF NOT EXISTS {dbName};")
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(60, $"创建数据库完成！")

        '创建数据库同步表
        UpdateInstallTip(65, $"创建同步表...")
        sqlCmd.Clear()
        sqlCmd.Append(SyncListTable.CreateTableString(dbName, db.DatabaseType))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(65, $"创建同步表完成！")

        '创建数据库日志表
        UpdateInstallTip(65, $"创建日志表...")
        sqlCmd.Clear()
        sqlCmd.Append(LogTable.CreateTableString(dbName, db.DatabaseType))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(65, $"创建日志表完成！")

        '创建项目类型表
        UpdateInstallTip(65, $"创建项目类型表...")
        sqlCmd.Clear()
        tableName = ProductTypesTable.TableName
        sqlCmd.Append(ProductTypesTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(65, $"创建项目类型表完成！")

        '创建项目表
        UpdateInstallTip(70, $"创建项目表...")
        sqlCmd.Clear()
        tableName = ProjectTable.TableName
        sqlCmd.Append(ProjectTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(70, $"创建项目表完成！")

        '创建站位表
        UpdateInstallTip(70, $"创建站位表...")
        sqlCmd.Clear()
        tableName = StationListTable.TableName
        sqlCmd.Append(StationListTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(70, $"创建站位表完成！")

        '创建站包发布历史表
        UpdateInstallTip(70, $"创建站包发布历史表...")
        sqlCmd.Clear()
        tableName = StationPacketReleaseLogTable.TableName
        sqlCmd.Append(StationPacketReleaseLogTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(70, $"创建站包发布历史表完成！")

        '创建内部单表
        UpdateInstallTip(70, $"创建内部单表...")
        sqlCmd.Clear()
        tableName = OrderInternalTable.TableName
        sqlCmd.Append(OrderInternalTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(70, $"创建内部单表完成！")

        '创建订单表
        UpdateInstallTip(70, $"创建订单表...")
        sqlCmd.Clear()
        tableName = OrdersTable.TableName
        sqlCmd.Append(OrdersTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(70, $"创建订单表完成！")

        '创建产线表
        UpdateInstallTip(75, $"创建产线表...")
        sqlCmd.Clear()
        tableName = ProductionLineTable.TableName
        sqlCmd.Append(ProductionLineTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(75, $"创建产线表完成！")

        '创建生产计划表
        UpdateInstallTip(75, $"创建生产计划表...")
        sqlCmd.Clear()
        tableName = ProductionPlanTable.TableName
        sqlCmd.Append(ProductionPlanTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(75, $"创建生产计划表完成！")

        '创建产商客户表
        UpdateInstallTip(75, $"创建产商客户表...")
        sqlCmd.Clear()
        tableName = VendorCustomerTable.TableName
        sqlCmd.Append(VendorCustomerTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(75, $"创建产商客户表完成！")

        '创建序号总表
        UpdateInstallTip(75, $"创建序号总表...")
        sqlCmd.Clear()
        tableName = SnListTable.TableName
        sqlCmd.Append(SnListTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName, "new"))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(75, $"创建序号总表完成！")

        '创建序号关联信息总表
        UpdateInstallTip(75, $"创建序号关联信息总表...")
        sqlCmd.Clear()
        tableName = ImportInfoTable.TableName
        sqlCmd.Append(ImportInfoTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName, "new"))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(75, $"创建序号关联信息总表完成！")


        '创建维修原因类型表
        UpdateInstallTip(75, $"创建维修原因类型表...")
        sqlCmd.Clear()
        tableName = RepairTypesTable.TableName
        sqlCmd.Append(RepairTypesTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(75, $"创建维修原因类型表完成！")

        '创建维修原因表
        UpdateInstallTip(75, $"创建维修原因表...")
        sqlCmd.Clear()
        tableName = RepairReasonTable.TableName
        sqlCmd.Append(RepairReasonTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(75, $"创建维修原因表完成！")

        '创建报修不良代码表
        UpdateInstallTip(75, $"创建报修不良代码表...")
        sqlCmd.Clear()
        tableName = RejectsExplainTable.TableName
        sqlCmd.Append(RejectsExplainTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(75, $"创建报修不良代码完成！")

        '创建报修记录表
        UpdateInstallTip(75, $"创建报修记录表...")
        sqlCmd.Clear()
        tableName = RepairRequestTable.TableName
        sqlCmd.Append(RepairRequestTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(75, $"创建报修记录表完成！")

        '创建维修结果表
        UpdateInstallTip(75, $"创建维修结果表...")
        sqlCmd.Clear()
        tableName = RepairResultTable.TableName
        sqlCmd.Append(RepairResultTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(75, $"创建维修结果表完成！")


        '创建维修记录表
        UpdateInstallTip(75, $"创建维修记录表...")
        sqlCmd.Clear()
        tableName = RepairLogTable.TableName
        sqlCmd.Append(RepairLogTable.CreateTableString(dbName, db.DatabaseType))
        sqlCmd.Append(SyncListTable.SyncTrigger(dbName, tableName))
        sqlCmd.Append(SyncListTable.AddSyncTableString(dbName, tableName))
        db.ExecuteNonQuery(sqlCmd.ToString())
        UpdateInstallTip(75, $"创建维修记录表完成！")
    End Sub

    Private Sub CreateVendorTables(lic As License)
        '生成对应数据库的对应数据表
        Dim connType As DbExecutor.DbTypeEnum = DbExecutor.DbTypeEnum.Mysql
        Dim connString As String = $"Server = {lic.MysqlServer};Port = {lic.MysqlPort};User id = {lic.MysqlUserID};Password = {lic.MysqlPassword};SslMode = none;Allow User Variables = True;"

        UpdateInstallTip(45, $"连接数据库中...")
        Using db As New DbExecutor(connType, connString)
            db.Open()

            UpdateInstallTip(50, $"连接数据库完成！")

            UpdateInstallTip(51, $"创建客户数据库中...")
            Try
                CreateDatabase(db, lic.MysqlDatabase)
                UpdateInstallTip(80, $"创建客户数据库完成！")
            Catch ex As Exception
                Throw New Exception($"创建客户数据库失败,{ex.Message}")
            End Try

            Try
                CreateProcedure(db, lic.MysqlDatabase)
            Catch ex As Exception
                Throw New Exception($"创建客户数据库存储过程失败,{ex.Message}")
            End Try

            UpdateInstallTip(81, $"注册客户中...")
            Try
                UpdateInstallTip(81, $"注册客户公司中...")
                UpdateCompanyTable(db, lic.PublicDb, lic.VendorName)
                UpdateInstallTip(85, $"注册客户公司中！")

                UpdateInstallTip(86, $"注册客户数据库中...")
                UpdateDatabaseTable(db, lic.PublicDb, lic.VendorName, lic.MysqlDatabase, lic.MysqlUserID, lic.MysqlPassword)
                UpdateInstallTip(90, $"注册客户数据库完成！")
            Catch ex As Exception
                Throw New Exception($"注册客户失败,{ex.Message}")
            End Try

            db.Close()
        End Using
    End Sub


    Private Sub UpdateFormByLicense(lic As License)
        TxtVendorName.Text = lic.VendorName
        DtpExpirationDate.Value = Date.Parse(lic.ExpirationDate)

        TxtRemoteServer.Text = lic.MysqlServer
        NudRemotePort.Value = CInt(lic.MysqlPort)
        TxtRemoteUser.Text = lic.MysqlUserID
        TxtRemotePwd.Text = lic.MysqlPassword
        TxtRemotePrivateDb.Text = lic.MysqlDatabase
        TxtRemotePublicDb.Text = lic.PublicDb

        TxtLocalFileName.Text = lic.SqliteName
        TxtLocalPwd.Text = lic.SqlitePassword

        TxtFtpHost.Text = lic.FtpHost
        NudFtpPort.Value = CInt(lic.FtpPort)
        TxtFtpUser.Text = lic.FtpUser
        TxtFtpPwd.Text = lic.FtpPwd

        TxtMac.Text = lic.Mac
        TxtRemard.Text = lic.Remark
    End Sub



    Private Sub BtnLoad_Click(sender As Object, e As EventArgs) Handles BtnLoad.Click
        Dim licensePath As String
        Using openDlg As New OpenFileDialog
            openDlg.Title = $"请选择模板鉴权License文件的路径"
            openDlg.Filter = $"License文件(*.dat)|*.dat"
            If openDlg.ShowDialog() <> DialogResult.OK Then Return
            licensePath = openDlg.FileName
        End Using

        Try
            Dim lic As New License(licensePath)
            UpdateFormByLicense(lic)
        Catch ex As Exception
            MsgBox($"Load license file error:{ex.Message}")
        End Try

    End Sub


    Private Sub UpdateProgressBar(value As Integer)
        TsPrgInstall.Value = value
    End Sub

    Private Sub UpdateInstallLog(value As Integer, log As String)
        If value = 0 Then RtxTip.Clear()

        RtxTip.AppendText($"[{value,3}%]-[{Now}]{log}{vbCrLf}")
        RtxTip.ScrollToCaret()
    End Sub

    Private Sub UpdateInstallTip(value As Integer, str As String)
        UpdateProgressBar(value)

        UpdateInstallLog(value, str)
    End Sub

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Text = $"{Application.ProductName} {Application.ProductVersion}"

        DtpExpirationDate.Value = Now.AddMonths(6)
    End Sub

    Private Sub GroupBox2_Enter(sender As Object, e As EventArgs) Handles GroupBox2.Enter

    End Sub
End Class
