<template>
  <div class="popup-wrap">
    <div class="popup-container">
      <div v-if="popup.popupType === 'image'" class="content">
        <img
          :src="imageUrl"
          :alt="fileList[0].fileNm + '.' + fileList[0].extnNm"
          class="img-link"
          @click="fnMove"
        />
      </div>
      <template v-if="popup.popupType === 'video'">
        <YouTube
          :src="popup.vdoUrl"
          ref="youtube"
          @ready="onReady"
          width="100%"
          height="100%"
          class="content"
        />
      </template>
    </div>
    <div class="popup-btn flex justify-end align-center pd10 border-t">
      <label for="today" class="detail-text cusor flex align-center mr10">
        <input
          type="checkbox"
          name="today"
          id="today"
          class="mr5"
          v-model="isNoShowToday"
        />
        오늘 하루 보지 않기
      </label>
      <div class="mr10">|</div>
      <div class="flex align-center">
        <button type="button" class="detail-text" @click="fnClose">닫기</button>
      </div>
    </div>
  </div>
</template>

<script>
import defaultAxios from "../../../resources/js/defaultAxios";
import YouTube from "vue3-youtube";

// API
import { sysDetailProc } from "../../../resources/api/popup";

export default {
  components: {
    YouTube,
  },
  data() {
    return {
      popupId: null, // 팝업 아이디
      // 팝업 객체
      popup: {},
      codeList: [],
      fileList: [],
      // 오늘 하루 보지 않기 체크 여부
      isNoShowToday: false,
      // 이미지 주소
      imageUrl: null,
    };
  },
  created() {
    this.$root.otherWindow = true;
    let urlParams = new URLSearchParams(window.location.search);
    this.popupId = decodeURIComponent(urlParams.get("popupId"));
    this.fnViewDetail();
  },
  methods: {
    // 영상 자동 재생
    onReady() {
      this.$refs.youtube.playVideo();
    },
    // 팝업 조회(상세)
    fnViewDetail() {
      let data = {
        popupId: this.popupId,
      };
      this.axiosViewDetail(data);
    },
    async axiosViewDetail(data) {
      try {
        const response = await sysDetailProc(data);
        this.popup = response.data["data"]["popupVO"];
        this.codeList = response.data["data"]["codeList"];
        this.fileList = response.data["data"]["fileList"];
        if (this.popup.popupType == "image") {
          this.downloadFile();
        }
      } catch (error) {
        const errorData = error.response.data;
        if (errorData.message != null && errorData.message != "") {
            alert(error.response.data.message);
        } else {
            alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
        }
      }
    },
    // 팝업 닫기
    fnClose() {
      if (this.isNoShowToday) {
        const today = new Date();
        let tomorrow = new Date(today.setDate(today.getDate() + 1));
        tomorrow.setHours(0, 0, 0, 0);
        tomorrow = new Date(tomorrow);

        let count = false;
        if (this.$cookies.get("popup").length > 0) {
          for (let cookie of this.$cookies.get("popup")) {
            if (this.popup.popupId == cookie) {
              count = true;
            }
          }
        }

        if (!count) {
          let cookies = [...this.$cookies.get("popup"), this.popupId];
          this.$cookies.set("popup", cookies, tomorrow);
        }
      }
      if (this.popup.popupType == "image") {
        window.URL.revokeObjectURL(this.imageUrl);
      }
      window.close();
    },
    // axios: 첨부파일 다운로드
    async downloadFile() {
      const file = this.fileList[0];
      try {
        const response = await defaultAxios({
          url: this.$filters.ctxPath("/sys/file/fileDownload.json"), // URL 경로 확인
          method: "post",
          headers: {
            "Content-Type": "application/json; charset=UTF-8",
            Authorization: this.$store.state.authorization,
          },
          data: file.fileId,
          responseType: "blob",
        });
        this.imageUrl = window.URL.createObjectURL(
          new Blob([response.data], { type: "image/" + file.extnNm })
        );
      } catch (error) {
        const errorData = error.response.data;
        if (errorData.message != null && errorData.message != "") {
            alert(error.response.data.message);
        } else {
            alert("에러가 발생했습니다.\n관리자에게 문의해주세요.");
        }
      }
    },
    fnMove() {
      if(this.popup.linkUrl.trim() == "") {
        return;
      }
      window.opener.location = this.popup.linkUrl;
      this.fnClose();
    },
  },
};
</script>