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

Partial Class uc_infoCard
    Inherits System.Web.UI.UserControl

    Private DBServerAuthUserId As String = ConfigurationManager.AppSettings("WebDavAuthUserId").ToString()
    Private DBServerAuthUserPass As String = ConfigurationManager.AppSettings("WebDavAuthUserPass").ToString()

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

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Session(S_Info_Selected_No) Is Nothing Then
            Session(S_Info_Selected_No) = 0
        End If

        frm_info.DataSource = GetData()
        frm_info.DataBind()

        gv_添付.DataSource = GetData_添付()
        gv_添付.DataBind()
    End Sub

#End Region

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

    '2020/08/26 ADD START #5608 /Liu
    Protected Sub frm_info_DataBound(sender As Object, e As EventArgs) Handles frm_info.DataBound
        If frm_info.DataItemCount > 0 Then
            Dim lbl_掲示詳細 As Label = CType(frm_info.FindControl("lbl_掲示詳細"), Label)
            lbl_掲示詳細.Text = AppCommon.CnvHyperLink(lbl_掲示詳細.Text)
        End If
    End Sub
    '2020/08/26 ADD END #5608 /Liu

    Protected Sub gv_添付_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles gv_添付.SelectedIndexChanged
        Dim Index As Integer
        Dim fileName As String
        Dim tFileName As String

        Index = gv_添付.SelectedIndex

        fileName = CType(gv_添付.Rows.Item(Index).FindControl("lb_FILE_NAME"), Label).Text & "." &
                        CType(gv_添付.Rows.Item(Index).FindControl("lb_拡張子"), Label).Text
        tFileName = CType(gv_添付.Rows.Item(Index).FindControl("lbtn_添付名"), LinkButton).Text

        Dim strFile As String
        strFile = Info_FileFolder_Path() & fileName.Replace(vbNullChar, "") '拡張子文字の右にNULL文字が入っているため空文字に変換

        If strFile <> "" Then

            DownloadFile(strFile, tFileName)

            '2021/02/19 DEL START /Liu >>>>
            ''--2018.01.09 MOD START /Liu
            ''--スマホでダウンロードすると直接ページ遷移になり、ポータルサイトの戻る機能が無効のため、再度ログインしないといけません。
            ''--解消するため別ウインドーでダウンロードするように変更
            ''Response.ContentType = "application/octet-stream"
            ''Response.HeaderEncoding = System.Text.Encoding.GetEncoding("SHIFT-JIS")     '2014.2.18 IE10～でファイル名が表示できないバグを回避/牧
            ''Response.AddHeader("Content-Disposition", "attachment; filename=" + tFileName)
            ''Response.WriteFile(strFile)
            ''Response.Flush()
            ''Response.End()

            'Dim scheme = System.Web.HttpContext.Current.Request.Url.Scheme
            'Dim authority = HttpContext.Current.Request.Url.Authority
            'Dim path = HttpRuntime.AppDomainAppVirtualPath

            ''2019.02.26 MOD START ファイル名を暗号化する /Liu
            ''Dim strLink As String = String.Format("{0}://{1}{2}", scheme, authority, path) & "/information/uc/infoDownload.aspx" & _
            ''                        "?tFileName=" & System.Web.HttpUtility.UrlEncode(tFileName) & _
            ''                        "&strFile=" & System.Web.HttpUtility.UrlEncode(FileName.Replace(vbNullChar, ""))

            'Dim strLink As String = String.Format("{0}://{1}{2}", scheme, authority, path) & "/information/uc/infoDownload.aspx" &
            '                        "?tFileName=" & HttpUtility.UrlEncode(CommonEncryption.EncryptString(tFileName)) &
            '                        "&strFile=" & HttpUtility.UrlEncode(CommonEncryption.EncryptString(FileName.Replace(vbNullChar, "")))
            ''2019.02.26 MOD END ファイル名を暗号化する /Liu

            'Dim strScript As String = "<script language='javascript'>window.open('" & strLink & "','_blank');</script>"

            'ScriptManager.RegisterStartupScript(Me.Page, Me.GetType(), Guid.NewGuid().GetHashCode().ToString, strScript, False)
            ''2018.01.09 MOD END /Liu
            '<<<< 2021/02/19 DEL END /Liu

            '2021/02/19 ADD START chromeのダウンロード不可現象を解消するため、直接ダウンロードする方法に戻す /Liu
            'iphoneの新しいiosでダウンロード仕様変更があり、ページ遷移にならないようになった




            'Try
            '    Response.ContentType = "application/octet-stream"
            '    Response.HeaderEncoding = System.Text.Encoding.GetEncoding("SHIFT-JIS")
            '    Response.AddHeader("Content-Disposition", "attachment; filename=" + tFileName)
            '    Response.WriteFile(strFile)
            '    Response.Flush()
            '    Response.End()
            'Catch ex As Exception
            '    ' JavaScriptのアラートを表示
            '    Page.ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('ファイルのダウンロードに失敗しました。');", True)
            'End Try

            '2021/02/19 ADD END /Liu
        End If
    End Sub

#End Region

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

    Private Function GetData() As DataSet
        Using spm As New StoredProcedureManager("掲示_掲示個別_SELECT")
            spm.AddPrmIn("@掲示NO", Data.SqlDbType.Int, Session(S_Info_Selected_No))
            spm.Fill()

            Return spm.ds
        End Using
    End Function

    Private Function GetData_添付() As DataSet
        Using spm As New StoredProcedureManager("掲示_掲示個別_添付_SELECT")
            spm.AddPrmIn("@掲示NO", Data.SqlDbType.Int, Session(S_Info_Selected_No))
            spm.Fill()

            Return spm.ds
        End Using
    End Function

    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.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('認証に失敗しました。ユーザーIDとパスワードを確認してください。');</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
