<template>
    <div :class="{
        'content overflow-y': true,
        'overflow-y': this.$route.path.startsWith('/kdm'),
    }">
        <div class="admin-page-title mb30" v-if="this.$route.path.startsWith('/kdm')">
            <p>교육 ・ 컨설팅</p>
        </div>
        <div :class="{ 'top-banner banner guide-banner': true, [bannerId]: true }"
            v-else-if="this.$route.path.startsWith('/aidt')">
            <div class="flex-column align-center justify-center content">
                <h1 class="banner-title text-ct white" aria-live="assertive">{{ $getMenuInfo().menuNm }}</h1>
                <p class="box-title text-ct white">{{ $getMenuInfo().menuCn }}</p>
            </div>
        </div>
        <PageNavigationBar v-if="this.$route.path.startsWith('/aidt')" />
        <div :class="{ 'w1280 pt100 pb100': this.$route.path.startsWith('/aidt') }">
            <!-- 매뉴얼 -->
            <div class="flex justify-end align-center mb30">
                <label class="visually-hidden">교육 · 컨설팅 메뉴얼 다운로드</label>
                <button class="small-btn darkg-border-btn" title="교육 · 컨설팅 메뉴얼 다운로드" style="border-radius: 3rem;" @click="$downloadFileById('FILE_0000000009', 'CMMN_FILE_0000000001', 'AI 디지털교과서 통합지원센터 교육 · 컨설팅 신청 절차 매뉴얼.pdf', 'BBS_0000000031', pageAuth)">교육 · 컨설팅 매뉴얼</button>
            </div>
            <div class="search-bar mb15 pd30 background radius">
                <div class="flex align-end pb10">
                    <div class="gd-2 pl0">
                        <label for="category" class="visually-hidden">카테고리</label>
                        <select name="category" id="category" class="full-select"
                            @change="updateCategory($event.target.value)">
                            <option value="all" selected>전체</option>
                            <option v-for="(ctgryCd, idx) in ctgryCdList" :key="idx" :value="ctgryCd.cdId">
                                {{ ctgryCd.cdNm }}
                            </option>
                        </select>
                    </div>
                    <div class="gd-4 pl0">
                        <div class="flex align-center no-gutters">
                            <div class="gd-5">
                                <label for="start-date" class="visually-hidden">시작날짜</label>
                                <input type="date" name="start-date" id="start-date" class="full-input"
                                    v-model="search.startDt" />
                            </div>
                            <div class="pl10 pr10">
                                -
                            </div>
                            <div class="gd-5">
                                <label for="end-date" class="visually-hidden">종료날짜</label>
                                <input type="date" name="end-date" id="end-date" class="full-input"
                                    v-model="search.endDt" />
                            </div>
                        </div>
                    </div>
                    <div class="gd-5 pl0">
                        <div class="flex align-center">
                            <div class="gd-3 pl0">
                                <label for="search-type" class="visually-hidden">검색조건</label>
                                <select name="search-type" id="search-type" class="full-select"
                                    v-model="search.searchType">
                                    <option value="title">제목</option>
                                    <option v-for="(item, idx) in codeList" :key="idx" :value="item.cdId">{{ item.cdNm
                                        }}</option>
                                </select>
                            </div>
                            <div class="gd-9 pl0">
                                <label for="search-text" class="visually-hidden">검색어</label>
                                <input type="text" name="search-text" id="search-text" class="full-input"
                                    placeholder="교육 및 컨설팅명을 입력하세요." v-model="search.searchText"
                                    @keyup.enter="findAll" />
                            </div>
                        </div>
                    </div>
                    <div class="gd-1 pl0 pr0">
                        <button class="large-btn blue-border-btn" title="검색" @click="findAll" aria-label="검색">검색</button>
                    </div>
                </div>
                <!-- 공개여부 필터 -->
                <ul class="flex justify-start align-center pt10 border-t" v-if="isAdmin()">
                    <p class="detail-text mr10">공개여부</p>
                    <div class="radio-container" v-for="(item, idx) in rlsYn" :key="idx">
                        <label :for="idx" class="detail-text">
                            <input type="radio" name="disclosure" :id="idx" :value="item.value"
                                v-model="search.searchFilter" @change="findAll" />
                            <span>{{ item.name }}</span></label>
                    </div>
                </ul>


            </div>
            <div class="table-zone mb10">
                <div class="flex justify-between align-center">
                    <p class="small-text black">총 <span style="font-weight: 700;">{{ listCnt }}건</span></p>
                    <label for="sort" class="visually-hidden">정렬 기준</label>
                    <select v-model="search.sort" id="sort" class="border-none small-text black" @change="findAll">
                        <option value="frst_reg_dt">최신순</option>
                        <option value="inq_cnt">조회순</option>
                    </select>
                </div>
                <div class="flex justify-start align-center">
                    <template v-if="list.length > 0">
                        <div v-for="(item, idx) in list" :key="idx" class="gd-4 pt10 pb10">
                            <div class="gall-item edu-item cursor pd30" @click="fnView(idx)" role="button" tabindex="0"
                                @keydown.enter.space="fnView(idx)">
                                <div class="gall-img mb20 relative">
                                    <img src="/clinet/resources/img/no_img.png" class="inline-block radius" alt="이미지 없음"
                                        v-if="item.imgFile.fileId === null">
                                    <img :src="$replaceImagePath(item.imgFile.ablstPathNm)" class="inline-block radius"
                                        v-else @error="handleImageError" :alt="item.edu_cnslt_ttl + ' 썸네일 이미지'" />
                                    <p class="master small-text" v-if="item.ent_mngr_yn === 'Y'">기업단위</p>
                                </div>
                                <div class="category mb5 small-text gray">
                                    <span class="edu-category inline-block small-text gray">{{ item.cd_nm
                                        }}&nbsp;</span>
                                    <span class="inline-block small-text gray" v-if="isAdmin()">|&nbsp; {{ item.rls_yn
                                        === 'Y' ? '공개' : '비공개' }}</span>
                                </div>
                                <div class="gall-title mb10">
                                    <h2 class="middle-title ellipsis">
                                        {{ item.edu_cnslt_ttl }}
                                    </h2>
                                </div>
                                <div class="gall-info pt5">
                                    <p class="text-rg small-text">{{ formatUnixToDate(item.frst_reg_dt) }}</p>
                                </div>
                            </div>
                        </div>
                    </template>
                    <div class="gd-12 border-t border-b" v-else>
                        <p class="text-ct pd10">등록된 정보가 존재하지 않습니다.</p>
                    </div>
                </div>
            </div>
            <div class="flex justify-between align-center no-gutters">
                <div class="gd-1"></div>
                <div class="gd-10">
                    <PaginationButton :className="'admin-pagination'" v-model:currentPage="search.currentPage"
                        :pagination='search' :click="findAll" />
                </div>
                <div class="gd-1">
                    <button class="large-btn blue-btn" title="등록" @click="fnAdd" v-show="this.$route.path.startsWith('/kdm')"
                        aria-label="등록">등록</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import ListTable from '../../../component/table/ListTable.vue';
