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

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

    Private Class UserInfo
        Public Property UserId As String
        Public Property Email As String
        Public Property CityCd As String
        Public Property OrgName As String
        Public Property DeptName As String
        Public Property StaffName As String
        Public Property Tel As String
        Public Property Pw As String

    End Class

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

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        'ヘッダの左領域を設定
        SetHeaderLeft(lb_user, lb_title)

        If Not IsPostBack Then
            'パスワードNGリストの追加 20250822 S.Iguchi
            SetHdfPassNgList()
        End If
        AddHandler uc_SearchCityCd.CitySelected, AddressOf Me.CitySelected

    End Sub

#End Region

#Region "***************** コントロールイベント *****************"

    Protected Sub sds_アカウント申請_Init(sender As Object, e As EventArgs) Handles sds_アカウント申請.Init
        sds_アカウント申請_select()
    End Sub

    Protected Sub sds_アカウント申請_select()

        Dim strMid As String = "" 'DBアカウント申請.CNT
        Dim strMkey As String = "" 'DBアカウント申請.CNT+DBアカウント申請.EMAILのハッシュ値

        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

        Dim dt As DataTable = GetApplicantInfo(strMid, strMkey)
        If dt.Rows.Count = 0 Then
            message.Text = "URLが無効です。"
            MessagePanel.Visible = True
            msp_table_main.Visible = False
            Exit Sub
        End If

        Dim email As String = dt.Rows(0)("EMAIL").ToString()
        Dim status As String = dt.Rows(0)("申請済").ToString()
        Dim deadline As DateTime

        If dt.Rows(0)("URL有効日時") IsNot DBNull.Value Then
            deadline = CType(dt.Rows(0)("URL有効日時"), DateTime)
        Else
            deadline = DateTime.MaxValue
        End If

        If Now > deadline Then
            message.Text = "URLの有効期限が切れています。再度Webポータルから新規アカウント登録をしてください。"
            MessagePanel.Visible = True
            msp_table_main.Visible = False
            Exit Sub
        End If

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

        With sds_アカウント申請

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

            'ストアド設定
            .SelectCommand = "dbo.PT_DBアカウント申請履歴_SELECT"
            .SelectCommandType = SqlDataSourceCommandType.StoredProcedure
            .CancelSelectOnNullParameter = False
            .ConnectionString = conStr

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


        '申請済の場合はコントロール非活性
        If status Then
            Dim timeStamp As String = "登録申請日時:" & dt.Rows(0)("申請日時").ToString
            btn登録.Enabled = False
            txtPID.Enabled = False
            txtCityCd.Enabled = False
            btn_検索.Enabled = False
            txtOrgName.Enabled = False
            txtDeptName.Enabled = False
            txtStaffName.Enabled = False
            txtTel.Enabled = False
            txtPw.Enabled = False
            txtPwChk.Enabled = False
            txtCityCd.Enabled = False

            lbl_timeStamp.Visible = True
            lbl_timeStamp.Text = timeStamp + "<br />既に申請済のURLです。<br />新たに申請する場合は、再度URLを発行してください。"
            msp_table_main.Visible = False
            MessagePanel.Visible = True
            Exit Sub
        End If
        ViewState("email") = email

    End Sub

    Protected Sub CitySelected(sender As Object, e As uc_SearchCityCd.CitySelectedEventArgs)
        ' 親画面の入力フィールドに値を設定します
        txtCityCd.Text = e.CityCd
        txtOrgName.Text = e.CityName
        ' モーダルを閉じる
        ScriptManager.RegisterStartupScript(Me, Me.GetType(), "closeModal", "closeModal();", True)
    End Sub

    Protected Sub btn登録_Click(sender As Object, e As EventArgs) Handles btn登録.Click

        Dim userId = txtPID.Text
        Dim cityCd = txtCityCd.Text
        Dim orgName = txtOrgName.Text
        Dim deptName = txtDeptName.Text
        Dim staffName = txtStaffName.Text
        Dim tel = txtTel.Text
        Dim pw = txtPw.Text
        Dim pwChk = txtPwChk.Text
        Dim email = ViewState("email").ToString()
        Dim strMid As String = "" 'DBアカウント申請.CNT

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

        'ユーザIDおよび直通電話番号の重複チェック
        Dim strOutput As String = ""
        strOutput = CHKアカウント(userId, cityCd, tel)

        If Not String.IsNullOrEmpty(strOutput) Then
            lbl_errorMsg.Text = strOutput
            Exit Sub
        End If

        If Not pw = pwChk Then
            lbl_errorMsg.Text = "入力されたパスワードが一致しません。もう一度確認してください。"
            Exit Sub
        End If


        '送信
        Dim userInfo As New UserInfo()
        userInfo.UserId = userId
        userInfo.CityCd = cityCd
        userInfo.OrgName = orgName
        userInfo.DeptName = deptName
        userInfo.StaffName = staffName
        userInfo.Tel = tel
        userInfo.Pw = pw
        userInfo.Email = email

        'アカウント承認テーブルに新規アカウント情報を登録する
        Dim newCnt As Integer = 送信処理(userInfo)

        If newCnt > 0 Then '登録成功

            lbl_errorMsg.Text = ""

            'アカウント仮登録通知メールの送信
            Dim sucFlg = AppMail.SendSignupApplyMail(email, userInfo.UserId, userInfo.StaffName, newCnt)

            'DBアカウント申請履歴に、申請済フラグを立てる
            Dim timeStamp = UpdateAccountStatus(strMid, email)

            ScriptManager.RegisterStartupScript(Page, Page.GetType(), Guid.NewGuid().GetHashCode().ToString, "javascript:alert('メールを送信しました。');", True)

            '登録ボタンの無効化
            btn登録.Enabled = False
            lbl_timeStamp.Visible = True
            lbl_timeStamp.Text = "登録申請日時:" & timeStamp

            'メッセージの表示、ログイン画面へ遷移
            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

            lbl_errorMsg.Text = "エラーが発生しました。"

        End If
    End Sub

    Protected Sub CustomValidator1_ServerValidate(source As Object, args As ServerValidateEventArgs)
        Dim inputPassword As String = args.Value.Trim()

        ' HiddenFieldからNGパスワードリストを取得
        Dim ngPasswordList As String = hdfPassNgList.Value

        If Not String.IsNullOrEmpty(ngPasswordList) AndAlso Not String.IsNullOrEmpty(inputPassword) Then
            ' カンマ区切りの文字列を配列に分割
            Dim ngPasswords() As String = ngPasswordList.Split(","c)

            ' 入力されたパスワードがNGリストに含まれているかチェック
            For Each ngPassword As String In ngPasswords
                If inputPassword.ToLower() = ngPassword.ToLower() Then ' 大文字小文字を区別しない場合
                    args.IsValid = False
                    Return
                End If
            Next
        End If

        ' NGパスワードに該当しない場合は有効
        args.IsValid = True
    End Sub

