Imports System.Text
Imports System.Text.RegularExpressions
Imports BaseFunction.PublicMethod
Imports System.Web
Imports System.Xml
Imports System.IO

Public Class FormatTmplate
    Private Structure CTLInfo
        Dim Tag As String
        Dim TagStart As String
        Dim TagHTML As String
    End Structure
    Private Structure URLRewrite
        Dim LookFor As String
        Dim SendTo As String
        Dim WriteTime As Date
    End Structure
    Private Structure ImgList
        Dim OldSrc As String
        Dim NewSrc As String
    End Structure
    Private Sub UrlRewriteSave(ByVal TmpID As Integer, ByVal Rewrite As List(Of URLRewrite))
        Dim mSiteID As Integer = CType(BaseFunction.PublicMethod.GetApplication("SiteID"), Integer)
        Dim mFindID As Integer
        Dim strLookFor As String
        Dim mTmpURL As New DB_Template.clsTemplateURL
        Dim mTmpRewrite = (From t In DB_Template.clsTemplateURL.GetLinq(mSiteID) _
                           Where t.TmpID = TmpID _
                           Select t).ToList
        For Each r In Rewrite
            strLookFor = r.LookFor
            mFindID = (From f In mTmpRewrite _
                       Where f.LookFor.ToLower = strLookFor.ToLower _
                       Select f.ID).FirstOrDefault
            If mFindID = 0 Then
                mTmpURL.Insert(TmpID, r.LookFor, r.SendTo, mSiteID, r.WriteTime)
            Else
                mTmpURL.Save(mFindID, TmpID, r.LookFor, r.SendTo, r.WriteTime)
            End If
        Next
    End Sub
    Private Function GetStream(ByVal xmlStr As String) As StreamReader
        Dim array() As Byte = Encoding.UTF8.GetBytes(xmlStr)
        Dim stream As New MemoryStream(array)
        Dim streamReader As New StreamReader(stream)
        Return streamReader
    End Function

    Public Function FormatSaveFile(ByVal HTML As String, ByVal FileName As String, ByVal ClassID As Integer, ByVal TempName As String, Optional ByVal EditID As Integer = 0) As Boolean
        Dim mSiteID As Integer = CType(BaseFunction.PublicMethod.GetApplication("SiteID"), Integer)
        Dim SourceHTML As String = FormatSaveHTML(HTML)
        Dim RegTitle As Regex = New Regex("<title>[\s\S]*?</title>", RegexOptions.IgnoreCase)
        Dim RegKeyWord As Regex = New Regex("<meta\s[^>]*name=['""]?(keywords)['""]?\s[^>]*\/>", RegexOptions.IgnoreCase)
        Dim RegDescription As Regex = New Regex("<meta\s[^>]*name=['""]?(description)['""]?\s[^>]*\/>", RegexOptions.IgnoreCase)
        Dim RegHead As Regex = New Regex("(<head)+[^<>]*>", RegexOptions.IgnoreCase)
        Dim RegForm As Regex = New Regex("(<form)+[^<>]*>", RegexOptions.IgnoreCase)
        Dim RegBody As Regex = New Regex("(<body)+[^<>]*>", RegexOptions.IgnoreCase)
        Dim RegEndBody As Regex = New Regex("</body>", RegexOptions.IgnoreCase)
        Dim RegEndForm As Regex = New Regex("</form>", RegexOptions.IgnoreCase)
        Dim strPageReg As New StringBuilder("<%@ Page Language=""VB"" EnableViewStateMac=""false"" %>")
        strPageReg.AppendLine("<%@ Register assembly=""PageControl"" namespace=""PageControl"" tagprefix=""CTL"" %>")

        If EditID > 0 Then
            Dim mSEO As DB_SiteInfoModular.SiteSEO = (From s In DB_SiteInfoModular.clsSiteSEO.GetLinq(mSiteID) _
                                                      Where s.BindType = 0 And s.BindID = EditID _
                                                      Select s).FirstOrDefault
            If mSEO IsNot Nothing Then
                HTML = RegTitle.Replace(HTML, "")
                HTML = RegKeyWord.Replace(HTML, "")
                HTML = RegDescription.Replace(HTML, "")
                HTML = RegHead.Replace(HTML, "<head runat='server'>" & vbCrLf & "<title>" & Base64DecryptData(mSEO.PageTitle) & "</title>" & vbCrLf & "<meta name=""keywords"" content=""" & Base64DecryptData(mSEO.KeyWords) & """ />" & vbCrLf & "<meta name=""Description"" content=""" & Base64DecryptData(mSEO.Description) & """ />")
            Else
                HTML = RegHead.Replace(HTML, "<head runat='server'>")
            End If
        Else
            HTML = RegHead.Replace(HTML, "<head runat='server'>")
        End If

        HTML = RegForm.Replace(HTML, "")
        HTML = RegEndForm.Replace(HTML, "")
        Dim strBody As String = RegBody.Match(HTML).Value
        HTML = HTML.Replace(strBody, strBody & "<form id='form1' runat='server'>")
        HTML = RegEndBody.Replace(HTML, "</form></body>")
        HTML = strPageReg.ToString & HTML


        Dim FilePath As String = HttpContext.Current.Server.MapPath("/Sites/Site" & GetApplication("SiteID") & "/Template" & ClassID.ToString & "/" & FileName & ".aspx")
        HTML = HTML.Replace("/&/&", "+")
        Try
            IO.File.WriteAllText(FilePath, HTML, Encoding.UTF8)
        Catch ex As Exception
            Return False
        End Try
        Dim mTmpList As New DB_Template.clsTemplateList
        Dim TmpID As Integer = 0
        If EditID = 0 Then
            TmpID = mTmpList.Insert(ClassID, Base64EncryptData(SourceHTML), False, TempName, FileName)
        Else
            If mTmpList.Save(EditID, ClassID, Base64EncryptData(SourceHTML), TempName) > 0 Then
                TmpID = EditID
            Else
                Return False
            End If
        End If

        If TmpID > 0 Then
            Dim mFileInfo As New IO.FileInfo(FilePath)
            Dim FileTime As Date = mFileInfo.LastWriteTime
            Dim SQLRewrite As New List(Of URLRewrite)
            SQLRewrite.Add(New URLRewrite With {.WriteTime = FileTime, .LookFor = "~/" & FileName & "\.html", .SendTo = "~/Sites/Site" & GetApplication("SiteID") & "/Template" & ClassID.ToString & "/" & FileName & ".aspx"})
            UrlRewriteSave(TmpID, SQLRewrite)
            Return True
        Else
            IO.File.Delete(FilePath)
            Return False
        End If
    End Function
    ''' <summary>
    ''' 处理成保存到数据库的代码
    ''' </summary>
    ''' <param name="HTML"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function FormatSaveHTML(ByVal HTML As String) As String
        Dim RegURL As Text.RegularExpressions.Regex = New Regex("http://" & BaseFunction.PublicMethod.GetApplication("WebURL"), RegexOptions.IgnoreCase)
        Dim RegImg As Text.RegularExpressions.Regex = New Regex("<IMG.*?src=""(.*?.*?)"".*?>", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
        Dim mImgList As List(Of ImgList) = (From m As System.Text.RegularExpressions.Match In RegImg.Matches(HTML) _
                                            Select New ImgList With {.OldSrc = m.Groups(1).Value, .NewSrc = RegURL.Replace(m.Groups(1).Value, "")}).ToList
        For Each m In mImgList
            HTML = HTML.Replace(m.OldSrc, m.NewSrc)
        Next
        Dim TmplateUrl As String = "/Sites/Site" & GetApplication("SiteID") & "/Template" & GetApplication("DefaultGroup") & "/"
        Dim RegScript As Text.RegularExpressions.Regex = New Regex("<SCRIPT.*?src=""(.*?.*?)"".*?>", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
        For Each m As System.Text.RegularExpressions.Match In RegScript.Matches(HTML)
            If Left(m.Groups(1).Value, 1) <> "/" Then
                HTML = HTML.Replace(m.Groups(1).Value, TmplateUrl & m.Groups(1).Value.Replace(TmplateUrl, ""))
            End If
        Next

        Dim RegCss As Text.RegularExpressions.Regex = New Regex("<LINK.*?href=""(.*?.*?)"".*?>", RegexOptions.IgnoreCase Or RegexOptions.Multiline)
        For Each m As System.Text.RegularExpressions.Match In RegCss.Matches(HTML)
            If Left(m.Groups(1).Value, 1) <> "/" Then
                HTML = HTML.Replace(m.Groups(1).Value, TmplateUrl & m.Groups(1).Value.Replace(TmplateUrl, ""))
            End If
        Next
        Return HTML
    End Function
    ''' <summary>
    ''' 设置默认首页
    ''' </summary>
    ''' <param name="TMPID"></param>
    ''' <param name="FileName"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Function SaveDefault(ByVal TMPID As Integer, ByVal FileName As String) As Integer
        Dim mTMP As New DB_Template.clsTemplateList
        Dim mSiteID As Integer = CType(GetApplication("SiteID"), Integer)
        Dim SaveValue As Integer = mTMP.Save(TMPID, mSiteID)
        Select Case SaveValue
            Case 0
                Return 0
            Case 2
                DeleteDefault(TMPID, FileName, False)
                Return 2
            Case 1
                Return DeleteDefault(TMPID, FileName, True)
        End Select
    End Function
    Private Function DeleteDefault(ByVal ID As Integer, ByVal FileName As String, ByVal SaveURL As Boolean) As Integer
        Dim mIIS As New SiteManager.clsIIS
        Dim DefaultFile As String = mIIS.IISDefaultFile
        Dim mTmp As New DB_Template.clsTemplateURL
        If mTmp.DeleteDefault(DefaultFile) Then
            If SaveURL Then
                Dim mFileInfo As New IO.FileInfo(HttpContext.Current.Server.MapPath("/Sites/Site" & GetApplication("SiteID") & "/Template" & GetApplication("DefaultGroup") & "/" & FileName & ".aspx"))
                Dim FileTime As Date = mFileInfo.LastWriteTime
                Dim mList As New List(Of URLRewrite)
                mList.Add(New URLRewrite With {.WriteTime = FileTime, .LookFor = "~/" & DefaultFile, .SendTo = "~/Sites/Site" & GetApplication("SiteID") & "/Template" & GetApplication("DefaultGroup") & "/" & FileName & ".aspx"})
                mList.Add(New URLRewrite With {.WriteTime = FileTime, .LookFor = "~/", .SendTo = "~/Sites/Site" & GetApplication("SiteID") & "/Template" & GetApplication("DefaultGroup") & "/" & FileName & ".aspx"})
                UrlRewriteSave(ID, mList)
            End If
            Return 1
        Else
            Return 3
        End If

    End Function
End Class
