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

Partial Class uc_ReplyForm
    Inherits System.Web.UI.UserControl

    Protected MaxFileSize As Integer 'ファイルサイズ上限
    Protected MaxFileSizeInMB As Integer
#Region "********************** プロパティ **********************"

    Public Property FromKubun() As String
        Get
            Return lbl_From区分.Text
        End Get
        Set(ByVal value As String)
            lbl_From区分.Text = value
        End Set
    End Property

    Public Property FromCD() As String
        Get
            Return lbl_FromCD.Text
        End Get
        Set(ByVal value As String)
            lbl_FromCD.Text = value
        End Set
    End Property

    Public Property FromName() As String
        Get
            Return lbl_From氏名.Text
        End Get
        Set(ByVal value As String)
            lbl_From氏名.Text = value
        End Set
    End Property

    Public Property ToKubun() As String
        Get
            Return lbl_To区分.Text
        End Get
        Set(ByVal value As String)
            lbl_To区分.Text = value
        End Set
    End Property

    Public Property ToCD() As String
        Get
            Return lbl_ToCD.Text
        End Get
        Set(ByVal value As String)
            lbl_ToCD.Text = value
        End Set
    End Property
    Public Property ToCDs() As String
        Get
            Return lbl_ToCDs.Text
        End Get
        Set(ByVal value As String)
            lbl_ToCDs.Text = value
        End Set
    End Property

    Public Property ToName() As String
        Get
            Return lbl_To氏名.Text
        End Get
        Set(ByVal value As String)
            lbl_To氏名.Text = value
        End Set
    End Property

    Public Property CcCD() As String
        Get
            Return lbl_CcCD.Text
        End Get
        Set(ByVal value As String)
            lbl_CcCD.Text = value
        End Set
    End Property

    Public Property ContactID() As String
        Get
            Return lbl_問合せID.Text
        End Get
        Set(ByVal value As String)
            lbl_問合せID.Text = value
        End Set
    End Property

    Public Property FromCDVisible() As Boolean
        Get
            Return lbl_FromCD.Visible
        End Get
        Set(ByVal bolVisible As Boolean)
            lbl_FromCD.Visible = bolVisible
        End Set
    End Property

    Public Property ToCDVisible() As Boolean
        Get
            Return lbl_ToCD.Visible
        End Get
        Set(ByVal bolVisible As Boolean)
            lbl_ToCD.Visible = bolVisible
        End Set
    End Property
#End Region

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

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

        If Not fu_問合せ資料.HasFile Then
            btnFileDelete.CssClass = "noDisplay"
        End If

        If Not IsPostBack Then
            Set禁止文字リスト()
        End If
    End Sub

