Imports System.ComponentModel
Imports System.Drawing
Imports System.Drawing.Imaging
Imports System.IO
Imports System.Text
Imports System.Xml
Imports UTS_Core.Database
Imports UTS_Core.UTSModule.Station

Namespace UTSModule.Project
    Public Class ProjectInfo

        ''' <summary>
        ''' 初始化项目模式
        ''' </summary>
        Enum InitializeModeEnum
            ''' <summary>
            ''' 从云端数据库加载项目信息
            ''' </summary>
            <Description("云数据库加载")>
            RemoteDatabaseLoad
            ''' <summary>
            ''' 从本地Xml文件加载项目信息
            ''' </summary>
            <Description("本地文件加载")>
            LocalXmlLoad
            ''' <summary>
            ''' 从本地数据库加载项目信息
            ''' </summary>
            <Description("本地数据库加载")>
            LocalDatabaseLoad
            ''' <summary>
            ''' 新建项目信息
            ''' </summary>
            <Description("新建项目")>
            Create
        End Enum

#Region "New"
        Sub New(userId As Integer, userName As String, projectName As String)
            Me.UserId = userId
            Me.UserName = userName
            Index = -1
            ProductTypeId = 0
            Name = projectName
            Description = String.Empty
            EolDate = Now.AddMonths(6) '有效期6个月
            InitializeMode = InitializeModeEnum.Create
            Station = New List(Of ProcessStation)()
            DeleteStation = New List(Of ProcessStation)()

            IsValid = True
            SnType = 1
        End Sub


        Sub New(userId As Integer, userName As String, projectName As String, mode As InitializeModeEnum)
            Me.UserId = userId
            Me.UserName = userName
            Index = -1
            ProductTypeId = 0
            Name = projectName
            Description = String.Empty
            EolDate = Now.AddMonths(6) '有效期6个月
            InitializeMode = mode
            Station = New List(Of ProcessStation)()
            DeleteStation = New List(Of ProcessStation)()

            IsValid = True
            SnType = 1

            InitializeProject(projectName, InitializeMode)
        End Sub


        Sub New(userId As Integer, userName As String, projectId As Integer, mode As InitializeModeEnum)
            Me.UserId = userId
            Me.UserName = userName

            Index = projectId
            ProductTypeId = 0
            Name = String.Empty
            Description = String.Empty
            EolDate = Now.AddMonths(6) '有效期6个月
            InitializeMode = mode
            Station = New List(Of ProcessStation)()
            DeleteStation = New List(Of ProcessStation)()

            IsValid = True
            SnType = 1

            InitializeProject(projectId, InitializeMode)
        End Sub

#End Region

#Region "Property"
        ''' <summary>
        ''' 当前项目初始化方式
        ''' </summary>
        ''' <returns></returns>
        Public Property InitializeMode() As InitializeModeEnum

        ''' <summary>
        ''' 项目索引，创建项目时生成
        ''' </summary>
        ''' <returns></returns>
        Public Property Index() As Integer

        ''' <summary>
        ''' 项目类型索引
        ''' </summary>
        ''' <returns></returns>
        Public Property ProductTypeId() As Integer

        ''' <summary>
        ''' 项目名称
        ''' </summary>
        ''' <returns></returns>
        Public Property Name() As String


        ''' <summary>
        ''' 项目图像在FTP中的文件名
        ''' </summary>
        ''' <returns></returns>
        Public Property ImageName() As String

        ''' <summary>
        ''' 项目描述
        ''' </summary>
        ''' <returns></returns>
        Public Property Description() As String

        ''' <summary>
        ''' 项目有效日期
        ''' </summary>
        ''' <returns></returns>
        Public Property EolDate() As Date

        ''' <summary>
        ''' 项目是否有效
        ''' </summary>
        ''' <returns></returns>
        Public Property IsValid As Boolean

        ''' <summary>
        ''' 1有订单模式，0无订单模式,暂无作用
        ''' </summary>
        ''' <returns></returns>
        Public Property SnType() As Integer

        ''' <summary>
        ''' 项目备注
        ''' </summary>
        ''' <returns></returns>
        Public Property Remark() As String

        ''' <summary>
        ''' 单价
        ''' </summary>
        ''' <returns></returns>
        Public Property Price() As Decimal


        ''' <summary>
        ''' 项目站集合
        ''' </summary>
        ''' <returns></returns>
        Public Property Station() As List(Of ProcessStation)

        ''' <summary>
        ''' 被删除测试站集合
        ''' </summary>
        ''' <returns></returns>
        Public Property DeleteStation() As List(Of ProcessStation)

        ''' <summary>
        ''' 项目信息是否被修改
        ''' </summary>
        ''' <returns></returns>
        Public Property InfoChanged() As Boolean

        ''' <summary>
        ''' 预览图被修改
        ''' </summary>
        ''' <returns></returns>
        Public Property PreviewImageChanged() As Boolean

        ''' <summary>
        ''' 项目当前操作人员索引
        ''' </summary>
        ''' <returns></returns>
        Public Property UserId() As Integer

        ''' <summary>
        ''' 项目当前操作人名称
        ''' </summary>
        ''' <returns></returns>
        Public Property UserName() As String



        Private _masterImg As Image
        Private _previewImg As Image

        Private _initLock As New Object

        ''' <summary>
        ''' 项目原图
        ''' </summary>
        ''' <returns></returns>
        Public Property MasterImage() As Image
            Get
                If _masterImg IsNot Nothing Then Return _masterImg
                If String.IsNullOrWhiteSpace(ImageName) Then Return Nothing
                SyncLock _initLock
                    Threading.Thread.MemoryBarrier()
                    If _masterImg IsNot Nothing Then Return _masterImg

                    Dim imgPath As String = UtsPath.ProductMasterImagePath(ImageName)
                    If File.Exists(imgPath) = False Then
                        Try
                            UtsFtp.CreateObject.FtpDownload(UtsPath.RemoteProductMasterImagePath(ImageName), imgPath)
                        Catch ex As Exception
                            Console.WriteLine($"下载产品原图失败,{ex.Message}")
                            Return Nothing
                        End Try
                    End If

                    Try
                        _masterImg = ImageProcessor.ImageProcessor.GetBitmapImage(imgPath)
                    Catch ex As Exception
                        _masterImg = Nothing
                    End Try
                End SyncLock

                Return _masterImg
            End Get
            Set(value As Image)
                _masterImg = value
            End Set
        End Property


        ''' <summary>
        ''' 项目预览图
        ''' </summary>
        ''' <returns></returns>
        Public Property PreviewImage() As Image
            Get
                If _previewImg IsNot Nothing Then Return _previewImg
                If String.IsNullOrWhiteSpace(ImageName) Then Return Nothing
                SyncLock _initLock
                    Threading.Thread.MemoryBarrier()
                    If _previewImg IsNot Nothing Then Return _previewImg

                    Dim imgPath As String = UtsPath.ProductPreviewImagePath(ImageName)
                    If File.Exists(imgPath) = False Then
                        Try
                            UtsFtp.CreateObject.FtpDownload(UtsPath.RemoteProductPreviewImagePath(ImageName), imgPath)
                        Catch ex As Exception
                            Console.WriteLine($"下载产品预览图失败,{ex.Message}")
                            Return Nothing
                        End Try
                    End If

                    _previewImg = ImageProcessor.ImageProcessor.GetBitmapImage(imgPath)
                End SyncLock
                Return _previewImg
            End Get
            Set(value As Image)
                _previewImg = value
            End Set
        End Property
#End Region

#Region "InitializeProject"
        ''' <summary>
        ''' 初始化项目
        ''' </summary>
        ''' <param name="projectName">项目名称</param>
        ''' <param name="mode">加载模式</param>
        Public Sub InitializeProject(projectName As String, mode As InitializeModeEnum)
            If mode = InitializeModeEnum.RemoteDatabaseLoad Then
                LoadRemoteDbProject(projectName)
            ElseIf mode = InitializeModeEnum.LocalDatabaseLoad Then
                LoadLocalDbProject(projectName)
            ElseIf mode = InitializeModeEnum.LocalXmlLoad Then
                LoadLocalXmlProject(projectName)
            ElseIf mode = InitializeModeEnum.Create Then

            Else
                Console.WriteLine($"InitializeProject Untreated Mode:{mode}")
            End If
        End Sub

        ''' <summary>
        ''' 初始化项目
        ''' </summary>
        ''' <param name="projectId">项目索引</param>
        ''' <param name="mode">加载模式</param>
        Public Sub InitializeProject(projectId As Integer, mode As InitializeModeEnum)
            If mode = InitializeModeEnum.RemoteDatabaseLoad Then
                LoadRemoteDbProject(projectId)
            ElseIf mode = InitializeModeEnum.LocalDatabaseLoad Then
                LoadLocalDbProject(projectId)
            ElseIf mode = InitializeModeEnum.LocalXmlLoad Then
                LoadLocalXmlProject(projectId.ToString())
            ElseIf mode = InitializeModeEnum.Create Then

            Else
                Console.WriteLine($"InitializeProject Untreated Mode:{mode}")
            End If
        End Sub


        ''' <summary>
        ''' 加载本地项目
        ''' </summary>
        ''' <param name="projectName">项目名称</param>
        Private Sub LoadLocalXmlProject(projectName As String)
            Dim filename As String = UtsPath.ProjectFilePath(projectName) '耦合了UTSPath类
            Dim xd As New XmlDocument() : xd.Load(filename)
            Dim nodeList As XmlNodeList = xd.SelectSingleNode("Project").ChildNodes
            For Each node As XmlNode In nodeList
                Dim xe As XmlElement = CType(node, XmlElement)
                Select Case xe.LocalName
                    Case $"Index"
                        Index = CInt(xe.InnerText)
                    Case $"ProductTypeId"
                        ProductTypeId = CInt(xe.InnerText)
                    Case $"Name"
                        Name = xe.InnerText
                    Case $"ImageName"
                        ImageName = xe.InnerText
                    'Case $"PreviewImage"
                    '    MasterImage = ImageProcessor.ImageProcessor.CompressImageWithSize(ImageProcessor.ImageProcessor.StringToImage(xe.InnerText))
                    Case $"Description"
                        Description = xe.InnerText
                    Case $"EolDate"
                        EolDate = CDate(xe.InnerText)
                    Case $"Remark"
                        Remark = xe.InnerText
                    Case $"Price"
                        Price = CDec(xe.InnerText)
                    Case "Stations"
                        LoadAllStation(node.ChildNodes)
                    Case Else
                        Console.WriteLine($"LoadLocalProject Unknow XmlNodeName:{xe.LocalName}")
                End Select
            Next
        End Sub

        ''' <summary>
        ''' 加载项目所有站
        ''' </summary>
        ''' <param name="nodeList"></param>
        Private Sub LoadAllStation(nodeList As XmlNodeList)
            Station.Clear()
            Dim xe As XmlElement
            For Each node As XmlNode In nodeList
                xe = CType(node, XmlElement)
                Select Case xe.LocalName
                    Case "ProcessStation"
                        LoadStation(xe.ChildNodes)
                End Select
            Next
        End Sub


        ''' <summary>
        ''' 加载测试站信息
        ''' </summary>
        ''' <param name="nodeList">Xml节点</param>
        Private Sub LoadStation(nodeList As XmlNodeList)
            Dim stationInfo As New ProcessStation(Me)
            Dim xe As XmlElement
            For Each node As XmlNode In nodeList
                xe = CType(node, XmlElement)
                Select Case xe.LocalName
                    Case $"StationID"
                        stationInfo.StationID = CInt(xe.InnerText)
                    Case $"ArtworkOrder"
                        stationInfo.ArtworkOrder = CInt(xe.InnerText)
                    Case $"Name"
                        stationInfo.Name = xe.InnerText
                    Case $"Type"
                        stationInfo.StationType = CType([Enum].Parse(GetType(ProcessStation.StationTypeEnum), xe.InnerText), ProcessStation.StationTypeEnum)
                        If [Enum].TryParse(xe.InnerText, stationInfo.StationType) = False Then
                            stationInfo.StationType = ProcessStation.StationTypeEnum.None
                        End If

                    Case $"PreviewImage"
                        stationInfo.PreViewImage = ImageProcessor.ImageProcessor.CompressImageWithSize(ImageProcessor.ImageProcessor.StringToImage(xe.InnerText))

                    Case $"DevType"
                        stationInfo.DevType = xe.InnerText
                    Case $"DevApp"
                        stationInfo.DevApp = xe.InnerText
                    Case $"Description"
                        stationInfo.Description = xe.InnerText
                    Case $"PacketName"
                        stationInfo.Packet.FileName = xe.InnerText
                    Case Else
                        Console.WriteLine($"LoadStationInfo Unknow XmlNodeName:{xe.LocalName}")
                End Select
            Next
            Station.Add(stationInfo)
        End Sub

        ''' <summary>
        ''' 通过数据表更新项目站信息
        ''' </summary>
        ''' <param name="dtStation"></param>
        Private Sub UpdateStationFromDataTable(dtStation As DataTable)
            Station.Clear()
            For Each row As DataRow In dtStation.Rows
                Dim stationInfo As New ProcessStation(Me)
                With stationInfo
                    .StationID = CInt(row(DbTableModel.Customer.StationListTable.ColNames.ID.ToString()))
                    .ArtworkOrder = CInt(row(DbTableModel.Customer.StationListTable.ColNames.ArtworkOrder.ToString()))

                    If [Enum].TryParse(CStr(row(DbTableModel.Customer.StationListTable.ColNames.StationType.ToString())), .StationType) = False Then
                        .StationType = ProcessStation.StationTypeEnum.None
                    End If

                    .SnType = CType([Enum].Parse(GetType(ProcessStation.SnTypeEnum), CStr(row(DbTableModel.Customer.StationListTable.ColNames.SnType.ToString()))), ProcessStation.SnTypeEnum)

                    .Name = row(DbTableModel.Customer.StationListTable.ColNames.StationName.ToString()).ToString()
                    .Description = row(DbTableModel.Customer.StationListTable.ColNames.StationDesc.ToString()).ToString()
                    .Packet.FileName = row(DbTableModel.Customer.StationListTable.ColNames.PacketName.ToString()).ToString()
                    .Packet.PacketMD5 = row(DbTableModel.Customer.StationListTable.ColNames.PacketMd5.ToString()).ToString()

                    .IsValid = CBool(row(DbTableModel.Customer.StationListTable.ColNames.Isvalid.ToString()))
                    .SnListOrder = CInt(row(DbTableModel.Customer.StationListTable.ColNames.SnListOrder.ToString()))

                    Dim image As Object = row(DbTableModel.Customer.StationListTable.ColNames.PreviewImage.ToString())
                    If IsDBNull(image) Then
                        .PreViewImage = Nothing
                    Else
                        .PreViewImage = ImageProcessor.ImageProcessor.BytesToImage(CType(image, Byte()))
                    End If
                End With
                Station.Add(stationInfo)
            Next
        End Sub

        ''' <summary>
        ''' 通过数据表更新项目信息
        ''' </summary>
        ''' <param name="dtProject"></param>
        Private Sub UpdateProjectFromDataTable(dtProject As DataTable)
            If Integer.TryParse(dtProject(0)(DbTableModel.Customer.ProjectTable.ColNames.ID.ToString()).ToString, Index) = False Then
                Index = -1
            End If

            If Integer.TryParse(dtProject(0)(DbTableModel.Customer.ProjectTable.ColNames.ProductTypeID.ToString()).ToString, ProductTypeId) = False Then
                ProductTypeId = -1
            End If

            Name = dtProject(0)(DbTableModel.Customer.ProjectTable.ColNames.ProjectName.ToString()).ToString()
            Description = dtProject(0)(DbTableModel.Customer.ProjectTable.ColNames.Description.ToString()).ToString()

            ImageName = dtProject(0)(DbTableModel.Customer.ProjectTable.ColNames.ImageName.ToString()).ToString()

            If Date.TryParse(dtProject(0)(DbTableModel.Customer.ProjectTable.ColNames.EolDate.ToString()).ToString, EolDate) = False Then
                EolDate = Now
            End If

            If Boolean.TryParse(dtProject(0)(DbTableModel.Customer.ProjectTable.ColNames.IsValid.ToString()).ToString, IsValid) = False Then
                IsValid = False
            End If

            If Integer.TryParse(dtProject(0)(DbTableModel.Customer.ProjectTable.ColNames.SnType.ToString()).ToString, SnType) = False Then
                SnType = -1
            End If

            Remark = dtProject(0)(DbTableModel.Customer.ProjectTable.ColNames.Remark.ToString()).ToString()

            If Decimal.TryParse(dtProject(0)(DbTableModel.Customer.ProjectTable.ColNames.Price.ToString()).ToString, Price) = False Then
                Price = 0
            End If
        End Sub


        ''' <summary>
        ''' 通过项目索引加载项目站信息
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="dbName">数据库名称</param>
        ''' <param name="projectId">项目索引</param>
        Private Sub LoadProjectStation(db As DbExecutor, dbName As String, projectId As Integer)
            Dim tableName As String = DbTableModel.Customer.StationListTable.TableName
            Dim condition As String = $"`{DbTableModel.Customer.StationListTable.ColNames.ProjectID}` = {projectId}  and `{DbTableModel.Customer.StationListTable.ColNames.Isvalid}` = 1 ORDER BY `{DbTableModel.Customer.StationListTable.ColNames.ArtworkOrder}`"
            Dim dtStation As DataTable = db.ExecuteDataTable(db.CmdHelper.DbSearchAll(dbName, tableName, condition))
            UpdateStationFromDataTable(dtStation)
        End Sub

        ''' <summary>
        ''' 通过项目索引初始化项目信息
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="dbName">数据库名称</param>
        ''' <param name="projectId">项目索引</param>
        Private Sub LoadProjectInfo(db As DbExecutor, dbName As String, projectId As Integer)
            Dim tableName As String = DbTableModel.Customer.ProjectTable.TableName
            Dim condition As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.ID}` = {projectId}"
            Dim dtProject As DataTable = db.ExecuteDataTable(db.CmdHelper.DbSearchAll(dbName, tableName, condition))

            If dtProject.Rows.Count <= 0 Then Throw New Exception($"Not Find ProjectID: {projectId}")
            UpdateProjectFromDataTable(dtProject)
        End Sub


        ''' <summary>
        ''' 通过项目索引从远程数据库初始化项目信息
        ''' </summary>
        ''' <param name="projectId">项目索引</param>
        Private Sub LoadRemoteDbProject(projectId As Integer)
            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()
                LoadProjectInfo(db, UtsDb.RemotePrivateDb, projectId)
                LoadProjectStation(db, UtsDb.RemotePrivateDb, projectId)
                db.Close()
            End Using
        End Sub


        ''' <summary>
        ''' 通过项目索引加载项目站信息
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="projectId">项目索引</param>
        Private Sub LoadProjectStation(db As DbExecutor, projectId As Integer)
            Dim tableName As String = DbTableModel.Customer.StationListTable.TableName
            Dim condition As String = $"`{DbTableModel.Customer.StationListTable.ColNames.ProjectID}` = {projectId} ORDER BY `{DbTableModel.Customer.StationListTable.ColNames.ArtworkOrder}`"
            Dim dtStation As DataTable = db.ExecuteDataTable(db.CmdHelper.SearchAll(tableName, condition))
            UpdateStationFromDataTable(dtStation)
        End Sub


        Private Function LoadStationPackets(db As DbExecutor, pid As Integer, sid As Integer) As List(Of StationPacketVo)
            Dim tableName As String = DbTableModel.Customer.StationPacketReleaseLogTable.TableName
            Dim colList As New List(Of String)
            colList.Add(DbTableModel.Customer.StationPacketReleaseLogTable.ColNames.ProjectID.ToString())
            colList.Add(DbTableModel.Customer.StationPacketReleaseLogTable.ColNames.StationID.ToString())
            colList.Add(DbTableModel.Customer.StationPacketReleaseLogTable.ColNames.PacketName.ToString())
            colList.Add(DbTableModel.Customer.StationPacketReleaseLogTable.ColNames.PacketMd5.ToString())
            colList.Add(DbTableModel.Customer.StationPacketReleaseLogTable.ColNames.Description.ToString())

            Dim condition As String = $"`{DbTableModel.Customer.StationPacketReleaseLogTable.ColNames.ProjectID}` = {pid} and `{DbTableModel.Customer.StationPacketReleaseLogTable.ColNames.StationID}` = {sid}"
            Dim dtProject As DataTable = db.ExecuteDataTable(db.CmdHelper.Search(colList, tableName, condition), False)

            Dim packetList As New List(Of StationPacketVo)
            For Each row As DataRow In dtProject.Rows
                Dim packet As New StationPacketVo With {
                    .ProjectID = CInt(row(DbTableModel.Customer.StationPacketReleaseLogTable.ColNames.ProjectID.ToString())),
                    .StationID = CInt(row(DbTableModel.Customer.StationPacketReleaseLogTable.ColNames.StationID.ToString())),
                    .PacketName = row(DbTableModel.Customer.StationPacketReleaseLogTable.ColNames.PacketName.ToString()).ToString(),
                    .PacketMd5 = row(DbTableModel.Customer.StationPacketReleaseLogTable.ColNames.PacketMd5.ToString()).ToString(),
                    .Description = row(DbTableModel.Customer.StationPacketReleaseLogTable.ColNames.Description.ToString()).ToString()
                }

                packetList.Insert(0, packet)
            Next

            Return packetList
        End Function


        ''' <summary>
        ''' 获取当前站位所有站包
        ''' </summary>
        ''' <param name="pid"></param>
        ''' <param name="sid"></param>
        ''' <returns></returns>
        Public Function LoadLocalDbStationPackets(pid As Integer, sid As Integer) As List(Of StationPacketVo)
            Dim packetList As New List(Of StationPacketVo)

            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()
                packetList.AddRange(LoadStationPackets(db, pid, sid))
                db.Close()
            End Using

            Return packetList
        End Function

        ''' <summary>
        ''' 通过项目索引初始化项目信息
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="projectId">项目索引</param>
        Private Sub LoadProjectInfo(db As DbExecutor, projectId As Integer)
            Dim tableName As String = DbTableModel.Customer.ProjectTable.TableName
            Dim condition As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.ID}` = {projectId}"
            Dim dtProject As DataTable = db.ExecuteDataTable(db.CmdHelper.SearchAll(tableName, condition))
            If dtProject.Rows.Count <= 0 Then Throw New Exception($"Not Find ProjectID: {projectId}")

            UpdateProjectFromDataTable(dtProject)
        End Sub

        ''' <summary>
        ''' 通过项目索引从本地数据库初始化项目信息
        ''' </summary>
        ''' <param name="projectId">项目索引</param>
        Private Sub LoadLocalDbProject(projectId As Integer)
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()
                LoadProjectInfo(db, projectId)
                LoadProjectStation(db, projectId)
                db.Close()
            End Using
        End Sub

        ''' <summary>
        ''' 通过项目名称加载数据库项目信息
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="dbName">数据库名</param>
        ''' <param name="projectName">项目名称</param>
        Private Sub LoadProjectInfo(db As DbExecutor, dbName As String, projectName As String)
            Dim tableName As String = DbTableModel.Customer.ProjectTable.TableName
            Dim condition As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.ProjectName}` = '{projectName}'"
            Dim dtProject As DataTable = db.ExecuteDataTable(db.CmdHelper.DbSearchAll(dbName, tableName, condition))
            If dtProject.Rows.Count <= 0 Then Throw New Exception($"Not Find projectName: {projectName}")

            UpdateProjectFromDataTable(dtProject)
        End Sub

        ''' <summary>
        ''' 通过项目名称从远程数据库初始化项目信息
        ''' </summary>
        ''' <param name="projectName">项目名称</param>
        Private Sub LoadRemoteDbProject(projectName As String)
            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()
                LoadProjectInfo(db, UtsDb.RemotePrivateDb, projectName)
                LoadProjectStation(db, UtsDb.RemotePrivateDb, Index)
                db.Close()
            End Using
        End Sub

        ''' <summary>
        ''' 通过项目名称加载数据库项目信息
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="projectName">项目名称</param>
        Private Sub LoadProjectInfo(db As DbExecutor, projectName As String)
            Dim tableName As String = DbTableModel.Customer.ProjectTable.TableName
            Dim condition As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.ProjectName}` = '{projectName}'"
            Dim dtProject As DataTable = db.ExecuteDataTable(db.CmdHelper.SearchAll(tableName, condition))
            If dtProject.Rows.Count <= 0 Then Throw New Exception($"Not Find projectName: {projectName}")

            UpdateProjectFromDataTable(dtProject)
        End Sub

        ''' <summary>
        ''' 通过项目名称从本地数据库初始化项目信息
        ''' </summary>
        ''' <param name="projectName">项目名称</param>
        Private Sub LoadLocalDbProject(projectName As String)
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()
                LoadProjectInfo(db, projectName)
                LoadProjectStation(db, Index)
                db.Close()
            End Using
        End Sub

