<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">{{ $getMenuInfo().menuNm }}</h1>
                <p class="box-title text-ct white">{{ $getMenuInfo().menuCn }}</p>
            </div>
        </div>
        <PageNavigationBar :navi="naviData" v-if="this.$route.path.startsWith('/aidt')" />
        <div :class="{ 'w1280 pt100 pb100 edu-page': this.$route.path.startsWith('/aidt') }">
            <table class="detail-table mb30 admin-detail edu-detail">
                <caption class="visually-hidden">{{ eduCn.edu_cnslt_ttl }}내용</caption>
                <colgroup>
                    <col width="10%" />
                    <col width="90%" />
                </colgroup>
                <tbody>
                    <tr class="detail-title">
                        <td colspan="2">
                            <div class="flex align-start">
                                <div class="gall-zone gd-6" style="margin-bottom: 0;">
                                    <div class="gall-slide" v-for="(item, idx) in imgFileList" :key="idx"
                                        style="height: 37rem;">
                                        <!-- <img :src="$imageDownByid(item.fileId, item.fileId)" :id="item.fileId" class="inline-block radius" @error="handleImageError" alt="수강 대표이미지"/> -->
                                        <img src="/client/resources/img/no_img.png" class="inline-block radius"
                                            v-if="item.fileId === null" :alt="eduCn.edu_cnslt_ttl + '대체 이미지'" />
                                        <img :src="$replaceImagePath(item.ablstPathNm)" class="inline-block radius"
                                            v-else @error="handleImageError" :alt="eduCn.edu_cnslt_ttl + '썸네일'" />
                                    </div>
                                </div>
                                <div class="gd-6">
                                    <div class="pb10 border-b">
                                        <h2 class="detail-table-title mb10">{{ eduCn.edu_cnslt_ttl }}</h2>
                                        <div class="flex justify-end align-center">
                                            <p class="mr20"><span>등록일 {{ formatUnixToDate(eduCn.frst_reg_dt) }}</span>
                                            </p>
                                            <p><span>조회수 {{ $comma(eduCn.inq_cnt) }}</span></p>
                                        </div>
                                    </div>
                                    <div class="pd15">
                                        <p class="mb10">
                                            <span class="dark-gray" v-if="minMax">
                                                <svg-icon type="mdi" :width="18" :height="18" :path="schedulePath"
                                                    role="img" aria-hidden="true"></svg-icon>
                                                일정 :
                                                <span
                                                    v-if="minMax.min_edu_cnslt_bgng_dt === minMax.max_edu_cnslt_end_dt">
                                                    {{ formatUnixToDate(minMax.min_edu_cnslt_bgng_dt) }}
                                                </span>
                                                <span v-else>
                                                    {{ formatUnixToDate(minMax.min_edu_cnslt_bgng_dt) }} ~ {{
                                                        formatUnixToDate(minMax.max_edu_cnslt_end_dt) }}
                                                </span>
                                            </span>


                                        </p>
                                        <p class="mb10" v-if="eduCn.ent_mngr_yn === 'N'">
                                            <span class="dark-gray" v-if="minMax">
                                                <svg-icon type="mdi" :width="18" :height="18" :path="peoplePath"
                                                    role="img" aria-hidden="true"></svg-icon>
                                                정원 : <span
                                                    v-if="minMax.min_edu_cnslt_pscp_cnt === minMax.max_edu_cnslt_pscp_cnt">
                                                    {{ minMax.min_edu_cnslt_pscp_cnt }}
                                                </span>
                                                <span v-else>
                                                    {{ minMax.min_edu_cnslt_pscp_cnt }} ~ {{
                                                        minMax.max_edu_cnslt_pscp_cnt }}
                                                </span>
                                            </span>
                                        </p>
                                        <p class="mb10" v-else>
                                            <span class="dark-gray">
                                                <svg-icon type="mdi" :width="18" :height="18" :path="peoplePath"
                                                    role="img" aria-hidden="true"></svg-icon>
                                                참석 인원 : {{ eduCn.rmrk_cn }}
                                            </span>
                                        </p>
                                        <p class="mb10"><span class="dark-gray"><svg-icon type="mdi" :width="18"
                                                    :height="18" :path="inquiryPath" role="img"
                                                    aria-hidden="true"></svg-icon> 문의처 : </span>{{
                                                        eduCn.edu_cnslt_cttpc_cn }}</p>
                                        <p class="mb10"><span class="dark-gray"><svg-icon type="mdi" :width="18"
                                                    :height="18" :path="markPath" role="img"
                                                    aria-hidden="true"></svg-icon> 장소 : </span>{{
                                                        eduCn.edu_cnslt_plc_nm }}</p>
                                        <p class="mb10" v-if="isAdmin()">
                                            <span class="dark-gray">
                                                <svg-icon type="mdi" :width="18" :height="18" :path="lockPath"
                                                    role="img" aria-hidden="true"></svg-icon>
                                                공개여부 : {{ eduCn.rls_yn === 'Y' ? '공개' : '비공개' }}
                                            </span>
                                        </p>
                                        <p class="mb10">
                                            <span class="dark-gray">
                                                <svg-icon type="mdi" :width="18" :height="18" :path="masterPath"
                                                    role="img" aria-hidden="true"></svg-icon>
                                                대상자 : {{ eduCn.ent_mngr_yn === 'Y' ? '기업단위' : '기업회원' }}
                                            </span>
                                        </p>
                                        <div>
                                            <p class="mb10"><span class="dark-gray"><svg-icon type="mdi" :width="18"
                                                        :height="18" :path="filePath" role="img"
                                                        aria-hidden="true"></svg-icon> 첨부자료 : </span></p>
                                            <div v-if="fileList.length == 0" class="pd15">
                                                <p>첨부된 파일이 없습니다.</p>
                                            </div>
                                            <ul v-else>
                                                <li v-for="(item, idx) in fileList" :key="idx" class="pd5 radius">
                                                    <div
                                                        class="download-item border flex justify-between align-center pd10">
                                                        <p class="ellipsis gd-10">{{ `${item.fileNm} [${item.extnNm},
                                                            ${formatFileSize(item.fileSz)}]` }}</p>
                                                        <div class="flex align-center justify-end gd-2">
                                                            <button class="icon-btn" aria-label="download button"
                                                                title="다운로드"
                                                                @click="$downloadFile(item, pageAuth)"><svg-icon
                                                                    type="mdi" :path="downloadPath" role="img"
                                                                    aria-labelledby="download button"></svg-icon></button>
                                                        </div>
                                                    </div>
                                                </li>
                                            </ul>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                    <tr class="border-t">
                        <td colspan="2">
                            <div class="pd15">
                                <ul class="edu-tab flex justify-between align-center pd10 border radius mb30">
                                    <template v-for="(row, idx) in tabList" :key="idx">
                                        <li v-if="authrtTypeLvl === '1' || (authrtTypeLvl !== '1' && row.tabName !== '신청자 리스트')"
                                            :class="{
                                                'gd-4 pd10 radius text-ct cursor': authrtTypeLvl === '1',
                                                'gd-6 pd10 radius text-ct cursor': authrtTypeLvl !== '1',
                                                'active': viewTab === row.id
                                            }" @click="showTab(row.id)">
                                            {{ row.tabName }}
                                        </li>
                                    </template>
                                </ul>
                                <div class="tab-content edu-content">
                                    <div v-show="viewTab === 1">
                                        <div>
                                            <!-- 수강일정이 하나도 없을때 -->
                                            <div class="flex justify-center align-center"
                                                v-if="scheduleList.length === 0">
                                                <button v-if="isAdmin()" class="small-btn black-btn" @click="classAdd"
                                                    v-show="this.$route.path.startsWith('/kdm')">수강 일정 등록</button>
                                                <p v-else>일정이 없습니다.</p>
                                            </div>
                                            <!-- 수강일정이 1개라도 등록했을때 -->
                                            <div v-else>
                                                <ul class="mb30">
                                                    <li v-for="(item, idx) in scheduleList" :key="idx"
                                                        class="pd15 border radius mb10">
                                                        <div class="flex justify-between align-center">
                                                            <div class="flex align-center gd-11">
                                                                <div class="mr30">
                                                                    <p class="detail-text">{{ idx + 1 }}</p>
                                                                </div>
                                                                <div class="gd-11">
                                                                    <h3 class="content-title2 mb10">{{
                                                                        item.edu_cnslt_schdl_ttl }}</h3>
                                                                    <p class="detail-text mb5">일자 : {{
                                                                        formatDateRange(item.edu_cnslt_bgng_dt,
                                                                            item.edu_cnslt_end_dt) }}</p>
                                                                    <p class="detail-text mb5">시간 : {{
                                                                        formatTime(item.edu_cnslt_bgng_hr) }} ~ {{
                                                                            formatTime(item.edu_cnslt_end_hr) }}</p>
                                                                    <p class="detail-text mb5">신청기간 : {{
                                                                        yyyymmdd(item.edu_aply_bgng_ymd) }} ~ {{
                                                                            yyyymmdd(item.edu_aply_end_ymd) }}</p>
                                                                    <p class="detail-text mb5" v-if="isAdmin()">공개여부 :
                                                                        {{ item.rls_yn === 'Y' ? '공개' :
                                                                            '비공개' }}</p>
                                                                </div>
                                                            </div>
                                                            <div class="gd-1">
                                                                <p class="detail-text text-ct mb5">정원 <span
                                                                        class="detail-bold blue">{{
                                                                            item.participant_cnt }}</span>/{{
                                                                            item.edu_cnslt_pscp_cnt }}</p>

                                                                <!-- 사용자에서 보이는 버튼 -->
                                                                <div v-if="!isAdmin()">
                                                                    <!-- 신청 가능 시점이고, 참여자가 인원보다 적을 때, 그리고 내가 참여 중이 아닐 때 -->
                                                                    <button
                                                                        v-if="isCanApplyPeriod(item) && item.participant_cnt < item.edu_cnslt_pscp_cnt && item.is_participant === 0"
                                                                        class="large-btn sky-blue-btn" title="신청"
                                                                        @click="applySchedule(item)">신청</button>
                                                                    <!-- 내가 참여 중일 때 -->
                                                                    <button v-else-if="item.is_participant === 1"
                                                                        class="large-btn green-btn" title="신청완료"
                                                                        style="cursor: default;">신청완료</button>
                                                                    <!-- 참여자와 인원수가 같을 때 -->
                                                                    <button title="마감"
                                                                        v-else-if="item.participant_cnt >= item.edu_cnslt_pscp_cnt"
                                                                        class="large-btn gray-btn">마감</button>
                                                                    <!-- 신청 불가능 시점일 때 -->
                                                                    <button v-else title="기한마감"
                                                                        class="large-btn gray-btn">기한마감</button>
                                                                </div>
                                                                <!-- 관리자에게 보이는 버튼 -->
                                                                <div v-else>
                                                                    <button class="large-btn sky-blue-btn mb10"
                                                                        @click="scheduleUpdateModal(item)">수정</button>
                                                                    <button class="large-btn red-border-btn mb10"
                                                                        @click="scheduleDelete(item)">삭제</button>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </li>
                                                </ul>
                                                <div class="flex justify-end align-center"
                                                    v-show="this.$route.path.startsWith('/kdm')">
                                                    <button class="small-btn black-btn" @click="classAdd"
                                                        v-show="this.$route.path.startsWith('/kdm')">일정 등록</button>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                    <div v-show="viewTab === 2" class="detail-edu">
                                        <div v-html="eduCn.edu_cnslt_cn"></div>
                                    </div>
                                    <div v-show="viewTab === 3">
                                        <details v-for="(item, idx) in scheduleList" :key="idx"
                                            class="pd15 border radius edu-list-item mb10">
                                            <summary class="edu-user-list pb15 relative " @click="ptcpFindAll(item)">
                                                <div class="flex justify-between align-center">
                                                    <div class="flex align-center gd-11">
                                                        <div class="mr30">
                                                            <p class="detail-text">{{ idx + 1 }}</p>
                                                        </div>
                                                        <div class="gd-11">
                                                            <p class="content-title2 mb10">{{ item.edu_cnslt_schdl_ttl
                                                                }}</p>
                                                            <p class="detail-text mb5">일자 : {{
                                                                formatDateRange(item.edu_cnslt_bgng_dt,
                                                                    item.edu_cnslt_end_dt) }}</p>
                                                            <p class="detail-text mb5">시간 : {{
                                                                formatTime(item.edu_cnslt_bgng_hr) }} ~ {{
                                                                    formatTime(item.edu_cnslt_end_hr) }}</p>
                                                            <p class="detail-text mb5">신청기간 : {{
                                                                yyyymmdd(item.edu_aply_bgng_ymd) }} ~ {{
                                                                    yyyymmdd(item.edu_aply_end_ymd) }}</p>
                                                            <p class="detail-text mb5">공개여부 : {{ item.rls_yn === 'Y' ?
                                                                '공개' : '비공개' }}</p>
                                                            <p class="detail-text">정원 <span class="detail-bold blue">{{
                                                                item.participant_cnt
                                                                    }}</span>/{{ item.edu_cnslt_pscp_cnt }}</p>
                                                        </div>
                                                    </div>
                                                </div>
                                            </summary>
                                            <div class="user-list border-t">
                                                <!-- <div class="table-zone pt15"> -->
                                                <div v-if="!item.memberList || item.memberList.length === 0"
                                                    class="border-t border-b">
                                                    <p class="text-ct pd10">등록된 정보가 존재하지 않습니다.</p>
                                                </div>
                                                <div v-else class="table-zone pt15">
                                                    <table class="list-table admin-list">
                                                        <colgroup>
                                                            <col width="5%" />
                                                            <col width="10%" />
                                                            <col width="10%" />
                                                            <col width="10%" />
                                                            <col width="10%" />
                                                            <col width="10%" />
                                                            <col width="10%" />
                                                            <col width="10%" />
                                                        </colgroup>
                                                        <thead>
                                                            <tr>
                                                                <th>NO</th>
                                                                <th>성명</th>
                                                                <th>직위(직급)</th>
                                                                <th>소속</th>
                                                                <th>전화번호</th>
                                                                <th>이메일</th>
                                                                <th>첨부파일</th>
                                                                <th>삭제</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr v-for="(member, idx) in item.memberList" :key="idx">
                                                                <td class="text-ct">{{ idx + 1 }}</td>
                                                                <td class="text-ct">{{
                                                                    $name_format_WithMasking(member.mbr_encpt_flnm) }}
                                                                </td>
                                                                <td class="text-ct">{{ member.mbr_jbgd_nm ?
                                                                    member.mbr_jbgd_nm : '-' }}</td>
                                                                <td>{{ member.ent_nm }}</td>
                                                                <td>{{
                                                                    $number_format_WithMasking(member.mbr_encpt_telno)
                                                                }}</td>
                                                                <td>{{ $email_format_WithMasking(member.mbr_encpt_emad)
                                                                    }}</td>
                                                                <td v-if="member.fileList" class="text-ct pl5 pr5">
                                                                    <button class="large-btn green-border-btn" title="첨부파일 다운로드"
                                                                        @click="fileDownload(member)">첨부파일
                                                                        다운로드</button>
                                                                </td>
                                                                <td v-else class="text-ct pl5 pr5">-</td>
                                                                <td class="text-ct pl5 pr5"><button
                                                                        class="large-btn red-border-btn" title="삭제"
                                                                        @click="fnDeleteMember(member, item)">삭제</button>
                                                                </td>
                                                            </tr>

                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </details>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
            <div class="flex justify-end align-center mb30">
                <div class="gd-1 pr0">
                    <button class="large-btn  gray-border-btn" title="a목록" @click="fnList">목록</button>
                </div>
                <div v-if="pageAuth.mdfcnAuthrtYn == 'Y' || mbrId == eduCn.frst_reg_uid" class="gd-1 pr0">
                    <button class="large-btn blue-border-btn" title="수정" @click="fnUpdate">수정</button>
                </div>
                <div v-if="pageAuth.delAuthrtYn == 'Y' || mbrId == eduCn.frst_reg_uid" class="gd-1 pr0">
                    <button class="large-btn red-border-btn" title="삭제" @click="fnDelete">삭제</button>
                </div>
            </div>
        </div>
        <!-- 수강일정 등록 모달 -->
        <Modal :showModal="classModal" :className="'large-modal'">
            <template v-slot:header>
                <p class="page-sub-title">일정 등록</p>
                <button class="close-btn" @click="fnModalClose">
                    <svg-icon type="mdi" :path="closePath"></svg-icon>
                </button>
            </template>
            <div class="content flex align-start">
                <div class="gd-4 content">
                    <div class="pd30 border radius content">
                        <div class="pb10 mb10 border-b">
                            <p class="detail-bold">일정</p>
                        </div>
                        <!-- <div class="form-table border-none" style="height: calc(100% - 84.5px);"> -->
                            <div class="form-table border-none overflow-y" style="height: calc(100% - 84.5px);">
                            <div class="input-group">
                                <label for="classDate" class="form-title detail-bold mb10">교육 ・ 행사명</label>
                                <input type="text" name="" id="" class="full-input" placeholder="교육 ・ 행사명을 입력해주세요."
                                    v-model="scheduleOne.edu_cnslt_schdl_ttl" />
                            </div>
                            <div class="input-group">
                                <label for="classDate" class="form-title detail-bold mb10">교육일자</label>
                                <div class="flex align-center no-gutters">
                                    <div class="gd-5"><input type="date" name="" id="" class="full-input"
                                            v-model="scheduleOne.edu_cnslt_bgng_dt"
                                            @change="checkDateValidity('edu_cnslt_bgng_dt', $event)" /></div>
                                    <div class="pd10">-</div>
                                    <div class="gd-5"><input type="date" name="" id="" class="full-input"
                                            v-model="scheduleOne.edu_cnslt_end_dt"
                                            @change="checkDateValidity('edu_cnslt_end_dt', $event)" /></div>
                                </div>
                            </div>
                            <div class="input-group">
                                <label for="classDate" class="form-title detail-bold mb10">교육시간</label>
                                <div class="flex align-center no-gutters">
                                    <div class="gd-5"><input type="time" name="" id="" class="full-input"
                                            placeholder="시작시간" v-model="scheduleOne.edu_cnslt_bgng_hr"
                                            @change="checkDateValidity('edu_cnslt_bgng_hr', $event)" /></div>
                                    <div class="pd10">-</div>
                                    <div class="gd-5"><input type="time" name="" id="" class="full-input"
                                            placeholder="종료시간" v-model="scheduleOne.edu_cnslt_end_hr"
                                            @change="checkDateValidity('edu_cnslt_end_hr', $event)" /></div>
                                </div>
                            </div>
                            <div class="input-group">
                                <label for="classDate" class="form-title detail-bold mb10">정원</label>
                                <div>
                                    <input type="number" name="" id="" class="half-input" 
                                        v-model.number="scheduleOne.edu_cnslt_pscp_cnt"
                                        @input="limitInputValue"/><span
                                        class="small-text ml10">명</span>
                                </div>
                            </div>
                            <div class="input-group">
                                <label for="classDate" class="form-title detail-bold mb10">신청기간</label>
                                <div class="flex align-center no-gutters">
                                    <div class="gd-5"><input type="date" name="" id="" class="full-input"
                                            v-model="scheduleOne.edu_aply_bgng_ymd"
                                            @change="checkDateValidity('edu_aply_bgng_ymd', $event)" /></div>
                                    <div class="pd10">-</div>
                                    <div class="gd-5"><input type="date" name="" id="" class="full-input"
                                            v-model="scheduleOne.edu_aply_end_ymd" 
                                            @change="checkDateValidity('edu_aply_end_ymd', $event)"/></div>
                                </div>
                            </div>
                            <div class="input-group">
                                <label for="classDate" class="form-title detail-bold mb10">공개여부</label>
                                <div class="flex align-center no-gutters">
                                    <div class="gd-4">
                                        <input type="radio" name="notice" id="y" class="mr5" value="Y"
                                            v-model="scheduleOne.rls_yn" />
                                        <label for="y" class="detail-text">공개</label>
                                    </div>
                                    <div class="gd-4">
                                        <input type="radio" name="notice" id="n" class="mr5" value="N"
                                            v-model="scheduleOne.rls_yn" />
                                        <label for="n" class="detail-text">비공개</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="flex justify-end">
                            <div class="gd-3"><button class="large-btn blue-btn" @click="addSchedule()">추가</button>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="gd-8 content">
                    <div class="pd30 border radius content">
                        <div class="pb10 mb10 border-b">
                            <p class="detail-bold">일정 리스트</p>
                        </div>
                        <div class="tablee-zone" style="height: calc(100% - 30.5px);">
                            <table class="list-table admin-list">
                                <colgroup>
                                    <col width="10%" />
                                    <col width="25%" />
                                    <col width="20%" />
                                    <col width="15%" />
                                    <col width="15%" />
                                    <col width="15%" />
                                </colgroup>
                                <thead>
                                    <tr>
                                        <th>NO</th>
                                        <th>일자</th>
                                        <th>시간</th>
                                        <th>정원</th>
                                        <th>공개여부</th>
                                        <th>삭제</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr v-for="(scheduleOne, idx) in insertList" :key="idx">
                                        <td class="text-ct">{{ idx + 1 }}</td>
                                        <td class="text-ct">{{ scheduleOne.edu_cnslt_bgng_dt }} ~ {{
                                            scheduleOne.edu_cnslt_end_dt }}</td>
                                        <td class="text-ct">{{ scheduleOne.edu_cnslt_bgng_hr }} ~ {{
                                            scheduleOne.edu_cnslt_end_hr }}</td>
                                        <td class="text-ct">0/{{ scheduleOne.edu_cnslt_pscp_cnt }}</td>
                                        <td class="text-ct">{{ scheduleOne.rls_yn }}</td>
                                        <td class="text-ct"><button class="large-btn red-border-btn"
                                                @click="removeSchedule(idx)">삭제</button></td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <template v-slot:footer>
                <div class="gd-1 pr0">
                    <button class="large-btn darkg-border-btn ml0" @click="insertCancel()">취소</button>
                </div>
                <div class="gd-1 pr0">
                    <button class="large-btn blue-border-btn ml0" @click="scheduleInsert()">등록</button>
                </div>
            </template>
        </Modal>

        <!-- 수강일정 수정 모달 -->
        <Modal :showModal="classUpdateModal" :className="'medium-modal'">
            <template v-slot:header>
                <p class="page-sub-title">일정 수정</p>
                <button class="close-btn" @click="scheduleUpdateModalCancel()">
                    <svg-icon type="mdi" :path="closePath"></svg-icon>
                </button>
            </template>
            <div class="content">
                <div class="content">
                    <div class="pd30 border radius content overflow-y">
                        <div class="form-table border-none">
                            <div class="input-group">
                                <label for="classDate" class="form-title detail-bold mb10">교육 ・ 행사명</label>
                                <input type="text" name="" id="" class="full-input" placeholder="교육 ・ 행사명을 입력해주세요."
                                    v-model="scheduleOne.edu_cnslt_schdl_ttl" />
                            </div>
                            <div class="input-group">
                                <label for="classDate" class="form-title detail-bold mb10">일자</label>
                                <div class="flex align-center no-gutters">
                                    <div class="gd-5"><input type="date" name="" id="" class="full-input"
                                            v-model="scheduleOne.edu_cnslt_bgng_dt"
                                            @change="checkDateValidity('edu_cnslt_bgng_dt', $event)" /></div>
                                    <div class="pd10">-</div>
                                    <div class="gd-5"><input type="date" name="" id="" class="full-input"
                                            v-model="scheduleOne.edu_cnslt_end_dt"
                                            @change="checkDateValidity('edu_cnslt_end_dt', $event)" /></div>
                                </div>
                            </div>
                            <div class="input-group">
                                <label for="classDate" class="form-title detail-bold mb10">시간</label>
                                <div class="flex align-center no-gutters">
                                    <div class="gd-5"><input type="time" name="" id="" class="full-input"
                                            placeholder="시작시간" v-model="scheduleOne.edu_cnslt_bgng_hr"
                                            @change="checkDateValidity('edu_cnslt_bgng_hr', $event)" /></div>
                                    <div class="pd10">-</div>
                                    <div class="gd-5"><input type="time" name="" id="" class="full-input"
                                            placeholder="종료시간" v-model="scheduleOne.edu_cnslt_end_hr"
                                            @change="checkDateValidity('edu_cnslt_end_hr', $event)" /></div>
                                </div>
                            </div>
                            <div class="input-group">
                                <label for="classDate" class="form-title detail-bold mb10">정원</label>
                                <div>
                                    <input type="number" name="" id="" class="half-input" 
                                        v-model.number="scheduleOne.edu_cnslt_pscp_cnt"
                                        @input="limitInputValue"/><span
                                        class="small-text ml10">명</span>
                                </div>
                            </div>
                            <div class="input-group">
                                <label for="classDate" class="form-title detail-bold mb10">신청기간</label>
                                <div class="flex align-center no-gutters">
                                    <div class="gd-5"><input type="date" name="" id="" class="full-input"
                                            v-model="scheduleOne.edu_aply_bgng_ymd"
                                            @change="checkDateValidity('edu_aply_bgng_ymd', $event)" /></div>
                                    <div class="pd10">-</div>
                                    <div class="gd-5"><input type="date" name="" id="" class="full-input"
                                            v-model="scheduleOne.edu_aply_end_ymd" 
                                            @change="checkDateValidity('edu_aply_end_ymd', $event)"/></div>
                                </div>
                            </div>
                            <div class="input-group">
                                <label for="classDate" class="form-title detail-bold mb10">공개여부</label>
                                <div class="flex align-center no-gutters">
                                    <div class="gd-4">
                                        <input type="radio" name="notice" id="y" class="mr5" value="Y"
                                            v-model="scheduleOne.rls_yn" />
                                        <label for="y" class="detail-text">공개</label>
                                    </div>
                                    <div class="gd-4">
                                        <input type="radio" name="notice" id="n" class="mr5" value="N"
                                            v-model="scheduleOne.rls_yn" />
                                        <label for="n" class="detail-text">비공개</label>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <template v-slot:footer>
                <div class="gd-2 pr0">
                    <button class="large-btn darkg-border-btn ml0" @click="scheduleUpdateModalCancel()">취소</button>
                </div>
                <div class="gd-2 pr0">
                    <button class="large-btn blue-border-btn ml0" @click="scheduleUpdate()">수정</button>
                </div>
            </template>
        </Modal>

        <!-- 개인정보 확약 문구 -->
        <Modal :showModal="terms" :className="'auto-height'" >
            <template v-slot:header>
                <p class="page-sub-title">개인정보 수집·이용 동의(선택)</p>
                <button class="close-btn" @click="modalClose" title="닫기">
                    <svg-icon type="mdi" :path="closePath"></svg-icon>
                </button>
            </template>
            <div class="border overflow-y pd30 mb5">
                <ul>
                    <li class=" mb10">
                        <p class="detail-text">1. 개인정보의 수집·이용 목적 : AI 디지털교과서 통합지원센터 추후 <span class="border-b">기술지원 신청 및
                                안내</span> </p>
                    </li>
                    <li class=" mb10">
                        <p class="detail-text mb5">2. 수집하는 개인정보의 항목 :</p>
                        <table class="terms-table border">
                            <colgroup>
                                <col width="30%">
                                <col width="70%">
                            </colgroup>
                            <thead>
                                <tr>
                                    <th rowspan="2" class="text-ct detail-text">회원유형</th>
                                    <th class="text-ct">개인정보항목</th>
                                </tr>
                                <tr>
                                    <th class="text-ct">선택 항목</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td class="text-ct detail-bold">기업회원</td>
                                    <td>
                                        <ul>
                                            <li>⦁이름, 연락처, 이메일, 기업명</li>
                                        </ul>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </li>
                    <li class=" mb10">
                        <p class="detail-text">3. 개인정보의 처리 및 보유기간 : <span class="border-b admin-sec-title">2년</span>
                        </p>
                    </li>
                    <li class=" mb10">
                        <p class="detail-text">4. 개인정보의 활용 동의를 거부하시더라도 회원가입 및 서비스 이용의 제한은 없습니다.<br /> 다만, AI 디지털교과서
                            통합지원센터의 기술
                            교육 신청 시 신청정보를 추가로 요구할 수 있습니다. </p>
                    </li>
                </ul>
            </div>
            <div class="flex align-center">
                <input type="checkbox" name="" id="privacy" v-model="isPrvsRlsAgree" />
                <label for="privacy" class="detail-text ml5"> 개인정보 수집 및 이용에 동의합니다.</label>
            </div>
            <template v-slot:footer>
                <div class="gd-2 pr0">
                    <button class="large-btn darkg-border-btn ml0" title="취소" @click="modalClose()">취소</button>
                </div>
                <div class="gd-2 pr0">
                    <button class="large-btn blue-border-btn ml0" title="완료" @click="agreeAndApply()">완료</button>
                </div>
            </template>
        </Modal>

        <!-- 관리자만 수강신청 할 수 있을때 모달 -->
        <Modal :showModal="companyUserModal" :className="'medium-modal auto-height'">
            <template v-slot:header>
                <p class="page-sub-title">교육 ・ 컨설팅 신청</p>
                <button class="close-btn" @click="modalClose" title="닫기">
                    <svg-icon type="mdi" :path="closePath"></svg-icon>
                </button>
            </template>
            <table class="form-table border-none">
                <tbody>
                    <tr>
                        <td>
                            <label for="" class="form-title block mb10">교육 ・ 컨설팅 신청서</label>
                            <Attachment @emitFileList="emitFileList" :text="'파일을 첨부해주세요'" />
                        </td>
                    </tr>
                </tbody>
            </table>
            <template v-slot:footer>
                <div class="gd-2 pr0">
                    <button class="large-btn darkg-border-btn ml0" title="취소" @click="modalClose()">취소</button>
                </div>
                <div class="gd-2 pr0">
                    <button class="large-btn blue-border-btn ml0" title="완료" @click="fnSave()">완료</button>
                </div>
            </template>
        </Modal>
    </div>
