<template>
  <div class="content">
    <div class="sub-title-area mb-30">
      <h2>영상 기록물</h2>
      <div class="breadcrumb-list">
        <ul>
          <li><img :src="homeicon" alt="Home Icon">
            <p>기록물</p>
          </li>
          <li><img :src="righticon" alt=""></li>
          <li>영상 기록물</li>
        </ul>
      </div>
    </div>
    <form class="gallery-form mb-40" @submit.prevent>
      <dl class="mb-20">
        <dd>
          <p>{{ findResult.sj }}</p>
          <div class="date flex align-center">
            <img :src="calendaricon" alt="">
            <span>{{ $dotFormatDate(findResult.rgsde) }}</span>
          </div>
        </dd>
      </dl>
      <div class="gallery video">
        <Video-component v-if="findResult.hasOwnProperty('files') && findResult.files.length > 0" :videoUrl="findResult.files[0].filePath" />
        <img v-else :src="eximg" alt="">
      </div>
    </form>
    <h3>내용</h3>
    <form class=" info-form mb-50" @submit.prevent>
      <dl>
        <dd>
          <ViewerComponent :content="findResult.cn" />
        </dd>
      </dl>
    </form>
    <h3>기본정보</h3>
    <form class="info-form mb-50" @submit.prevent>
      <dl>
        <dd class="mb-20">
          <img :src="addressicon" alt="">
          <span>주소</span>
          <p>{{ findResult.adres }}</p>
        </dd>
        <dd class="mb-20">
          <img :src="yearicon" alt="">
          <span>생산연도</span>
          <p>{{ $dotFormatDate(findResult.prdctnYear) }}</p>
        </dd>
        <dd>
          <img :src="categoryicon" alt="">
          <span>카테고리</span>
          <ul class="category">
            <li v-for="(item, idx) of findResult.ctgrys" :key="idx" class="category">{{ item.ctgryNm }}</li>
          </ul>
        </dd>
      </dl>
    </form>
    <div class="btn-group flex-center">
      <button v-if="isRegister" type="button" class="red-line" @click="fnDelete">삭제</button>
      <button v-if="isRegister" type="button" class="blue-line" @click="fnMoveTo('edit', pageId)">수정</button>
      <button type="button" class="gray-line-bg" @click="fnMoveTo('list')">목록</button>
      <button type="button" class="gradient" @click="fnDownload">다운로드</button>
      <div v-if="loading" class="loading-overlay">
        <div class="loading-spinner"></div>
        <p>파일을 다운로드 중입니다...</p>
      </div>
    </div>
  </div>
</template>
<script>
// COMPONENT
import VideoComponent from '@/views/component/player/VideoComponent.vue';
import ViewerComponent from '@/views/component/editor/ViewerComponent.vue';
// API
import { findDcryProc, deleteDcryProc } from '@/resources/api/dcry';
import { fileDownloadProc } from '@/resources/api/file';

export default {
  components: {
    VideoComponent,
    ViewerComponent,
  },

  data() {
    return {
      // ICON
      calendaricon: 'client/resources/images/icon/calendaricon.png',
      homeicon: 'client/resources/images/icon/home.png',
      erroricon: 'client/resources/images/icon/error.png',
      righticon: 'client/resources/images/icon/right.png',
      addressicon: 'client/resources/images/icon/addressicon.png',
      yearicon: 'client/resources/images/icon/yearicon.png',
      categoryicon: 'client/resources/images/icon/categoryicon.png',

      pageId: null,
      findResult: {},
      selectedFiles: [],
      loading: false,

      isRegister: false,
    };
  },

  created() {
    this.pageId = this.$route.query.id;
    if (this.$isEmpty(this.pageId)) {
      alert("게시물 존재하지 않습니다.");
      this.fnMoveTo('list');
    }
  },

  mounted() {
    this.fnFindDcry(); // 상세 조회
  },

  methods: {
    // 상세 조회
    async fnFindDcry() {
      try {
        const response = await findDcryProc(this.pageId);

        this.findResult = response.data.data.dcry;
        if (this.findResult.ty !== 'V') {
          alert('올바른 접근이 아닙니다.');
          this.fnMoveTo('list'); // 목록으로 이동
        }
        this.isRegister = this.$registerChk(this.findResult.register);
      } catch (error) {
        alert('조회중 오류가 발생했습니다.');
        this.fnMoveTo('list');

        if (error.response) {
          alert(error.response.data.message);
        }
        console.error(error.message);
      }
    },

    // 파일 다운로드
    async fnDownload() {
      let url = null;
      let link = null;
      this.loading = true; // Show loading spinner

      try {
        // 파일 ID 수집
        let file = this.findResult.files[0];
        const response = await fileDownloadProc(file);

        // 파일명 조회
        let filename = 'downloadFile.bin';
        const filenameRegex = /file[Nn]ame[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
        const matches = filenameRegex.exec(response.headers['content-disposition']);
        if (matches != null && matches[1]) {
          filename = matches[1].replace(/['"]/g, '');
        }

        // 파일 다운로드 생성
        url = window.URL.createObjectURL(new Blob([response.data]));
        link = document.createElement('a');
        link.href = url;
        link.setAttribute('download', filename);
        document.body.appendChild(link);
        link.click();
      } catch (error) {
        alert('파일 다운로드 중 오류가 발생했습니다.');
      } finally {
        // 리소스 정리
        setTimeout(() => {
          if (url) {
            window.URL.revokeObjectURL(url);
          }
          if (link && link.parentNode) {
            document.body.removeChild(link);
          }
          this.loading = false;  // Hide loading spinner
        }, 100);
      }
    },

    // 삭제
    async fnDelete() {
      let isCheck = confirm("해당 페이지를 삭제하시겠습니까?");
      if (!isCheck) {
        return;
      }

      try {
        const response = await deleteDcryProc(this.pageId);
        alert('해당 페이지를 삭제했습니다.');

        this.fnMoveTo('list');
      } catch (error) {
        if (error.response) {
          alert(error.response.data.message);
        }
        console.error(error.message);
      }
    },

    // 페이지 이동
    fnMoveTo(type, id) {
      const routes = {
        'list': { name: 'VideoHistorySearch' },
        'view': { name: 'VideoHistoryDetail', query: { id } },
        'edit': { name: 'VideoHistoryInsert', query: this.$isEmpty(id) ? {} : { id } },
      };

      if (routes[type]) {
        this.$router.push(routes[type]);
      } else {
        alert("올바르지 않은 경로를 요청하여 목록으로 이동합니다.");
        this.$router.push(routes['list']);
      }
    },
  },
};
</script>