<template>
    <div class="w1400">
        <div class="page">
            <div class="page-logo flex-start">
                <img src="../../../../resources/jpg/data-img-text.png" alt="">
                <h1>자료집</h1>
            </div>
            <div class="data-dtail">
                <table class="insert-table">
                    <tbody>
                        <tr>
                            <td class="title-zone" colspan="2">
                                <p class="flex"><span class="post-title">{{ post.post_title }}</span>
                                    <span class="category-zone"  v-if="post.ctgry_nm === 'policy'">정책자료</span>
                                    <span class="category-zone"  v-else-if="post.ctgry_nm === 'research'">연구자료</span>
                                    <span class="category-zone"  v-else>가이드라인</span></p>
                                <div class="flex-end write-info">
                                   <p><span class="writer">작성자 </span><span>{{ post.rgtr_id }}</span>
                                    <span class="view">조회수 </span><span>{{ post.view_cnt }}</span></p>
                                    </div>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="2" style="border-bottom: 1px solid #007aff;">
                                <div id="viewer" ref="viewer" class="viewer"></div>
                            </td>
                        </tr>
                        <tr>
                            <th style="width: 10%;">첨부파일명</th>
                            <td>
                                <div v-if="fileList.length == 0">
                                    <label>첨부된 파일이 없습니다.</label>
                                </div>
                                <ul v-else v-for="(item, idx) in fileList" :key="idx">
                                    <li @click="downloadFile(item)">{{ item.real_file_nm }}</li>
                                </ul>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <div>
                    <div class="article-list">
                        <ul>
                            <li><span class="next">다음글</span>
                                <span>
                                    <span v-if="nextPost" @click="movePost(nextPost)" class="sub-content-title">
                                        {{ nextPost.post_title }}
                                    </span> 
                                    <span v-else class="sub-content-title">다음글이 없습니다.</span>
                                </span>
                            </li>
                            <li><span class="prev">이전글</span>
                                <span>
                                    <span v-if="prevPost" @click="movePost(prevPost)" class="sub-content-title">
                                        {{ prevPost.post_title }}
                                    </span> 
                                    <span v-else class="sub-content-title">이전글이 없습니다.</span>
                                </span>
                            </li>
                        </ul>
                    </div>
                    <div class="dtail-navigation-in">
                        <button @click="goBack">목록</button>
                    </div>
                </div>

            </div>
        </div>
    </div>
</template>
<script>
import axios from 'axios';
import COMMON_UTIL from '../../../../resources/js/commonUtil.js';
import { useRoute } from 'vue-router';
import Viewer from '@toast-ui/editor/dist/toastui-editor-viewer';
import '@toast-ui/editor/dist/toastui-editor.css';
import '@toast-ui/editor/dist/i18n/ko-kr';
import * as FileSaver from 'file-saver';

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,
            },
            prevPost: {
                post_id: null,
                post_title: null,
                file_id: null,
            },
            nextPost: {
                post_id: null,
                post_title: null,
                file_id: null,
            },
            fileList: [],
            oEditors: [], // oEditors는 스마트에디터용
            route: useRoute(),
        };
    },
    methods: {
        goBack() {
            this.$router.go(-1);
        },
        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,
                        'bbs_id': vm.route.query.bbs_id }
            }).then(function (response) {
                vm.prevPost = response.data.postSelectOne.prevPost;
                vm.post = response.data.postSelectOne.post;
                vm.nextPost = response.data.postSelectOne.nextPost;

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

                vm.getViewer(vm.post.post_content)

                axios({
                    url: '/statistics/postLogInsert.json',
                    method: 'post',
                    hearder: {
                        'Content-Type': "application/json; charset=UTF-8",
                    },
                    data: vm.post
                })
            }).catch(function (error) {
                console.log("error - ", error)
                alert("게시글 상세보기 조회 오류, 관리자에게 문의하세요.");
            })
        },

        getViewer(data) {
            this.viewer = new Viewer({
                el: this.$refs.viewer,
                initialEditType: 'wysiwyg',
                previewStyle: 'vertical',
                initialValue: data,
                customHTMLRenderer: {
                    htmlBlock: {
                        iframe(node) {
                            return [
                                { type: 'openTag', tagName: 'iframe', outerNewLine: true, attributes: node.attrs },
                                { type: 'html', content: node.childrenHTML },
                                { type: 'closeTag', tagName: 'iframe', outerNewLine: true },
                            ];
                        },
                    }
                },
            });
        },

        downloadFile: function (item) {
            const vm = this;
            let path = item.file_path + '/' + item.file_nm + '.' + item.file_extn_nm;
            axios({
                url: '/file/downloadFile.json',
                method: 'post',
                headers: {
                    "Content-Type": "application/x-www-form-urlencoded",
                },
                responseType: 'blob',
                data: `file_path=${encodeURIComponent(path)}`
            }).then((response) => {
                const blob = new Blob([response.data]);
                const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

                if (isSafari) {
                    FileSaver.saveAs(blob, item.real_file_nm);
                } else {
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.style.display = 'none';
                    a.href = url;
                    a.download = item.real_file_nm;
                    document.body.appendChild(a);
                    a.click();
                    window.URL.revokeObjectURL(url);
                }

                item.post_id = vm.post.post_id;
                item.bbs_id = vm.post.bbs_id;
                item.ctgry_nm = vm.post.ctgry_nm;
                
                axios({
                    url: '/statistics/fileLogInsert.json',
                    method: 'post',
                    hearder: {
                        'Content-Type': "application/json; charset=UTF-8",
                    },
                    data: item
                }).then(function(response){
                    vm.$router.go(0);
                })
                
            }).catch(function (error) {
                console.log('error - ', error)
                alert('에러발생');
            });
        },

        movePost : function (post1) {
            const vm = this;
            console.log(vm.route)
            axios({
                url: '/post/postSelectOne.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: { 'post_id': post1.post_id, 
                        'file_id': post1.file_id,
                        'bbs_id': post1.bbs_id }
            }).then(function (response) {
                vm.prevPost = response.data.postSelectOne.prevPost;
                vm.post = response.data.postSelectOne.post;
                vm.nextPost = response.data.postSelectOne.nextPost;
                vm.fileList = response.data.selectFileList;
                

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

        //날짜 시,분,초 자르기
        yyyymmdd: function (date) {
            return COMMON_UTIL.yyyymmdd(date);
        },
    },

    mounted() {
        this.postSelectOne();
    },
}
</script>