#End Region

#Region "LoadProjectList"
        ''' <summary>
        ''' 加载本地项目列表
        ''' </summary>
        ''' <param name="projectDirPath"></param>
        ''' <returns></returns>
        Private Shared Function LoadLocalProjectList(projectDirPath As String) As String()
            If Directory.Exists(projectDirPath) = False Then Return New String() {}
            Dim prjName, prjDirName As String
            Dim lstProjects As New List(Of String)
            Dim prjDirPaths As String() = Directory.GetDirectories(projectDirPath)
            For Each prjDirPath As String In prjDirPaths
                For Each fileName As String In Directory.GetFiles(prjDirPath)
                    prjName = Path.GetFileNameWithoutExtension(fileName)
                    prjDirName = Path.GetDirectoryName(fileName)
                    If prjDirName.EndsWith(prjName) Then
                        lstProjects.Add(prjName)
                        Exit For
                    End If
                Next
            Next
            Return lstProjects.ToArray()
        End Function


        ''' <summary>
        ''' 从数据表中提取项目名称列表
        ''' </summary>
        ''' <param name="dtProject"></param>
        ''' <returns></returns>
        Private Shared Function GetProjectsNameFromDataTable(dtProject As DataTable) As String()
            Dim lstProjects As New List(Of String)
            For Each row As DataRow In dtProject.Rows
                lstProjects.Add(row($"{DbTableModel.Customer.ProjectTable.ColNames.ProjectName}").ToString())
            Next
            Return lstProjects.ToArray()
        End Function


        ''' <summary>
        ''' 从远程数据库加载项目名列表
        ''' </summary>
        ''' <returns></returns>
        Private Shared Function LoadRemoteProjectList() As String()
            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()
                Dim tableName As String = DbTableModel.Customer.ProjectTable.TableName
                Dim colNames As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.ProjectName}`"
                Dim condition As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.IsValid}` = 1 order by `{DbTableModel.Customer.ProjectTable.ColNames.ProjectName}` asc"
                Dim dtProject As DataTable = db.ExecuteDataTable(db.CmdHelper.DbSearch(UtsDb.RemotePrivateDb, colNames, tableName, condition))
                db.Close()
                Return GetProjectsNameFromDataTable(dtProject)
            End Using
        End Function

        ''' <summary>
        ''' 从本地数据库加载项目名列表
        ''' </summary>
        ''' <returns></returns>
        Private Shared Function LoadLocalProjectList() As String()
            Using db As New DbExecutor(UtsDb.LocalDbType, UtsDb.LocalConnString)
                db.Open()
                Dim tableName As String = DbTableModel.Customer.ProjectTable.TableName
                Dim colNames As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.ProjectName}`"
                Dim condition As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.IsValid}` = 1 order by `{DbTableModel.Customer.ProjectTable.ColNames.ProjectName}` asc"
                Dim dtProject As DataTable = db.ExecuteDataTable(db.CmdHelper.Search(colNames, tableName, condition))
                db.Close()
                Return GetProjectsNameFromDataTable(dtProject)
            End Using
        End Function

        ''' <summary>
        ''' 加载项目列表
        ''' </summary>
        ''' <param name="mode">加载模式</param>
        ''' <returns></returns>
        Public Shared Function LoadProjectList(mode As InitializeModeEnum) As String()
            Select Case mode
                Case InitializeModeEnum.RemoteDatabaseLoad
                    Return LoadRemoteProjectList()
                Case InitializeModeEnum.LocalDatabaseLoad
                    Return LoadLocalProjectList()
                Case InitializeModeEnum.LocalXmlLoad
                    Dim projectDirPath As String = UtsPath.ProjectDesignDirPath() '耦合了UTSPath类
                    Return LoadLocalProjectList(projectDirPath)
                Case InitializeModeEnum.Create
                    Console.WriteLine($"LoadProjectList Untreated Mode:{mode}")
                    Return New String() {}
                Case Else
                    Console.WriteLine($"LoadProjectList Untreated Mode:{mode}")
                    Return New String() {}
            End Select
        End Function
#End Region

#Region "ExportToXml"
        ''' <summary>
        ''' 保存项目所有站信息
        ''' </summary>
        ''' <param name="xw"></param>
        Private Sub SaveProjectAllStation(xw As XmlWriter)
            xw.WriteStartElement($"Stations") '保存测试站信息节点
            For Each stationInfo As ProcessStation In Station
                xw.WriteStartElement($"Station")
                xw.WriteElementString("StationID", stationInfo.StationID.ToString())
                xw.WriteElementString("ArtworkOrder", stationInfo.ArtworkOrder.ToString())
                xw.WriteElementString("Name", stationInfo.Name)
                xw.WriteElementString("Type", stationInfo.StationType.ToString())
                xw.WriteElementString("PreviewImage", ImageProcessor.ImageProcessor.ImageToString(ImageProcessor.ImageProcessor.CompressImageWithSize(stationInfo.PreViewImage)))
                xw.WriteElementString("DevType", stationInfo.DevType)
                xw.WriteElementString("DevApp", stationInfo.DevApp)
                xw.WriteElementString("Description", stationInfo.Description)
                xw.WriteElementString("PacketName", stationInfo.Packet.FileName)
                xw.WriteEndElement()
            Next
            xw.WriteEndElement()
        End Sub

        ''' <summary>
        ''' 保存项目至本地文件
        ''' </summary>
        ''' <param name="filePath"></param>
        Private Sub SaveProjectToLocalFile(filePath As String)
            Dim xws As New XmlWriterSettings
            With xws
                .Indent = True
                .NewLineOnAttributes = False
                .Encoding = New UTF8Encoding(False)
            End With

            Using xw As XmlWriter = XmlWriter.Create(filePath, xws)
                xw.WriteStartDocument()
                xw.WriteStartElement($"Project") '创建跟节点

                xw.WriteElementString("Index", Index.ToString())
                xw.WriteElementString("ProductTypeId", ProductTypeId.ToString())
                xw.WriteElementString("Name", Name)
                xw.WriteElementString("ImageName", ImageName)
                'xw.WriteElementString("PreviewImage", ImageProcessor.ImageProcessor.ImageToString(ImageProcessor.ImageProcessor.CompressImageWithSize(MasterImage)))
                xw.WriteElementString("Description", Description)
                xw.WriteElementString("EolDate", EolDate.ToString())
                xw.WriteElementString("Remark", Remark)
                xw.WriteElementString("Price", Price.ToString())


                SaveProjectAllStation(xw)

                xw.WriteEndElement()
                xw.WriteEndDocument()
                xw.Flush()
                xw.Close()
            End Using
        End Sub

        ''' <summary>
        ''' 将项目信息保存至本Xml文件
        ''' </summary>
        Public Sub ExportToXml(filePath As String)
            Dim fileDirPath As String = filePath.Substring(0, filePath.LastIndexOf("\"c))

            If Directory.Exists(fileDirPath) = False Then Directory.CreateDirectory(fileDirPath) '判断本地文件夹是否存在
            If File.Exists(filePath) Then File.Delete(filePath)
            SaveProjectToLocalFile(filePath)
        End Sub
#End Region

#Region "Update Project"
        Private Function ProjectNameExists(db As DbExecutor, dbName As String, project As ProjectInfo) As Boolean
            Dim tableName As String = DbTableModel.Customer.ProjectTable.TableName
            Dim colNames As String = $"Count(*)"
            Dim condition As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.ProjectName}` = '{project.Name}' and 
                                        `{DbTableModel.Customer.ProjectTable.ColNames.ID}` != '{project.Index}' "

            Return CInt(db.ExecuteScalar(db.CmdHelper.DbSearch(dbName, colNames, tableName, condition))) > 0
        End Function



        ''' <summary>
        ''' 查询项目是否存在
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="dbName">数据库名称</param>
        ''' <param name="project">项目信息</param>
        ''' <returns></returns>
        Private Function ProjectExists(db As DbExecutor, dbName As String, project As ProjectInfo) As Boolean
            Dim tableName As String = DbTableModel.Customer.ProjectTable.TableName
            Dim colNames As String = $"Count(*)"
            Dim condition As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.ProjectName}` = '{project.Name}' or `{DbTableModel.Customer.ProjectTable.ColNames.ID}` = '{project.Index}' "
            Return CInt(db.ExecuteScalar(db.CmdHelper.DbSearch(dbName, colNames, tableName, condition))) > 0
        End Function


        ''' <summary>
        ''' 项目表修改原有项目信息
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="dbName">数据库名称</param>
        ''' <param name="project">项目信息</param>
        Private Sub UpdateProjectTable(db As DbExecutor, dbName As String, project As ProjectInfo)
            Dim tableName As String = DbTableModel.Customer.ProjectTable.TableName
            Dim condition As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.ID}` = '{project.Index}'"

            Dim colName As String
            Dim colNames As New List(Of String)

            db.ClearDbParameter()
            If project.PreviewImageChanged Then
                colName = $"{DbTableModel.Customer.ProjectTable.ColNames.ImageName}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.AnsiString, colName, project.ImageName)

                SaveProjectImage(project) '保存项目图像文件至本地,发布至Ftp
            End If


            If project.InfoChanged Then
                colName = $"{DbTableModel.Customer.ProjectTable.ColNames.ProductTypeID}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.Int32, colName, project.ProductTypeId)

                colName = $"{DbTableModel.Customer.ProjectTable.ColNames.ProjectName}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.AnsiString, colName, project.Name)

                colName = $"{DbTableModel.Customer.ProjectTable.ColNames.Description}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.AnsiString, colName, project.Description)

                colName = $"{DbTableModel.Customer.ProjectTable.ColNames.EolDate}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.DateTime, colName, $"{project.EolDate:yyyy-MM-dd HH:mm:ss}")

                colName = $"{DbTableModel.Customer.ProjectTable.ColNames.Remark}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.AnsiString, colName, project.Remark)

                colName = $"{DbTableModel.Customer.ProjectTable.ColNames.Price}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.AnsiString, colName, project.Price)

                colName = $"{DbTableModel.Customer.ProjectTable.ColNames.SnType}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.Int32, colName, project.SnType)
            End If

            If colNames.Count = 0 Then Return '无更改则退出
            db.ExecuteNonQuery(db.CmdHelper.DbUpdateParam(dbName, tableName, colNames, condition))
        End Sub


        ''' <summary>
        ''' 项目表添加新项目
        ''' </summary>
        ''' <param name="db">数据库执行器</param>
        ''' <param name="dbName">数据库名称</param>
        ''' <param name="project">项目信息</param>
        Private Sub InsertProjectTable(db As DbExecutor, dbName As String, project As ProjectInfo)
            Dim tableName As String = DbTableModel.Customer.ProjectTable.TableName

            Dim colName As String
            Dim colNames As New List(Of String)

            db.ClearDbParameter()

            colName = $"{DbTableModel.Customer.ProjectTable.ColNames.ProductTypeID}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.Int32, colName, project.ProductTypeId)

            colName = $"{DbTableModel.Customer.ProjectTable.ColNames.ProjectName}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.AnsiString, colName, project.Name)

            colName = $"{DbTableModel.Customer.ProjectTable.ColNames.Description}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.AnsiString, colName, project.Description)

            colName = $"{DbTableModel.Customer.ProjectTable.ColNames.UserID}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.Int32, colName, project.UserId)

            colName = $"{DbTableModel.Customer.ProjectTable.ColNames.CreateTime}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.DateTime, colName, $"{Now:yyyy-MM-dd HH:mm:ss}")

            colName = $"{DbTableModel.Customer.ProjectTable.ColNames.EolDate}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.DateTime, colName, $"{project.EolDate:yyyy-MM-dd HH:mm:ss}")

            colName = $"{DbTableModel.Customer.ProjectTable.ColNames.ImageName}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.AnsiString, colName, project.ImageName)

            colName = $"{DbTableModel.Customer.ProjectTable.ColNames.Price}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.AnsiString, colName, project.Price)

            colName = $"{DbTableModel.Customer.ProjectTable.ColNames.SnType}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.Int32, colName, project.SnType)

            colName = $"{DbTableModel.Customer.ProjectTable.ColNames.Remark}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.AnsiString, colName, project.Remark)

            db.ExecuteNonQuery(db.CmdHelper.DbInsertParam(dbName, tableName, colNames))
        End Sub

        ''' <summary>
        ''' 更新项目索引
        ''' </summary>
        Private Function UpdateProjectIndex(db As DbExecutor, dbName As String, projectName As String) As Integer
            Dim tableName As String = DbTableModel.Customer.ProjectTable.TableName
            Dim colNames As String = $"{DbTableModel.Customer.ProjectTable.ColNames.ID}"
            Dim condition As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.ProjectName}` = '{projectName}'"
            Return CInt(db.ExecuteScalar(db.CmdHelper.DbSearch(dbName, colNames, tableName, condition)))
        End Function


        Private Sub UploadProjectTable(db As DbExecutor, dbName As String, project As ProjectInfo)
            '项目重名检测
            If ProjectNameExists(db, dbName, project) Then
                Throw New Exception($"{project.Name} already exists!")
            End If

            '项目已发布检测
            If ProjectExists(db, dbName, project) Then
                UpdateProjectTable(db, dbName, project)
            Else
                InsertProjectTable(db, dbName, project) '项目表添加一行

                SaveProjectImage(project) '保存项目图像文件至本地,发布至Ftp

                project.Index = UpdateProjectIndex(db, dbName, project.Name) '更新项目索引
            End If

            project.PreviewImageChanged = False
            project.InfoChanged = False
        End Sub

        ''' <summary>
        ''' 更新上传项目信息
        ''' </summary>
        ''' <param name="db"></param>
        ''' <param name="project"></param>
        Private Sub UploadProjectInfo(db As DbExecutor, dbName As String, project As ProjectInfo)

            '将项目信息更新到项目表
            UploadProjectTable(db, dbName, project)
        End Sub


        Private Sub SaveProjectImage(project As ProjectInfo)
            Directory.CreateDirectory(UtsPath.ProductMasterImageDirPath())
            Directory.CreateDirectory(UtsPath.ProductPreviewImageDirPath())

            Dim imgPath As String
            Dim ftp As UtsFtp = UtsFtp.CreateObject

            imgPath = UtsPath.ProductMasterImagePath(project.ImageName)
            project.MasterImage.Save(imgPath)
            ftp.FtpUpload(UtsPath.RemoteProductMasterImagePath(project.ImageName), imgPath)

            imgPath = UtsPath.ProductPreviewImagePath(project.ImageName)
            project.PreviewImage.Save(imgPath)
            ftp.FtpUpload(UtsPath.RemoteProductPreviewImagePath(project.ImageName), imgPath)
        End Sub
#End Region

#Region "Update Station"
        Private Function StationExists(db As DbExecutor, dbName As String, processStation As ProcessStation) As Boolean
            Dim tableName As String = DbTableModel.Customer.StationListTable.TableName
            Dim colName As String = "Count(*)"
            Dim condition As String = $"`{DbTableModel.Customer.StationListTable.ColNames.ProjectID}` = {processStation.ParentProject.Index} and (`{DbTableModel.Customer.StationListTable.ColNames.StationName}` = '{processStation.Name}' or  `{DbTableModel.Customer.StationListTable.ColNames.ID}` = '{processStation.StationID}')"
            Return CInt(db.ExecuteScalar(db.CmdHelper.DbSearch(dbName, colName, tableName, condition))) > 0
        End Function


        Private Sub InsertRowStationTable(db As DbExecutor, dbName As String, processStation As ProcessStation)
            Dim tableName As String = DbTableModel.Customer.StationListTable.TableName
            Dim colName As String
            Dim colNames As New List(Of String)

            db.ClearDbParameter()

            colName = $"{DbTableModel.Customer.StationListTable.ColNames.ProjectID}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.Int32, colName, processStation.ParentProject.Index)

            colName = $"{DbTableModel.Customer.StationListTable.ColNames.StationName}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.AnsiString, colName, processStation.Name)

            colName = $"{DbTableModel.Customer.StationListTable.ColNames.StationType}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.AnsiString, colName, processStation.StationType.ToString())

            colName = $"{DbTableModel.Customer.StationListTable.ColNames.ArtworkOrder}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.Int32, colName, processStation.ArtworkOrder)

            colName = $"{DbTableModel.Customer.StationListTable.ColNames.SnListOrder}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.Int32, colName, processStation.SnListOrder)

            colName = $"{DbTableModel.Customer.StationListTable.ColNames.SnType}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.Int32, colName, processStation.SnType)

            colName = $"{DbTableModel.Customer.StationListTable.ColNames.StationDesc}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.AnsiString, colName, processStation.Description)

            colName = $"{DbTableModel.Customer.StationListTable.ColNames.LastUpdateDate}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.DateTime, colName, Now.ToString("yyyy-MM-dd HH:mm:ss"))

            '最新包名
            colName = $"{DbTableModel.Customer.StationListTable.ColNames.PacketName}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.AnsiString, colName, processStation.Packet.FileName)

            '预览图
            colName = $"{DbTableModel.Customer.StationListTable.ColNames.PreviewImage}"
            colNames.Add(colName)
            db.AddDbParameter(DbType.Binary, colName, ImageProcessor.ImageProcessor.ImageToBytes(processStation.PreViewImage, ImageFormat.Png))

            db.ExecuteNonQuery(db.CmdHelper.DbInsertParam(dbName, tableName, colNames))
        End Sub


        Private Sub UpdateRowStationTable(db As DbExecutor, dbName As String, processStation As ProcessStation)
            Dim tableName As String = DbTableModel.Customer.StationListTable.TableName
            Dim condition As String = $"`{DbTableModel.Customer.StationListTable.ColNames.ProjectID}` = {processStation.ParentProject.Index} and `{DbTableModel.Customer.StationListTable.ColNames.ID}` = '{processStation.StationID}'"

            Dim colName As String
            Dim colNames As New List(Of String)

            db.ClearDbParameter()

            '基础信息
            If processStation.InfoChanged Then
                colName = $"{DbTableModel.Customer.StationListTable.ColNames.StationName}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.AnsiString, colName, processStation.Name)

                colName = $"{DbTableModel.Customer.StationListTable.ColNames.StationType}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.AnsiString, colName, processStation.StationType.ToString())

                colName = $"{DbTableModel.Customer.StationListTable.ColNames.ArtworkOrder}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.Int32, colName, processStation.ArtworkOrder)

                colName = $"{DbTableModel.Customer.StationListTable.ColNames.SnType}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.Int32, colName, processStation.SnType)

                colName = $"{DbTableModel.Customer.StationListTable.ColNames.StationDesc}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.AnsiString, colName, processStation.Description)

                colName = $"{DbTableModel.Customer.StationListTable.ColNames.LastUpdateDate}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.DateTime, colName, Now.ToString("yyyy-MM-dd HH:mm:ss"))

                '最新包名
                colName = $"{DbTableModel.Customer.StationListTable.ColNames.PacketName}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.AnsiString, colName, processStation.Packet.FileName)
            End If

            '预览图
            If processStation.PreviewImageChanged Then
                colName = $"{DbTableModel.Customer.StationListTable.ColNames.PreviewImage}"
                colNames.Add(colName)
                db.AddDbParameter(DbType.Binary, colName, ImageProcessor.ImageProcessor.ImageToBytes(processStation.PreViewImage, ImageFormat.Png))
            End If

            If colNames.Count = 0 Then Return '无修改

            db.ExecuteNonQuery(db.CmdHelper.DbUpdateParam(dbName, tableName, colNames, condition))
        End Sub


        ''' <summary>
        ''' 更新工艺站索引
        ''' </summary>
        Private Function UpdateStationIndex(db As DbExecutor, dbName As String, processStation As ProcessStation) As Integer
            Dim tableName As String = DbTableModel.Customer.StationListTable.TableName
            Dim colNames As String = $"{DbTableModel.Customer.StationListTable.ColNames.ID}"
            Dim condition As String = $"`{DbTableModel.Customer.StationListTable.ColNames.ProjectID}` = {processStation.ParentProject.Index} And `{DbTableModel.Customer.StationListTable.ColNames.StationName}` = '{processStation.Name}'"
            Return CInt(db.ExecuteScalar(db.CmdHelper.DbSearch(dbName, colNames, tableName, condition)))
        End Function


        Private Sub UploadStationTable(db As DbExecutor, dbName As String, processStation As ProcessStation)
            If StationExists(db, dbName, processStation) Then
                UpdateRowStationTable(db, dbName, processStation)
            Else
                '查询总数,赋值
                Dim condition As String = $"`{DbTableModel.Customer.StationListTable.ColNames.ProjectID}` = {processStation.ParentProject.Index}"
                Dim tbName As String = DbTableModel.Customer.StationListTable.TableName
                processStation.SnListOrder = CInt(db.ExecuteScalar(db.CmdHelper.DbSearchCount(UtsDb.RemotePrivateDb, tbName, condition))) + 1

                InsertRowStationTable(db, dbName, processStation)

                processStation.StationID = UpdateStationIndex(db, dbName, processStation)
            End If
        End Sub


        Private Sub UploadTestLogTable(db As DbExecutor, dbName As String, processStation As ProcessStation)
            Dim tbName As String = DbTableModel.Customer.TestLogTable.TableName(processStation.ParentProject.Index, processStation.StationID)

            '创建测试记录表
            db.ExecuteNonQuery(DbTableModel.Customer.TestLogTable.CreateTableString(dbName, tbName, db.DatabaseType))

            '不同类型检测必要字段是否添加
            Dim field As New Dictionary(Of String, String)
            Select Case processStation.StationType
                Case ProcessStation.StationTypeEnum.AOI
                    field.Add("ImagePath", "varchar(128)")
                    field.Add("ImagePath2", "varchar(128)")
                Case ProcessStation.StationTypeEnum.Assem
                    field.Add("AssemblySn", "varchar(128)")
                Case ProcessStation.StationTypeEnum.PE

                Case ProcessStation.StationTypeEnum.QA
                    field.Add("QA_FlowLog", "varchar(1024)")
                    field.Add("QA_CheckResult", "varchar(128)")
                Case ProcessStation.StationTypeEnum.Test

                Case ProcessStation.StationTypeEnum.Test2

            End Select

            Dim colList As List(Of String) = DbConnect.DbConnector.GetUnExistsColList(db, dbName, tbName, field.Keys.ToList())

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


        Private Sub UploadStationInfo(db As DbExecutor, dbName As String, project As ProjectInfo)
            For Each stationInfo As ProcessStation In project.Station
                '更新测试站信息
                UploadStationTable(db, dbName, stationInfo)

                '创建测试站记录表
                UploadTestLogTable(db, dbName, stationInfo)

                stationInfo.PreviewImageChanged = False
                stationInfo.InfoChanged = False
                stationInfo.TypeChange = False
            Next
        End Sub

#End Region

#Region "Release Project"
        Private Sub ReleaseDataToDatabase()
            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()

                UploadProjectInfo(db, UtsDb.RemotePrivateDb, Me) '更新项目表

                DeleteStationInfo(db, UtsDb.RemotePrivateDb, Me) '删除数据库项目站相关信息

                UploadStationInfo(db, UtsDb.RemotePrivateDb, Me) '更新数据库项目站相关信息

                db.Close()
            End Using
        End Sub


        ''' <summary>
        ''' 发布项目，将项目保存至本地,然后发布项目
        ''' </summary>
        Public Sub Release(filePath As String)
            ExportToXml(filePath)

            ReleaseDataToDatabase()
        End Sub
#End Region

#Region "Delete Station"
        Private Sub DeleteStationInfo(db As DbExecutor, dbName As String, project As ProjectInfo)
            Dim tableName As String = DbTableModel.Customer.StationListTable.TableName
            For Each stationInfo As ProcessStation In project.DeleteStation
                Dim condition As String = $"`{DbTableModel.Customer.StationListTable.ColNames.ProjectID}` = '{project.Index}' And `{DbTableModel.Customer.StationListTable.ColNames.ID}` = '{stationInfo.StationID}'"
                Dim destStr As String = $"`{DbTableModel.Customer.StationListTable.ColNames.Isvalid}` = 0"
                db.ExecuteNonQuery(db.CmdHelper.DbUpdate(dbName, tableName, destStr, condition))
            Next
            project.DeleteStation.Clear()
        End Sub
#End Region

#Region "Delete Project"

        ''' <summary>
        ''' 删除项目在云端所有相关信息
        ''' </summary>
        Public Sub Delete()
            Dim tableName As String = DbTableModel.Customer.ProjectTable.TableName
            Using db As New DbExecutor(UtsDb.RemoteDbType, UtsDb.RemoteConnString)
                db.Open()

                Dim condition As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.ID}` = {Index}"
                Dim destStr As String = $"`{DbTableModel.Customer.ProjectTable.ColNames.IsValid}` = 0"
                db.CmdHelper.DbUpdate(UtsDb.RemotePrivateDb, tableName, destStr, condition)

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