Imports System.IO
Imports System.Net
Imports System.Windows.Forms
Imports UTS_Core.UTSModule.Login
Imports UTS_Core.UTSModule.Production
Imports UTS_Core.UTSModule.Station

Namespace UTSModule.Project
    Public Class FrmProject

        Private _userProject As ProjectInfo
        Private _userInfo As UserInfo
        Private _productTypeManager As ProductTypeManager

        Public Sub ShowForm(parentControl As Control, userInfo As UserInfo)
            FormBorderStyle = FormBorderStyle.None
            TopLevel = False
            Dock = DockStyle.Fill
            Parent = parentControl

            _userInfo = userInfo
            Show()
        End Sub


        Private Sub EnabledSaveProject(isEnabled As Boolean)
            TsBtnSaveProject.Enabled = isEnabled
            TsBtnReleaseProject.Enabled = isEnabled
            TsBtnDeleteProject.Enabled = isEnabled

            TxtProjectName.Enabled = isEnabled
            TxtDescription.Enabled = isEnabled
            GrdStations.Enabled = isEnabled
            PicProject.Enabled = isEnabled
            TxtRemark.Enabled = isEnabled
            NudPrice.Enabled = isEnabled

            CboProjectType.Enabled = isEnabled
            DtpValidDate.Enabled = isEnabled

            RadOrderCreate.Enabled = isEnabled
            RadTestCreate.Enabled = isEnabled
        End Sub

        Private Sub InitializeForm()
            _productTypeManager = ProductTypeManager.CreateManager()
            CboProjectType.Items.AddRange(_productTypeManager.GetAllProductType())

            EnabledSaveProject(_userProject IsNot Nothing)
        End Sub


        Private Sub FrmProject_Load(sender As Object, e As EventArgs) Handles Me.Load
            InitializeForm()

        End Sub

        Private Sub LoadProjectInitForm(project As ProjectInfo)
            TxtProjectName.Text = project.Name
            TxtDescription.Text = project.Description
            TxtRemark.Text = project.Remark
            PicProject.Image = project.MasterImage
            NudPrice.Value = project.Price

            Select Case project.SnType
                Case 0
                    RadTestCreate.Checked = True
                Case 1
                    RadOrderCreate.Checked = True
            End Select

            'todo:初始化产品类型ID
            CboProjectType.SelectedIndex = CboProjectType.Items.IndexOf(_productTypeManager.GetProductType(project.ProductTypeId))
            DtpValidDate.Value = project.EolDate

            EnabledSaveProject(_userProject IsNot Nothing)
            ProjectStationGrid.InitTestStationGrid(GrdStations, project)
        End Sub

        Private Sub TsBtnNewProject_Click(sender As Object, e As EventArgs) Handles TsBtnNewProject.Click
            Using dlg As New DlgCreateProject
                If dlg.ShowDialog() <> DialogResult.OK Then Return
                _userProject = New ProjectInfo(_userInfo.UserId, _userInfo.UserName, dlg.ProjectName)
                LoadProjectInitForm(_userProject)
            End Using
        End Sub


        Private Sub TsBtnLoadProject_Click(sender As Object, e As EventArgs) Handles TsBtnLoadProject.Click
            Using dlg As New DlgLoadProject
                If dlg.ShowDialog() <> DialogResult.OK Then Return
                Try
                    _userProject = New ProjectInfo(_userInfo.UserId, _userInfo.UserName, dlg.ProjectName, dlg.LoadMode)
                    LoadProjectInitForm(_userProject) '初始化页面
                Catch ex As Exception
                    MsgBox($"Load Project Error:{ex.Message}")
                End Try
            End Using
        End Sub


        Private Sub TsBtnCloneProject_Click(sender As Object, e As EventArgs) Handles TsBtnCloneProject.Click
            Using dlg As New DlgLoadProject
                If dlg.ShowDialog() <> DialogResult.OK Then Return
                Try
                    _userProject = New ProjectInfo(_userInfo.UserId, _userInfo.UserName, dlg.ProjectName, dlg.LoadMode)
                    LoadProjectInitForm(_userProject) '初始化页面
                    _userProject.Index = -1
                Catch ex As Exception
                    MsgBox($"Clone Project Error:{ex.Message}")
                End Try
            End Using

        End Sub

        ''' <summary>
        ''' 检测用户对项目的修改是否输入合法
        ''' 不合法时会抛出异常
        ''' </summary>
        Private Sub CheckUserAlter()
            If String.IsNullOrEmpty(TxtProjectName.Text) Then Throw New Exception($"项目名称不能空，请重新输入！")
            '后续可新增对项目名中非常规字符的检测

            For row As Integer = 1 To GrdStations.Rows - 1
                If String.IsNullOrEmpty(GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.Name).Text) Then
                    GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.Name).SetFocus()
                    Throw New Exception($"项目站名不能为空，如若未使用，请右键删除该站！")

                    '后续可新增对项目站名中非常规字符的检测
                End If


                If String.IsNullOrEmpty(GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.Type).Text) Then
                    GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.Type).SetFocus()
                    Throw New Exception($"项目类型不能为空，如若未使用，请右键删除该站！")

                    '后续可新增对项目站名中非常规字符的检测
                End If


                If String.IsNullOrEmpty(GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.SnType).Text) Then
                    GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.SnType).SetFocus()
                    Throw New Exception($"项目条码规则不能为空，如若未使用，请右键删除该站！")

                    '后续可新增对项目站名中非常规字符的检测
                End If
            Next
        End Sub

        Private Sub UpdateProjectInfo(project As ProjectInfo)
            project.UserId = _userInfo.UserId '当前操作项目站用户索引
            project.UserName = _userInfo.UserName '当前操作项目站用户名称

            If String.Compare(project.Name, TxtProjectName.Text) <> 0 Then
                project.Name = TxtProjectName.Text
                project.InfoChanged = True
            End If

            'todo:检测产品类型修改
            Dim tmpIndex As Integer = _productTypeManager.GetProductIndex(CboProjectType.Text)
            If project.ProductTypeId <> tmpIndex Then
                project.ProductTypeId = tmpIndex
                project.InfoChanged = True
            End If

            If String.Compare(project.Description, TxtDescription.Text) <> 0 Then
                project.Description = TxtDescription.Text
                project.InfoChanged = True
            End If

            If String.Compare(project.Remark, TxtRemark.Text) <> 0 Then
                project.Remark = TxtRemark.Text
                project.InfoChanged = True
            End If

            'Momo 2025-07-17 新增对项目有效期的修改检测
            MsgBox（DtpValidDate.Value)
            If String.Compare(project.EolDate.ToString, DtpValidDate.Value.ToString) <> 0 Then
                project.EolDate = DtpValidDate.Value
                project.InfoChanged = True
            End If

            If project.Price <> NudPrice.Value Then
                project.Price = NudPrice.Value
                project.InfoChanged = True
            End If

            If RadOrderCreate.Checked Then
                If project.SnType <> 1 Then
                    project.SnType = 1
                    project.InfoChanged = True
                End If
            ElseIf RadTestCreate.Checked Then
                If project.SnType <> 0 Then
                    project.SnType = 0
                    project.InfoChanged = True
                End If
            End If


            For row As Integer = 1 To GrdStations.Rows - 1
                Dim info As ProcessStation = project.Station.Item(row - 1)
                With info
                    .UserId = _userInfo.UserId '当前操作项目站用户名

                    Dim stationType As ProcessStation.StationTypeEnum = CType([Enum].Parse(GetType(ProcessStation.StationTypeEnum), GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.Type).Text), ProcessStation.StationTypeEnum)
                    If .StationType <> stationType Then
                        .StationType = stationType
                        .TypeChange = True
                    End If

                    Dim stationNum As Integer = row
                    If .ArtworkOrder <> stationNum Then
                        .ArtworkOrder = stationNum
                        .InfoChanged = True
                    End If

                    Dim stationName As String = GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.Name).Text
                    If String.Compare(.Name, stationName) <> 0 Then
                        .Name = stationName
                        .InfoChanged = True
                    End If

                    Dim stationDesc As String = GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.Description).Text
                    If String.Compare(.Description, stationDesc) <> 0 Then
                        .Description = stationDesc
                        .InfoChanged = True
                    End If

                    Dim snType As ProcessStation.SnTypeEnum = CType([Enum].Parse(GetType(ProcessStation.SnTypeEnum), GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.SnType).Text), ProcessStation.SnTypeEnum)
                    If .SnType <> snType Then
                        .SnType = snType
                        .InfoChanged = True
                    End If

                    Dim stationDevType As String = GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.DevType).Text
                    If String.Compare(.DevType, stationDevType) <> 0 Then
                        .DevType = stationDevType
                        .InfoChanged = True
                    End If

                    Dim stationDevApp As String = GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.DevApp).Text
                    If String.Compare(.DevApp, stationDevApp) <> 0 Then
                        .DevApp = stationDevApp
                        .InfoChanged = True
                    End If

                    Dim stationPacketName As String = GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.PacketName).Text
                    If String.Compare(.Packet.FileName, stationPacketName) <> 0 Then
                        .Packet.FileName = stationPacketName
                        .InfoChanged = True
                    End If
                End With
            Next
        End Sub


        Private Sub TsBtnSaveProject_Click(sender As Object, e As EventArgs) Handles TsBtnSaveProject.Click
            Try
                CheckUserAlter()
                UpdateProjectInfo(_userProject)

                Dim filePath As String = UtsPath.ProjectFilePath(_userProject.Name)
                _userProject.ExportToXml(filePath)
                MsgBox($"Save {_userProject.Name} Project Succes!")
            Catch ex As Exception
                MsgBox($"Save {_userProject.Name} Project Fail,{ex.Message}")
            End Try
        End Sub


        Private Sub TsBtnReleaseProject_Click(sender As Object, e As EventArgs) Handles TsBtnReleaseProject.Click
            Try
                CheckUserAlter()

                UpdateProjectInfo(_userProject)

                Dim filePath As String = UtsPath.ProjectFilePath(_userProject.Name)
                _userProject.Release(filePath)

                MsgBox($"Release {_userProject.Name} Project Succes!")
            Catch ex As Exception
                MsgBox($"Release {_userProject.Name} Project Fail,{ex.Message}")
                Return
            End Try

            Try
                '通过AUTS STUDIO添加机型后，需要调用网站API，更新网站缓存，否则网页不会显示新增的机型信息
                '临时屏蔽，待新网站完成后此步骤重新启用
                '’Dim msg As String = GetData("http://uts-data.com/api/Common/ClearCache")
                '’Console.WriteLine($"Msg:{msg}")
            Catch ex As Exception
                MsgBox($"更新缓存数据失败,{ex.Message}")
            End Try

        End Sub

        Public Shared Function GetData(url As String) As String
            Dim request As HttpWebRequest = CType(WebRequest.Create(url & "?" & $"cmd=UP&dbName={UtsDb.RemotePrivateDb}"), 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
#Region "测试站检测"

        Private Sub GrdStations_ButtonClick(sender As Object, e As FlexCell.Grid.ButtonClickEventArgs) Handles GrdStations.ButtonClick
            Select Case e.Col
                Case ProjectStationGrid.ColNameEnum.PacketName

            End Select
        End Sub

        Private Sub TsmAddStation_Click(sender As Object, e As EventArgs) Handles TsmAddStation.Click
            GrdStations.AddItem(String.Empty)

            _userProject.Station.Add(New ProcessStation(_userProject))
        End Sub

        Private Sub TsmRemoveStation_Click(sender As Object, e As EventArgs) Handles TsmRemoveStation.Click
            If GrdStations.Selection Is Nothing Then Return

            If GrdStations.Cell(GrdStations.Selection.FirstRow, ProjectStationGrid.ColNameEnum.Name).Text.Length = 0 Then
                _userProject.Station.RemoveAt(GrdStations.Selection.FirstRow - 1)
                GrdStations.Selection.DeleteByRow()
            Else
                If MsgBox("数据库会删除对应测试站，该操作不可逆，是否继续此操作？", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
                    GrdStations.Selection.DeleteByRow()

                    _userProject.DeleteStation.Add(_userProject.Station.Item(GrdStations.Selection.FirstRow - 1))
                    _userProject.Station.RemoveAt(GrdStations.Selection.FirstRow - 1)
                End If
            End If
        End Sub

        Private Sub TsmMoveUpStation_Click(sender As Object, e As EventArgs) Handles TsmMoveUpStation.Click
            Dim row As Integer = GrdStations.Selection.FirstRow
            If row = 1 Then Return
            GrdStations.Row(row).Position -= 1


            Dim stationIndex As Integer = row - 1
            Dim srcProcessStation As ProcessStation = _userProject.Station.Item(stationIndex)
            _userProject.Station.Item(stationIndex) = _userProject.Station.Item(stationIndex - 1)
            _userProject.Station.Item(stationIndex - 1) = srcProcessStation
        End Sub

        Private Sub TsmMoveDownStation_Click(sender As Object, e As EventArgs) Handles TsmMoveDownStation.Click
            Dim row As Integer = GrdStations.Selection.FirstRow
            If row = GrdStations.Rows - 1 Then Return
            GrdStations.Row(row).Position += 1


            Dim stationIndex As Integer = row - 1
            Dim srcProcessStation As ProcessStation = _userProject.Station.Item(stationIndex)
            _userProject.Station.Item(stationIndex) = _userProject.Station.Item(stationIndex + 1)
            _userProject.Station.Item(stationIndex + 1) = srcProcessStation
        End Sub


        Private Sub TsBtnDeleteProject_Click(sender As Object, e As EventArgs) Handles TsBtnDeleteProject.Click
            If MsgBox("是否确定删除该项目", MsgBoxStyle.OkCancel) = MsgBoxResult.Ok Then
                If _userProject Is Nothing Then Return
                Try
                    _userProject.Delete()
                    _userProject = Nothing
                    EnabledSaveProject(_userProject IsNot Nothing)
                    ProjectStationGrid.InitTestStationGrid(GrdStations)
                    MsgBox("删除完成!")
                Catch ex As Exception
                    MsgBox("删除失败：" & ex.Message)
                End Try
            End If
        End Sub


        Private Sub PicProject_DoubleClick(sender As Object, e As EventArgs) Handles PicProject.DoubleClick
            Using dlgFile As New OpenFileDialog
                dlgFile.Filter = $"设备图像 (*.bmp;*.gif;*.jpg;*.png)|*.bmp;*.gif;*.jpg;*.png"
                If dlgFile.ShowDialog() <> DialogResult.OK Then Return

                Dim imagePath As String = dlgFile.FileName

                _userProject.MasterImage = ImageProcessor.ImageProcessor.CompressImageWithWidth(CType(ImageProcessor.ImageProcessor.GetBitmapImage(imagePath), Drawing.Bitmap), 600)
                _userProject.PreviewImage = ImageProcessor.ImageProcessor.CompressImageWithWidth(New Drawing.Bitmap(_userProject.MasterImage), 120)

                _userProject.ImageName = $"P_{_userProject.Name}_{Now:yyyyMMdd_HHmmss}.png"

                PicProject.Image = _userProject.MasterImage
                If _userProject.PreviewImageChanged = False Then _userProject.PreviewImageChanged = True
            End Using
        End Sub


        Private Sub MsiStationPreview_Click(sender As Object, e As EventArgs) Handles MsiStationPreview.Click
            Dim row As Integer = GrdStations.Selection.FirstRow
            If row >= GrdStations.Rows OrElse row < 1 Then Return

            Using dlgFile As New OpenFileDialog
                dlgFile.Filter = $"设备图像 (*.bmp;*.gif;*.jpg;*.png)|*.bmp;*.gif;*.jpg;*.png"
                If dlgFile.ShowDialog() <> DialogResult.OK Then Return

                Dim imagePath As String = dlgFile.FileName

                _userProject.Station(row - 1).PreViewImage = ImageProcessor.ImageProcessor.CompressImageWithWidth(CType(ImageProcessor.ImageProcessor.GetBitmapImage(imagePath), Drawing.Bitmap), 600)
                If _userProject.Station(row - 1).PreviewImageChanged = False Then _userProject.Station(row - 1).PreviewImageChanged = True

                Dim imgKey As String
                If String.IsNullOrEmpty(GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.Preview).ImageKey) Then
                    imgKey = GrdStations.Images.Count().ToString()
                Else
                    imgKey = GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.Preview).ImageKey
                    GrdStations.Images.Remove(imgKey)
                End If

                GrdStations.Images.Add(_userProject.Station(row - 1).PreViewImage, imgKey)
                GrdStations.Cell(row, ProjectStationGrid.ColNameEnum.Preview).SetImage(imgKey)
            End Using
        End Sub

        Private Sub GrdStations_Load(sender As Object, e As EventArgs) Handles GrdStations.Load

        End Sub
#End Region
    End Class

End Namespace