<template>
    <div class="news-page page">
        <div class="w1400">
            <div class="news">
                <div class="page-logo flex-start" style="gap: 1rem;">
                    <img src="../../../../resources/jpg/info-logo.png" alt="홍보뉴스 아이콘">
                    <h1>홍보/뉴스</h1>
                </div>
                <div class="tech-search-box">

                    <div class="data-wrap-search">
                        <select v-model="postListSearch.searchType" name="data-table-sild" id="data-table-sild"
                            class="data-table-search">
                            <option v-for="(item, idx) in option" :key="idx" :value=item.value>
                                {{ item.name }}
                            </option>
                        </select>
                        <div class="input-group">
                            <input type="text" class="input" placeholder="검색어를 입력해주세요." v-model="postListSearch.searchText"
                                @keyup.enter="postSelectList()">
                            <input class="button--submit data-button-sum" value="검색" type="submit"
                                @click="postSelectList()">
                        </div>
                    </div>
                    <!-- 최신순 조회순 -->
                    <div class="sort-wrap">
                        <ul class="flex-end">
                            <li v-for="(item, index) in sorts" :key="index" :class="{ active: activeIndex === index }"
                                @click="changeColor(index)">
                                {{ item.name }}
                            </li>
                        </ul>
                    </div>
                </div>
                <ul class="news-bos">
                    <li class="news-bos-box" v-for="(item, idx) in postList" :key="idx" @click="openModal(item)">
                        <div class="modal-img">
                            <img :src="'http://localhost:8080' + item.file_path + '/' + item.file_nm + '.' + item.file_extn_nm"
                                alt="thumbnail" />
                        </div>
                        <div>
                            <h3>{{ item.post_title }}</h3>
                        </div>
                        <div class="news-box-sed">
                            <p class="content-detail">{{ removeTag(item.real_content) }}</p>
                        </div>
                        <div class="news-box-end">
                            <p>작성자 <span>{{ item.rgtr_id }}</span></p>
                            <p>조회수 <span>{{ item.view_cnt }}</span></p>
                        </div>
                    </li>
                </ul>
            </div>
            <div class="bottom-wrap">
                <PaginationButton v-model:currentPage="postListSearch.currentPage" :perPage="postListSearch.perPage"
                    :totalCount="postListCount" :maxRange="5" :click="postSelectListPage" />
            </div>
            <div v-show="isModalOpen" class="modal">
                <div class="modal-content">
                    <div class="modal-content-wrap">

                        <div ref="modalInner"></div>
                        <div class="modal-content-box" v-if="modalItem">
                            <p class="modal-news-title">{{ modalItem.post_title }}</p>
                            <p v-if="realContent" v-html="realContent"></p>
                            <div class="flex-align-start">
                                <p class="file-zone-title" v-if="realFileList && realFileList.length > 0">첨부파일</p>
                                <ul v-if="realFileList">
                                    <li v-for="(     file, idx     ) in      realFileList     " :key="idx"
                                        @click="downloadFile(file)">{{
                                            file.real_file_nm }}</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    <!-- 모달 닫기 버튼 -->
                    <button @click="closeModal" class="blue-btn">닫기</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import axios from 'axios';
import COMMON_UTIL from '../../../../resources/js/commonUtil.js';
import PaginationButton from '../../../component/pagination/PaginationButton.vue';