#End Region

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

    Protected Sub btn_送信_Click(sender As Object, e As EventArgs) Handles btn_送信.Click

        Dim str問合せID As String = lbl_問合せID.Text
        Dim str問合せ件名 As String = ""
        Dim str問合せ登録者区分 As String = ""  '2019/02/06 ADD /Liu
        Dim strFrom区分 As String = lbl_From区分.Text
        Dim strFromCD As String = lbl_FromCD.Text
        Dim strFromName As String = lbl_From氏名.Text
        Dim strTo区分 As String = lbl_To区分.Text
        Dim strToCD As String = lbl_ToCD.Text
        Dim strToCDs As String = lbl_ToCDs.Text
        Dim strToName As String = lbl_To氏名.Text
        Dim str返信内容 As String = Me.txt_返信内容.Text
        Dim fileId As String = ""
        Dim userInfo As LoginUser = Session(S_COM_LoginUser)
        Dim 自治体職員ID As String = lbl_CcCD.Text

        '問合せIDから詳細取得
        Dim dt問合せ As DataTable = AppQA.Get問合せ詳細(str問合せID)
        If dt問合せ IsNot Nothing Then
            If dt問合せ.Rows.Count = 1 Then
                str問合せ件名 = dt問合せ.Rows(0).Item("件名").ToString
                str問合せ登録者区分 = dt問合せ.Rows(0).Item("登録者区分").ToString  '2019/02/06 ADD /Liu
            End If
        End If

        lbl_errMes.Text = ""
        lbl_errMes.Text = 必須入力チェック()
        '問合せID、送信対象、内容チェック
        If lbl_errMes.Text IsNot "" Then
            lbl_errMes.Visible = True
            Exit Sub
        End If

        '添付ファイルチェック、アップロード
        Try
            If fu_問合せ資料.HasFile Then
                TempUploadFile(fu_問合せ資料)

                fileId = UploadFileAndGetFileId()
            End If

        Catch ex As Exception
            Exit Sub
        End Try

        'DB問合せSUB登録
        Dim newRepId = 0
        newRepId = AppQA.問合せSUB_INSERT(str問合せID,
                               strFrom区分,
                               strFromCD,
                               strTo区分,
                               strToCD,
                               str返信内容,
                               fileId)

        Dim mailSucFlg = False

        Dim str掲示種別CD As String = AppInfo.GetInfoKindCd("問い合わせ")

        If newRepId > 0 Then
            Select Case strTo区分
                Case "職員"
                    '職員への掲示を登録
                    AppInfo.掲示登録(str掲示種別CD,
                                 "Re:お問合せ" & IIf(str問合せ件名.Length > 0, "(" & str問合せ件名 & ")", ""),
                                 Nothing,
                                 IIf(strFrom区分 = "職員", "事務局", "(" & strFrom区分 & ")" & strFromName),
                                 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                 Nothing,
                                 "重要",
                                 strFromCD,
                                 "教職員所属/職員",
                                 "教職員所属",
                                 "/faculty/QADetail.aspx",
                                 "menu_kj_qa02",
                                 str問合せID
                                 )

                    '問合せ閲覧通知メールの送信
                    '学生からの問合せを自治体窓口に共有
                    If strFrom区分 = "学生" Then
                        mailSucFlg = AppMail.SendQAViewMail(loginUserInfo:=userInfo, qaId:=str問合せID, toUserCd:=自治体職員ID)
                    End If

                Case "教員"
                    '教員への掲示、メール通知を登録
                    Dim str掲示詳細 As String
                    str掲示詳細 = str返信内容

                    AppInfo.掲示登録(str掲示種別CD,
                                 "Re:お問合せ" & IIf(str問合せ件名.Length > 0, "(" & str問合せ件名 & ")", ""),
                                 str掲示詳細,
                                 IIf(strFrom区分 = "職員", "事務局", "(" & strFrom区分 & ")" & strFromName),
                                 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                 Nothing,
                                 "重要",
                                 strFromCD,
                                 strToCD,
                                 "教職員",
                                 "/teacher/QADetail.aspx",
                                 "menu_kj_qa02",
                                 str問合せID,
                                 Boolean.Parse("true"),
                                 strToCD,
                                 "教員")
                Case "学生"
                    '学生への掲示を登録
                    AppInfo.掲示登録(str掲示種別CD,
                                 "Re:お問合せ" & IIf(str問合せ件名.Length > 0, "(" & str問合せ件名 & ")", ""),
                                 Nothing,
                                 IIf(strFrom区分 = "職員", "事務局", "(" & strFrom区分 & ")" & strFromName),
                                 DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                                 Nothing,
                                 "重要",
                                 strFromCD,
                                 strToCD,
                                 "学生",
                                 "/student/QADetail.aspx",
                                 "menu_kj_qa02",
                                 str問合せID
                                 )

            End Select

            '掲示板メールの宛先は、講座担当者と宛先ユーザ
            '関係ユーザを/区切りで格納
            Dim defaultToCd As String = Com_Get_変数("PT_QA_TO_DEFAULT_USERCD") '講座担当未設定時送信先ユーザ
            If strToCDs <> "" And strToCDs <> defaultToCd Then
                strToCD += "/" + strToCDs
            End If

            Dim str問合せ包括ID = str問合せID & "-" & newRepId.ToString()

            '掲示板通知メールの送信
            mailSucFlg = AppMail.SendQABoardInfoMails(loginUserInfo:=userInfo, qaId:=str問合せ包括ID, subject:=str問合せ件名,
                                                      toUserCds:=strToCD)

            Response.Redirect(Request.RawUrl.ToString)
        End If
    End Sub

    'Protected Sub btn_FileDelete_Click(sender As Object, e As EventArgs) Handles btnFileDelete.Click
    '    '一時保存ファイルを削除
    '    'DeleteTempFile()
    '    fu_問合せ資料.Attributes.Clear()
    '    'トークンのクリア
    '    ViewState("UploadToken") = String.Empty
    'End Sub

    Private Function 必須入力チェック() As String
        Dim strErrorMsg As String = ""
        If lbl_問合せID.Text = "" Then
            strErrorMsg = "問い合わせが見つかりません。"
        End If
        If lbl_ToCD.Text = "" Then
            strErrorMsg = "宛先が見つかりません。"
        End If
        If fu_問合せ資料.PostedFile.ContentLength > ConfigSettings.MaxFileSize Then
            strErrorMsg = "ファイルサイズが大きすぎます。" _
                            & ConfigSettings.MaxFileSizeInMB & "MB以下のファイルを選択してください。"
        End If
        If fu_問合せ資料.HasFile Then
            'ファイル名の禁止文字チェック
            Dim mes As String = ""
            If Not ValidateFileName(fu_問合せ資料.FileName, mes) Then
                strErrorMsg = mes
            End If
        End If
        Return strErrorMsg
    End Function


    Private Sub TempUploadFile(fu As FileUpload)

        If fu.HasFile Then

            Dim fileId As String = Guid.NewGuid().ToString()
            Dim tempPath As String = GetTempFolderPath()
            Dim tempFileName As String = Path.Combine(tempPath, fileId & Path.GetExtension(fu.FileName))
            '一時フォルダに保存
            Try
                fu.SaveAs(tempFileName)

                '確認後アップ時
                Session(S_QA_Uploaded_File_ID) = fileId
                Session(S_QA_Uploaded_File_Path) = tempFileName
            Catch

            End Try
        End If

    End Sub

    Private Function UploadFileAndGetFileId() As String
        Dim tempFilePath As String = Session(S_QA_Uploaded_File_Path).ToString()
        Dim fileId As String = Session(S_QA_Uploaded_File_ID).ToString()
        Dim orgFileName As String = fu_問合せ資料.FileName '元ファイル名

        orgFileName = HttpUtility.UrlDecode(orgFileName, System.Text.Encoding.UTF8) '20250513 ファイル名の文字化け防止


        If String.IsNullOrEmpty(tempFilePath) Or String.IsNullOrEmpty(fileId) Then
            Return String.Empty
        End If

        Dim rootPath As String = GetFileFolderPath()

        Try
            If rootPath.StartsWith("http://") OrElse rootPath.StartsWith("https://") Then
                ' リモートサーバーへのアップロード
                Dim permanentUrl = AppQA.CombineUrlPaths(rootPath, Path.GetFileName(tempFilePath))
                AppQA.UploadFileToRemoteServer(tempFilePath, permanentUrl)

                ' DBに添付ファイル情報を登録
                AppQA.問合せ添付追加(fileId, orgFileName, permanentUrl)
            Else
                ' ローカルファイルの移動
                If Not File.Exists(tempFilePath) Then
                    Throw New FileNotFoundException("一時ファイルが見つかりません。", tempFilePath)
                End If

                rootPath = If(rootPath.Last() = Path.DirectorySeparatorChar, rootPath, rootPath & Path.DirectorySeparatorChar)
                Dim permanentPath = Path.Combine(rootPath, Path.GetFileName(tempFilePath))

                File.Move(tempFilePath, permanentPath)

                ' DBに添付ファイル情報を登録
                AppQA.問合せ添付追加(fileId, orgFileName, permanentPath)
            End If

            ' 一時ファイルの削除
            DeleteTempFile()

            Return fileId
        Catch ex As Exception
            Return String.Empty
        End Try
    End Function


    Private Sub DeleteTempFile()

        Dim tempFilePath As String = Session(S_QA_Uploaded_File_Path).ToString()

        If File.Exists(tempFilePath) Then
            '一時ファイルの削除
            File.Delete(tempFilePath)
            Session.Remove(S_QA_Uploaded_File_ID)
            Session.Remove(S_QA_Uploaded_File_Path)  ' Clean up the session variable
        End If

    End Sub

    Public Sub SetUniqueIDs(index As Integer)
        txt_返信内容.ID = "txt_返信内容_" & index
    End Sub

    Private Sub Set禁止文字リスト()
        Try
            ' 禁止文字を取得
            Dim prohibitedChars As List(Of String) = Get禁止文字ListFromDB()

            ' カンマ区切りに変換
            Dim csvString As String = String.Join(",", prohibitedChars.Select(Function(c) EscapeSpecialChar(c)).ToArray())
            hf_禁止文字リスト.Value = csvString

        Catch ex As Exception
            ' エラー時はデフォルト値
            hf_禁止文字リスト.Value = "&lt;,&gt;,:,&quot;,|,?,*,\,/,&amp;,%"
        End Try
    End Sub

#End Region

End Class
