Imports System.Data
Imports System.IO
Imports AppVariable
Imports AppCommon
Imports AppQA
Imports AppVariable_QA
Imports System.Net

Partial Class student_QADetail
    Inherits System.Web.UI.Page

#Region "************************* 定数 *************************"
    Private DBServerAuthUserId As String = ConfigurationManager.AppSettings("WebDavAuthUserId").ToString()
    Private DBServerAuthUserPass As String = ConfigurationManager.AppSettings("WebDavAuthUserPass").ToString()

#End Region

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


    Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
        If IsPostBack = False Then
            frm_問合せ.DataSource = GetData_問合せ()
            frm_問合せ.DataBind()

            If Not Session(S_QA_Detail_RedirectFrom) Is Nothing Then
                Select Case Session(S_QA_Detail_RedirectFrom)
                    Case "トップページ"
                        btn_履歴.Text = "トップページに戻る"
                    Case "個人へのお知らせ"
                        btn_履歴.Text = "個人へのお知らせに戻る"
                    Case "お問合せ一覧"
                        btn_履歴.Text = "お問合せ一覧に戻る"
                End Select
            End If
        End If

       
    End Sub

#End Region

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

    Protected Sub sql_問合せ返信_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles sql_問合せ返信.Init
        sql_問合せ返信_select()
    End Sub

    Protected Sub btn_履歴_Click(sender As Object, e As EventArgs) Handles btn_履歴.Click
        If Not Session(S_QA_Detail_RedirectFrom) Is Nothing Then
            Select Case Session(S_QA_Detail_RedirectFrom)
                Case "トップページ"
                    'トップページに戻る
                    Response.Redirect(Com_Get_Content("menu_cm_001"))
                Case "個人へのお知らせ"
                    '個人へのお知らせに戻る
                    Response.Redirect(Com_Get_Content("menu_kj_001"))
                Case "お問合せ一覧"
                    '一覧画面に戻る
                    Response.Redirect(Com_Get_Content("menu_kj_qa01"))
            End Select
        Else
            '一覧画面に戻る
            Response.Redirect(Com_Get_Content("menu_kj_qa01"))
        End If
    End Sub

    Protected Sub frm_問合せ_DataBound(sender As Object, e As EventArgs) Handles frm_問合せ.DataBound
        If frm_問合せ.CurrentMode = FormViewMode.ReadOnly Then
            If frm_問合せ.DataItemCount > 0 Then

                Dim lbl_問い合わせ内容 As Label = CType(frm_問合せ.FindControl("lbl_問い合わせ内容"), Label)
                lbl_問い合わせ内容.Text = lbl_問い合わせ内容.Text.Replace(vbCrLf, "<br />")

                Dim btn_返信 As Button = CType(frm_問合せ.FindControl("btn_返信"), Button)
                Dim pnlPopup As Panel = CType(frm_問合せ.FindControl("pnlPopup"), Panel)
                Dim lbl_問合せID As Label = CType(frm_問合せ.FindControl("lbl_問合せID"), Label)
                Dim lbl_登録者区分 As Label = CType(frm_問合せ.FindControl("lbl_登録者区分"), Label)
                Dim lbl_登録者CD As Label = CType(frm_問合せ.FindControl("lbl_登録者CD"), Label)
                Dim lbl_登録者名 As Label = CType(frm_問合せ.FindControl("lbl_登録者名"), Label)
                Dim lbl_問合せ先区分 As Label = CType(frm_問合せ.FindControl("lbl_問合せ先区分"), Label)
                Dim lbl_問合せ先CD As Label = CType(frm_問合せ.FindControl("lbl_問合せ先CD"), Label)
                Dim lbl_教職員ID01 As Label = CType(frm_問合せ.FindControl("lbl_教職員ID01"), Label)
                Dim lbl_教職員ID02 As Label = CType(frm_問合せ.FindControl("lbl_教職員ID02"), Label)
                Dim uc_ReplyForm As uc_ReplyForm = CType(frm_問合せ.FindControl("uc_ReplyFormStudent"), uc_ReplyForm)

                '自分の返信履歴の場合は返信ボタンを非表示
                If lbl_登録者CD.Text = Session(S_COM_UserCD) Then
                    btn_返信.Visible = False
                    pnlPopup.Visible = False
                Else
                    btn_返信.Visible = True
                    pnlPopup.Visible = True
                End If

                '返信ボタンクリック時のユーザコントロールを設定                
                '問合せID
                uc_ReplyForm.ContactID = lbl_問合せID.Text
                'Fromは自分
                uc_ReplyForm.FromKubun = Session(S_COM_PortalKbn)
                uc_ReplyForm.FromCD = Session(S_COM_UserCD)
                uc_ReplyForm.FromName = Session(S_COM_User_Name)
                'Toはクリックした返信アイテムのFrom
                uc_ReplyForm.ToKubun = lbl_登録者区分.Text
                uc_ReplyForm.ToCD = lbl_登録者CD.Text
                uc_ReplyForm.ToCDVisible = False
                uc_ReplyForm.ToName = lbl_登録者名.Text

                Dim str問合せ先CD = ""
                Dim To教職員ID As String = lbl_教職員ID01.Text

                If To教職員ID IsNot "" Then
                    str問合せ先CD += To教職員ID
                    If Not lbl_教職員ID02.Text = "" Then
                        To教職員ID = lbl_教職員ID02.Text
                        str問合せ先CD += "/" + To教職員ID '複数送信先がある場合は、スラッシュ区切りでDBに登録
                    End If
                End If

                If str問合せ先CD IsNot "" Then
                    uc_ReplyForm.ToCDs = str問合せ先CD
                End If

                '送信元が学生か問い合わせ先が学生の場合は自治体職員に通知
                If lbl_登録者区分.Text = "学生" Then
                    Dim dt As DataTable = AppQA.Get申込詳細(lbl_登録者CD.Text)
                    uc_ReplyForm.CcCD = dt.Rows(0)("自治体職員ID").ToString()
                End If
                If lbl_問合せ先区分.Text = "学生" Then
                    Dim dt As DataTable = AppQA.Get申込詳細(lbl_問合せ先CD.Text)
                    uc_ReplyForm.CcCD = dt.Rows(0)("自治体職員ID").ToString()
                End If

            End If
        End If
    End Sub

    Protected Sub frm_問合せ_ItemCommand(sender As Object, e As FormViewCommandEventArgs) Handles frm_問合せ.ItemCommand

        Dim lbl_添付ファイル As Label = CType(frm_問合せ.FindControl("lbl_添付ファイル"), Label)

        If e.CommandName = "Download" Then
            Dim filePath As String = e.CommandArgument.ToString()
            '基幹のWebDavの絶対パス
            Dim coreWebDavPath As String = Com_Get_変数("COMMON_DIRECTORY")

            '基幹の絶対パスの場合、直接参照できないので、URLパスに変換
            If filePath.StartsWith(coreWebDavPath) Then

                Dim urlWebDavPath As String = Com_Get_変数("PT_COMMON_DIRECTORY")
                filePath = filePath.Replace(coreWebDavPath, urlWebDavPath)
            End If

            Dim fileName As String = lbl_添付ファイル.Text
            DownloadFile(filePath, fileName)
        End If
    End Sub

    Protected Sub lsv_返信_ItemCommand(sender As Object, e As ListViewCommandEventArgs) Handles lsv_返信.ItemCommand

        Dim lbl_添付ファイル As Label = CType(e.Item.FindControl("lbl_添付ファイル"), Label)

        If e.CommandName = "Download" Then
            Dim filePath As String = e.CommandArgument.ToString()
            '基幹のWebDavの絶対パス
            Dim coreWebDavPath As String = Com_Get_変数("COMMON_DIRECTORY")

            '基幹の絶対パスの場合、直接参照できないので、URLパスに変換
            If filePath.StartsWith(coreWebDavPath) Then

                Dim urlWebDavPath As String = Com_Get_変数("PT_COMMON_DIRECTORY")
                filePath = filePath.Replace(coreWebDavPath, urlWebDavPath)
            End If

            Dim fileName As String = lbl_添付ファイル.Text
            DownloadFile(filePath, fileName)
        End If

    End Sub

    Protected Sub lsv_返信_ItemDataBound(sender As Object, e As ListViewItemEventArgs) Handles lsv_返信.ItemDataBound
        If e.Item.ItemType = ListViewItemType.DataItem Then
            Dim lbl_返信内容 As Label = CType(e.Item.FindControl("lbl_返信内容"), Label)
            '返信内容改行
            lbl_返信内容.Text = lbl_返信内容.Text.Replace(vbCrLf, "<br />")


            Dim btn_返信 As Button = CType(e.Item.FindControl("btn_返信"), Button)
            Dim pnlPopup As Panel = CType(e.Item.FindControl("pnlPopup"), Panel)

            '返信ボタンクリック時のユーザコントロールを設定
            Dim lbl_問合せID As Label = CType(e.Item.FindControl("lbl_問合せID"), Label)
            Dim lbl_From区分 As Label = CType(e.Item.FindControl("lbl_From区分"), Label)
            Dim lbl_FromCD As Label = CType(e.Item.FindControl("lbl_FromCD"), Label)
            Dim lbl_From名前 As Label = CType(e.Item.FindControl("lbl_From名前"), Label)
            Dim lbl_To区分 As Label = CType(e.Item.FindControl("lbl_To区分"), Label)
            Dim lbl_ToCD As Label = CType(e.Item.FindControl("lbl_ToCD"), Label)
            Dim lbl_ToCDs As Label = CType(e.Item.FindControl("lbl_ToCDs"), Label)
            Dim lbl_教職員ID01 As Label = CType(e.Item.FindControl("lbl_教職員ID01"), Label)
            Dim lbl_教職員ID02 As Label = CType(e.Item.FindControl("lbl_教職員ID02"), Label)
            Dim lbl_From自治体職員ID As Label = CType(e.Item.FindControl("lbl_From自治体職員ID"), Label)
            Dim lbl_To自治体職員ID As Label = CType(e.Item.FindControl("lbl_To自治体職員ID"), Label)
            Dim uc_ReplyForm As uc_ReplyForm = CType(e.Item.FindControl("uc_ReplyFormStudent"), uc_ReplyForm)

            '自分の返信履歴の場合は返信ボタンを非表示
            If lbl_FromCD.Text = Session(S_COM_UserCD) Then
                btn_返信.Visible = False
                pnlPopup.Visible = False
            Else
                btn_返信.Visible = True
                pnlPopup.Visible = True
            End If

            Dim str問合せ先CD = ""
            Dim To教職員ID As String = lbl_教職員ID01.Text

            If To教職員ID IsNot "" Then
                str問合せ先CD += To教職員ID
                If Not lbl_教職員ID02.Text = "" Then
                    To教職員ID = lbl_教職員ID02.Text
                    str問合せ先CD += "/" + To教職員ID '複数送信先がある場合は、スラッシュ区切りでDBに登録
                End If
            End If

            If str問合せ先CD IsNot "" Then
                lbl_ToCDs.Text = str問合せ先CD
            End If


            '問合せID
            uc_ReplyForm.ContactID = lbl_問合せID.Text
            'Fromは自分
            uc_ReplyForm.FromKubun = Session(S_COM_PortalKbn)
            uc_ReplyForm.FromCD = Session(S_COM_UserCD)
            uc_ReplyForm.FromName = Session(S_COM_User_Name)
            'Toはクリックした返信アイテムのFrom
            uc_ReplyForm.ToKubun = lbl_From区分.Text
            uc_ReplyForm.ToCD = lbl_FromCD.Text
            uc_ReplyForm.ToCDs = lbl_ToCDs.Text
            uc_ReplyForm.ToCDVisible = False
            uc_ReplyForm.ToName = lbl_From名前.Text
            '宛先が学生のときはToを参照、問い合わせ元が学生のときはFromを参照
            If lbl_From区分.Text = "学生" Then
                uc_ReplyForm.CcCD = lbl_From自治体職員ID.Text
            End If
            If lbl_To区分.Text = "学生" Then
                uc_ReplyForm.CcCD = lbl_To自治体職員ID.Text
            End If
            '学生区分の場合のみ、CD(学籍番号)を表示
            lbl_FromCD.Visible = IIf(lbl_From区分.Text = "学生", True, False)
            lbl_ToCD.Visible = IIf(lbl_To区分.Text = "学生", True, False)

        End If
    End Sub

