<template>
    <div class="notice-wrap">
        <div class="content-box">
            <div class="title-wrap">
                <div class="flex-start">
                    <img src="../../../../resources/jpg/notic-logo-img.png" alt="공지사항 아이콘" class="title-icon">
                    <h2 class="main-title">공지사항</h2>
                </div>
            </div>
            <div class="content-wrap">
                <table class="insert-table">
                    <tbody>
                        <tr>
                            <th>제목</th>
                            <td><input type="text" name="" id="newsTitle" v-model="post.post_title"></td>
                        </tr>
                        <tr>
                            <th>게시물 상단고정 사용여부</th>
                            <td><input type="checkbox" v-model="post.notice_yn" true-value="Y" false-value="N"><label>사용</label></td>
                        </tr>
                        <tr>
                            <th>내용</th>
                            <td><textarea name="smart" id="smart" style="width:100%"></textarea></td>
                        </tr>
                        <tr>
                            <th>등록된 첨부파일</th>
                            <td colspan="6">
                                <div v-if="fileList.length == 0">
                                    <label>첨부된 파일이 없습니다.</label>
                                </div>
                                <ul v-else v-for="(item, idx) in fileList" :key="idx">
                                    <li class="flex file-list">
                                        <p>{{ item.real_file_nm }}</p>
                                        <button class="red-btn" @click="fileRemove(item, idx)">삭제</button>
                                    </li>
                                </ul>
                            </td>
                        </tr>
                        <tr>
                            <th>추가 첨부파일</th>
                            <td colspan="6">
                                <div class="btn-upload" @click="openFileInput">파일 업로드</div>
                                <input type="file" name="file" id="file" ref="fileInput" style="display: none"
                                    @change="fileUpload()">
                                <ul  v-for="(item, idx) in insertFileList" :key="idx" >
                                    <li v-if="insertFileList.length != 0" class="file-item">{{ item.name }} <button class="aclose-btn"
                                            @click="fileRemove(item, idx)">X</button></li>
                                </ul>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <div class="btn-wrap">
                    <button class="dark-gray-btn" @click="postSelectListPage()">이전</button>
                    <button class="blue-btn" @click="openUpdateModal()">수정</button>
                </div>
            </div>
        </div>
        <div v-show="isUpdateModalOpen" class="modal-wrapper">
            <div class="modal-container admin-alert">
                <div class="modal-content-monthly alert-modal">
                <p>해당 공지사항을 수정하시겠습니까?</p>
            </div>
                <div class="modal-end">
                    <button class="dark-gray-btn  small-btn" @click="closeUpdateModal()">취소</button>
                    <button class="blue-btn  small-btn" @click="postUpdateCheck">확인</button>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import axios from 'axios';
import COMMON_UTIL from '../../../../resources/js/commonUtil.js';
import { useRoute } from 'vue-router';

