<!DOCTYPE html>
<html lang="en" xmlns:th=http://www.thymeleaf.org>
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width,initial-scale=1"/>
    <meta name="theme-color" content="#000000"/>
    <meta name="description" content="포항시 교통정보센터입니다"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <title>포항시 교통정보센터</title>
    <th:block th:include="/include/head.html"></th:block>
    <th:block th:include="/include/daterangepicker.html"></th:block>
    <link rel="stylesheet" th:href="@{/css/notice.css}">
</head>
<body id="body">
<th:block th:include="/include/admin-header.html"></th:block>
<div class="noticeWrap">
    <div class="container view">
        <h2 class="admin-header">팝업 공지</h2>
        <div class="content admin-view">
            <div class="button-box">
                <div class="bl-button" onclick="movePath('/phits/popup-list')">목록</div>
                <div style="display: flex;">
                    <div class="bl-button save-btn" onclick="save()">저장</div>
                </div>
            </div>
            <div class="view-box">
                <div>
                    <input class="title modify" name="b_subject" placeholder="팝업 제목을 입력해주세요.">
                    <textarea class="b_content modify" rows="16" name="b_content" placeholder="링크 주소가 있다면 URL을 입력해주세요. ex) https://www.naver.com"></textarea>
                    <div class="post-box">
                        <div>공지 기간</div>
                        <input type="text" id="post" th:class="modify" name="post">
                    </div>
                    <div class="attach-box admin">
                        <div class="attach modify">
                            <div>첨부파일 없음</div>
                        </div>
                        <input type="file" name="attachFile" id="attach-file">
                        <div class="bl-button attach-btn" onclick="attachFile()">파일첨부</div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<th:block th:include="/include/footer.html"></th:block>
</body>
</html>
<script th:inline="javascript">
    const $title      = $('.title');
    const $content    = $('.b_content');
    const $attach     = $('.attach');
    const $attachFile = $('#attach-file');
    const $post       = $('#post');

    const post = $post.daterangepicker({
        timePicker: false,
        startDate: new Date(),
        endDate: new Date(new Date().setDate(new Date().getDate() + 1)),
        locale: {
            format: 'YYYY-MM-DD',
            separator: " ~ ",
            applyLabel: "확인",
            cancelLabel : "취소",
            daysOfWeek: ["일", "월", "화", "수", "목", "금", "토"],
            monthNames: ["1월", "2월", "3월", "4월", "5월", "6월", "7월", "8월", "9월", "10월", "11월", "12월"],
        },
        disabled : true,
        autoApply: true,
        opens: 'center',
        drops: 'up',
    });

    let isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);

    if (isMobile) {
        $content.attr('rows', 10);
    }

    function attachFile() {
        $attachFile.click();
    }

    $attachFile.on("change", function() {
        const changeFile = $(this)[0].files[0];
        if (changeFile) {
            const fileName = changeFile.name;
            $attach.html('<div><span class="attach-delete" title="첨부파일 제거" onclick="deleteAttach()"></span>'+fileName+'</div>');
        }
    })

    function deleteAttach() {
        $attachFile.val("");
        $attach.html("<div>첨부파일 없음</div>")
    }

    function save() {
        const title   = $title.val();
        const url     = $content.val();
        const file    = $attachFile[0].files[0];
        const postVal = $post.val();

        let postFrom  = "";
        let postTo    = "";

        //첨부파일 기간값 유효성 체크
        if (!isNull(postVal)) {
            const postArray = postVal.split(" ~ "); // separator " ~ " 를 이용해 post_from, post_to 값을 구분
            if (postArray.length === 2) {
                postFrom = postArray[0];
                postTo   = postArray[1];
            }
        }

        const formData = new FormData();

        // 유효성 체크
        if (isNull(title)) {
            $title.focus();
            return alert("팝업 공지 제목을 입력해주세요.");
        }

        if (isNull(postFrom)) {
            $post.focus();
            return alert("팝업 공지 기간 시작일을 입력해주세요.");
        }

        if (isNull(postTo)) {
            $post.focus();
            return alert("팝업 공지 기간 종료일을 입력해주세요.");
        }

        if (!file) {
            return alert("팝업 이미지 파일을 첨부해주세요.")
        }

        formData.append("title", title);
        formData.append("url", url);
        formData.append("postForm", postFrom);
        formData.append("postTo", postTo);
        formData.append("attachFile", file);

        $.ajax({
            url: '/api/popup/writePopup',
            processData : false,
            contentType: false,
            data: formData,
            type: 'POST',
            success: function(jsonData) {
                if (jsonData) {
                    alert(jsonData.message);
                    if (jsonData.success === "S") {
                        window.location.href = "/phits/popup-list";
                    }
                }
            },
            error: function(error) {
                alert(error.responseJSON.message);
            }
        });
    }
</script>