<template>
    <div class="content">
        <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">{{ $getMenuInfo().menuNm }}</h1>
                <p class="box-title text-ct white">{{ $getMenuInfo().menuCn }}</p>
            </div>
        </div>
        <PageNavigationBar :navi="naviData" />
        <div :class="{'pt100 pb100 user-page':true,'flex-column justify-center' :myInfoUpdate&&innerStep === 0}" style="min-height: calc(100vh - 595px);">
            <div class="w1280">
                <!----------------------------------------------- 내정보 조회 화면 ------------------------------------------------>
                <div class="selectlist-zone" v-if="myInfo.mbr_encpt_flnm && !myInfoUpdate">
                    <div class="mb25">
                        <h2 class="page-sub-title">나의 정보</h2>
                    </div>
                    <!-- 일반회원 마이페이지 -->
                    <div v-if="myInfo.authrt_id === 'ROLE_USER' || myInfo.authrt_id === 'ROLE_CO_USER' || myInfo.authrt_id === 'ROLE_CO_MANAGER'">
                        <div class="border pd30 mb30">
                            <div class="mb15">
                                <div class="flex justify-start align-center mb10">
                                    <p class="content-title2">{{ myInfo.mbr_encpt_flnm }} <span v-if="myInfo.mbr_jbgd_nm">({{
                                            myInfo.mbr_jbgd_nm }})</span></p>
                                    <p class="pl5 pr5">&#183;</p>
                                    <p class="detail-text">{{ myInfo.lgn_id }}</p>
                                </div>
                            </div>
                            <div class="conpany-info mb25">
                                <div class=" flex justify-start align-center pt15 pb10">
                                    <div class="gd-4">
                                        <span class="detail-bold mr15">회원유형</span>
                                        <span class="detail-text">{{ myInfo.authrt_nm }}</span>
                                    </div>
                                    <!-- 일반회원일 경우 권한 안보임 -->
                                    <div class="gd-4" v-if="myInfo.ent_nm">
                                        <span class="detail-bold mr15">기업명</span>
                                        <span class="detail-text">{{ myInfo.ent_nm }}</span>
                                    </div>
                                    <div class="gd-4">
                                        <span class="detail-bold mr15">구독서비스</span>
                                        <span class="detail-text" v-if="myInfo.rcptn_agre_yn == 'Y'">구독 중</span>
                                        <span class="detail-text" v-else>구독안함</span>
                                    </div>
                                </div>
                                <div class="flex justify-start align-center pt10 pb15">
                                    <div class="gd-4">
                                        <span class="detail-bold mr15">전화번호</span>
                                        <span class="detail-text">{{ hyphenMinus(myInfo.mbr_encpt_telno) }}</span>
                                    </div>
                                    <div class="gd-4">
                                        <span class="detail-bold mr15">이메일</span>
                                        <span class="detail-text">{{ myInfo.mbr_encpt_emad }}</span>
                                    </div>
                                </div>
                            </div>
                            <div class="download-zone" v-if="myInfo.file_nm">
                                <div class="company-profile mb25">
                                    <div class="mb10">
                                        <h3 class="content-title2">재직증명서 첨부파일</h3>
                                    </div>
                                    <div class="download-item border flex justify-between align-center pd10">
                                        <p class="ellipsis gd-10">{{ myInfo.file_nm }}.{{myInfo.extn_nm }}</p>
                                        <div class="flex align-center justify-end gd-2">
                                            <button class="icon-btn" aria-label="pdfPreviewButton" id="pdfPreviewButton" title="미리보기" @click="$openPdfViewrWindwow(myInfo.file_id, pageAuth)"> <svg-icon type="mdi" :path="pdfPath" role="img"  aria-labelledby="pdfPreviewButton"></svg-icon></button>
                                            <!-- <button class="icon-btn" title="다운로드"  @click="downloadFile(myInfo)"><svg-icon type="mdi" :path="downloadPath"></svg-icon></button> -->
                                        </div>                           
                                    </div>
                                    <!-- <div class="download-item border flex justify-between align-center pd10">
                                        <p class="detail-text">{{ myInfo.file_nm }}</p>
                                        <div @click="downloadFile(myInfo)">
                                            <span class="mr10 detail-text">다운로드</span>
                                            <button class="icon-btn"><img
                                                    src="../../../../resources/img/download.png" alt=""></button>
                                        </div>
                                    </div> -->
                                </div>
                            </div>
                            <div class="btn-zone flex justify-end">
                                <div class="gd-1 pl0 pr0">
                                    <button class="large-btn blue-btn ml0" title="수정" @click="userUpdatePage()">수정하기</button>
                                </div>
                            </div>
                        </div>

                        <!-- 신청존 -->
                        <div v-if="myInfo.aprv_aply_stts_cd == 'request' || myInfo.aprv_aply_stts_cd == 'reject' " >
                            <div class="mb25">
                                <h3 class="page-sub-title">신청정보</h3>
                            </div>
                            <div class="table-zone">
                                <table class="list-table application-info-table">
                                    <colgroup>
                                        <col width="20%">
                                        <col width="20%">
                                        <col width="15%">
                                        <col width="15%">
                                        <col width="10%">
                                        <col width="20%">
                                    </colgroup>
                                    <thead>
                                        <tr>
                                            <th>기업명</th>
                                            <th>신청내용</th>
                                            <th>신청일자</th>
                                            <th>반려일자</th>
                                            <th>상태</th>
                                            <th>반려내용</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <tr>
                                            <td  v-if="myInfo.aprv_aply_stts_cd == 'request'" class="text-ct">{{ myInfo.ent_nm }}</td>
                                            <td  v-if="myInfo.aprv_aply_stts_cd == 'reject'" class="text-ct">{{ myInfo.last_ent }}</td>
                                            <td class="text-ct">{{ myInfo.rprs_yn === 'Y' ? '기업관리자' : '기업회원' }} 신청</td>
                                            <td>
                                                <p  v-if="myInfo.aprv_aply_stts_cd == 'request'" class="text-ct">{{  $formatUnixToDate(myInfo.request_dt) }}</p>
                                                <p v-else class="text-ct">-</p>
                                            </td>
                                            
                                            <td>
                                                <p v-if="myInfo.aprv_aply_stts_cd == 'reject'" class="text-ct">{{ $formatUnixToDate(myInfo.reject_dt) }}</p>
                                                <p v-else class="text-ct">-</p>
                                            </td>
                                            <td>
                                                <p v-if="myInfo.aprv_aply_stts_cd == 'request'" class="text-ct">처리중</p>
                                            <p v-if="myInfo.aprv_aply_stts_cd == 'reject'" class="text-ct">반려</p>
                                            </td>
                                            <td >
                                                <p v-if="myInfo.aprv_aply_stts_cd == 'reject'" class="text-ct">{{ myInfo.rjct_cn }}</p>
                                                <p v-else class="text-ct">-</p>
                                            </td>

                                        </tr>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                    <!-- 영역별 담당자 및 관리자 -->
                    <div class="border pd30 mb30" v-else>
                        <div class="mb15">
                            <div class="flex justify-start align-center mb10">
                                <!-- 이름 -->
                                <p class="content-title2">{{ myInfo.mbr_encpt_flnm }} <span
                                        v-if="myInfo.mbr_jbgd">({{ myInfo.mbr_jbgd_nm }})</span></p>
                                <p class="pl5 pr5">&#183;</p>
                                <!-- 아이디 -->
                                <p class="detail-text">{{ myInfo.lgn_id }}</p>
                            </div>
                        </div>
                        <div class="conpany-info mb25">
                            <div class=" flex justify-start align-center pt15 pb10">
                                <!-- <div class="gd-4">
                                    <span class="detail-bold mr15">회원유형</span>
                                    <span class="detail-text">{{ myInfo.authrt_nm }}</span>
                                </div> -->
                                <div class="gd-4" v-if="myInfo.ent_nm">
                                    <span class="detail-bold mr15">소속기관</span>
                                    <span class="detail-text">{{ myInfo.ogdp_inst_nm }}</span>
                                </div>
                                <div class="gd-4">
                                    <span class="detail-bold mr15">권한</span>
                                    <span class="detail-text" v-if="myInfo.authrt_id == 'ROLE_ADMIN'">KERIS관리자</span>
                                    <span class="detail-text" v-else-if="myInfo.authrt_id == 'ROLE_MANAGER'">영역별담당자</span>
                                    <span class="detail-text" v-else-if="myInfo.authrt_id == 'ROLE_EDU_MANAGER'">교육부담당자</span>
                                    <!-- <span class="detail-text" v-if="myInfo.rcptn_agre_yn == 'Y'">구독</span>
                                    <span class="detail-text" v-else>비구독</span> -->
                                </div>
                                <div class="gd-4">
                                    <span class="detail-bold mr15">이메일</span>
                                    <span class="detail-text">{{ myInfo.mbr_encpt_emad }}</span>
                                </div>
                            </div>

                        </div>
                        <div class="btn-zone flex justify-end">
                            <div class="gd-1 pr0" v-if="isAdmin()">
                                <button class="large-btn darkg-border-btn" title="관리자 포털" @click="fnSiteMove()">관리자 포털</button>
                            </div>
                            <div class="gd-1 pr0">
                                <button class="large-btn blue-btn" title="수정" @click="userUpdatePage()">수정하기</button>
                            </div>
                        </div>
                    </div>
                </div>

                <!----------------------------------------------- 내정보 수정 화면 ------------------------------------------------>

                <div v-if="myInfoUpdate">
                    <div v-if="innerStep === 0" class="content">
                        <div class="flex-column justify-center align-center content">
                            <div class="login-wrap pd30 border">
                                <div class="page-title mb30">
                                    <p class="text-ct">비밀번호 확인</p>
                                </div>
                                <div class="pw-zone mb10">
                                    <input type="password" name="" id="pw" placeholder="PASSWORD를 입력하세요." v-model="mbrEncptPswd"
                                        @keyup.enter="checkPwd()" autocomplete="off" class="full-input" />
                                </div>
                                <button class="large-btn blue-btn ml0" title="확인" @click="checkPwd()">
                                    확인
                                </button>
                            </div>
                        </div>
                    </div>
                    <div  v-else>
                        <!-- 관리자 외  -->
                        <div
                            v-if="myInfo.authrt_id === 'ROLE_USER' || myInfo.authrt_id === 'ROLE_CO_USER' || myInfo.authrt_id === 'ROLE_CO_MANAGER'">
                            <div class="border pd30 mb30">
                                <div class="flex justify-between align-center border-b mb30">
                                    <div class="content-border-title">
                                        <h2>회원정보</h2>
                                    </div>
                                </div>
                                <div class="form-table-style">
                                    <table class="form-table mb10">
                                        <tr>
                                            <td class="text-lf">
                                                <div class="gd-12 pl0 pr0">
                                                    <div class="mb16">
                                                        <label for="id" class="fw-bold">아이디</label>
                                                    </div>
                                                    <div class="flex justify-start align-center">
                                                        <div class="gd-6 pl0">
                                                            <input type="text" class="full-input" id="id" :value="myInfo.lgn_id" disabled />
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="text-lf">
                                                <div class="gd-8 pl0">
                                                    <div class="flex justify-start align-center mb16">
                                                        <label for="pw" class="fw-bold">비밀번호</label>
                                                        <div class="gd-2"><button class="large-btn blue-border-btn" title="비밀번호 변경" id="pw"
                                                                @click="newPwShow">비밀번호 변경</button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="text-lf">
                                                <div class="flex justify-start align-center">
                                                    <div class="gd-5 pl0 mb10">
                                                        <label for="name" class="fw-bold mb16">이름</label>
                                                        <input type="text" class="full-input" id="name" v-model="myInfo.mbr_encpt_flnm" disabled />
                                                    </div>
                                                    <!-- 없으면 표기 X -->
                                                    <div class="gd-5 pl0 pr0 mb10" v-if="myInfo.authrt_id !== 'ROLE_USER'">
                                                        <label for="rank" class="fw-bold mb16">직위(직급)</label>
                                                        <input type="text" class="full-input" id="rank"  v-model="myInfo.mbr_jbgd_nm" />
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="text-lf">
                                                <div class="gd-12 pl0 pr0">
                                                    <label for="number" class="fw-bold mb16">전화번호</label>
                                                    <div class="flex justify-start no-gutters">
                                                        <div class="gd-2 pl0 pr0">
                                                            <input type="text" class="full-input ml0" id="number" v-model="tel.tel1"
                                                                disabled />
                                                        </div>
                                                        <div class="pd10">-</div>
                                                        <div class="gd-2 pl0 pr0">
                                                            <input type="text" class="full-input ml0" v-model="tel.tel2"
                                                                disabled />
                                                        </div>
                                                        <div class="pd10">-</div>
                                                        <div class="gd-2 pl0 pr0">
                                                            <input type="text" class="full-input ml0" v-model="tel.tel3"
                                                                disabled />
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="text-lf">
                                                <div class="gd-12 pl0 pr0">
                                                    <label for="email_id" class="fw-bold mb16">이메일</label>
                                                    <div class="flex justify-start">
                                                        <div class="gd-2 pl0 pr0">
                                                            <input type="text" class="full-input" v-model="email.id" id="email_id" autocomplete="off" ref="emailId"/>
                                                        </div>
                                                        <div class="pd10">@</div>
                                                        <div class="gd-2 pl0 pr0" v-show="email.select == 'self'" >
                                                            <input type="text" class="full-input" v-model="email.address" v-show="email.select == 'self'" ref="emailAddress"/>
                                                        </div>
                                                        <div class="gd-2">
                                                            <select name="" id="" class="full-select ml0"
                                                                v-model="email.select" ref="emailSelect">
                                                                <option value="">선택해주세요</option>
                                                                <option value="self">직접입력</option>
                                                                <option value="naver.com">naver.com</option>
                                                                <option value="google.com">google.com</option>
                                                                <option value="hanmail.net">hanmail.net</option>
                                                                <option value="nate.com">nate.com</option>
                                                                <option value="kakao.com">kakao.com</option>
                                                            </select>
                                                        </div>
                                                        <div class="gd-2 pl0 pr0">
                                                            <button class="large-btn blue-border-btn" title="중복확인" v-if="!isPreviousEmail"  
                                                                @click="fnEmlDuplication()">중복확인</button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        <tr v-if="myInfo.ent_id">
                                            <td class="text-lf">
                                                <div class="flex justify-start align-center">
                                                    <div class="gd-12 pl0 pr0">
                                                        <div class="mb16">
                                                                <label for="" class="fw-bold">재직증명서</label>
                                                                <p class="detail-text red-text">※ 재직증명서 내 주민등록번호를 반드시 마스킹하여 업로드 해야
                                                                    합니다.</p>
                                                            </div>
                                                        <!-- <Attachment @emitFiles="emitFiles" :type="'certification'" :text="'재직증명서를 첨부해주세요.'"/> -->
                                                        <Attachment @emitFiles="emitFiles" :type="'certification'"  @file-deleted="handleFileDeleted"
                                                        :text="'재직증명서를 첨부해주세요.'" :options="{ allowedExtensions: ['pdf'] }" />
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="text-lf">
                                                <div class="flex justify-start align-center">
                                                    <div class="gd-12 pl0 pr0">
                                                        <p class="form-title mb16">구독 서비스</p>
                                                        <div class="flex justify-start align-center">
                                                            <input type="checkbox" name="" id="subscribe" v-model="isSubscribed">
                                                            <label for="subscribe" class="ml5">통합지원센터 소식 구독</label>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                            <div class="btn-zone flex justify-between align-center no-gutters">
                                <div class="gd-1">
                                    <button class="large-btn darkg-border-btn ml0" title="취소" @click="isCancel">취소</button>
                                </div>
                                <div class="gd-6 flex justify-end align-center">
                                    <div class="gd-2 pr0">
                                        <button class="large-btn blue-btn ml0" title="수정" @click="axiosUpdateMbr()">수정</button>
                                    </div>
                                    <div class="gd-2 pr0">
                                        <button class="large-btn red-btn ml0" title="회원탈퇴" @click="fnWithdraw()">회원탈퇴</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- 관리자 -->
                        <div v-else>
                            <div class="border pd30 mb30">
                                <div class="flex justify-between align-center border-b mb30">
                                    <div class="content-border-title">
                                        <p>회원정보</p>
                                    </div>
                                </div>
                                <div class="form-table-style">
                                    <table class="form-table mb10">
                                        <tr>
                                            <td class="text-lf">
                                                <div class="gd-12 pl0 pr0">
                                                    <div class="mb16">
                                                        <p class="form-title ">아이디</p>
                                                    </div>
                                                    <div class="flex justify-start align-center">
                                                        <div class="gd-6 pl0">
                                                            <input type="text" class="full-input" :value="myInfo.lgn_id" disabled />
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="text-lf">
                                                <div class="gd-8 pl0">
                                                    <div class="flex justify-start align-center mb16">
                                                        <p class="form-title ">비밀번호</p>
                                                        <div class="gd-2"><button class="large-btn blue-border-btn" title="비밀번호 변경"
                                                                @click="newPwShow">비밀번호 변경</button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="text-lf">
                                                <div class="flex justify-start align-center">
                                                    <div class="gd-4 pl0">
                                                        <p class="form-title mb16">이름</p>
                                                        <input type="text" class="full-input" v-model="myInfo.mbr_encpt_flnm" autocomplete="off"/>
                                                    </div>
                                                    <div class="gd-4 pl0">
                                                        <p class="form-title mb16">소속기관</p>
                                                        <input type="text" class="full-input" v-model="myInfo.ogdp_inst_nm" autocomplete="off"/>
                                                    </div>
                                                    <div class="gd-4 pl0 pr0">
                                                        <p class="form-title mb16">권한</p>
                                                        <input type="text" class="full-input" v-model="myInfo.authrt_nm" disabled />
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                        <tr>
                                            <td class="text-lf">
                                                <div class="gd-12 pl0 pr0">
                                                    <p class="form-title mb16">이메일</p>
                                                    <div class="flex justify-start">
                                                        <div class="gd-2 pl0 pr0">
                                                            <input type="text" class="full-input" v-model="email.id" id="email_id" autocomplete="off" ref="emailId"/>
                                                        </div>
                                                        <div class="pd10">@</div>
                                                        <div class="gd-2 pl0 pr0" v-show="email.select == 'self'" >
                                                            <input type="text" class="full-input" v-model="email.address" v-show="email.select == 'self'" ref="emailAddress"/>
                                                        </div>
                                                        <div class="gd-2">
                                                            <select name="" id="" class="full-select ml0"
                                                                v-model="email.select" ref="emailSelect">
                                                                <option value="">선택해주세요</option>
                                                                <option value="self">직접입력</option>
                                                                <option value="naver.com">naver.com</option>
                                                                <option value="google.com">google.com</option>
                                                                <option value="hanmail.net">hanmail.net</option>
                                                                <option value="nate.com">nate.com</option>
                                                                <option value="kakao.com">kakao.com</option>
                                                            </select>
                                                        </div>
                                                        <div class="gd-2 pl0 pr0">
                                                            <button class="large-btn blue-border-btn" v-if="!isPreviousEmail"  title="중복확인"
                                                                @click="fnEmlDuplication()">중복확인</button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </td>
                                        </tr>
                                    </table>
                                </div>
                            </div>
                            <div class="flex justify-between align-center">
                                <div class="gd-1 pd0">
                                    <button class="large-btn darkg-border-btn ml0" title="취소" @click="isCancel">취소</button>
                                </div>
                                <div class="gd-1 pd0">
                                    <button class="large-btn blue-btn ml0" title="수정" @click="axiosUpdateAdm()">수정</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div v-show="isCancelModal" class="modal-wrapper" role="dialog" 
        aria-modal="true">
            <div class="modal-container small-modal">
                <div class="modal-title">
                    <div class="flex justify-between align-center">
                        <h2 class="page-sub-title">알림</h2>
                        <button class="icon-btn black"  aria-label="close" id="close" @click="closeCancelModal"  title="닫기" >
                            <svg-icon type="mdi" :path="closePath" role="img"  aria-labelledby="close"></svg-icon>
                        </button>
                    </div>
                </div>
                <div class="modal-content-monthly">
                    <p class="detail-text">회원 정보 수정을 취소하시겠습니까?</p>
                </div>
                <div class="flex justify-between align-center">
                    <div class="gd-6"><button class="gray-btn large-btn" title="취소" @click="closeCancelModal">취소</button>
                    </div>
                    <!-- 유저상세페이지로 이동 -->
                    <div class="gd-6"><button class="blue-btn large-btn" title="확인" @click="userSelectPage">확인</button></div>
                </div>
            </div>
        </div>
            <!-- 비밀번호 변경 모달 -->
        <div v-show="newPwZone" class="modal-wrapper" role="dialog" 
        aria-modal="true">
            <div class="modal-container medium-modal" style="height: auto; min-height: auto;">
                <div class="modal-title">
                    <div class="flex justify-between align-center">
                        <h2>비밀번호 변경</h2>
                        <button class="icon-btn black" aria-label="close2" id="close2" @click="closeCancelModal"  title="닫기" >
                            <svg-icon type="mdi" :path="closePath" role="img"  aria-labelledby="close2"></svg-icon>
                        </button>
                    </div>
                </div>
                <div class="modal-content-monthly">
                    <table class="form-table border-none">
                        <tbody>
                            <tr>
                                <td class="pb10">
                                    <div class="gd-12">
                                        <label for="newPw" class="form-title mb10">변경할 비밀번호</label>
                                        <input type="password" class="full-input" placeholder="영문, 숫자, 특수문자 조합된 6~20자리" id="newPw"
                                                        v-model="pswd.newPswd" autocomplete="off" minlength="6"
                                                        maxlength="20" />
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <td class="text-lf">
                                    <div class="gd-12">
                                        <label for="newPw_check" class="form-title mb10">변경할 비밀번호 확인</label>
                                        <div>
                                            <p class="green" v-if="(pswd.newPswd === pswd.newPswdChk) && pswd.newPswdChk">비밀번호 일치합니다.</p>
                                            <p class="red" v-if="(pswd.newPswd !== pswd.newPswdChk) && pswd.newPswdChk">비밀번호가 일치하지 않습니다.</p>
                                        </div>
                                        <input type="password" class="full-input" placeholder="비밀번호를 한번 더 입력하세요."
                                                        id="newPw_check" v-model="pswd.newPswdChk" autocomplete="off" minlength="6"
                                                        maxlength="20" />
                                    </div>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div class="modal-end flex justify-end align-center">
                    <div class="gd-2 pr0">
                       <button class="large-btn gray-btn" title="취소"  @click="closeCancelModal">취소</button>
                    </div> 
                    <div class="gd-2 pr0">
                       <button class="large-btn blue-btn" title="변경"  @click="axiosUpdatePswd()">변경</button>
                    </div>    
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import PageNavigationBar from '../../../component/pagenavigationbar/PageNavigationBar.vue';
import _ from "lodash";
import { useRoute } from 'vue-router';
import COMMON_UTIL from '../../../../resources/js/commonUtil';
import { useStore } from "vuex";
import { mdiWindowClose, mdiFileSearchOutline,mdiFileDownloadOutline } from '@mdi/js';
import Attachment from '../../../component/file/Attachment.vue';
import axios from 'axios';
// api
import { detailProc , pwdCheck , updatePswdProc, emlDupProc } from '../../../../resources/api/userPage';
import { withdrawProc, updateAdmProc } from '../../../../resources/api/mbrInfo'

