Imports System.IO
Imports UTS_Core.DebugLog
Imports UTS_Core.UTSModule
Imports UTS_Core.UTSModule.Station

Public Class FrmStationRelease
    Implements IProcessStation
    Implements IProductionLine

    Private _utsApp As UtsAppForm

    Public Event StationRelease(station As ProcessStation) '项目发布事件


    Public Sub Station_Changed() Implements IProcessStation.StationChanged
        ApplicationLog.WriteInfoLog($"发布页面站位变更中，PN：{_utsApp.ProcessStation.ParentProject.Name} - SN:{_utsApp.ProcessStation.Name} - TP:{_utsApp.ProcessStation.Packet.Name}!")

        UpdateStationPacket(_utsApp.ProcessStation.Packet)

        ApplicationLog.WriteInfoLog($"发布页面站位变更完成。")
    End Sub

    Public Sub ProductionLineChanged() Implements IProductionLine.ProductionLineChanged
        ApplicationLog.WriteInfoLog($"发布页面生产线变更中。")


        ApplicationLog.WriteInfoLog($"发布页面生产线变更完成。")
    End Sub



    Private _isAutoAugment As Boolean = True

    Public Property StationPacket() As StationPacket


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

        Enabled = StationPacket IsNot Nothing

        Show()
    End Sub



    ''' <summary>修改窗体标题</summary>
    Private Sub ShowFormTitle()
        Text = $"{My.Application.Info.ProductName} StationDesign"
    End Sub

    Private Sub ShowFormTitle(packetName As String)
        Text = $"{My.Application.Info.ProductName} StationDesign -- {packetName}"
    End Sub


    Private Sub UpdateStationPacket(packet As StationPacket)
        StationPacket = packet
        Enabled = StationPacket IsNot Nothing
        If StationPacket IsNot Nothing Then
            ShowFormTitle(StationPacket.Name)
            LoadProjectInitForm()
        End If
    End Sub


    Private Sub LoadProjectInitForm()
        TxtProjectName.Text = StationPacket.ParentProcessStation.ParentProject.Name
        TxtTestStation.Text = StationPacket.ParentProcessStation.Name
        TxtEditPwd.Text = StationPacket.EditPwd
        TxtReleasePwd.Text = StationPacket.ReleasePwd


        NudStationVersion.Text = CType(StationPacket.StationVersion, String)
        RtxHistoryImprint.Text = StationPacket.PacketImprintsToString(StationPacket.HistoryImprints)
        RtxCurrentImprint.Text = StationPacket.CurrentImprint.ToString()

        If StationPacket.ValidDate >= DtpValidDate.MaxDate Then
            DtpValidDate.Value = Now.AddMonths(6) '默认有效期六个月
        ElseIf StationPacket.ValidDate <= DtpValidDate.MinDate Then
            DtpValidDate.Value = Now.AddMonths(6) '默认有效期六个月
        Else
            DtpValidDate.Value = StationPacket.ValidDate
        End If
    End Sub


    Private Sub FrmStationDesign_Load(sender As Object, e As EventArgs) Handles Me.Load
        ApplicationLog.WriteInfoLog($"发布页面加载中。")
        '初始化UTS窗体信息,失败则关闭窗体
        If InitializeUtsApp() = False Then Return

        '初始化窗体页面
        InitializeForm()

        ApplicationLog.WriteInfoLog($"发布页面加载完成。")
    End Sub

    Private Function InitializeUtsApp() As Boolean
        _utsApp = UtsAppForm.CreateSingleton()
        _utsApp.AddStatisticsObserver(Me)

        Try
            If _utsApp.IsInitialized = False Then
                _utsApp.Initialize(ProcessStation.StationTypeEnum.Package) 'Todo:可根据需要限定可选站位
            End If
        Catch ex As Exception
            ApplicationLog.WriteErrorLog($"初始化窗体失败,原因：{ex.Message}!")

            MsgBox($"初始化窗体失败,原因：{ex.Message}")
            Close()
            Return False
        End Try

        Return True
    End Function

    Private Sub InitializeForm()
        ShowFormTitle()
    End Sub

    Private Sub UpdateStationPacket()
        StationPacket.ModifiedTime = Now
        StationPacket.EditPwd = TxtEditPwd.Text
        StationPacket.ReleasePwd = TxtReleasePwd.Text
        StationPacket.ValidDate = DtpValidDate.Value
        StationPacket.CurrentImprint = New StationPacketImprint(RtxCurrentImprint.Text)
        If _isAutoAugment Then
            StationPacket.StationVersion += 1
        Else
            StationPacket.StationVersion = CInt(NudStationVersion.Value)
        End If
    End Sub

    Private Sub AfterReleasePacketSuccess()
        RtxCurrentImprint.Text = StationPacket.CurrentImprint.ToString()
        RtxHistoryImprint.Text = StationPacket.PacketImprintsToString(StationPacket.HistoryImprints)
        NudStationVersion.Value = StationPacket.StationVersion

        ShowFormTitle(StationPacket.Name)
    End Sub

    Private Sub AfterReleasePacketFail()
        RtxCurrentImprint.Text = StationPacket.CurrentImprint.ToString()
        RtxHistoryImprint.Text = StationPacket.PacketImprintsToString(StationPacket.HistoryImprints)
        StationPacket.StationVersion = CInt(NudStationVersion.Value)

        ShowFormTitle(StationPacket.Name)
    End Sub

    Private Sub TsBtnReleaseStation_Click(sender As Object, e As EventArgs) Handles TsBtnReleaseStation.Click
        Try
            If String.IsNullOrEmpty(TxtEditPwd.Text) Then
                MsgBox("请输入编辑密码...")
                Return
            End If

            If String.IsNullOrEmpty(TxtReleasePwd.Text) Then
                MsgBox("请输入发布密码...")
                Return
            End If

            If String.IsNullOrEmpty(RtxCurrentImprint.Text) Then
                MsgBox("请输入版本说明...")
                Return
            End If

            ApplicationLog.WriteInfoLog($"项目站包发布准备中。")

            UpdateStationPacket()
            StationPacket.ReleasePacket()
            AfterReleasePacketSuccess()

            RaiseEvent StationRelease(StationPacket.ParentProcessStation)

            ApplicationLog.WriteInfoLog($"项目站包 {StationPacket.FileName} 发布成功!")
            MsgBox($"项目站包 {StationPacket.FileName} 发布成功!")
        Catch ex As Exception
            ApplicationLog.WriteErrorLog($"项目站包发布失败,原因：{ex.Message}")
            MsgBox($"项目站包发布失败,原因：{ex.Message}")

            AfterReleasePacketFail()
        End Try
    End Sub

    Private Sub ChkAutoAugment_CheckedChanged(sender As Object, e As EventArgs) Handles ChkAutoAugment.CheckedChanged
        _isAutoAugment = ChkAutoAugment.Checked
        NudStationVersion.Enabled = Not _isAutoAugment
    End Sub

    Private Sub TsBtnAddResource_Click(sender As Object, e As EventArgs) Handles TsBtnAddResourceFile.Click
        dlgOpenFile.Multiselect = True
        dlgOpenFile.Filter = $"资源文件 (*.*)|*.*"

        If dlgOpenFile.ShowDialog <> DialogResult.OK Then Return

        ApplicationLog.WriteInfoLog($"项目站包资源文件添加中。")
        Try
            For Each fileName As String In dlgOpenFile.FileNames
                ApplicationLog.WriteInfoLog($"正在添加{fileName}")
                FileIO.FileSystem.CopyFile(fileName, $"{UtsPath.StationPacketResourceDirPath}\{Path.GetFileName(fileName)}")
            Next
            ApplicationLog.WriteInfoLog($"项目站包资源文件添加完成。")
            MsgBox($"项目站包资源文件添加完成。")
        Catch ex As Exception
            ApplicationLog.WriteErrorLog($"项目站包资源文件添加失败，原因：{ex.Message}")
            MsgBox($"项目站包资源文件添加失败，原因：{ex.Message}")
        End Try
    End Sub

    Private Sub TsBtnAddResourceDir_Click(sender As Object, e As EventArgs) Handles TsBtnAddResourceDir.Click
        If dlgOpenFolder.ShowDialog() <> DialogResult.OK Then Return
        ApplicationLog.WriteInfoLog($"项目站包资源文件夹添加中，目标文件夹：{dlgOpenFolder.SelectedPath}。")
        Try
            CopyDirectory(New DirectoryInfo(dlgOpenFolder.SelectedPath), New DirectoryInfo(UtsPath.StationPacketResourceDirPath))
            ApplicationLog.WriteInfoLog($"项目站包资源文件夹添加完成。")
            MsgBox($"项目站包资源文件夹添加完成")
        Catch ex As Exception
            ApplicationLog.WriteErrorLog($"项目站包资源文件添加失败，原因：{ex.Message}")
            MsgBox($"项目站包资源文件添加失败，原因：{ex.Message}")
        End Try
    End Sub

    Public Sub CopyDirectory(directorySrc As DirectoryInfo, directoryDes As DirectoryInfo)
        Dim strDirectoryDesPath As String = $"{directoryDes.FullName}\{directorySrc.Name}"
        If Directory.Exists(strDirectoryDesPath) = False Then
            Directory.CreateDirectory(strDirectoryDesPath)
        End If

        For Each f As FileInfo In directorySrc.GetFiles()
            File.Copy(f.FullName, $"{strDirectoryDesPath}\{ f.Name}", True)
        Next

        ' 递归调用自身
        For Each dirSrc As DirectoryInfo In directorySrc.GetDirectories()
            CopyDirectory(dirSrc, New DirectoryInfo(strDirectoryDesPath))
        Next
    End Sub


    Private Sub TsBtnSearchResource_Click(sender As Object, e As EventArgs) Handles TsBtnSearchResource.Click

        '定位到/Resource文件夹内
        Process.Start("Explorer.exe", $"{UtsPath.GetStationPacketResourceDirPath(StationPacket.Name)}")
    End Sub
End Class