﻿
Imports System.Web.Configuration

Partial Public Class ExportsList
  Inherits System.Web.UI.Page

  Private Shared intDateColumn As Integer
  Private Shared dblRows As Double = 0
  Private Shared strGVFilter As String = ""
  Private Shared blnSelected As Boolean = False

  Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then dblRows = 0

    lblMessage.Text = ""
  End Sub

  Private Sub Page_LoadComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.LoadComplete

    If Not Page.IsPostBack Then
      Dim arrFilter(0) As String
      Dim intStart, intEnd As Integer
      intDateColumn = gvExports.Columns.Count - 3

      If ddlBrand.SelectedIndex > -1 Then
        sdsBrandProduct.FilterExpression = "refBrandID = " & ddlBrand.SelectedValue
      Else
        sdsBrandProduct.FilterExpression = ""
      End If

      'If ddlPeriod.SelectedIndex = -1 Then ddlPeriod.SelectedValue = Date.Now.ToString("yyyyMM")

      gvExports.PageSize = WebConfigurationManager.AppSettings("PAGESIZE")
      If WebConfigurationManager.AppSettings("ULEVEL") <> 5 Then
        btnAdd1.Enabled = False
        btnProcess.Enabled = False
      End If

      If WebConfigurationManager.AppSettings("strPage") = "ExportsDetails" Then

        If WebConfigurationManager.AppSettings("ShowMore") = True Then
          gvExports.PageSize = WebConfigurationManager.AppSettings("MAXPAGESIZE")
        End If

        gvExports.PageIndex = WebConfigurationManager.AppSettings("intListIndex")
        strGVFilter = WebConfigurationManager.AppSettings("intListFilter")
        Try
          arrFilter(0) = strGVFilter.Replace(" AND ", Chr(31))
          arrFilter = arrFilter(0).Split(Chr(31))
          For i As Integer = 1 To arrFilter.Length - 1
            
            'If arrFilter(i).Contains("refExportID") Then ddlKeyAccount.SelectedValue = arrFilter(i).Substring(arrFilter(i).IndexOf("=") + 1).Trim
          Next

          sdsExports.FilterExpression = strGVFilter
          'Exit Sub
        Catch ex As Exception

        End Try

      End If

      btnSearch_Click(sender, e)
    End If

    dblRows = gvExports.PageIndex * gvExports.PageSize     '< has to run for every action				
  End Sub

  Private Sub Page_PreRenderComplete(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRenderComplete
    Dim s As String = ""

    btnExport.Enabled = True

    'If strGVFilter.Length > 0 Then s = "WHERE " & strGVFilter
    'If sqlDB.CountRows("SELECT ExportID, CASE WHEN refBrandID is NULL THEN -1 ELSE refBrandID END AS refBrandID FROM mstExports LEFT JOIN mstProduct ON strProdCode = mstProdCode " & s) = 0 Then
    '  lblMessage.Text = "<div width='100%' align='center'>- No Exports found -</div>"
    '  btnExport.Enabled = False
    'End If
  End Sub

  Private Sub gvExports_Sorting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewSortEventArgs) Handles gvExports.Sorting
    sdsExports.FilterExpression = strGVFilter
    dblRows = 0
  End Sub

  Private Sub gvExports_PageIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gvExports.PageIndexChanged
    sdsExports.FilterExpression = strGVFilter
    WebConfigurationManager.AppSettings("intListIndex") = gvExports.PageIndex
  End Sub

  Private Sub gvExports_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvExports.RowDataBound
    Dim s As String = ""
    If e.Row.RowType = DataControlRowType.DataRow Then

      Dim btnDelete As LinkButton = CType(e.Row.Cells(e.Row.Cells.Count - 2).Controls(0), LinkButton)
      Dim chkProcessed As CheckBox = CType(e.Row.Cells(e.Row.Cells.Count - 6).Controls(1), CheckBox)
      If WebConfigurationManager.AppSettings("ULEVEL") = 5 Then
        If chkProcessed.Checked = True Then
          btnDelete.Enabled = False
        Else
          btnDelete.OnClientClick = String.Format("return confirm('Are you certain you want to delete Exports ""{0}"" ?');", _
                   DirectCast(DirectCast(e.Row.Cells(1).Controls(0), System.Web.UI.Control), System.Web.UI.WebControls.HyperLink).Text)
        End If
    Else
      btnDelete.Enabled = False
    End If
    Try
        dblRows += 1
        Try
          s = e.Row.Cells(e.Row.Cells.Count - 5).Text.ToString.Substring(0, 6)
        Catch ex As Exception
          s = "999999"
        End Try
        e.Row.BackColor = Drawing.Color.FromArgb(DailyLog.getHexColour(s, "R"), DailyLog.getHexColour(s, "G"), DailyLog.getHexColour(s, "B"))
      e.Row.Cells(0).Text = dblRows
      e.Row.Cells(intDateColumn).Text = sqlDB.SqlDate(e.Row.Cells(intDateColumn).Text, "d MMM yyyy")  ' "d MMM yyyy HH:mm")
    Catch ex As Exception
      e.Row.Cells(intDateColumn).Text = Date.Now.ToString("n/a")
    End Try
    End If
  End Sub

  Private Sub gvExports_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvExports.RowDeleting
    Dim intRows As Integer = 0
    lblMessage.Text = ""
    intRows = 0

    If intRows > 0 Then
      lblMessage.Text = "<div width='100%' align='right'>Unable to delete Exports '" & e.Keys(1) & "': Exports is in use</div>"
      e.Cancel = True
    Else
      e.Cancel = False
      btnSearch_Click(sender, e:=New System.EventArgs())
    End If
  End Sub

  Protected Sub btnSearch_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSearch.Click
    sdsExports.FilterExpression = "1=1"
    dblRows = 0

    Dim s As String

    If ddlCustomer.SelectedIndex > 0 Then
      sdsExports.FilterExpression &= " AND mstCustomer = '" & ddlCustomer.SelectedValue & "'"
    End If
    If ddlProduct.SelectedIndex > 0 Then
      sdsExports.FilterExpression &= " AND mstProdCode = '" & ddlProduct.SelectedValue & "'"
    End If
    If ddlPeriod.SelectedIndex > 0 Then
      sdsExports.FilterExpression &= " AND mstPeriod = '" & ddlPeriod.SelectedValue & "'"
    Else
      If ddlBrand.SelectedIndex > 0 Then
        sdsExports.FilterExpression &= " AND refBrandID = " & ddlBrand.SelectedValue
      End If
    End If
    If ddlStatus.SelectedIndex > 0 Then
      sdsExports.FilterExpression &= " AND blnProcessed = " & ddlStatus.SelectedValue
    End If

    strGVFilter = sdsExports.FilterExpression
    WebConfigurationManager.AppSettings("intListFilter") = strGVFilter

  End Sub

  Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnAdd1.Click
    Response.Redirect("ExportsDetails.aspx?EID=0")
  End Sub

  Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnExport.Click
    sdsExports.FilterExpression = strGVFilter
    gvExport.Visible = True

    Response.Clear()
    Response.Buffer = True
    Response.ContentType = "application/vnd.ms-excel"
    Response.Charset = ""
      Response.AddHeader("Content-Disposition", _
       "attachment;filename=ExportsList_" & Session.Item("User").Replace(" ", "") & "_" & Date.Today.ToString("yyyyMMdd") & ".xls") 'v1.4.5 - 20160913 - Fixed logged In user & savings (i.e use session instead) - maanie
    Me.EnableViewState = False

    Dim oStringWriter As New System.IO.StringWriter()
    Dim oHtmlTextWriter As New System.Web.UI.HtmlTextWriter(oStringWriter)
    Dim frm As HtmlForm = New HtmlForm()
    Me.Controls.Add(frm)
    frm.Controls.Add(gvExport)
    frm.RenderControl(oHtmlTextWriter)
    Response.Write(oStringWriter.ToString())

    gvExport.Visible = False

    Response.End()
  End Sub

  Protected Sub chkResize_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) Handles chkResize.CheckedChanged
    gvExports.PageIndex = 0
    sdsExports.FilterExpression = strGVFilter
    If chkResize.Checked Then
      gvExports.PageSize = WebConfigurationManager.AppSettings("MAXPAGESIZE")
      WebConfigurationManager.AppSettings("ShowMore") = True
    Else
      gvExports.PageSize = WebConfigurationManager.AppSettings("PAGESIZE")
      WebConfigurationManager.AppSettings("ShowMore") = False
    End If
  End Sub

  Protected Sub ddlBrand_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs) Handles ddlBrand.SelectedIndexChanged
    sdsBrandProduct.FilterExpression = "refBrandID = 0 OR refBrandID = " & ddlBrand.SelectedValue
  End Sub

  Protected Sub btnProcess_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnProcess.Click
    Dim chk As CheckBox
    Dim ExportID, strBatch As String
    Dim blnRan As Boolean = False
    Dim dr As DataRow
    Dim ds As DataSet

    strBatch = Date.Now.Ticks

    For Each row As GridViewRow In gvExports.Rows
      Try
        If row.Cells(14).Controls.Count > 2 Then
          chk = row.Cells(14).Controls(1)
          If chk.Checked = True And chk.Visible = True Then
            ExportID = DirectCast(DirectCast(DirectCast(row.Cells(1), System.Web.UI.WebControls.TableCell).Controls(0), System.Web.UI.Control), System.Web.UI.WebControls.HyperLink).NavigateUrl
            ExportID = CDbl(ExportID.Substring(ExportID.IndexOf("=") + 1))
            dr = sqlDB.GetRow(sqlDB.sql_get_Export(ExportID))
            If sqlDB.Nz(dr!refBrandID, 0) <> 0 Then
                     sqlDB.doQueryDS(sqlDB.sql_process_Export(ExportID, strBatch, Session.Item("User")))
              blnRan = True
            Else
              sqlDB.WriteLog("Export & DC Sales: dwfSales", "Processing Error", "Missing or incomplete product information: ProdCode = ''" & dr!mstProdCode & "'', ExportID = ''" & ExportID & "''", strBatch, 1)
            End If

          End If
        End If
      Catch ex As Exception

      End Try
    Next

    If blnRan Then
      Try
        ds = sqlDB.doQueryDS(sqlDB.sql_delete_Sales_Exports(strBatch))
        sqlDB.doQueryDS(sqlDB.sql_insert_Sales_Exports(strBatch))
      Catch ex As Exception
        'undo Process!
        sqlDB.WriteLog("Export & DC Sales: dwfSales", "Processing Error", "UNDOING PROCESS: " & sqlDB.CleanString(ex), strBatch, 1)
            sqlDB.doQueryDS(sqlDB.sql_process_Export_undo(strBatch, Session.Item("User")))
      End Try

    End If

    'reload
    blnSelected = False
    WebConfigurationManager.AppSettings("strPage") = "ExportsDetails"
    Response.Redirect("ExportsList.aspx")
  End Sub

  Protected Sub btnSelectAll_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnSelectAll.Click
    Dim chk As CheckBox

    blnSelected = Not blnSelected

    For Each row As GridViewRow In gvExports.Rows
      Try
        If row.Cells(14).Controls.Count > 2 Then
          chk = row.Cells(14).Controls(1)
          chk.Checked = blnSelected
        End If
      Catch
      End Try
    Next
  End Sub
End Class