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

Partial Class teacher_DocList
    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(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If IsPostBack = False Then
            gv_科目一覧.DataSource = GetData()
            gv_科目一覧.DataBind()

            'ページの位置を復元
            If Not Session(S_TeacherProf_PAGE_INDEX) Is Nothing Then
                gv_科目一覧.SetPageIndex(Session(S_TeacherProf_PAGE_INDEX))
            End If
        End If

    End Sub

#End Region

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

    Protected Sub gv_科目一覧_RowCommand(sender As Object, e As GridViewCommandEventArgs) Handles gv_科目一覧.RowCommand
        If e.CommandName = "doc" Then

            Dim folderPath As String = Com_Get_変数("PT_IRAI_DIRECTORY")
            Dim fileName As String = "【講師依頼文】" & Convert.ToString(Session(S_COM_UserCD)) & "_" & Convert.ToString(Session(S_COM_User_Name)) & "講師_" & e.CommandArgument.ToString() & ".pdf"
            Dim filePath = folderPath & fileName
            'URLの場合
            If filePath.StartsWith("http://") OrElse filePath.StartsWith("https://") Then
                filePath = filePath.Replace("\", "/")
                DownloadFromUrl(filePath)
            Else
                'ローカルファイルパスの場合
                DownloadLocalFile(filePath)
            End If
        End If
        If e.CommandName = "prof" Then
            'IDをセッションに保存
            Session(S_TeacherProf_Selected_ID) = e.CommandArgument.ToString() 'TMP講師貼付.CNT

            ''プロフ編集画面へ
            Response.Redirect(Com_Get_Content("menu_ks_002"))
        End If
        If e.CommandName = "request" Then
            'IDをセッションに保存
            Session(S_TeacherProf_Selected_ID) = e.CommandArgument.ToString()

            '事務連絡票入力画面へ
            Response.Redirect(Com_Get_Content("menu_ks_003"))
        End If
    End Sub

    Protected Sub gv_科目一覧_PageIndexChanging(sender As Object, e As GridViewPageEventArgs) Handles gv_科目一覧.PageIndexChanging
        gv_科目一覧.PageIndex = e.NewPageIndex

        'ページの位置を保持
        Session(S_TeacherProf_PAGE_INDEX) = gv_科目一覧.PageIndex.ToString

        gv_科目一覧.DataSource = GetData()
        gv_科目一覧.DataBind()

    End Sub

    Protected Sub gv_科目一覧_Sorting(sender As Object, e As GridViewSortEventArgs) Handles gv_科目一覧.Sorting
        If Session(S_TeacherProf_SORT_COLUMN) Is Nothing Then
            Session(S_TeacherProf_SORT_COLUMN) = e.SortExpression

            e.SortDirection = SortDirection.Ascending
            Session(S_TeacherProf_SORT_DIR) = "ASC"

        Else
            If e.SortExpression = Session(S_TeacherProf_SORT_COLUMN) Then
                Select Case Session(S_TeacherProf_SORT_DIR)
                    Case "ASC"
                        e.SortDirection = SortDirection.Descending
                        Session(S_TeacherProf_SORT_DIR) = "DESC"

                    Case "DESC"
                        Session(S_TeacherProf_SORT_DIR) = "Default"

                        Session(S_TeacherProf_SORT_COLUMN) = "既定SORT順"
                        Session(S_TeacherProf_SORT_DIR) = "ASC"

                    Case "Default"
                        e.SortDirection = SortDirection.Ascending
                        Session(S_TeacherProf_SORT_DIR) = "ASC"

                End Select
            Else
                Session(S_TeacherProf_SORT_COLUMN) = e.SortExpression

                e.SortDirection = SortDirection.Ascending
                Session(S_TeacherProf_SORT_DIR) = "ASC"

            End If
        End If

        gv_科目一覧.DataSource = GetData()
        gv_科目一覧.DataBind()

    End Sub

    Protected Sub gv_科目一覧_RowCreated(sender As Object, e As GridViewRowEventArgs) Handles gv_科目一覧.RowCreated
        If e.Row.RowType = DataControlRowType.Header Then
            Dim strDir As String = ""
            If Not Session(S_TeacherProf_SORT_DIR) Is Nothing Then
                If Session(S_TeacherProf_SORT_DIR) = "Default" Then strDir = ""
                If Session(S_TeacherProf_SORT_DIR) = "ASC" Then strDir = " ▲"
                If Session(S_TeacherProf_SORT_DIR) = "DESC" Then strDir = " ▼"
            End If

            If Not Session(S_TeacherProf_SORT_COLUMN) Is Nothing Then
                If Session(S_TeacherProf_SORT_COLUMN) = "研修期間開始" Then
                    e.Row.Cells(0).Controls.Add(New LiteralControl(strDir))
                ElseIf Session(S_TeacherProf_SORT_COLUMN) = "研修期間終了" Then
                    e.Row.Cells(1).Controls.Add(New LiteralControl(strDir))
                ElseIf Session(S_TeacherProf_SORT_COLUMN) = "科目名" Then
                    e.Row.Cells(2).Controls.Add(New LiteralControl(strDir))
                ElseIf Session(S_TeacherProf_SORT_COLUMN) = "宛先名前表示" Then
                    e.Row.Cells(3).Controls.Add(New LiteralControl(strDir))
                ElseIf Session(S_TeacherProf_SORT_COLUMN) = "プロフ提出期限" Then
                    e.Row.Cells(4).Controls.Add(New LiteralControl(strDir))
                ElseIf Session(S_TeacherProf_SORT_COLUMN) = "プロフ提出日時" Then
                    e.Row.Cells(6).Controls.Add(New LiteralControl(strDir))
                ElseIf Session(S_TeacherProf_SORT_COLUMN) = "事務連絡票提出日時" Then
                    e.Row.Cells(7).Controls.Add(New LiteralControl(strDir))
                ElseIf Session(S_TeacherProf_SORT_COLUMN) = "事務連絡票提出期限" Then
                    e.Row.Cells(9).Controls.Add(New LiteralControl(strDir))
                ElseIf Session(S_TeacherProf_SORT_COLUMN) = "レジュメ提出期限" Then
                    e.Row.Cells(10).Controls.Add(New LiteralControl(strDir))
                End If
            End If

        End If
    End Sub

#End Region

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

    Function GetData() As DataTable
        Using spm As New StoredProcedureManager("連絡票_研修一覧_SELECT")
            spm.AddPrmIn("@USERCD", Data.SqlDbType.VarChar, 20, Session(S_COM_UserCD))
            spm.Fill()

            Dim dt As DataTable = spm.ds.Tables(0)

            If Not Session(S_TeacherProf_SORT_COLUMN) Is Nothing And Not Session(S_TeacherProf_SORT_DIR) Is Nothing Then
                dt.DefaultView.Sort = String.Format("{0} {1}", Session(S_TeacherProf_SORT_COLUMN).ToString(), Session(S_TeacherProf_SORT_DIR).ToString())
            End If

            Return dt.DefaultView.ToTable

        End Using
    End Function
    Private Sub DownloadLocalFile(filePath As String)
        Dim fileName As String = Path.GetFileName(filePath)
        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)
        Try
            ' ファイルをダウンロード
            Dim fileName As String = Path.GetFileName(url)
            ' レスポンスヘッダーを設定
            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('認証に失敗しました。ユーザー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

    Private Function UrlExists(url As String) As Boolean
        Try
            Dim request As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
            request.Method = "HEAD"
            request.Timeout = 5000 ' 5秒のタイムアウト

            Dim username As String = DBServerAuthUserId
            Dim password As String = DBServerAuthUserPass
            Dim credentials As String = Convert.ToBase64String(Encoding.ASCII.GetBytes(username & ":" & password))
            request.Headers("Authorization") = "Basic " & credentials

            Using response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
                Return (response.StatusCode = HttpStatusCode.OK)
            End Using

        Catch ex As WebException
            '404 Not Found や他のエラーの場合
            Dim errorResponse As HttpWebResponse = TryCast(ex.Response, HttpWebResponse)
            If errorResponse IsNot Nothing AndAlso errorResponse.StatusCode = HttpStatusCode.Unauthorized Then

            End If
            Return False
        Catch ex As Exception
            Return False
        End Try
    End Function
#End Region





End Class
