<template>
    <div :class="{
        'content': true,
        ' overflow-y': this.$route.path.startsWith('/kdm')
    }">
        <div :class="{ 'top-banner banner ': true, [bannerId]: true }" v-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-between align-start no-gutters">
                <div class="gd-5"></div>
                <div class="search-bar mb15 gd-7">
                    <div class="flex justify-end align-center no-gutters">
                        <div class="gd-9">
                            <div class="flex align-center">
                                <div class="gd-3 pl0">
                                    <select name="selectType" id="selectType" class="full-select" v-model="search.searchType">
                                        <option v-for="(item, idx) in codeList" :key="idx" :value="item.cdId">{{ item.cdNm }}</option>
                                    </select>
                                </div>
                                <div class="gd-9 pl0">
                                        <input type="text" class="full-input  condition-input" placeholder="검색어를 입력해주세요." v-model="search.searchText" @keyup.enter="findAll" />
                                </div>
                            </div>
                        </div>
                        <div class="gd-2">
                            <button class="large-btn blue-border-btn" title="검색" @click="findAll">검색</button>
                        </div>
                    </div>
                </div>
            </div>
            <div class="table-zone">
                <div class="flex justify-between align-center">
                    <p class="small-text black">총 <span style="font-weight: 700;">{{ applyListCount }}건</span></p>
                </div>
                <table class="list-style-table edu-status-list mb10" style="border-top:2px solid #ddd; border-bottom:2px solid #ddd">
                    <colgroup>
                        <col width="5%" />
                        <col width="85%" />
                        <col width="10%" />
                    </colgroup>
                    <tbody>
                        <tr class="border-t cursor" v-for="(item, idx) in applyList" :key="idx">
                            <td>
                                <p class="text-ct">{{ applyIdx - idx }}</p>
                            </td>
                            <td class="pd10">
                                <div class="flex align-center">
                                    <div class="img-zone support-img gd-3" v-for="(imgFile, idx) in item.imgFileList" :key="idx">
                                        <img src="/clinet/resources/img/no_img.png" class="inline-block radius" v-if="imgFile.fileId === null" @click="fnView(item.edu_cnslt_id)" alt="썸네일 대체 이미지" /> 
                                        <img :src="$replaceImagePath(imgFile.ablstPathNm)" 
                                        class="inline-block radius" v-else @error="handleImageError" @click="fnView(item.edu_cnslt_id)" :alt="item.edu_cnslt_schdl_ttl + '썸네일'"/>
                                    </div>
                                    <div class="gd-9" style="line-height: 160%;">
                                        <div class="flex mb15">
                                            <p class="middle-title">{{ item.edu_cnslt_ttl }}</p>
                                        </div>
                                        <p class="mb5">{{ item.edu_cnslt_schdl_ttl }}</p>
                                        <p class="mb5">일자 : {{ $formatUnixToDate(item.edu_cnslt_bgng_dt) }} ~ {{ $formatUnixToDate(item.edu_cnslt_end_dt) }}</p>
                                        <p class="mb5">시간 : {{ formatTime(item.edu_cnslt_bgng_hr) }} ~ {{ formatTime(item.edu_cnslt_end_hr) }}</p>
                                    </div>
                                </div>
                            </td>
                            <td>
                               <div class="flex-column justify-center align-center">
                                    <button class="small-btn red-border-btn mb5" title="신청취소" @click="fnDelete(item)">신청취소</button>
                                    <button class="small-btn sky-blue-btn mb5" title="상세보기" @click="fnView(item.edu_cnslt_id)">상세보기</button>
                                    <!-- 관리자가 신청 시 첨부파일이 있는경우 -->
                                    <button v-if="item.file_mng_id" class="small-btn darkg-border-btn" title="제출한자료" @click="fileDownload(item)">제출한 자료</button>
                               </div>
                            </td>
                        </tr>
                        <tr v-if="pagination.totalRecordCount == 0 && applyList.length == 0">
                            <td colspan="3" class="text-ct pd10">신청 목록이 존재하지 않습니다.</td>
                        </tr>
                    </tbody>
                </table>
            </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="pagination"
                        :click="findAll"
                    />
                </div>
                <div class="gd-1"></div>
            </div>
        </div>
    </div>
</template>

<script>
import PaginationButton from '../../../component/pagination/PaginationButton.vue';
import PageNavigationBar from '../../../component/pagenavigationbar/PageNavigationBar.vue';
import { mdiEye } from '@mdi/js';
import queryParams from "../../../../resources/js/queryParams";
import { defaultSearchParams } from "../../../../resources/js/defaultSearchParams";
import { toRaw } from "vue";
//api
import { findAllByMbrId , deleteMySchedule } from "../../../../resources/api/eduCn.js"
export default {
    mixins: [queryParams],
    data() {
        return {
            // 페이지 권한 객체
            pageAuth: JSON.parse(localStorage.getItem("vuex")).pageAuth,
            path: this.$store.state.path,
            viewPath: mdiEye,
            errorImages: new Set(),
            // 검색 정보 담는 객체
            search: { ...defaultSearchParams },

            codeList: [{ cdId: 'title', cdNm: '제목'},],
           
            // 목록 조회 정보 담는 객체
            pagination: {},

            applyList: [],
            applyListCount: null,
            applyIdx: null,
            bannerId:'mypage-banner'
        }
    },
    created() {
        this.init();
    },
    methods: {
        async init() {
            this.resotreQueryParams("queryParams");
            this.search.searchType = 'title';
            this.findAll();
        },

        async fnDelete(item){
            if(!confirm(this.$getCmmnMessage("cnf008","해당 교육일정 참여를 "))) return

            try {
                const res = await deleteMySchedule(item);
                if(res.status == 200){
                    alert(res.data.message)
                    if(res.data.success){
                        this.init()
                    }
                }
                
            } catch (error) {
                const errorData = error.response.data;
                if (errorData.message != null && errorData.message != "") {
                alert(error.response.data.message);
                } else {
                // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
                alert(this.$getCmmnMessage('err005'));
                }
            }
        },

        //파일 다운로드
        fileDownload(item){
            const fileList = item.fileList;
            for(const file of fileList){
                this.$downloadFile(file, this.pageAuth);
            }
        },

        //상세페이지로 이동
        fnView(Id) {
            this.$router.push({
                path: '/aidt/tech/edu/view.page', query: { 'pageId' : Id }
            });
        },

        //나의 신청 목록 조회
        async findAll() {
            this.saveQueryParams("queryParams", this.search); // 검색조건 저장
            try {
                const res = await findAllByMbrId(toRaw(this.search));

                this.applyList = res.data.data.list;
                this.search = res.data.data.pagination;
                this.pagination = res.data.data.pagination;
                this.applyListCount = res.data.data.totalCount;
                this.applyIdx = this.pagination.totalRecordCount -
                (this.pagination.currentPage - 1) * this.pagination.recordSize;
            } catch (error) {
                const errorData = error.response.data;
                if (errorData.message != null && errorData.message != "") {
                alert(error.response.data.message);
                } else {
                // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
                alert(this.$getCmmnMessage('err005'));
                }
            }
        },

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

        formatTime(timeString) {
            // 시간, 분 추출
            const hours = timeString.slice(0, 2);
            const minutes = timeString.slice(2, 4);
            return `${hours}:${minutes}`;
        },

    },
    watch: {
    },
    components: {
        'PaginationButton': PaginationButton,
        'PageNavigationBar':PageNavigationBar
    },
    mounted() {
         this.naviData = { 'main': '기술지원', 'sub': '교육 ・ 컨설팅' };
    }
}
</script>