export default {
    data() {
        return {
            isModalOpen: false,
            videoUrl: '',
            postList: [],
            postListCount: 0,
            postIdx: 0,
            postListSearch: {
                currentPage: 0,
                perPage: 9,
                searchType: 'all',
                searchText: null,
                bbs_id: '1',
                sort: 'dt'
            },
            page_nm: '홍보뉴스',
            modalItem: null,
            realContent: null,
            fileList: [],
            realFileList: [],
            // 최신순 조회순
            sorts: [{ name: '최신순', value: 'dt' },
            { name: '조회수순', value: 'view' }],
            activeIndex: 0,

            option: [
                { name: '전체', value: 'all' },
                { name: '제목', value: 'title' },
                { name: '내용', value: 'content' },
                { name: '작성자', value: 'writer' },
            ],

            post:{}
        }
    },
    methods: {
        //  최신순 조회순
        changeColor(index) {
            this.activeIndex = index;
            this.postListSearch.sort = this.sorts[index].value;
            this.postSelectListPage();
            this.postSelectList();
        },

        openModal: function (item) {
            const vm = this;

            axios({
                url: '/post/postViewCount.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: { 'post_id': item.post_id, 'bbs_id': item.bbs_id }
            }).then(function (response) {
                vm.findFiles(item)
                vm.isModalOpen = true;
                vm.videoUrl = item.post_content;
                vm.urlHTML(vm.videoUrl)
                vm.modalItem = item;
                vm.realContent = item.real_content;
                vm.post = item;
                axios({
                    url: '/statistics/postLogInsert.json',
                    method: 'post',
                    hearder: {
                        'Content-Type': "application/json; charset=UTF-8",
                    },
                    data: item
                })
            }).catch(function (error) {
                alert("홍보/뉴스 상세보기 오류, 관리자에게 문의바랍니다.");
            })
        },

        urlHTML: function (content) {
            let divRef = this.$refs['modalInner'];
            divRef.innerHTML = content;
        },

        closeModal() {
            this.videoUrl = "";
            this.urlHTML(this.videoUrl);
            this.isModalOpen = false;
            this.postSelectList();
        },

        postSelectList: function () {
            const vm = this;

            axios({
                url: '/post/newsSelectListForMain.json',
                method: 'post',
                hearder: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: vm.postListSearch
            }).then(function (response) {
                vm.postList = response.data.postSelectList;
                vm.postListCount = response.data.postSelectListCount;
                vm.postIdx = vm.postListCount - (vm.postListSearch.currentPage - 1) * vm.postListSearch.perPage;
            }).catch(function (error) {
                alert('홍보/뉴스 목록 조회 오류, 관리자에게 문의하세요.');
            })
        },

        findFiles: function (item) {

            const vm = this;

            axios({
                url: '/file/selectFileList.json',
                method: 'post',
                headers: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: { "file_id": item.file_id }
            }).then(function (response) {
                vm.realFileList = [];
                if (response.data.length !== 0) {
                    vm.fileList = response.data;
                    for (let i = 0; i < vm.fileList.length; i++) {
                        if (vm.fileList[i].file_ty === 'attach') {
                            vm.realFileList.push(vm.fileList[i])
                        }
                    }
                }
            }).catch(function (error) {
                alert('홍보/뉴스 상세 조회 오류, 관리자에게 문의하세요.');
            })
        },

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

        // content html 제거
        removeTag: function (data) {
            return COMMON_UTIL.removeTag(data);
        },

        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;

                axios({
                    url: '/statistics/fileLogInsert.json',
                    method: 'post',
                    hearder: {
                        'Content-Type': "application/json; charset=UTF-8",
                    },
                    data: item
                })

            }).catch(function (error) {
                alert('파일 다운로드 실패, 다시 시도해주세요.');
            });
        },

        /**페이지 접속 로그 등록 */
        pageLogInsert: function() {
            const vm = this;

            axios({
                url: '/statistics/pageLogInsert.json',
                method: 'post',
                headers: {
                    'Content-Type': "application/json; charset=UTF-8",
                },
                data: { "page_nm": vm.page_nm }
            })
        },

        postSelectListPage: function() {
            this.$router.push({ path: '/News.page', query: { 'page': this.postListSearch.currentPage, 'sort': this.postListSearch.sort } });
        },
    },
    watch: {
        'postListSearch.currentPage': function () {
            this.postSelectList();
        },
    },
    computed: {

    },
    components: {
        PaginationButton: PaginationButton,
    },
    created() {
        if(this.$route.query.page) {
            this.postListSearch.currentPage = Number(this.$route.query.page);

            this.sorts.forEach((sorts, idx) => {
                if(sorts.value == this.$route.query.sort) {
                    this.activeIndex = idx;
                    this.postListSearch.sort = this.sorts[idx].value
                }
            })
        } else {
            this.postListSearch.currentPage = 1;
        }
    },
    mounted() {
        this.pageLogInsert();
        if(!this.$route.query.page) {
            this.postSelectList();
        }
    }
}
</script>