export default {
    data() {
        return {
            post: {
                post_id: null,
                post_title: null,
                post_content: null,
                notice_yn: null,
                notice_start_dt: null,
                notice_end_dt: null,
                reg_dt: null,
                mdfcn_dt: null,
                link_url: null,
                view_cnt: null,
                file_id: null,
                bbs_id: null,
                rgtr_id: null,
                mdfr_id: null,
                ctgry_nm: null,
                notice_yn: null,
            },
            fileList: [],
            deleteFileList: [],
            insertFileList: [],
            filecount: 0,
            insertCount: 0,
            deleteCount: 0,
            oEditors: [], // oEditors는 스마트에디터용
            route: useRoute(),
            isUpdateModalOpen:false
        };
    },
    methods: {
        openUpdateModal: function () {
            this.isUpdateModalOpen = true;
        },

        closeUpdateModal: function () {
            this.isUpdateModalOpen = false;
        },

        //게시글 및 첨부파일 등록
        postSelectOne: function () {
            const vm = this;
            axios({
                url: '/post/postSelectOne.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: { 'post_id': vm.route.query.post_id, 'file_id': vm.route.query.file_id }
            }).then(function (response) {
                vm.post = response.data.postSelectOne.post;

                if (response.data.selectFileList.length != 0) {
                    vm.fileList = response.data.selectFileList;
                    vm.filecount = response.data.selectFileList.length;
                }

                vm.initEditor(vm.post.post_content);
            }).catch(function (error) {
                console.log("error - ", error)
                alert("게시글 상세보기 조회 오류, 관리자에게 문의하세요.");
            })
        },

        //게시글 및 첨부파일 등록
        postUpdate: function () {
            const vm = this;
            let formData = new FormData();
            
            if (vm.insertFileList.length > 0 || vm.deleteFileList.length > 0) {
                if (vm.insertFileList.length > 0) {
                    for (let i = 0; i < vm.insertFileList.length; i++) {
                        formData.append('file', vm.insertFileList[i]);
                        console.log('file - ', formData.get('file'));
                    }
                }

                if (vm.deleteFileList.length > 0) {
                    formData.append('deleteFile', JSON.stringify(vm.deleteFileList));
                    console.log('deleteFile - ', formData.get('deleteFile'));
                }

                formData.append("post", JSON.stringify(vm.post));

                axios({
                    url: '/post/postFileUpdate.file',
                    method: 'post',
                    headers: {
                        'Content-Type': 'multipart/form-data',
                    },
                    data: formData
                }).then(function (response) {
                    console.log("qnaInsert - response : ", response);
                    let result = response.data;
                    console.log("result===" + result)
                    if (result > 0) {
                        alert("수정을 완료하였습니다.");
                        vm.postSelectListPage()
                    } else {
                        alert("수정 실패, 관리자에게 문의해주세요.");
                    }
                }).catch(function (error) {
                    console.log("qnaInsert - error : ", error);
                    alert("수정 오류, 관리자에게 문의해주세요.");
                });
            } else {

                axios({
                    url: '/post/postFileUpdate.json',
                    method: 'post',
                    headers: {
                        'Content-Type': "application/json; charset=UTF-8",
                    },
                    data: vm.post
                }).then(function (response) {
                    console.log("noticeInsert - response : ", response);
                    let result = response.data;
                    if (result > 0) {
                        alert("수정을 완료하였습니다.");
                        vm.postSelectListPage()
                    } else {
                        alert("수정 실패, 관리자에게 문의해주세요.");
                    }
                }).catch(function (error) {
                    console.log("noticeInsert - error : ", error);
                    alert("수정 오류, 관리자에게 문의해주세요.");
                });
            }
        },

        //등록 유효성 검사
        postUpdateCheck: function () {
            const oEditors = this.oEditors;
            oEditors.getById["smart"].exec("UPDATE_CONTENTS_FIELD", []);
            // 스마트에디터의 iframe에 있는 내용을 textarea로. 
            this.post.post_content = document.getElementById("smart").value;

            if (COMMON_UTIL.isEmpty(this.post.post_title) === false) {
                alert("제목을 입력해주세요.");
                return false;
            }

            if (COMMON_UTIL.isEmpty(this.post.post_content) === false || this.post.post_content === "<p><br></p>") {
                alert("내용을 입력해주세요.");
                return false;
            }

            this.postUpdate();
        },

        // 에디터 만들기 
        initEditor: function (initData) {
            // 스마트 에디터 적용
            const oEditors = this.oEditors;
            nhn.husky.EZCreator.createInIFrame({
                oAppRef: oEditors,
                elPlaceHolder: "smart",
                sSkinURI: "/client/smarteditor2-2.8.2.3/SmartEditor2Skin.html",
                htParams: {
                    bSkipXssFilter: true,
                    bUseVerticalResizer: true,
                    bUseModeChanger: true
                },
                fOnAppLoad: function () {
                    oEditors.getById["smart"].exec("PASTE_HTML", [initData]);
                },
                fCreator: "createSEditor2"
            });
        },
        //파일업로드
        fileUpload: function () {
            
            this.insertFileList[this.insertCount] = this.$refs.fileInput.files[0];
            this.insertCount += 1;
            console.log("insertFile - ", this.insertFileList);
        },

        //파일업로드 중 업로드 파일 삭제
        fileRemove(item, idx) {
            if (item.file_path === undefined) {
                this.insertFileList.splice(idx, 1);
                this.insertCount = this.insertFileList.length;
                console.log("insertfile", this.insertFileList);

            } else {
                this.fileList.splice(idx, 1);
                this.deleteFileList[this.deleteCount] = item
                this.deleteCount += 1
                this.filecount = this.fileList.length;
                console.log("deleteFile - ", this.deleteFileList);
            }

        },

        //게시글 리스트로 이동
        postSelectListPage: function () {
            this.$router.push({ path: '/adm/noticeSelectList.page' });
        },

        // 파일 업로드 커스텀을 위한 함수
        openFileInput: function () {
            this.$refs.fileInput.click(); // 파일 업로드 input 요소를 클릭
        }
    },
    watch: {},
    computed: {},
    components: {},
    mounted() {
        this.postSelectOne();
    }
};
</script>