#End Region

#Region "******************* Sub及びFunction ********************"
    Private Function CHKアカウント(userId As String, cityCd As String,
                                   tel As String) As String

        Using spm As New StoredProcedureManager("PT_認証_NEW_ACCOUNT_OUTPUT")
            spm.AddPrmIn("@userId", Data.SqlDbType.VarChar, 20, userId)
            spm.AddPrmIn("@cityCd", Data.SqlDbType.VarChar, 20, cityCd)
            spm.AddPrmIn("@tel", Data.SqlDbType.VarChar, 20, tel)
            spm.AddPrmOut("@ERRMSG", Data.SqlDbType.VarChar, 200)

            spm.Exec()

            Dim errMsg = spm.GetValue("@ERRMSG")
            Return errMsg
        End Using
    End Function

    Private Function 送信処理(userInfo As UserInfo) As Integer

        Dim newCnt = 0

        Using spm As New StoredProcedureManager("PT_DBアカウント申請_INSERT")
            spm.AddPrmIn("@userId", Data.SqlDbType.VarChar, 100, userInfo.UserId)
            spm.AddPrmIn("@email", Data.SqlDbType.VarChar, 100, userInfo.Email)
            spm.AddPrmIn("@cityCd", Data.SqlDbType.VarChar, 20, userInfo.CityCd)
            spm.AddPrmIn("@orgName", Data.SqlDbType.VarChar, 200, userInfo.OrgName)
            spm.AddPrmIn("@deptName", Data.SqlDbType.VarChar, 100, userInfo.DeptName)
            spm.AddPrmIn("@staffName", Data.SqlDbType.NVarChar, 50, userInfo.StaffName)
            spm.AddPrmIn("@tel", Data.SqlDbType.VarChar, 20, userInfo.Tel)
            spm.AddPrmIn("@pw", Data.SqlDbType.VarChar, 20, userInfo.Pw)
            spm.AddPrmOut("@out_Cnt", Data.SqlDbType.Int)
            spm.Exec()

            newCnt = spm.GetValue("@out_Cnt")

        End Using

        Return newCnt

    End Function

    Private Function GetApplicantInfo(mid As String, mkey As String) As DataTable

        Dim dt As DataTable

        Using spm As New StoredProcedureManager("PT_DBアカウント申請履歴_SELECT")
            spm.AddPrmIn("@mid", Data.SqlDbType.VarChar, 100, mid)
            spm.AddPrmIn("@mkey", Data.SqlDbType.VarChar, 32, mkey)
            spm.Fill()

            dt = spm.ds.Tables(0)
        End Using

        Return dt

    End Function
#End Region

    Private Function UpdateAccountStatus(mid As String, email As String) As String

        Dim timeStamp As String = ""

        Using spm As New StoredProcedureManager("PT_DBアカウント申請履歴_UPDATE")
            spm.AddPrmIn("@mid", Data.SqlDbType.VarChar, 100, mid)
            spm.AddPrmIn("@email", Data.SqlDbType.VarChar, 100, email)
            spm.AddPrmOut("@out_timeStamp", Data.SqlDbType.VarChar, 100)
            spm.Exec()

            timeStamp = spm.GetValue("@out_timeStamp")

        End Using

        Return timeStamp

    End Function

    Private Sub SetHdfPassNgList()
        Dim dt As DataTable

        Using spm As New StoredProcedureManager("共通_変数_DDL")
            spm.AddPrmIn("@変数", Data.SqlDbType.VarChar, "PASSWORD_NG")
            spm.Fill()
            dt = spm.ds.Tables(0)
        End Using

        ' カラム[内容]の値をカンマ区切り文字列に変換
        Dim valueList As New List(Of String)

        For Each row As DataRow In dt.Rows
            If Not IsDBNull(row("内容")) Then
                valueList.Add(row("内容").ToString())
            End If
        Next

        ' カンマ区切り文字列をHiddenFieldに設定
        Dim commaSeparatedValues As String = String.Join(",", valueList)
        hdfPassNgList.Value = commaSeparatedValues
    End Sub


End Class