import PaginationButton from '../../../component/pagination/PaginationButton.vue';
import { toRaw } from 'vue'
import queryParams from '../../../../resources/js/queryParams';
import { defaultSearchParams } from '../../../../resources/js/defaultSearchParams';
import PageNavigationBar from '../../../component/pagenavigationbar/PageNavigationBar.vue';
import COMMON_UTIL from '../../../../resources/js/commonUtil';
import { template } from 'lodash';
//API
import { findAll } from '../../../../resources/api/eduCn.js'


export default {
    mixins: [queryParams],
    components: {
        'ListTable': ListTable,
        'PaginationButton': PaginationButton,
        'PageNavigationBar': PageNavigationBar
    },
    data() {
        return {
            tbody: [],
            search: { ...defaultSearchParams },
            path: this.$store.state.path,
            pageAuth: this.$store.state.pageAuth,
            role: this.$store.state.roles,
            list: [], // 게시판 내용 목록
            listCnt: 0,
            pagination: {},
            bbsMng: {}, // 게시판 관리
            errorImages: new Set(),
            bannerId: 'guide-banner',
            ctgryCdList: [], //카테고리 목록
            rlsYn: [{ name: '전체', value: '' }, { name: '공개', value: 'Y' }, { name: '비공개', value: 'N' }],
        }
    },
    created() {
        this.resotreQueryParams('queryParams');
        this.search.searchType = 'title';
        this.findAllCtgry();
        this.findAll();
    },
    methods: {
        // 목록 조회
        async findAll() {
            this.search.recordSize = 9;
            this.saveQueryParams('queryParams', this.search); // 검색조건 저장        
            try {
                const res = await findAll(toRaw(this.search));
                this.list = res.data.data.list; // 게시판 관리 목록
                this.listCnt = res.data.data.listCnt; // 게시판 관리 목록 갯수
                this.search = res.data.data.pagination; // 페이징처리 및 검색 내용
            } catch (error) {
                // alert('에러가 발생했습니다.\n시스템관리자에게 문의하세요.');
                alert(this.$getCmmnMessage('err005'));
            }
        },
        // 상세 조회
        fnView(idx) {
            this.saveQueryParams('queryParams', this.search); // 검색조건 저장
            this.$router.push({
                path: this.path + '/view.page',
                query: {
                    pageId: this.list[idx]["edu_cnslt_id"]
                },
            });
        },
        // 등록페이지 이동
        fnAdd() {
            this.$router.push({
                path: this.path + '/insert.page'
            });
        },

        //에러이미지 표출
        handleImageError(event) {
            if (!this.errorImages.has(event.target.id)) {
                this.errorImages.add(event.target.id);
                event.target.src = require('../../../../resources/img/no_img.png'); // 대체 이미지 경로
            }
        },

        removeTag(data) {
            return COMMON_UTIL.removeTag(data);
        },

        formatUnixToDate(unixTimestamp) {
            const date = new Date(unixTimestamp);
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        },

        //카테고리 리스트 불러오기
        async findAllCtgry() {
            this.ctgryCdList = await this.$getCommonCode('techEduCtgryCd');
        },

        //카테고리 업데이트
        updateCategory(selectedCtgry) {
            if (selectedCtgry === 'all') {
                this.search.searchCtgry = '';
            } else {
                this.search.searchCtgry = selectedCtgry;
            }
            this.findAll();
        },

        // KERIS관리자 여부 확인
        isAdmin() {
            return this.role.some(role => role.authority === 'ROLE_ADMIN');
        },
    },
    watch: {
        $route(to, from) {
            // path가 다를 때만 조회
            if (to.path !== from.path) {
                this.resotreQueryParams('queryParams');
                this.findAll();
            }
        }

    },
    computed: {

    },
    mounted() {

    }
}
</script>
