Imports System.Data
Imports System.Data.SqlClient
Imports AppVariable
Imports AppAuth
Imports AppCommon

Partial Public Class PasswordReset
    Inherits System.Web.UI.Page

#Region "******************** ページイベント ********************"

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        'ヘッダの左領域を設定
        SetHeaderLeft(lb_user, lb_title)

        '---------------------------------------------------------------
        'HTMLタグを追加
        '---------------------------------------------------------------
        Dim ctl As Control = Page.FindControl("login_header")
        'JS
        SetTagJs(ctl, "common.js")
        SetTagJs(ctl, "jquery-1.8.3.min.js")
        SetTagJs(ctl, "login.js")
        'CSS
        SetTagCss(ctl, "login.css?20230605")
        SetTagCss(ctl, "master.css")
        SetTagCss(ctl, "common.css")
        'ファビコン
        SetTagFavicon(ctl)

        If Not IsPostBack Then
            'メッセージの表示切替
            CheckFlagAndUpdateDisplay()
        End If
    End Sub

#End Region

#Region "***************** コントロールイベント *****************"
    Protected Sub sds_PW変更_Init(sender As Object, e As EventArgs) Handles sds_PW変更.Init

        sds_PW変更_select()

    End Sub

    ''' <summary>
    ''' SqlDataSourceパラメータ設定
    ''' </summary>
    ''' <remarks></remarks>
    Protected Sub sds_PW変更_select()

        Dim strMid As String = "" 'DBPW変更.CNT
        Dim strMkey As String = "" 'DBPW変更.CNT+DBPW変更.PORTALIDのハッシュ値

        If Page.Request.QueryString.Get("mid") <> "" Then
            strMid = Page.Request.QueryString.Get("mid")
        End If
        If Page.Request.QueryString.Get("mkey") <> "" Then
            strMkey = Page.Request.QueryString.Get("mkey")
        End If


        'DB接続文字列取得
        Dim conStr As String = System.Configuration.ConfigurationManager.ConnectionStrings(DB_strCon).ConnectionString

        With sds_PW変更

            'パラメータをクリア
            .SelectParameters.Clear()

            'ストアド設定
            .SelectCommand = "dbo.PW_PW変更_SELECT"
            .SelectCommandType = SqlDataSourceCommandType.StoredProcedure
            .CancelSelectOnNullParameter = False
            .ConnectionString = conStr

            'パラメータ追加
            .SelectParameters.Add("mid", strMid)
            .SelectParameters.Add("mkey", strMkey)
        End With

    End Sub

    Protected Sub lsv_PW変更_ItemDataBound(sender As Object, e As ListViewItemEventArgs) Handles lsv_PW変更.ItemDataBound
        If e.Item.ItemType = ListViewItemType.DataItem Then

            Dim btn変更 As Button = CType(e.Item.FindControl("btn変更"), Button)
            Dim hdf_変更済FLG As String = CType(e.Item.FindControl("hdf_変更済FLG"), HiddenField).Value
            Dim str処理結果MSG As String = CType(e.Item.FindControl("hdf_処理結果MSG"), HiddenField).Value

            '処理済みの場合、ボタン使用不可
            If str処理結果MSG.Length > 0 Then
                btn変更.Enabled = False
                btn変更.CssClass = ""
                btn変更.ForeColor = Drawing.Color.Gray
                lsv_PW変更.Visible = False
            End If

        End If
    End Sub

    Protected Sub btn変更_Click(sender As Object, e As EventArgs)
        Dim txtNewPass As TextBox = CType(CType(sender, Button).Parent.FindControl("txtNewPass"), TextBox)
        Dim txtConfirmPass As TextBox = CType(CType(sender, Button).Parent.FindControl("txtConfirmPass"), TextBox)
        Dim lbl_errorMsg As Label = CType(CType(sender, Button).Parent.FindControl("lbl_errorMsg"), Label)
        Dim intCNT As Integer = 0
        If Integer.TryParse(CType(sender, Button).CommandArgument, intCNT) Then
            intCNT = CType(sender, Button).CommandArgument
        End If

        If txtNewPass.Text <> "" Then
            If txtNewPass.Text = txtConfirmPass.Text Then

                Dim strOutput As String = ""
                strOutput = 処理前チェック(intCNT)
                If Not String.IsNullOrEmpty(strOutput) Then
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().GetHashCode().ToString, "javascript:alert('" & strOutput & "');", True)
                    lsv_PW変更.DataBind()
                    Exit Sub
                End If

                'パスワードを更新
                If PassWord更新(intCNT, _
                                txtNewPass.Text) = True Then
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().GetHashCode().ToString, "javascript:alert('パスワードを変更しました。');", True)
                    lsv_PW変更.DataBind()

                    Dim logoutUrl As String = ResolveUrl(Request.ApplicationPath & Logout_FilePath)
                    Dim script As String = "showAlertAndRedirect('パスワードを変更しました。', '" & logoutUrl & "');"
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().ToString(), script, True)

                Else
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().GetHashCode().ToString, "javascript:alert('*エラーが発生しました。');", True)

                    lsv_PW変更.DataBind()
                    Exit Sub
                End If
            Else
                lbl_errorMsg.Text = "入力したパスワードが一致しません。"
                Exit Sub
            End If
        End If


    End Sub