#End Region

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

    Private Function GetData_問合せ() As DataTable
        Using spm As New StoredProcedureManager("QA_問合せ詳細_SELECT")
            spm.AddPrmIn("@問合せID", Data.SqlDbType.Int, Session(S_QA_Selected_ID))

            spm.Fill("Contact")

            Dim dt As DataTable = spm.ds.Tables("Contact")

            Return dt.DefaultView.ToTable

        End Using
    End Function

    Private Sub sql_問合せ返信_select()
        Dim sds As SqlDataSource = sql_問合せ返信
        WebControlsUtil.DeclareSP(sds, "QA_問合せ返信一覧_SELECT")
        With sds
            .SelectParameters.Add("問合せID", DbType.Int32, Session(S_QA_Selected_ID))
            .SelectParameters.Add("USERCD", DbType.String, Session(S_COM_UserCD))
        End With
    End Sub

    Private Sub DownloadFile(filePath As String, fileName As String)

        ' URLの場合
        If filePath.StartsWith("http://") OrElse filePath.StartsWith("https://") Then
            filePath = filePath.Replace("\", "/")
            DownloadFromUrl(filePath, fileName)
        Else
            'ローカルファイルパスの場合
            DownloadLocalFile(filePath, fileName)
        End If
    End Sub

    Private Sub DownloadLocalFile(filePath As String, fileName As String)
        If File.Exists(filePath) Then
            Response.ContentType = "application/octet-stream"
            Response.AppendHeader("Content-Disposition", String.Format("attachment; filename=""{0}""", fileName))
            Response.TransmitFile(filePath)
            Response.End()
        Else
            Response.Write("<script>alert('指定されたファイルが存在しません。');</script>")
        End If
    End Sub

    Private Sub DownloadFromUrl(url As String, fileName As String)
        Try

            Response.Clear()
            Response.Buffer = False
            Response.ContentType = "application/octet-stream"
            Response.AddHeader("Content-Disposition", "attachment; filename=""" & fileName & """")

            Using client As New WebClient()
                ' 認証情報を設定
                Dim username As String = DBServerAuthUserId
                Dim password As String = DBServerAuthUserPass
                Dim credentials As String = Convert.ToBase64String(Encoding.ASCII.GetBytes(username & ":" & password))
                client.Headers("Authorization") = "Basic " & credentials

                ' ファイルをダウンロード
                Dim fileData As Byte() = client.DownloadData(url)
                Response.AddHeader("Content-Length", fileData.Length.ToString())
                Response.OutputStream.Write(fileData, 0, fileData.Length)

                Response.Flush()
                Response.Close()
            End Using
        Catch ex As WebException
            Dim errorResponse As HttpWebResponse = TryCast(ex.Response, HttpWebResponse)
            If errorResponse IsNot Nothing Then
                Select Case errorResponse.StatusCode
                    Case HttpStatusCode.Unauthorized
                        Response.Write("<script>alert('認証に失敗しました。ユーザー名とパスワードを確認してください。');</script>")
                    Case HttpStatusCode.NotFound
                        Response.Write("<script>alert('指定されたファイルが見つかりません。');</script>")
                    Case Else
                        Response.Write(String.Format("<script>alert('ファイルのダウンロードに失敗しました: {0}');</script>", ex.Message))
                End Select
            Else
                Response.Write(String.Format("<script>alert('ネットワークエラーが発生しました: {0}');</script>", ex.Message))
            End If
        Catch ex As Exception
            ' その他の例外処理
            Response.Write(String.Format("<script>alert('エラーが発生しました: {0}');</script>", ex.Message))
        End Try
    End Sub

#End Region


End Class