export default {
    data() {
        return {
            pdfPath:mdiFileSearchOutline ,
            downloadPath:mdiFileDownloadOutline,
            path: this.$store.state.path,
            pageAuth: this.$store.state.pageAuth,
            role: this.$store.state.roles,
            mbrId: this.$store.state.mbrId,
            myInfo: {},
            route: useRoute(),
            store: useStore(),
            myInfoUpdate:false,
            newPwZone: false,
            isCancelModal: false,
            innerStep: 0,
            closePath:mdiWindowClose,
            mbrEncptPswd: null,
             //비밀번호 정보 객체
            pswd: {
                newPswd: null,
                newPswdChk: null,
            },
            email: {
                id: null,
                select: "",
                address: null,
            },
            tel : {
                tel1: null,
                tel2: null,
                tel3: null,
            },
            previousEmail: null,
            isPreviousEmail: true,
            rcptn_agre_yn: false,
            file: new FormData(),
            bannerId:'mypage-banner',
            naviData: {},

        }
    },
    methods: {
        // 모달
        newPwShow: function () {
            this.newPwZone = true;
        },
        isCancel: function () {
            this.isCancelModal = true
            this.myInfo.rcptn_agre_yn = this.rcptn_agre_yn
        },
        closeCancelModal: function () {
            this.isCancelModal = false
            this.newPwZone = false;
        },
        userSelectPage: function(){
            this.myInfoUpdate = false
            this.innerStep = 0
            this.mbrEncptPswd = null
            this.closeCancelModal()
        },

        //내정보 조회
        async init() {
            const vm = this;
            try {
                const res = await detailProc();
                if(res.status == 200) {
                    this.myInfo = res.data.data;
                    this.rcptn_agre_yn = this.myInfo.rcptn_agre_yn;
                    vm.myInfoUpdate = false;
                }
            } catch(error) {
                alert(error.response.data.message)
                this.$router.push({ path: '/'})
            }
        },

        // 첨부파일 다운로드 로직
        async downloadFile(myInfo) {
            
            if(this.pageAuth.fileDwnldAuthrtYn != 'Y') {
                alert('다운로드 권한이 없습니다.');
                return;
            }
            
            const file = {
                'fileId' : myInfo.file_id,
                'fileNm' : myInfo.file_nm,
                'extnNm' : myInfo.extn_nm,
            }

            await this.$downloadFile(file, this.pageAuth);           
        },     

        // 전화번호 - 처리 
        hyphenMinus: function(telno) {
            return COMMON_UTIL.HyphenMinus(telno);
        },

        // 전화번호 분리
        splitPhoneNumber(data) {
            const phoneNumber = data;
            if (phoneNumber.length === 11) {
                this.tel.tel1 = phoneNumber.slice(0, 3);
                this.tel.tel2 = phoneNumber.slice(3, 7);
                this.tel.tel3 = phoneNumber.slice(7, 11);
            } 
        },
        
        // 회원정보 수정페이지로 이동
        userUpdatePage: function () {
            this.myInfoUpdate = true;
            this.emailSplit(this.myInfo.mbr_encpt_emad)
            this.previousEmail = this.myInfo.mbr_encpt_emad
            this.splitPhoneNumber(this.myInfo.mbr_encpt_telno);
        },

        stepGo: function (num) {
            this.innerStep = num
        },

        // 현재 비밀번호 검증
        async checkPwd() {
            const vm = this;
            if(this.$isEmpty(this.mbrEncptPswd)) return
            
            const data = { 'mbrEncptPswd' : this.mbrEncptPswd }

            try {
                const res = await pwdCheck(data);
                if(res.status == 200) {
                    vm.stepGo(1)
                }
            } catch(error) {  
                alert(error.response.data.message)
            }
        },     

        // 비밀번호 변경 유효성검사
        pwUpdateValid() {
            if (this.$isEmpty(this.pswd.newPswd)) {
                alert("변경할 비밀번호를 입력해주세요.")
                return false
            } else if (this.$isEmpty(this.pswd.newPswdChk)) {
                alert("비밀번호 확인을 입력해주세요.")
                return false
            } else if (this.pswd.newPswd !== this.pswd.newPswdChk) {
                alert("비밀번호가 불일치합니다.");
                return false
            } else if (!this.$pwCheck(this.pswd.newPswd)) {
                alert('비밀번호는 영문, 숫자, 특수문자를 포함한 6~20자이어야 합니다.')
                return false
            }
            return true
        },

        // 비밀번호 변경
        async axiosUpdatePswd() {
            if(!this.pwUpdateValid()) return
            
            let data = {
                mbrId : this.mbrId ,
                newMbrEncptPswd : this.pswd.newPswd
            }
  
            try {
                const res = await updatePswdProc(data);

                // axios 결과
                alert(this.$getCmmnMessage("msg004", "비밀번호 수정이 "));

                this.newPwZone = false;
                //비밀번호input 비우기
                this.pswd.newPswd = null;
                this.pswd.newPswdChk = 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'));
                }
            }
        },

        // 이메일 분리
        emailSplit(data) {
            const email = data.split("@");
            this.email.id = email[0];
            switch (email[1]) {
                case "naver.com":
                case "google.com":
                case "hanmail.net":
                case "nate.com":
                case "kakao.com":
                this.email.select = email[1];
                break;
                default:
                this.email.select = "self";
                this.email.address = email[1];
                break;
            }
        },

        // 이메일 비교(중복검사 창 활성화 용)
        compareEmail() {
            this.isPreviousEmail = (this.emailSum() === this.previousEmail)
        },

        // 이메일 합체
        emailSum() {
            if (this.email.select != "self") {
                return this.email.id + "@" + this.email.select;
            } else {
                return this.email.id + "@" + this.email.address;
            }
        },

         //이메일 중복 검사
        fnEmlDuplication() {
            //유효성검사
            let email = this.emailSum();
            if (!this.mailValidation(email)) {
                return;
            } else {
                this.axiosEmlDuplication(email);
            }
        },
        //이메일 유효성 검사
        mailValidation: function (email) {
            //1.null검사
            this.email.id = this.email.id ? this.email.id.trim() : null
            if (this.$isEmpty(this.email.id)) {
                alert('이메일 ID를 입력해주세요.');
                this.$refs.emailId.focus()
                return false;
            }
            // 이메일 선택 여부
            if (this.$isEmpty(this.email.select)) {
                alert("도메인을 선택하세요.");
                this.$refs.emailSelect.focus();
                return false;
            }
            // 이메일 직접입력 입력 여부
            if (this.email.select == "self") {
                this.email.address = this.email.address ? this.email.address.trim() : null
                if (this.$isEmpty(this.email.address)) {
                    alert("도메인을 입력해주세요.");
                    this.$refs.emailAddress.focus();
                    return false;
                }
            } else {

            }
            //2.정규식 검사
            if (!this.$email(email)) {
                alert('이메일 형식을 확인해 주세요.');
                this.$refs.emailId.focus()
                return false;
            }
            return true;
        },

        //이메일 중복 검사
        async axiosEmlDuplication(email) {
            // 데이터 세팅
            const data = {'mbrEncptEmad' : email};
            // 실행
            try {
                const res = await emlDupProc(data);

                // axios 결과
                alert(res.data.message);
                if(res.status === 200) {
                    this.isPreviousEmail = true;
                }
            } 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'));
                }
            }
        },

        //파일목록 받아오기
        emitFiles: function (files) {
            this.file.append(files.type, files.filelist[0])
        },

        //사용자 수정
        axiosUpdateMbr: function() {
            if(!this.isPreviousEmail) { 
                alert("이메일 중복확인은 필수입니다.")
                return
            }
            const vm = this;
            vm.myInfo.mbr_encpt_emad = vm.emailSum()
            const request = new FormData();
            if(this.file !== null) {
                for(const key of this.file.keys()){
                    request.append(key, this.file.get(key))
                }
            }

            request.append("mbrInfo",JSON.stringify(this.myInfo))
            
            axios({
                url: '/mbr/updateProc.json',
                method: 'post',
                headers: {
                    'Content-Type': 'multipart/form-data; charset=UTF-8',
                    Authorization: this.$store.state.authorization,
                },
                data: request
            }).then(function (res) {
                if(res.status === 200) {
                    //수정 성공
                    alert(res.data.message)
                    vm.init()
                }
            }).catch(function (error) {
                const errorData = error.response.data;
                if (errorData.message != null && errorData.message != "") {
                    alert(error.response.data.message);
                }
            });
        },

        //관리자 수정
        async axiosUpdateAdm() {
            const vm = this;
            vm.myInfo.mbr_encpt_emad = vm.emailSum()
            let data = {
                "mbrId" : vm.myInfo.mbr_id,
                "mbrEncptFlnm" : vm.myInfo.mbr_encpt_flnm,
                "ogdpInstNm" : vm.myInfo.ogdp_inst_nm,
                "authrtId" : vm.myInfo.authrt_id,
                "mbrEncptEmad" : vm.myInfo.mbr_encpt_emad
            }

            try {
                const res = await updateAdmProc(data);

                if (res.status == 200) { //수정 성공
                    alert(res.data.message)
                    vm.init()
                
                }
            } 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'));
                }
            }
        },
        

        // 삭제
        fnWithdraw() {
            if (confirm(this.$getCmmnMessage("cnf002"))) {
                this.axiosWithdraw();
            } else {
                return;
            }
        },

         // axios: 회원탈퇴
        async axiosWithdraw() {
            // 데이터 세팅
            let data = {"mbrId" : this.myInfo.mbr_id}
            // 실행
            try {
                const response = await withdrawProc(data);

                // axios 결과
                alert(this.$getCmmnMessage('msg005', '회원탈퇴가 '));
                this.$store.commit("setStoreReset");
                // 메인으로 이동
                // this.$router.push({ path: '/'})
                window.location.href = '/'
            } 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'));
                }
            }
        },

        //PDF 파일 이외에 첨부금지
        handleFileDeleted(deletedFileKey) {
            let newFormData = new FormData;
            for (let [key, value] of this.file.entries()) {
                if (key !== deletedFileKey) {
                    newFormData.append(key, value);
                }
            }

            // 새로운 FormData 객체로 업데이트
            this.file = newFormData;
        }, 

         // KERIS관리자 여부 확인
         isAdmin() {
            return this.role.some(role => role.authority === 'ROLE_ADMIN');
        },

        fnSiteMove() {
            this.$router.push({
                path: "/kdm/main.page",
            });
        },
    },
    watch: {
        'email.id': 'compareEmail',
        'email.select': 'compareEmail',
        'email.address': 'compareEmail',
    },
    computed: {
        isSubscribed: {
            get() {
                return this.myInfo.rcptn_agre_yn === 'Y';
            },
            set(value) {
                this.myInfo.rcptn_agre_yn = value ? 'Y' : 'N';
            }
        }
    },
    components: {
        'PageNavigationBar': PageNavigationBar,
        'Attachment': Attachment,
    },
    mounted() {
        // 초기화
        this.naviData = { 'main': '마이페이지', 'sub': '나의 정보관리' };
        this.init();
    }
}
</script>