#End Region

#Region "******************* Sub及びFunction ********************"

    Private Function 処理前チェック(ByVal intCNT As Integer) As String

        Dim cnStr As String = System.Configuration.ConfigurationManager.ConnectionStrings(DB_strCon).ConnectionString
        Using con As New SqlConnection(cnStr)

            con.Open()

            Try

                Dim cmd As SqlCommand = New SqlCommand("dbo.PW_PW変更_処理前CHK_OUTPUT", con)
                cmd.CommandType = CommandType.StoredProcedure

                Dim param1 As SqlParameter = cmd.Parameters.Add("@CNT", SqlDbType.Int)
                param1.Value = intCNT

                Dim param10 As SqlParameter = cmd.Parameters.Add("@ERRMSG", Data.SqlDbType.VarChar, 200)
                param10.Direction = ParameterDirection.Output

                cmd.ExecuteNonQuery()

                If Not String.IsNullOrEmpty(param10.Value.ToString) Then
                    Return param10.Value.ToString
                Else
                    Return ""
                End If

            Catch ex As Exception
                con.Close()
                Return "エラーが発生しました。"
            End Try

            con.Close()

        End Using
    End Function

    Private Function PassWord更新(ByVal intCNT As Integer,
                                  ByVal strNewPass As String) As Boolean

        Dim cnStr As String = System.Configuration.ConfigurationManager.ConnectionStrings(DB_strCon).ConnectionString
        Using con As New SqlConnection(cnStr)

            con.Open()

            Try

                Dim cmd As SqlCommand = New SqlCommand("dbo.PW_PW変更_処理_UPDATE", con)
                cmd.CommandType = CommandType.StoredProcedure

                Dim param1 As SqlParameter = cmd.Parameters.Add("@CNT", SqlDbType.Int)
                param1.Value = intCNT

                Dim param2 As SqlParameter = cmd.Parameters.Add("@NewPass", SqlDbType.VarChar, 20)
                param2.Value = strNewPass

                cmd.ExecuteNonQuery()

                Return True

            Catch ex As Exception
                con.Close()
                Return False
            End Try

            con.Close()

        End Using
    End Function

    Private Sub CheckFlagAndUpdateDisplay()
        Dim dataView As DataView = DirectCast(sds_PW変更.Select(DataSourceSelectArguments.Empty), DataView)

        If dataView IsNot Nothing AndAlso dataView.Count > 0 Then
            Dim flagValue As Boolean = Convert.ToBoolean(dataView(0)("変更済FLG"))

            If flagValue Then
                lsv_PW変更.Visible = False
                MessagePanel.Visible = True
            Else
                lsv_PW変更.Visible = True
                MessagePanel.Visible = False
            End If
        End If
    End Sub


#End Region


End Class