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

Partial Class faculty_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 Session(S_QA_Detail_RedirectFrom) IsNot 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 Session(S_QA_Detail_RedirectFrom) IsNot 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 portalKbn = Session(S_COM_PortalKbn)
                Dim btn_返信 As Button = CType(frm_問合せ.FindControl("btn_返信"), Button)
                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_ToCD As Label = CType(frm_問合せ.FindControl("lbl_ToCD"), Label)
                Dim lbl_ToCDs As Label = CType(frm_問合せ.FindControl("lbl_ToCDs"), Label)
                Dim lbl_教職員ID01 As Label = CType(frm_問合せ.FindControl("lbl_教職員ID01"), Label)
                Dim lbl_教職員ID02 As Label = CType(frm_問合せ.FindControl("lbl_教職員ID02"), Label)
                Dim pnlPopup As Panel = CType(frm_問合せ.FindControl("pnlPopup"), Panel)
                Dim uc_ReplyFormStaff As uc_ReplyForm = CType(frm_問合せ.FindControl("uc_ReplyFormStaff"), uc_ReplyForm)

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

                '自分の返信履歴の場合は返信ボタンを非表示
                If lbl_登録者CD.Text = Session(S_COM_UserCD) Then
                    btn_返信.Visible = False
                    pnlPopup.Visible = False
                ElseIf lbl_登録者区分.Text = "学生" Or lbl_問合せ先区分.Text = "学生" 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

                '事務局から回答する場合
                'Fromは自分
                uc_ReplyFormStaff.FromKubun = portalKbn
                uc_ReplyFormStaff.FromCD = Session(S_COM_UserCD)
                uc_ReplyFormStaff.FromCDVisible = IIf(portalKbn = "学生", True, False)
                uc_ReplyFormStaff.FromName = Session(S_COM_User_Name)
                'Toは問合せ者へ
                uc_ReplyFormStaff.ToKubun = lbl_登録者区分.Text
                uc_ReplyFormStaff.ToCD = lbl_登録者CD.Text
                uc_ReplyFormStaff.ToName = lbl_登録者名.Text
                uc_ReplyFormStaff.ToCDVisible = IIf(lbl_登録者区分.Text = "学生", True, False)
                uc_ReplyFormStaff.ToCDs = lbl_ToCDs.Text
                '問合せID
                uc_ReplyFormStaff.ContactID = CType(frm_問合せ.FindControl("lbl_問合せID"), Label).Text

            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 pnlPopupStaff As Panel = CType(e.Item.FindControl("pnlPopupStaff"), Panel)
            Dim lbl_FromCD As Label = CType(e.Item.FindControl("lbl_FromCD"), Label)
            Dim lbl_問合せ先区分 As Label = CType(e.Item.FindControl("lbl_問合せ先区分"), Label)
            Dim lbl_登録者区分 As Label = CType(e.Item.FindControl("lbl_登録者区分"), Label)

            '自分の返信履歴の場合は返信ボタンを非表示
            If lbl_FromCD.Text = Session(S_COM_UserCD) Then
                btn_返信.Visible = False
                pnlPopupStaff.Visible = False
            ElseIf lbl_登録者区分.Text = "学生" Or lbl_問合せ先区分.Text = "学生" Then '学生からの問い合わせ、学生宛の問い合わせには返信不可
                btn_返信.Visible = False
                pnlPopupStaff.Visible = False
            Else
                btn_返信.Visible = True
                pnlPopupStaff.Visible = True
            End If

            '返信ボタンクリック時のユーザコントロールを設定
            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_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 uc_ReplyForm As uc_ReplyForm = CType(e.Item.FindControl("uc_ReplyForm"), uc_ReplyForm)

            Dim modalPopupExtender As AjaxControlToolkit.ModalPopupExtender = CType(e.Item.FindControl("ModalPopup2"), AjaxControlToolkit.ModalPopupExtender)
            Dim btnCancel As Button = CType(e.Item.FindControl("btn_Cancel"), Button)
            'uc_ReplyForm.SetUniqueIDs(e.Item.DataItemIndex)


            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.ToName = lbl_From名前.Text

            '学生区分の場合のみ、CD(学籍番号)を表示
            uc_ReplyForm.FromCDVisible = IIf(lbl_To区分.Text = "学生", True, False)
            uc_ReplyForm.ToCDVisible = IIf(lbl_From区分.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
            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

