Imports System.ComponentModel
Imports DocumentFormat.OpenXml.Drawing.Spreadsheet
Imports DocumentFormat.OpenXml.Office2010.Excel
Imports System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel
Imports VERAG_PROG_ALLGEMEIN.TESTJSON
Imports DocumentFormat.OpenXml.Spreadsheet
Imports DocumentFormat.OpenXml.Wordprocessing
Imports GrapeCity.ActiveReports.ReportsCore.Tools

Public Class usrCntlERS

    Dim MONAT As Date = CDate("01." & Now.Month & "." & Now.Year) '.AddMonths(-1)
    Dim srcTAG As Date = CDate(Now.ToShortDateString)

    Dim JAHR As Date = CDate("01.01." & Now.Year)

    Private Sub usrCntlAPI_Load(sender As Object, e As EventArgs) Handles Me.Load
        txtAbfertDat.Text = Now.ToShortDateString 'CDate("01." & Now.ToString("MM.yyyy")).AddMonths(-1).txtAbfertDatBisToShortDateString
        txtAbfertDatBis.Text = Now.ToShortDateString

        btnMonat.Text = MONAT.ToString("MMMM")
        btnJahr.Text = JAHR.Year

        txtUser.initKdBox(Me.FindForm) '   initKdAbsender()

        cboFirma.fillWithSQL("SELECT  distinct(isnull(ers_Firma,'')) FROM [tblERS] ", False, "ADMIN", True)

        cboDatum.Items.Clear()
        cboDatum.Items.Add(New VERAG_PROG_ALLGEMEIN.MyListItem("Error-Datum", "EDat"))
        cboDatum.changeItem("EDat")

        cboProgram.Items.Clear()
        cboProgram.fillWithSQL("SELECT [prog_id],[prog_codename] from [tblProgramme]", False, "ADMIN", True)
        cboProgram.changeItem("")

        cboType.Items.Clear()
        cboType.fillWithSQL("SELECT distinct(ers_Type) FROM [tblERS] ", False, "ADMIN", True)
        cboType.changeItem("")

    End Sub

    Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
        txtAbfertDat._value = CDate(sender.value).ToShortDateString
    End Sub

    Private Sub DateTimePicker2_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker2.ValueChanged
        txtAbfertDatBis._value = CDate(sender.value).ToShortDateString
    End Sub

    Private Sub btnMonat_Click(sender As Object, e As EventArgs) Handles btnMonat.Click
        initBtns("Monat")
    End Sub
    Sub initBtns(MonatJahr)
        btnMonat.Text = MONAT.ToString("MMMM")
        btnJahr.Text = JAHR.Year
        Select Case MonatJahr
            Case "Monat"
                DateTimePicker1.Value = MONAT
                DateTimePicker2.Value = MONAT.AddMonths(1).AddDays(-1)
            Case "Jahr"
                '  If cbxGeschaftsjahr.Checked Then
                'DateTimePicker1.Value = JAHR.AddMonths(1)
                ' DateTimePicker2.Value = JAHR.AddYears(1).AddMonths(1).AddDays(-1)
                ' Else
                DateTimePicker1.Value = JAHR
                DateTimePicker2.Value = JAHR.AddYears(1).AddDays(-1)
                'End If
            Case "Tag"
                '  If cbxGeschaftsjahr.Checked Then
                'DateTimePicker1.Value = JAHR.AddMonths(1)
                ' DateTimePicker2.Value = JAHR.AddYears(1).AddMonths(1).AddDays(-1)
                ' Else
                DateTimePicker1.Value = srcTAG
                DateTimePicker2.Value = srcTAG
                If srcTAG = Now.ToShortDateString Then
                    Button5.Text = "Heute"
                ElseIf srcTAG = Now.AddDays(-1).ToShortDateString Then
                    Button5.Text = "Gestern"
                ElseIf srcTAG = Now.AddDays(-2).ToShortDateString Then
                    Button5.Text = "Vorgestern"
                Else
                    Button5.Text = srcTAG.ToString("dd.MM")
                End If

                'End If
            Case ""
                DateTimePicker1.Value = ("01." & Now.Month & "." & Now.Year)
                DateTimePicker2.Value = Now
        End Select

    End Sub

    Private Sub btnJahr_Click(sender As Object, e As EventArgs) Handles btnJahr.Click
        initBtns("Jahr")
    End Sub

    Private Sub btnBisMonat_Click(sender As Object, e As EventArgs) Handles btnBisMonat.Click
        MONAT = MONAT.AddMonths(1)
        initBtns("Monat")
    End Sub

    Private Sub btnVonMonat_Click(sender As Object, e As EventArgs) Handles btnVonMonat.Click
        MONAT = MONAT.AddMonths(-1)
        initBtns("Monat")
    End Sub

    Private Sub btnBisJahr_Click(sender As Object, e As EventArgs) Handles btnBisJahr.Click
        JAHR = JAHR.AddYears(1)
        initBtns("Jahr")
    End Sub

    Private Sub btnVonJahr_Click(sender As Object, e As EventArgs) Handles btnVonJahr.Click
        JAHR = JAHR.AddYears(-1)
        initBtns("Jahr")
    End Sub



    Private Sub btnSuche_Click(sender As Object, e As EventArgs) Handles btnSuche.Click
        Me.Cursor = Cursors.WaitCursor

        Dim sqlstr As String = ""
        Dim TopMax = If(IsNumeric(txtMaxSrch.Text), " TOP " & txtMaxSrch.Text, "")
        sqlstr &= "SELECT " & TopMax & " [ers_id],[ers_progId],[ers_progName],[ers_progVersion],[ers_datetime],[ers_errCode],[ers_errStack],[ers_errMessage],[ers_errMethodName],[ers_Testsystem],[ers_Type],[ers_EMail],[ers_maId],[ers_userName],[ers_Firma],[ers_infotext]
                  FROM [tblERS] WHERE 1=1 "

        With DataGridView
            '  .DataSource = myTable
            .SET_SQL(sqlstr & getErrordatumWhere() & " ORDER BY ers_datetime", "ADMIN", getErrorList)
            .LOAD()

            If .RowCount = 0 Then Me.Cursor = Cursors.Default : Exit Sub
            .RowHeadersVisible = False
            .ReadOnly = True
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            .MultiSelect = False

            .Columns("ers_id").Visible = False
            .Columns("ers_progId").Visible = False

            For Each cc As DataGridViewColumn In .Columns
                cc.HeaderText = cc.Name.Replace("ers_", "")
            Next

            '.Columns("RechnungsNr").Width = 70
            '.Columns("RechnungsNr").HeaderText = "Rechnugs-Nr"
            '.Columns("RechnungsNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            '.Columns("RechnungsNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            '.Columns("RechnungsDatum").Width = 100
            '.Columns("RechnungsDatum").HeaderText = "Rg-Dat."
            '.Columns("RechnungsDatum").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            '.Columns("RechnungsDatum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            '.Columns("Sammelrechnung").Width = 45
            '.Columns("Sammelrechnung").HeaderText = "SR"

            '.Columns("FilialenNr").Width = 45
            '.Columns("FilialenNr").HeaderText = "Filiale"
            '.Columns("FilialenNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            '.Columns("FilialenNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            '.Columns("AbfertigungsNr").Width = 70
            '.Columns("AbfertigungsNr").HeaderText = "Abf-Nr"
            '.Columns("AbfertigungsNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            '.Columns("AbfertigungsNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            '.Columns("UnterNr").Width = 45
            '.Columns("UnterNr").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            '.Columns("UnterNr").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter
            '.Columns("Abfertigungsdatum").Width = 100
            '.Columns("Abfertigungsdatum").HeaderText = "Abf-Dat."
            '.Columns("Abfertigungsdatum").HeaderCell.Style.Alignment = DataGridViewContentAlignment.TopCenter
            '.Columns("Abfertigungsdatum").DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopCenter

            '.Columns("RechnungAn").MinimumWidth = 150
            '.Columns("RechnungAn").HeaderText = "Rechnung an"
            '.Columns("RechnungAn").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            .Columns("ers_errStack").MinimumWidth = 150
            .Columns("ers_errStack").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            .Columns("ers_errMessage").MinimumWidth = 150
            .Columns("ers_errMessage").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            ''.Columns("Empfänger").MinimumWidth = 150
            ''.Columns("Empfänger").HeaderText = "Empfänger"
            ''.Columns("Empfänger").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            '.Columns("LKW Kennzeichen").Width = 120
            '.Columns("LKW Kennzeichen").HeaderText = "LKW Kennzeichen"

            '.Columns("Sachbearbeiter").MinimumWidth = 100
            '.Columns("Sachbearbeiter").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

            '.Columns("SteuerpflichtigerGesamtbetrag").Width = 120
            '.Columns("SteuerpflichtigerGesamtbetrag").HeaderText = "Betrag (stpfl.)"
            '.Columns("SteuerpflichtigerGesamtbetrag").DefaultCellStyle.Format = "N2"
            '.Columns("SteuerfreierGesamtbetrag").Width = 120
            '.Columns("SteuerfreierGesamtbetrag").HeaderText = "Betrag (stfr.)"
            '.Columns("SteuerfreierGesamtbetrag").DefaultCellStyle.Format = "N2"


            lblErgebnis.Text = "Ergebnisse: " & .RowCount
        End With

        Me.Cursor = Cursors.Default
    End Sub

    Function getErrordatumWhere() As String
        Dim sqlstr = ""
        If txtUser.Text <> "" And IsNumeric(txtUser.Text) Then sqlstr &= " AND [ers_userName] LIKE @User "

        If txtAbfertDat.Text <> "" Then
            If txtAbfertDatBis.Text <> "" Then
                sqlstr &= " AND ([ers_datetime] BETWEEN @Datum_von AND @Datum_bis ) "
            Else
                sqlstr &= " AND ([ers_datetime] BETWEEN @Datum_von AND @Datum_von ) "
            End If
        End If

        If cboFirma._value <> "" Then sqlstr &= " AND [ers_Firma] LIKE @ersFirma "
        If cboType._value <> "" Then sqlstr &= " AND [ers_Type] LIKE @ersType "
        If cboProgram._value <> "" Then sqlstr &= " AND [ers_progId] = @ersprogId "
        If cbxTestSys.CheckState <> CheckState.Indeterminate Then
            sqlstr &= " AND [ers_Testsystem] = @ersTestsystem "
        End If

        If txtFehlersuche.Text <> "" Then
            sqlstr &= " AND ([ers_errStack] like '" & txtFehlersuche.Text.Replace("*", "%") & "' Or [ers_errMessage] like '" & txtFehlersuche.Text.Replace("*", "%") & "' OR [ers_errMethodName] like '" & txtFehlersuche.Text.Replace("*", "%") & "')  "

        End If

        Return sqlstr
    End Function

    Function getErrorList() As List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)

        Dim list As New List(Of VERAG_PROG_ALLGEMEIN.SQLVariable)
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("User", txtUser.KdNr_value))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Datum_von", txtAbfertDat.Text & " 00:00:00"))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("Datum_bis", txtAbfertDatBis.Text & " 23:59:59"))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("ersFirma", cboFirma._value))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("ersType", cboType._value))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("ersprogId", cboProgram._value))
        list.Add(New VERAG_PROG_ALLGEMEIN.SQLVariable("ersTestsystem", cbxTestSys.Checked))

        Return list

    End Function

    Private Sub DataGridView_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles DataGridView.CellDoubleClick
        Me.Cursor = Cursors.WaitCursor
        Dim err As New frmERS With {
            .id = sender.CurrentRow.Cells("ers_id").Value,
            .progId = sender.CurrentRow.Cells("ers_progId").Value,
            .progName = sender.CurrentRow.Cells("ers_progName").Value,
            .progVersion = sender.CurrentRow.Cells("ers_progVersion").Value,
            .datetime = sender.CurrentRow.Cells("ers_datetime").Value,
            .testsystem = sender.CurrentRow.Cells("ers_testsystem").Value,
            .type = sender.CurrentRow.Cells("ers_type").Value,
            .mail = sender.CurrentRow.Cells("ers_email").Value,
            .maId = sender.CurrentRow.Cells("ers_maId").Value,
            .userName = sender.CurrentRow.Cells("ers_userName").Value,
            .firma = sender.CurrentRow.Cells("ers_firma").Value,
            .errorCode = sender.CurrentRow.Cells("ers_progId").Value,
            .errStack = sender.CurrentRow.Cells("ers_errStack").Value,
            .errMessage = sender.CurrentRow.Cells("ers_errMessage").Value & IIf(sender.CurrentRow.Cells("ers_infotext").Value <> "", vbNewLine & vbNewLine & "SQL-QUERY:" & vbNewLine & sender.CurrentRow.Cells("ers_infotext").Value, ""),
            .errMethodName = sender.CurrentRow.Cells("ers_errMethodName").Value
            }


        err.Show(Me)
        sender.RELOAD()
        Me.Cursor = Cursors.Default
    End Sub

    Private Sub txtFehlersuche_KeyDown(sender As Object, e As KeyEventArgs) Handles txtFehlersuche.KeyDown
        If e.KeyCode = Keys.Enter Then

            Me.btnSuche_Click(sender, e)
                e.Handled = True
            End If

    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        srcTAG = srcTAG.AddDays(-1)
        initBtns("Tag")
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles Button7.Click
        srcTAG = srcTAG.AddDays(1)
        initBtns("Tag")
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        initBtns("Tag")
    End Sub
End Class