</template>

<script>
import PaginationButton from '../../../component/pagination/PaginationButton.vue';
import axios from "axios";
import Modal from '../../../component/modal/Modal.vue';
import queryParams from '../../../../resources/js/queryParams.js';
import PageNavigationBar from '../../../component/pagenavigationbar/PageNavigationBar.vue';
import Attachment from '../../../component/file/Attachment.vue';
import { mdiWindowClose, mdiCellphone, mdiEmail, mdiAccount, mdiMapMarker, mdiTooltipQuestion, mdiCloseBox, mdiFileDownloadOutline, mdiCalendarBlank, mdiAccountMultiple, mdiCalendarBlankMultiple, mdiFileOutline, mdiLockCheckOutline, mdiAccountStar } from '@mdi/js';

//API
import { findByEduId, updateVwCnt, deleteProc, deleteMySchedule } from '../../../../resources/api/eduCn.js'
import { saveProc, findAll, updateProc, deleteSchedule } from '../../../../resources/api/eduSchedule.js'
export default {
    mixins: [queryParams],
    components: {
        'PaginationButton': PaginationButton,
        'PageNavigationBar': PageNavigationBar,
        'Modal': Modal,
        'Attachment': Attachment
    },
    data() {
        return {
            tabList: [{ id: 1, tabName: "신청" }, { id: 2, tabName: "상세" }, { id: 3, tabName: "신청자 리스트" }],
            role: this.$store.state.roles,
            path: this.$store.state.path,
            authrtTypeLvl: this.$store.state.authrtTypeLvl,
            pageAuth: this.$store.state.pageAuth,
            downloadPath: mdiFileDownloadOutline,
            viewTab: 1,
            privacy: false,
            terms: false,
            classUpdateModal: false,//수정모달
            companyManager: 'Y',
            companyUserModal: false,
            closePath: mdiWindowClose,
            emailPath: mdiEmail,
            phonePath: mdiCellphone,
            userPath: mdiAccount,
            inquiryPath: mdiTooltipQuestion,
            markPath: mdiMapMarker,
            boxPath: mdiCloseBox,
            periodPath: mdiCalendarBlankMultiple,
            schedulePath: mdiCalendarBlank,
            peoplePath: mdiAccountMultiple,
            filePath: mdiFileOutline,
            lockPath: mdiLockCheckOutline,
            masterPath: mdiAccountStar,
            classModal: false,
            bannerId: 'guide-banner',


            //세현추가
            eduCn: {},
            minMax: {},
            //첨부파일 목록
            fileList: [],
            //이미지 목록
            imgFileList: [],
            errorImages: new Set(),
            //일정 목록
            scheduleList: [],
            scheduleOne: {},
            tempScheduleOne: {},
            //추가할 일정 목록
            insertList: [],
            //약관 동의 여부
            isPrvsRlsAgree: false,
            //일정 참여자 목록
            memberList: [],
            //파일 업로드
            files: null,
            // 네비데이터 초기화
            naviData: {},

        }
    },
    created() {
        this.fnIdExtraction();
        this.updateVwCnt();
        this.fnSelectOne();
    },
    methods: {
        showTab(tabId) {
            this.viewTab = tabId
        },
        showModal(scheduleOne) {
            this.terms = true;
            this.tempScheduleOne = scheduleOne;
        },
        fnModalClose() {
            if (this.terms) {
                this.privacy = false;
                this.terms = false;
            } else if (this.companyUserModal) {
                this.companyUserModal = false;
            } else if (this.classModal) {
                this.classModal = false;
            }
        },
        goStep() {
            this.terms = false;
            this.companyUserModal = true;
        },
        classAdd() {
            this.classModal = true;
        },
        toggleEmployee(employee) {
            const index = this.selectedEmployees.findIndex(e => e.id === employee.id);
            if (index === -1) {
                this.selectedEmployees.push(employee);
            } else {
                this.selectedEmployees.splice(index, 1);
            }
        },
        removeEmployee(employee) {
            const index = this.selectedEmployees.findIndex(e => e.id === employee.id);
            if (index !== -1) {
                this.selectedEmployees.splice(index, 1);
            }
        },
        isSelected(employee) {
            return this.selectedEmployees.some(e => e.id === employee.id);
        },


        /******************************* 세현 *******************************/
        limitInputValue(event) {
            const value = event.target.value;
            if (value > 10000) {
               this.scheduleOne.edu_cnslt_pscp_cnt = 10000;
            } else if (value < 0) {
                this.scheduleOne.edu_cnslt_pscp_cnt = 0;
            }
        },

        modalClose() {
            this.isPrvsRlsAgree = false;
            this.fnModalClose()
        },
        //수강 일정 등록 취소
        insertCancel() {
            if (!confirm(this.$getCmmnMessage("cnf008", "등록을 "))) return
            //1. insertList 비우기
            this.insertList = []
            //2. 일정 객체 비우기
            for (let key in this.scheduleOne) {
                if (this.scheduleOne.hasOwnProperty(key)) {
                    this.scheduleOne[key] = null;
                }
            }
            this.fnModalClose()
        },

        //일정 추가 버튼 클릭
        addSchedule() {
            //1. 유효성검사
            if (!this.validateSchedule()) return
            //2. 교육PK 추가
            this.scheduleOne.edu_cnslt_id = this.pageId
            //2. insertList에 추가
            this.insertList.push({ ...this.scheduleOne });
            //3. input 비워주기
            for (let key in this.scheduleOne) {
                if (this.scheduleOne.hasOwnProperty(key)) {
                    this.scheduleOne[key] = null;
                }
            }
        },

        //수강 일정 삭제
        removeSchedule(idx) {
            this.insertList.splice(idx, 1);
        },

        //일정 추가 유효성 검사
        validateSchedule() {
            if (this.$isEmpty(this.scheduleOne.edu_cnslt_schdl_ttl)) {
                alert("교육행사명을 입력해주세요.")
                return false;
            }

            if (this.$isEmpty(this.scheduleOne.edu_cnslt_bgng_dt)) {
                alert("교육 시작 일자를 입력해주세요.");
                return false;
            }

            if (this.$isEmpty(this.scheduleOne.edu_cnslt_end_dt)) {
                alert("교육 종료 일자를 입력해주세요.");
                return false;
            }

            if (this.$isEmpty(this.scheduleOne.edu_cnslt_bgng_hr)) {
                alert("교육 시작 시간을 입력해주세요.");
                return false;
            }

            if (this.$isEmpty(this.scheduleOne.edu_cnslt_end_hr)) {
                alert("교육 종료 시간을 입력해주세요.");
                return false;
            }

            if (this.$isEmpty(this.scheduleOne.edu_cnslt_pscp_cnt)) {
                alert("교육 정원을 입력해주세요.");
                return false;
            }

            if (!/^\d+$/.test(this.scheduleOne.edu_cnslt_pscp_cnt)) {
                alert("교육 정원은 숫자만 입력 가능합니다.");
                return false;
            }

            if (parseInt(this.scheduleOne.edu_cnslt_pscp_cnt) <= 0) {
                alert("유효한 교육 정원을 입력해주세요.");
                return false;
            }

            if (parseInt(this.scheduleOne.edu_cnslt_pscp_cnt) >= 10000) {
                alert("유효한 교육 정원을 입력해주세요.");
                return false;
            }


            //신청 시작 일자
            if (this.$isEmpty(this.scheduleOne.edu_aply_bgng_ymd)) {
                alert("신청 시작일자를 입력해주세요.")
                return false;
            }

            //신청 종료 일자
            if (this.$isEmpty(this.scheduleOne.edu_aply_end_ymd)) {
                alert("신청 종료일자를 입력해주세요.")
                return false;
            }

            //공개 여부
            if (this.$isEmpty(this.scheduleOne.rls_yn)) {
                alert("공개 여부를 선택해주세요.");
                return false;
            }
            const eduCnsltBgngDt = new Date(this.scheduleOne.edu_cnslt_bgng_dt);
            const eduAplyEndYmd = new Date(this.scheduleOne.edu_aply_end_ymd);

            if (eduCnsltBgngDt < eduAplyEndYmd) {
                alert("교육 시작일자 보다 신청 종료일자를 늦게 설정하실 수 없습니다.");
                return false;
            }
            return true
        },


        // 상세조회
        async fnSelectOne() {
            try {
                const params = { 'edu_cnslt_id': this.pageId }
                this.$setLoading(true);
                const res = await findByEduId(params);
                if (res.status == 200) {
                    this.eduCn = res.data.data.eduCn;
                    this.fileList = res.data.data.fileList;
                    this.imgFileList = res.data.data.imgFileList;
                    this.scheduleList = res.data.data.scheduleList;
                    this.minMax = res.data.data.minMax;
                    // this.isPrvsRlsAgree = res.data.data.isPrvsRlsAgree;

                    if (this.eduCn.frst_reg_uid == this.$store.state.mbrId) {
                        return;
                    }

                    if (this.pageAuth.rdAuthrtYn != 'Y') {
                        alert("조회 권한이 없습니다.");
                        this.fnList();
                    }
                }
            } catch (error) {
                // alert('에러가 발생했습니다.\n시스템관리자에게 문의하세요.');
                alert(this.$getCmmnMessage('err005'));
            } finally {
                this.$setLoading(false);
            }
        },

        //일정 등록
        async scheduleInsert() {
            if (this.insertList.length === 0) {
                alert("등록된 일정이 없습니다.")
                return;
            }
            if (!confirm(this.$getCmmnMessage("cnf003", "해당 일정을 "))) return
            // 데이터 세팅
            const data = this.insertList;
            // 실행
            try {
                const res = await saveProc(data);
                alert(res.data.message);
                if (res.status == 200) {
                    this.fnSelectOne()
                    this.fnModalClose()
                    
                    this.insertList = []
                    for (let key in this.scheduleOne) {
                        if (this.scheduleOne.hasOwnProperty(key)) {
                            this.scheduleOne[key] = null;
                        }
                    }
                }
            } catch (error) {
                console.log("axiosInsert error: ", error);
            }
        },

        // 조회수 증가
        async updateVwCnt() {
            try {
                const params = {
                    'edu_cnslt_id': this.pageId,
                }
                const res = await updateVwCnt(params);
            } catch (error) {
                // alert('에러가 발생했습니다.\n시스템관리자에게 문의하세요.');
                alert(this.$getCmmnMessage('err005'));
            }
        },

        // 파일사이즈
        formatFileSize: function (size) {
            const units = ['B', 'KB', 'MB', 'GB', 'TB'];
            let i;

            // 파일 크기를 적절한 단위로 변환
            for (i = 0; size >= 1024 && i < units.length - 1; i++) {
                size /= 1024;
            }

            // 파일 크기와 단위를 문자열로 반환
            if (i === units.length - 1) {
                return `${size.toFixed(2)} ${units[i]}`;
            } else {
                return `${size.toFixed(2)} ${units[i]}`;
            }
        },

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

        // 교육일자, 교육시간 유효성 체크
        checkDateValidity(changeType, event) {
            const val = event.target.value; // 변경된 값

            // 날짜 유효성 체크
            if (changeType === 'edu_cnslt_bgng_dt') {
                if (this.scheduleOne.edu_cnslt_end_dt !== null && this.scheduleOne.edu_cnslt_end_dt < val) {
                    alert('시작일은 종료일보다 클 수 없습니다.');
                    this.scheduleOne.edu_cnslt_bgng_dt = null; // 유효하지 않은 경우, 시작일을 초기화
                } else {
                    this.scheduleOne.edu_cnslt_bgng_dt = val;
                }
            } else if (changeType === 'edu_cnslt_end_dt') {
                if (this.scheduleOne.edu_cnslt_bgng_dt !== null && this.scheduleOne.edu_cnslt_bgng_dt > val) {
                    alert('종료일은 시작일보다 작을 수 없습니다.');
                    this.scheduleOne.edu_cnslt_end_dt = null; // 유효하지 않은 경우, 종료일을 초기화
                } else {
                    this.scheduleOne.edu_cnslt_end_dt = val;
                }
            }

            // 시간 유효성 체크 (시작일과 종료일이 같은 경우)
            else if (changeType === 'edu_cnslt_bgng_hr') {
                if (this.scheduleOne.edu_cnslt_bgng_dt === this.scheduleOne.edu_cnslt_end_dt) {
                    if (this.scheduleOne.edu_cnslt_end_hr !== null && this.scheduleOne.edu_cnslt_end_hr < val) {
                        alert('시작시간은 종료시간보다 클 수 없습니다.');
                        this.scheduleOne.edu_cnslt_bgng_hr = null; // 유효하지 않은 경우, 시작시간을 초기화
                    } else {
                        this.scheduleOne.edu_cnslt_bgng_hr = val;
                    }
                } else {
                    this.scheduleOne.edu_cnslt_bgng_hr = val; // 날짜가 다르면 시간만 설정
                }
            } else if (changeType === 'edu_cnslt_end_hr') {
                if (this.scheduleOne.edu_cnslt_bgng_dt === this.scheduleOne.edu_cnslt_end_dt) {
                    if (this.scheduleOne.edu_cnslt_bgng_hr !== null && this.scheduleOne.edu_cnslt_bgng_hr > val) {
                        alert('종료시간은 시작시간보다 작을 수 없습니다.');
                        this.scheduleOne.edu_cnslt_end_hr = null; // 유효하지 않은 경우, 종료시간을 초기화
                    } else {
                        this.scheduleOne.edu_cnslt_end_hr = val;
                    }
                } else {
                    this.scheduleOne.edu_cnslt_end_hr = val; // 날짜가 다르면 시간만 설정
                }
            } else if (changeType === 'edu_aply_bgng_ymd') {
                if (this.scheduleOne.edu_aply_end_ymd !== null && this.scheduleOne.edu_aply_end_ymd < val) {
                    alert('신청 시작일은 신청 종료일보다 클 수 없습니다.');
                    this.scheduleOne.edu_aply_bgng_ymd = null; // 유효하지 않은 경우, 시작일을 초기화
                } else {
                    this.scheduleOne.edu_aply_bgng_ymd = val;
                }
            } else if (changeType === 'edu_aply_end_ymd') {
                if (this.scheduleOne.edu_aply_bgng_ymd !== null && this.scheduleOne.edu_aply_bgng_ymd > val) {
                    alert('신청 종료일은 신청 시작일보다 작을 수 없습니다.');
                    this.scheduleOne.edu_aply_end_ymd = null; // 유효하지 않은 경우, 종료일을 초기화
                } else {
                    this.scheduleOne.edu_aply_end_ymd = val;
                }
            }
        },

        //unix -> date 변환
        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}`;
        },

        formatDateRange(startTimestamp, endTimestamp) {
            const startDate = this.formatUnixToDate(startTimestamp);
            const endDate = this.formatUnixToDate(endTimestamp);
            if (startDate === endDate) {
                return startDate;
            } else {
                return `${startDate} ~ ${endDate}`;
            }
        },

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

        yyyymmdd(dateStr) {
            const year = dateStr.substring(0, 4);
            const month = dateStr.substring(4, 6);
            const day = dateStr.substring(6, 8);
            // 원하는 형식으로 조합
            return `${year}-${month}-${day}`;
        },

        fnList() {
            this.$router.push({
                path: this.path + '/list.page'
            });
        },

        fnUpdate() {
            this.$router.push({
                path: this.path + '/insert.page', query: { 'pageId': this.eduCn.edu_cnslt_id }
            });
        },

        // 삭제
        async fnDelete() {
            if (!confirm(this.$getCmmnMessage("cnf002"))) return

            // 데이터 세팅
            const data = this.eduCn
            try {
                const res = await deleteProc(data);
                alert(this.$getCmmnMessage('msg003'));
                this.fnList();
            } 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'));
                }
            }
        },

        // 첨부파일 등록
        fnFileInsert() {
            // files 개수 만큼 반복해서 type, size 체크
            this.files = this.$refs.file.files;
            for (let i = 0; i < this.files.length; i++) {
                const file = this.files[i];
                const extnNm = file.name.split('.').pop().toLowerCase();

                if (extnNm === 'exe') {
                    alert('exe 파일은 첨부할 수 없습니다.')
                    return;
                }

            }

            this.fileList = [...this.fileList, ...Array.from(this.files)];
        },

        agreeAndApply() {
            this.applySchedule(this.tempScheduleOne)
        },

        // 기업관리자 여부 확인
        isCoManager() {
            return this.role.some(role => role.authority === 'ROLE_CO_MANAGER');
        },
        // KERIS관리자 여부 확인
        isAdmin() {
            return this.role.some(role => role.authority === 'ROLE_ADMIN');
        },
        //기술신청 클릭 
        applySchedule(scheduleOne) {
            if (!this.isCanApplyPeriod(scheduleOne)) {
                alert("신청 기간이 아닙니다.")
                return;
            }
            //1. 해당 기술신청의 관리자전용 유무 확인
            const forCoManager = this.eduCn.ent_mngr_yn == 'Y' ? true : false
            //2. 사용자의 권한 검사 및 검증
            const isCoManager = this.isCoManager()
            if (forCoManager && !isCoManager) {
                alert("기업관리자 전용 일정입니다.")
                return
            }

            // //3. 사용자의 약관 동의 여부 파악 및 미동의 시 약관 동의 팝업 표출
            if (!this.isPrvsRlsAgree) {
                //이미 showModal이 활성화 된 경우
                if (this.terms) {
                    alert('개인정보 수집ㆍ이용 동의는 필수입니다.');
                    return
                }
                this.showModal(scheduleOne)
                return
            }
            //4. 사용자 권한에 따라 기업회원이면 바로 신청요청, 기업관리자면 파일업로드 팝업 표출
            if (isCoManager) {
                this.goStep()
                return
            }

            //5. 기술 일정 신청 API
            this.fnSave()

        },

        //기술 일정 신청
        async fnSave() {
            const vm = this;

            if (!this.validateCoManager()) return;

            // 폼데이터 생성
            var formData = new FormData();
            formData.append("scheduleInfo", JSON.stringify(this.tempScheduleOne));

            if (this.isCoManager()) {
                if ((this.files)) {
                    for (const file of this.files) {
                        formData.append("file", file);
                    }
                }
            }

            // axios 호출
            this.$setLoading(true);
            await axios({
                url: "/edu/schdl/ptcp/save.file",
                method: "post",
                headers: {
                    "Content-Type": "multipart/form-data; charset=UTF-8",
                    Authorization: this.$store.state.authorization,
                },
                data: formData,
            }).then((res) => {
                if (res.status === 200) {
                    alert(res.data.message);
                    if (res.data.success) {
                        vm.fnSelectOne()
                        vm.modalClose()
                        vm.tempScheduleOne = null;
                    }
                }

            }).catch((error) => {
                const errorData = error.response.data;
                if (errorData.message != null && errorData.message != "") {
                    alert(error.response.data.message);
                } else {
                    // alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
                    alert(vm.$getCmmnMessage('err005'));
                }
            }).finally(function () {
                vm.$setLoading(false);
            });
        },

        //파일 컴포넌트에서 파일 리스트 받기
        emitFileList: function (files) {
            const vm = this;
            this.files = files;
        },

        //기업관리자 유효성 검사
        validateCoManager() {
            const isCoManager = this.isCoManager();

            // 기업관리자인 경우 파일이 있는지 확인
            if (this.eduCn.atch_file_esntl_yn === 'Y') {
                if (isCoManager && (this.files === null || this.files.length === 0)) {
                    alert('파일을 업로드 해주세요.');
                    return false;
                }
            }

            return true;
        },

        //해당 기술교육 일정의 참가자 목록 조회
        async ptcpFindAll(item) {
            try {
                const res = await findAll(item);
                if (!item.memberList) {
                    item.memberList = []; // memberList가 없을 경우 초기화
                }
                item.memberList = res.data.data;
            } catch (error) {
                console.log(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);
            }
        },

        //신청자 삭제
        async fnDeleteMember(member, item) {
            if (!confirm(this.$getCmmnMessage('cnf002'))) return

            try {
                const res = await deleteMySchedule(member);
                if (res.status == 200) {
                    alert(res.data.message)
                    if (res.data.success) {
                        this.ptcpFindAll(item)
                    }
                }

            } 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'));
                }
            }
        },

        //일정 수정 모달 표출
        scheduleUpdateModal(item) {
            this.classUpdateModal = true
            this.scheduleOne = _.cloneDeep(item);

            this.scheduleOne.edu_cnslt_bgng_dt = this.formatUnixToDate(this.scheduleOne.edu_cnslt_bgng_dt)
            this.scheduleOne.edu_cnslt_end_dt = this.formatUnixToDate(this.scheduleOne.edu_cnslt_end_dt)
            this.scheduleOne.edu_cnslt_bgng_hr = this.formatTime(this.scheduleOne.edu_cnslt_bgng_hr)
            this.scheduleOne.edu_cnslt_end_hr = this.formatTime(this.scheduleOne.edu_cnslt_end_hr)
            this.scheduleOne.edu_aply_bgng_ymd = this.yyyymmdd(this.scheduleOne.edu_aply_bgng_ymd)
            this.scheduleOne.edu_aply_end_ymd = this.yyyymmdd(this.scheduleOne.edu_aply_end_ymd)
        },

        //일정 수정 모달 닫기
        scheduleUpdateModalCancel() {
            if (!confirm(this.$getCmmnMessage("cnf008", "해당 기술일정 수정을 "))) return
            this.classUpdateModal = false
            for (let key in this.scheduleOne) {
                if (this.scheduleOne.hasOwnProperty(key)) {
                    this.scheduleOne[key] = null;
                }
            }
        },

        //기술 일정 수정
        async scheduleUpdate() {
            if (!confirm(this.$getCmmnMessage("cnf004", "해당 기술일정을 "))) return
            if (!this.validateSchedule()) return

            try {
                const res = await updateProc(this.scheduleOne);
                if (res.status == 200) {
                    alert(res.data.message)
                    if (res.data.success) {
                        this.fnSelectOne()
                        this.classUpdateModal = false
                        for (let key in this.scheduleOne) {
                            if (this.scheduleOne.hasOwnProperty(key)) {
                                this.scheduleOne[key] = null;
                            }
                        }
                    }
                }
            } 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'));
                }
            }
        },

        //기술 일정 삭제
        async scheduleDelete(item) {
            if (!confirm(this.$getCmmnMessage("cnf002", "해당 기술일정을 "))) return

            try {
                const res = await deleteSchedule(item);
                if (res.status == 200) {
                    alert(res.data.message)
                    this.fnSelectOne()
                }
            } 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'));
                }
            }
        },

        isCanApplyPeriod(scheduleOne) {
            const currentDate = new Date();
            // edu_aply_bgng_ymd를 Date 객체로 변환
            const eduAplyBgngYmd = new Date(scheduleOne.edu_aply_bgng_ymd.substring(0, 4) + '-' + scheduleOne.edu_aply_bgng_ymd.substring(4, 6) + '-' + scheduleOne.edu_aply_bgng_ymd.substring(6, 8) + 'T00:00:00');
            // edu_aply_end_ymd를 Date 객체로 변환하고 시간을 23시 59분 59초로 설정
            const eduAplyEndYmd = new Date(scheduleOne.edu_aply_end_ymd.substring(0, 4) + '-' + scheduleOne.edu_aply_end_ymd.substring(4, 6) + '-' + scheduleOne.edu_aply_end_ymd.substring(6, 8) + 'T23:59:59');
            return currentDate >= eduAplyBgngYmd && currentDate <= eduAplyEndYmd;
        },
    },
    watch: {
        $route(to, from) {
            // path가 다를 때만 조회
            if (to.path !== from.path) {
                this.fnBbsIdExtraction();
                this.resotreQueryParams('queryParams');
                this.fnSelectOne();
            }
        }

    },
    computed: {},
    mounted() {
        this.naviData = { 'main': '기술지원', 'sub': '교육 ・ 컨설팅' };

    }
}
</script>
