Imports System.Web.Script.Serialization
Partial Class Manager_Tags_SQLBuild
    Inherits System.Web.UI.Page
    Private Structure jsTable
        Dim ID As Integer
        Dim Name As String
        Dim Note As String
    End Structure
    Private Structure jsFields
        Dim TableID As Integer
        Dim FieldID As Integer
        Dim FieldName As String
        Dim TableName As String
        Dim PrimaryKey As Boolean
    End Structure
    Private Structure jsWhere
        Dim Field As String
        Dim Method As String
        Dim iOperator As String
        Dim NameValue As String
        Dim Decrypt As String
        Dim isEmpty As Boolean
        Dim isIgnore As Boolean
        Dim RowID As Integer
        Dim Connect As String
    End Structure
    Private Structure jsOrder
        Dim FieldSource As String
        Dim FieldName As String
        Dim OrderSource As String
        Dim OrderName As String
    End Structure
    Private Structure jsInner
        Dim FieldA As String
        Dim FieldB As String
    End Structure
    Private Structure jsPar
        Dim Sourcess As String
        Dim Tag As String
        Dim Type As String
        Dim Value As String
    End Structure
    Public Structure Tags
        Dim Type As String
        Dim Name As String
        Dim Tag As String
        Dim Sourcess As String
    End Structure
    Protected Sub imgReflash_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgReflash.Click
        Dim mJson As New JavaScriptSerializer
        Dim strTable As String = hfTableJson.Value
        Dim strField As String = hfSelectFields.Value
        Dim strWhere As String = hfWhere.Value
        Dim strOrder As String = hfOrderBY.Value
        Dim strInner As String = hfInner.Value

        Dim mJsonTable As List(Of jsTable) = mJson.Deserialize(Of List(Of jsTable))(strTable)
        Dim mJsonField As List(Of jsFields) = mJson.Deserialize(Of List(Of jsFields))(strField)
        Dim mJsonWhere As List(Of jsWhere) = mJson.Deserialize(Of List(Of jsWhere))(strWhere)
        Dim mJsonOrder As List(Of jsOrder) = mJson.Deserialize(Of List(Of jsOrder))(strOrder)
        Dim mJsonInner As List(Of jsInner) = mJson.Deserialize(Of List(Of jsInner))(strInner)

        Dim SQLType As Integer = 0
        Dim SQLMain As New StringBuilder
        Dim SQLCount As New StringBuilder
        Dim SQLWhere As New StringBuilder
        Dim SQLOrder As New StringBuilder
        Dim arryFields() As String = Nothing
        Dim strFields As String = ""
        If mJsonField IsNot Nothing AndAlso mJsonField.Count > 0 Then
            arryFields = (From f In mJsonField _
                          Let strName = f.TableName & "." & f.FieldName _
                          Select strName).ToArray
            strFields = (String.Join(",", arryFields))
        End If
        Integer.TryParse(dplSQLTemplate.SelectedValue, SQLType)
        Select Case SQLType
            Case -1 '查询
                If strFields.Length = 0 Then
                    ClientScript.RegisterClientScriptBlock(Page.GetType, "ScriptAlert", "$.dialog.alert('<div style=""width:300px;padding:0px 0px 0px 15px;"">请选择输出的字段！</div>');", True)
                    Exit Sub
                End If
                If mJsonTable.Count = 1 Then '-----------单表查询输出
                    SQLMain.Append("SELECT " & strFields)
                    SQLMain.Append(vbCrLf & " FROM " & mJsonTable.FirstOrDefault.Name)
                    SQLCount.Append("SELECT ")
                    Dim mKeyField As String = (From f In DB_SQL.clsTableFields.GetLinq(mJsonTable.FirstOrDefault.Name) _
                                               Where f.IsPrimaryKey = True _
                                               Select f.FieldName).FirstOrDefault
                    If mKeyField Is Nothing OrElse mKeyField.Length = 0 Then
                        mKeyField = mJsonField.FirstOrDefault.FieldName
                    End If
                    SQLCount.Append("COUNT(" & mKeyField & ")  FROM " & mJsonTable.FirstOrDefault.Name)

                    If mJsonWhere IsNot Nothing AndAlso mJsonWhere.Count > 0 Then
                        SQLMain.Append(" WHERE ")
                        SQLCount.Append(" WHERE ")
                    End If

                    For Each w In mJsonWhere
                        SQLWhere.Append("<Value Type=""WHERE"" Condition=""" & w.Field & """ Operator=""" & w.iOperator & """ ValueType=""" & w.Method & """ Name=""" & w.NameValue & """ Decrypt=""" & w.Decrypt & """ IsEmpty=""" & w.isEmpty & """ IsIgnore=""" & w.isIgnore & """ Connect=""" & w.Connect & """ />")
                    Next
                    If SQLWhere.Length > 0 Then
                        SQLMain.Append(SQLWhere.ToString)
                        SQLCount.Append(SQLWhere.ToString)
                    End If
                    If mJsonOrder IsNot Nothing AndAlso mJsonOrder.Count > 0 Then
                        SQLOrder.Append(vbCrLf & " ORDER BY ")
                        For Each o In mJsonOrder
                            SQLOrder.Append("<Value Type=""ORDER"" FieldSource=""" & o.FieldSource & """ FieldName=""" & o.FieldName & """ DescSource=""" & o.OrderSource & """ DescName=""" & o.OrderName & """ />")
                        Next
                    End If
                    If SQLOrder.Length > 0 Then
                        SQLMain.Append(SQLOrder.ToString)
                    End If
                Else '-----------------------------------多表联合查询
                    SQLMain.Append("SELECT " & strFields)
                    Dim MainTable = (From t In mJsonTable _
                                    Where t.Name = mJsonInner.FirstOrDefault.FieldA.Split(".")(0) _
                                    Select t).FirstOrDefault
                    SQLMain.Append(" FROM " & MainTable.Name)
                    SQLCount.Append("SELECT ")
                    Dim mTables() As String = (From t In mJsonTable Select t.Name).ToArray
                    Dim mKeyField As String = (From f In DB_SQL.clsTableFields.GetLinq(mTables) _
                                               Where f.IsPrimaryKey = True _
                                               Let strKeyName = f.TableName & "." & f.FieldName _
                                               Select strKeyName).FirstOrDefault
                    If mKeyField Is Nothing OrElse mKeyField.Length = 0 Then
                        mKeyField = mJsonField.FirstOrDefault.TableName & "." & mJsonField.FirstOrDefault.FieldName
                    End If
                    SQLCount.Append("COUNT(" & mKeyField & ") FROM " & MainTable.Name)
                    mJsonTable.Remove(MainTable)
                    For Each j In mJsonInner
                        SQLMain.Append(" INNER JOIN " & j.FieldB.Split(".")(0) & " ON " & j.FieldA & "=" & j.FieldB)
                        SQLCount.Append(" INNER JOIN " & j.FieldB.Split(".")(0) & " ON " & j.FieldA & "=" & j.FieldB)
                    Next
                  
                    If mJsonWhere IsNot Nothing AndAlso mJsonWhere.Count > 0 Then
                        SQLMain.Append(" WHERE ")
                        SQLCount.Append(" WHERE ")
                    End If
                    For Each w In mJsonWhere
                        SQLWhere.Append("<Value Type=""WHERE"" Condition=""" & w.Field & """ Operator=""" & w.iOperator & """ ValueType=""" & w.Method & """ Name=""" & w.NameValue & """ Decrypt=""" & w.Decrypt & """ IsEmpty=""" & w.isEmpty & """ IsIgnore=""" & w.isIgnore & """ Connect=""" & w.Connect & """ />")
                    Next
                    SQLMain.Append(SQLWhere.ToString)
                    SQLCount.Append(SQLWhere.ToString)
                    If mJsonOrder IsNot Nothing AndAlso mJsonOrder.Count > 0 Then
                        SQLMain.Append(" ORDER BY ")
                        For Each o In mJsonOrder
                            SQLMain.Append("<Value Type=""ORDER"" FieldSource=""" & o.FieldSource & """ FieldName=""" & o.FieldName & """ DescSource=""" & o.OrderSource & """ DescName=""" & o.OrderName & """ />")
                        Next
                    End If
                End If
            Case -2 '添加
                If mJsonTable.Count = 1 Then
                    SQLMain.Append("INSERT INTO " & mJsonTable.FirstOrDefault.Name)
                    Dim ShortFields As String = ""
                    If mJsonField IsNot Nothing AndAlso mJsonField.Count > 0 Then
                        arryFields = (From f In mJsonField _
                                      Select f.FieldName).ToArray
                        ShortFields = (String.Join(",", arryFields))
                    End If
                    SQLMain.Append(" ( " & ShortFields & ") VALUES(" & ShortFields & ")")
                Else
                    ClientScript.RegisterClientScriptBlock(Page.GetType, "ScriptAlert", "$.dialog.alert('<div style=""width:300px;padding:0px 0px 0px 15px;"">添加操作只能选择一个表进行，请删除多余的表！</div>');", True)
                    Exit Sub
                End If
            Case -3 '更新
                If mJsonTable.Count = 1 Then
                    SQLMain.Append("UPDATE " & mJsonTable.FirstOrDefault.Name)
                    SQLMain.Append(" SET ")
                    For Each i In mJsonField
                        SQLMain.Append(i.FieldName & "='',")
                    Next
                    If SQLMain.ToString.EndsWith(",") Then
                        SQLMain = SQLMain.Remove(SQLMain.ToString.Length - 1, 1)
                    End If
                    If mJsonWhere IsNot Nothing AndAlso mJsonWhere.Count > 0 Then SQLMain.Append(" WHERE ")
                    For Each w In mJsonWhere
                        SQLMain.Append("<Value Type=""WHERE"" Condition=""" & w.Field & """ Operator=""" & w.iOperator & """ ValueType=""" & w.Method & """ Name=""" & w.NameValue & """ Decrypt=""" & w.Decrypt & """ IsEmpty=""" & w.isEmpty & """ IsIgnore=""" & w.isIgnore & """ Connect=""" & w.Connect & """ />")
                    Next
                Else
                    ClientScript.RegisterClientScriptBlock(Page.GetType, "ScriptAlert", "$.dialog.alert('<div style=""width:300px;padding:0px 0px 0px 15px;"">更新操作只能选择一个表进行，请删除多余的表！</div>');", True)
                    Exit Sub
                End If
            Case -4 '删除
                If mJsonTable.Count = 1 Then
                    SQLMain.Append("DELETE " & mJsonTable.FirstOrDefault.Name)
                    If mJsonWhere IsNot Nothing AndAlso mJsonWhere.Count > 0 Then SQLMain.Append(" WHERE ")
                    For Each w In mJsonWhere
                        SQLMain.Append("<Value Type=""WHERE"" Condition=""" & w.Field & """ Operator=""" & w.iOperator & """ ValueType=""" & w.Method & """ Name=""" & w.NameValue & """ Decrypt=""" & w.Decrypt & """ IsEmpty=""" & w.isEmpty & """ IsIgnore=""" & w.isIgnore & """ Connect=""" & w.Connect & """ />")
                    Next
                Else
                    ClientScript.RegisterClientScriptBlock(Page.GetType, "ScriptAlert", "$.dialog.alert('<div style=""width:300px;padding:0px 0px 0px 15px;"">删除操作只能选择一个表进行，请删除多余的表！</div>');", True)
                    Exit Sub
                End If
            Case -5 '特殊查询
                Exit Sub
            Case Else '模板
                Dim mclsTemp As New DB_SQL.clsSQLTemplate
                Dim mTMP = mclsTemp.GetSingle(CType(dplSQLTemplate.SelectedValue, Integer))
                If mTMP IsNot Nothing Then
                    Dim strTmp As String = mTMP.SQLContent
                    Dim tmpWhere As New StringBuilder
                    Dim tmpOrder As New StringBuilder
                    Dim tmpTable As New StringBuilder
                    Dim i As Integer = 1
                    If mJsonWhere IsNot Nothing AndAlso mJsonWhere.Count > 0 Then tmpWhere.Append(" WHERE ")
                    For Each w In mJsonWhere
                        tmpWhere.Append("<Value Type=""WHERE"" Condition=""" & w.Field & """ Operator=""" & w.iOperator & """ ValueType=""" & w.Method & """ Name=""" & w.NameValue & """ Decrypt=""" & w.Decrypt & """ IsEmpty=""" & w.isEmpty & """ IsIgnore=""" & w.isIgnore & """ Connect=""" & w.Connect & """ />")
                    Next


                    Dim mTables() As String = (From t In mJsonTable Select t.Name).ToArray
                    Dim mKeyField As String = (From f In DB_SQL.clsTableFields.GetLinq(mTables) _
                                               Where f.IsPrimaryKey = True _
                                               Let strKeyName = f.TableName & "." & f.FieldName _
                                               Select strKeyName).FirstOrDefault
                    If mKeyField Is Nothing OrElse mKeyField.Length = 0 Then
                        mKeyField = mJsonField.FirstOrDefault.TableName & "." & mJsonField.FirstOrDefault.FieldName
                    End If
                    If mJsonTable.Count > 1 Then
                        Dim MainTable = (From t In mJsonTable _
                                    Where t.Name = mJsonInner.FirstOrDefault.FieldA.Split(".")(0) _
                                    Select t).FirstOrDefault

                        SQLCount.Append("SELECT COUNT(" & mKeyField & ") FROM " & MainTable.Name)
                        tmpTable.Append(MainTable.Name)
                        For Each j In mJsonInner
                            tmpTable.Append(" INNER JOIN " & j.FieldB.Split(".")(0) & " ON " & j.FieldA & "=" & j.FieldB)
                            SQLCount.Append(" INNER JOIN " & j.FieldB.Split(".")(0) & " ON " & j.FieldA & "=" & j.FieldB)
                        Next
                    Else
                        SQLCount.Append("SELECT COUNT(" & mKeyField & ") FROM " & mJsonTable(0).Name)
                        tmpTable.Append(mJsonTable(0).Name)
                    End If
                   

                    If mJsonOrder IsNot Nothing AndAlso mJsonOrder.Count > 0 Then
                        For Each o In mJsonOrder
                            tmpOrder.Append("<Value Type=""ORDER"" FieldSource=""" & o.FieldSource & """ FieldName=""" & o.FieldName & """ DescSource=""" & o.OrderSource & """ DescName=""" & o.OrderName & """ />")
                        Next
                    End If
                    txtSQLMain.Text = FormatSQL(strTmp.Replace("@Fields", strFields).Replace("@Where", tmpWhere.ToString).Replace("@Order", tmpOrder.ToString).Replace("@Table", tmpTable.ToString))
                    txtSQLCount.Text = FormatSQL(SQLCount.ToString & tmpWhere.ToString)
                    Exit Sub
                End If
        End Select
        If SQLMain.Length > 0 Then
            If SQLMain.ToString.EndsWith(",") Then
                txtSQLMain.Text = FormatSQL(SQLMain.ToString.Remove(SQLMain.ToString.Length - 1, 1))
            Else
                txtSQLMain.Text = FormatSQL(SQLMain.ToString)
            End If
        End If
        If SQLCount.Length > 0 Then
            If SQLCount.ToString.EndsWith(",") Then
                txtSQLCount.Text = FormatSQL(SQLCount.ToString.Remove(SQLCount.ToString.Length - 1, 1))
            Else
                txtSQLCount.Text = FormatSQL(SQLCount.ToString)
            End If
        End If
        lblExValue.text = ""
    End Sub
    Private Function intToString(ByVal intHTML As String) As String
        Select Case intHTML
            Case "等于"
                Return "="
            Case "大于"
                Return ">"
            Case "小于"
                Return "<"
            Case "大于等于"
                Return ">="
            Case "小于等于"
                Return "<="
            Case "不等于"
                Return "<>"
            Case "LIKE"
                Return " LIKE "
            Case Else
                Return ""
        End Select
    End Function

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            Dim mTmp As List(Of DB_SQL.SQLTemplate) = DB_SQL.clsSQLTemplate.GetLinq(CType(BaseFunction.PublicMethod.GetApplication("SiteID"), Integer)).ToList
            dplSQLTemplate.Items.Clear()
            dplSQLTemplate.Items.Add(New ListItem("查询", "-1"))
            dplSQLTemplate.Items.Add(New ListItem("添加", "-2"))
            dplSQLTemplate.Items.Add(New ListItem("更新", "-3"))
            dplSQLTemplate.Items.Add(New ListItem("删除", "-4"))
            dplSQLTemplate.Items.Add(New ListItem("特殊查询", "-5"))
            For Each t In mTmp
                dplSQLTemplate.Items.Add(New ListItem(t.SQLName, t.ID.ToString))
            Next
            dplSQLTemplate.SelectedIndex = 0
            Dim mSQLClass As List(Of DB_SQL.SQLClass) = DB_SQL.clsSQLClass.GetLinq(CType(BaseFunction.PublicMethod.GetApplication("SiteID"), Integer)).ToList
            dplSQLClassID.Items.Clear()
            dplSQLClassID.Items.Add(New ListItem("选择分类", "0"))
            For Each c In mSQLClass
                dplSQLClassID.Items.Add(New ListItem(c.ClassName, c.ID.ToString))
            Next
            dplSQLClassID.SelectedIndex = 0
            If Request("Action") = "Edit" Then
                imgSave.ToolTip = "保存"
                imgSave.ImageUrl = "/App_Themes/ManagerTheme/Images/bc.jpg"
                Dim ID As Integer = 0
                If Integer.TryParse(Request("ID"), ID) Then
                    Dim mclsSQL As New DB_SQL.clsSQLData
                    Dim mSQL As DB_SQL.SQLData = mclsSQL.GetSingle(ID)
                    With mSQL
                        txtSQLName.Text = .SQLName
                        txtDependOf.Text = .DependOf
                        txtSQLCount.Text = .CountSQL
                        txtSQLMain.Text = .SQLData
                        dplSQLClassID.SelectedValue = .ClassID.ToString
                        dplCacheLifeType.SelectedValue = .CacheLifeType.ToString
                        dplSQLTemplate.SelectedValue = .SQLType.ToString
                    End With
                    Dim mclsSQLDesign As New DB_SQL.clsSQLDesign
                    Dim mSQLDesign As DB_SQL.SQLDesign = mclsSQLDesign.GetSingle(ID)
                    With mSQLDesign
                        hfHTMLInner.Value = .hfHTMLInner
                        hfHTMLMain.Value = .hfHTMLMain
                        hfHTMLOrder.Value = .hfHTMLOrder
                        hfHTMLWhere.Value = .hfHTMLWhere
                        hfInner.Value = .hfInner
                        hfOrderBY.Value = .hfOrderBY
                        hfSelectFields.Value = .hfSelectFields
                        hfTableJson.Value = .hfTableJson
                        hfWhere.Value = .hfWhere
                    End With
                End If
            End If
        End If
    End Sub

   
    Protected Sub imgRun_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgRun.Click
        Dim HTML As New StringBuilder
        Dim strSQL As String
        If hftxtSQL.value = "TabSQLMain" Or hftxtSQL.value = "" Then
            strSQL = txtSQLMain.Text
        Else
            strSQL = txtSQLCount.Text
        End If
        Dim mXDoc As XDocument = XDocument.Parse("<root>" & txtSQLMain.Text & "</root>")
        Dim mWhere = (From a As XElement In mXDoc.Root.Elements("Value") _
                         Where a.Attribute("Type").Value = "WHERE" _
                         Select a).ToList
        Dim mWhereTag = (From w In mWhere _
                         Where w.Attribute("ValueType").Value.ToLower <> "value" _
                         Select New Tags With {.Type = w.Attribute("ValueType").Value, .Tag = "WHERE", .Name = w.Attribute("Name").Value, .Sourcess = w.ToString}).ToList

        Dim mOrderTag = (From a As XElement In mXDoc.Root.Elements("Value") _
                             Where a.Attribute("Type").Value = "ORDER" _
                             Select a).ToList

        Dim mOrderFieldTag = (From a In mOrderTag _
                              Where a.Attribute("FieldSource").Value.ToLower = "request" Or a.Attribute("FieldSource").Value.ToLower = "cookie" _
                              Select New Tags With {.Type = a.Attribute("FieldSource").Value, .Tag = "ORDERFIELD", .Name = a.Attribute("FieldName").Value, .Sourcess = a.ToString}).ToList

        Dim mOrderDescTag = (From a In mOrderTag _
                             Where a.Attribute("DescSource").Value.ToLower = "request" Or a.Attribute("DescSource").Value.ToLower = "cookie" _
                             Select New Tags With {.Type = a.Attribute("DescSource").Value, .Tag = "ORDERDESC", .Name = a.Attribute("DescName").Value, .Sourcess = a.ToString}).ToList
       

        Dim mVariable = (From a As XElement In mXDoc.Root.Elements("Value") _
                         Where a.Attribute("Type").Value.ToLower = "variable" _
                         Select New Tags With {.Type = a.Attribute("ValueType").Value, .Tag = "VARIABLE", .Name = a.Attribute("Name").Value, .Sourcess = a.ToString}).ToList

        Dim mDoc As New List(Of Tags)
        If dplSQLTemplate.SelectedValue = "-5" Then
            mDoc.AddRange(mVariable)
        Else
            mDoc.AddRange(mWhereTag)
            mDoc.AddRange(mOrderFieldTag)
            mDoc.AddRange(mOrderDescTag)
            mDoc.AddRange(mVariable)
        End If
        Dim mNewList As New List(Of Tags)
        If mDoc.Count > 0 Then
            HTML.AppendLine("<table style=""width: 100%"" id=""ParTable"" Count=""" & mDoc.Count & """>")
            Dim i As Integer = 1
            Dim vName As String
            Dim vType As String
            For Each v As Tags In mDoc
                If mNewList IsNot Nothing AndAlso mNewList.Count > 0 Then
                    vName = v.Name
                    vType = v.Type
                    If mNewList.Where(Function(c) c.Name = vName And c.Type = vType).Count > 0 Then
                        Continue For
                    Else
                        mNewList.Add(v)
                    End If
                Else
                    mNewList.Add(v)
                End If
                HTML.Append("<tr><td Sourcess='" & v.Sourcess & "' id=""p" & i.ToString & """ tag=""" & v.Tag & """ type=""" & v.Type & """  style=""width:200px;text-align:right;"">" & v.Type & "(&quot;" & v.Name & "&quot;)&nbsp;=&nbsp;</td><td><input type=""text"" id=""v" & i.ToString & """ style=""width:90%;color:#999999;"" value=""请输入测试值"" onfocus=""if(this.value=='请输入测试值'){this.value='';this.style.color='#000000';}"" onblur=""if(this.value==''){this.value='请输入测试值';this.style.color='#999999';}"" /></td><td style=""width:300px;""></td></tr>")
                i += 1
            Next
            HTML.AppendLine("</table>")
            lblParList.Text = HTML.ToString
        Else
            btnRunPars_Click(sender, e)
        End If


    End Sub

    Protected Sub btnRunPars_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnRunPars.Click
        Dim strPar As String = hfParList.Value
        Dim mJson As New JavaScriptSerializer
        Dim mJsonPar As List(Of jsPar) = mJson.Deserialize(Of List(Of jsPar))(strPar)
        Dim strSQL As String
        If hftxtSQL.Value = "TabSQLMain" Or hftxtSQL.Value = "" Then
            strSQL = txtSQLMain.Text
        Else
            strSQL = txtSQLCount.Text
        End If
        lblParList.Text = ""
        Dim mPar As jsPar
        Dim mXDoc As XDocument = XDocument.Parse("<root>" & strSQL & "</root>")
        Dim mWhere = From w In mXDoc.Root.Elements _
                     Where w.Attribute("Type").Value = "WHERE" _
                     Select w
        Dim mOrder = From o In mXDoc.Root.Elements _
                     Where o.Attribute("Type").Value = "ORDER" _
                     Select o
        Dim mVariable = From v In mXDoc.Root.Elements _
                        Where v.Attribute("Type").Value = "Variable" _
                        Select v
        Dim strWhere As String = ""
        Dim strValue As String = ""
        Dim mFirst As Boolean = True
        Dim strW As String = ""
        For Each w In mWhere
            If Not mFirst Then
                strWhere = w.Attribute("Connect").Value
            Else
                mFirst = False
            End If
            strWhere = strWhere & " " & w.Attribute("Condition").Value
            strWhere = strWhere & intToString(w.Attribute("Operator").Value)
            If w.Attribute("ValueType").Value = "Value" Then
                strValue = w.Attribute("Name").Value
            Else
                If mJsonPar IsNot Nothing Then
                    strW = w.ToString
                    mPar = (From p In mJsonPar Where p.Sourcess = strW Select p).FirstOrDefault
                    If mPar.Value = "请输入测试值" Then
                        strValue = ""
                    Else
                        strValue = mPar.Value
                    End If
                End If
            End If
            Select Case w.Attribute("Decrypt").Value
                Case "MD5"
                    strValue = BaseFunction.PublicMethod.MD5(strValue, 16)
                Case "编码"
                    strValue = Server.UrlDecode(strValue)
            End Select
            If w.Attribute("Operator").Value <> "LIKE" Then
                strWhere = strWhere & "'" & strValue & "'"
            Else
                strWhere = strWhere & "'%" & strValue & "%'"
            End If
            strSQL = strSQL.Replace(w.ToString, strWhere)
            strWhere = ""
        Next
        Dim strO As String = ""
        Dim strOrder As String = ""
        Dim strDesc As String = ""
        Dim HasFirst As Boolean = False
        For Each o In mOrder
            strO = o.ToString
            If o.Attribute("FieldSource").Value.ToLower <> "request" And o.Attribute("FieldSource").Value.ToLower <> "cookie" Then
                strOrder = o.Attribute("FieldSource").Value & "." & o.Attribute("FieldName").Value
            Else
                strOrder = (From f In mJsonPar Where f.Sourcess = strO And f.Tag = "ORDERFIELD" Select f.Value).FirstOrDefault
                If strOrder = "请输入测试值" Then
                    strOrder = ""
                End If
            End If
            If o.Attribute("DescSource").Value.ToLower <> "request" And o.Attribute("DescSource").Value.ToLower <> "cookie" Then
                strDesc = o.Attribute("DescName").Value
            Else
                strDesc = (From f In mJsonPar Where f.Sourcess = strO And f.Tag = "ORDERDESC" Select f.Value).FirstOrDefault
                If strDesc = "请输入测试值" Then
                    strDesc = ""
                End If
            End If
            If strOrder Is Nothing OrElse strOrder.Length = 0 Then
                strSQL = strSQL.Replace(o.ToString, "")
            Else
                If HasFirst Then
                    strSQL = strSQL.Replace(o.ToString, " ," & strOrder & " " & strDesc)
                Else
                    strSQL = strSQL.Replace(o.ToString, strOrder & " " & strDesc)
                    HasFirst = True
                End If
            End If
        Next
        Dim strV As String = ""
        For Each v In mVariable
            If mJsonPar IsNot Nothing Then
                strV = v.ToString
                mPar = (From p In mJsonPar Where p.Sourcess = strV Select p).FirstOrDefault
                If mPar.Value = "请输入测试值" Then
                    mPar.Value = ""
                End If
                If mPar.Sourcess IsNot Nothing Then
                    strSQL = strSQL.Replace(mPar.Sourcess, mPar.Value)
                End If
            End If
        Next

        lblExValue.Text = RunSQL(strSQL)
    End Sub


    Private Function RunSQL(ByVal sql As String) As String
        Dim strReturn As New StringBuilder
        Dim iTable As Data.DataTable
        Dim sqlType As Integer = 0
        Integer.TryParse(dplSQLTemplate.SelectedValue, sqlType)

        Using mConn As New Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings("XrenCRMConnString").ConnectionString)
            mConn.Open()
            Dim mCMD As New Data.SqlClient.SqlCommand
            mCMD.Connection = mConn
            mCMD.CommandText = sql
            If sqlType = -2 OrElse sqlType = -3 OrElse sqlType = -4 Then
                strReturn.Append("查询已执行，影响的行数为：" & mCMD.ExecuteNonQuery.ToString)
                mConn.Close()
                Return strReturn.ToString
            Else
                Dim mDA As New Data.SqlClient.SqlDataAdapter(mCMD)
                Dim mDT As New Data.DataSet
                Try
                    mDA.Fill(mDT)
                Catch ex As Exception
                    strReturn.Append("<br /><span style=""color:red;"">" & ex.Message & "</span><br /><br /><span style=""cursor:pointer;color:blue;"" onclick='showErrorSQL();'>点击查看SQL语句</span><div id=""errorSQL"" style=""display:none;"">" & sql & "</div>")
                    Return strReturn.ToString
                End Try
                iTable = mDT.Tables(0)
            End If
            mConn.Close()
        End Using
        strReturn.Append("<table cellspacing=""0"" style=""width: 100%;border-right: 1px solid #C0C0C0;border-bottom: 1px solid #C0C0C0;"">")
        strReturn.Append("<tr>")
        For Each iCol As Data.DataColumn In iTable.Columns
            strReturn.Append("<td style=""border-left: 1px solid #C0C0C0;border-top: 1px solid #C0C0C0;line-height:20px;padding-left:5px;background-color:#3399FF;color:#FFFFFF;"">" & iCol.ColumnName & "</td>")
        Next
        strReturn.Append("</tr>")
        For i As Integer = 0 To iTable.Rows.Count - 1
            strReturn.Append("<tr>")
            For j As Integer = 0 To iTable.Columns.Count - 1
                strReturn.Append("<td style=""border-left: 1px solid #C0C0C0;border-top: 1px solid #C0C0C0;line-height:20px;padding-left:5px;"">" & iTable.Rows(i)(j).ToString() & "</td>")
            Next
            strReturn.Append("</tr>")
        Next
        strReturn.Append("</table>")
        Return strReturn.ToString
    End Function

    Function FormatSQL(ByVal StrSQL As String) As String
        Dim mXDoc As XDocument = XDocument.Parse("<root>" & StrSQL & "</root>")
        Dim tagList As List(Of String) = (From a As XElement In mXDoc.Root.Elements("Value") _
                                          Let str = a.ToString _
                                          Select str).ToList
        Dim ReSQL As String = New Regex("^\s*$").Replace(StrSQL, " ")
        ReSQL = New Regex("select ", RegexOptions.IgnoreCase).Replace(ReSQL, "SELECT " & vbCrLf & vbTab)
        ReSQL = New Regex("insert into ", RegexOptions.IgnoreCase).Replace(ReSQL, "INSERT INTO " & vbCrLf & vbTab)
        ReSQL = New Regex("update ", RegexOptions.IgnoreCase).Replace(ReSQL, "UPDATE " & vbCrLf & vbTab)
        ReSQL = New Regex("delete ", RegexOptions.IgnoreCase).Replace(ReSQL, "DELETE " & vbCrLf & vbTab)
        ReSQL = New Regex("from ", RegexOptions.IgnoreCase).Replace(ReSQL, vbCrLf & "FROM " & vbCrLf & vbTab)
        ReSQL = New Regex("where ", RegexOptions.IgnoreCase).Replace(ReSQL, vbCrLf & "WHERE " & vbCrLf & vbTab)
        ReSQL = New Regex(" and ", RegexOptions.IgnoreCase).Replace(ReSQL, " AND " & vbCrLf & vbTab)
        ReSQL = New Regex(" or ", RegexOptions.IgnoreCase).Replace(ReSQL, " OR " & vbCrLf & vbTab)
        ReSQL = New Regex("order by ", RegexOptions.IgnoreCase).Replace(ReSQL, vbCrLf & "ORDER BY " & vbCrLf & vbTab)
        ReSQL = New Regex("inner join ", RegexOptions.IgnoreCase).Replace(ReSQL, vbCrLf & "INNER JOIN " & vbCrLf & vbTab)
        ReSQL = New Regex(" on ", RegexOptions.IgnoreCase).Replace(ReSQL, " ON ")
        For Each a As String In tagList
            ReSQL = New Regex("'" & a & "'", RegexOptions.IgnoreCase).Replace(ReSQL, vbCrLf & vbTab & "'" & a & "'" & vbCrLf & vbTab)
            ReSQL = New Regex("(?<=[^'])" & a & "(?=[^']?)").Replace(ReSQL, vbCrLf & vbTab & a & vbCrLf & vbTab)
        Next
        Return ReSQL.Replace(vbCrLf & vbTab & vbCrLf, vbCrLf)
    End Function

    Protected Sub imgSave_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgSave.Click
        Dim strMsg As String = ChkInput()
        If strMsg.Length = 0 Then
            Dim mclsSQL As New DB_SQL.clsSQLData
            Dim mSiteID As Integer = 0
            Dim mClassID As Integer = 0
            Dim mCacheType As Integer = 0
            Dim mSQLTmp As Integer = 0
            Integer.TryParse(BaseFunction.PublicMethod.GetApplication("SiteID"), mSiteID)
            Integer.TryParse(dplSQLClassID.SelectedValue, mClassID)
            Integer.TryParse(dplCacheLifeType.SelectedValue, mCacheType)
            Integer.TryParse(dplSQLTemplate.SelectedValue, mSQLTmp)
            Dim ID As Integer = 0
            Dim mclsSQLdesign As New DB_SQL.clsSQLDesign
            If imgSave.ToolTip = "添加" Then
                ID = mclsSQL.Insert(mSiteID, mClassID, mCacheType, txtSQLName.Text, mSQLTmp, txtSQLMain.Text, txtSQLCount.Text, txtDependOf.Text)
                If ID > 0 Then
                    mclsSQLdesign.Insert(ID, hfWhere.Value, hfOrderBY.Value, hfSelectFields.Value, hfTableJson.Value, hfHTMLMain.Value, hfHTMLWhere.Value, hfHTMLOrder.Value, hfInner.Value, hfHTMLInner.Value)
                    BaseFunction.PublicMethod.ShowMessage(Page, "提示", "添加成功！", "/Manager/Tags/SQLManager.aspx")
                Else
                    BaseFunction.PublicMethod.ShowMessage(Page, "提示", "添加失败！", "/Manager/Tags/SQLManager.aspx")
                End If
            Else
                If Integer.TryParse(Request("ID"), ID) Then
                    If mclsSQL.Save(ID, mClassID, mCacheType, txtSQLName.Text, mSQLTmp, txtSQLMain.Text, txtSQLCount.Text, txtDependOf.Text) > 0 Then
                        mclsSQLdesign.Save(ID, hfWhere.Value, hfOrderBY.Value, hfSelectFields.Value, hfTableJson.Value, hfHTMLMain.Value, hfHTMLWhere.Value, hfHTMLOrder.Value, hfInner.Value, hfHTMLInner.Value)
                        BaseFunction.PublicMethod.ShowMessage(Page, "提示", "保存成功！", "/Manager/Tags/SQLManager.aspx")
                    Else
                        BaseFunction.PublicMethod.ShowMessage(Page, "提示", "保存失败！", "/Manager/Tags/SQLManager.aspx")
                    End If
                End If
            End If
        Else
            BaseFunction.PublicMethod.ShowMessage(Page, "提示", strMsg, "/Manager/Tags/SQLManager.aspx")
        End If
    End Sub
    Private Function ChkInput() As String
        Dim strReturn As String = ""
        If txtSQLName.Text.Length = 0 Then strReturn = "查询名称不能为空！<br />"
        If dplSQLClassID.SelectedValue = "0" Then strReturn = "请选择查询分类！<br />"
        If txtSQLMain.Text.Length = 0 Then strReturn = "查询语句不能为空<br />"
        Return strReturn
    End Function
End Class
