<template>
  <div class="visual mb-50 w1500">
    <div class="swiper mySwiper swiper-container" ref="swiperContainer">
      <div class="swiper-wrapper">
        <div class="swiper-slide" v-for="(item, index) in slides" :key="index">
          <img :src="item.img" :alt="item.alt" />
        </div>
      </div>
      <div class="swiper-button-next"></div>
      <div class="swiper-button-prev"></div>
      <div class="pagination_container">
        <div class="swiper-pagination"></div>
        <div class="flex align-center">
          <div class="swiper-pagination2"></div>
          <button class="swiper-play-pause-btn" @click="toggleAutoplay">
            <component :is="isAutoplay ? 'PauseOutlined' : 'CaretRightOutlined'" />
          </button>
        </div>
      </div>
    </div>
    <div class="search-wrap">
      <div class="search-area">
        <div class="custom-select" @click="toggleDropdown">
          <div class="selected-option">{{ getSelectedText }}</div>
          <ul v-if="isDropdownOpen" class="select-options">
            <li v-for="option in options" :key="option.value" @click.stop="selectOption(option)"> {{ option.text }} </li>
          </ul>
        </div>
        <div class="line"></div>
        <div style="width: 60%;"><input type="text" placeholder="검색어를 입력하세요" v-model="searchText" @keyup.enter="fnMoveTo('TotalSearch')"></div>
        <button type="button" class="search-btn" @click="fnMoveTo('TotalSearch')"><img :src="search" alt=""></button>
      </div>
      <div class="total-search">
        <button type="button" class="total-btn" @click="fnMoveTo('TotalSearch')">상세검색</button>
      </div>
    </div>
  </div>
  <div class="current-status mb-60">
    <div class="board  w1500">
      <div class="current-banner">
        <div><span>기록물 현황</span></div>
      </div>
      <ul>
        <template v-for="(item, idx) of icons" :key="idx">
          <li @click="fnMoveTo(item.routeName)">
            <div class="labeling"><img :src="item.url" :alt="item.name + '아이콘'"><span>{{ item.name }}</span></div>
            <div :class="{ 'count': true, 'all': item.id === 'TOTAL' }">{{ item.rowCo }}</div>
          </li>
          <li class="line" v-if="idx < icons.length - 1"></li>
        </template>
      </ul>
    </div>
  </div>
  <div class="new-update w1500">
    <div v-for="(tab, index) in tabs" :key="index" class="tabs mb-50">
      <div class="title mb-30">
        <h4>{{ tab.title }}</h4>
        <button type="button" class="gopage" @click="fnMoveTo(tab.contents.search)">더보기</button>
      </div>
      <div class="tab-content">
        <div class="new-pic">
          <div v-for="(item, idx2) in tab.contents.list" :key="idx2" class="box-wrap">
            <div class="box" @click="fnMoveTo(tab.contents.view, item.dcryId)">
              <div class="img-area">
                <img :src="item.thumbnail.filePath" :alt="item.sj" class="tab-image" />
              </div>
              <div class="info">
                <p>{{ item.sj }}</p>
                <span>{{ $dotFormatDate(item.rgsde) }}</span>
              </div>
            </div>
          </div>
          <div v-for="i in Math.max(0, 3 - tab.contents.list.length)" :key="`empty-${i}`" class="box-wrap">
            <div class="box">
              <div class="img-area"><img :src="noimg" class="tab-image" /></div>
              <div class="info">
                <p>등록된 게시물이 없습니다.</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="new-update w1500 mb-50 flex-sp-bw">
    <div class="new-media">
      <div class="title mb-30">
        <h4>신규 미디어 영상</h4>
        <router-link :to="{ name: 'MediaVideoSearch' }" class="gopage">더보기</router-link>
      </div>
      <div class="media-wrap">
        <template v-for="(item, idx) of mediaContents" :key="idx">
          <div class="media-box" @click="fnMoveTo('MediaVideoDetail', item.mediaVidoId)">
            <div class="img-area"><img :src="item.url" :alt="item.sj" class="media-image" /></div>
            <div class="info">
              <p>{{ item.sj }}</p>
              <span>{{ $dotFormatDate(item.rgsde) }}</span>
            </div>
          </div>
        </template>
        <!-- 게시글이 없는 경우 -->
        <div v-for="i in Math.max(0, 2 - mediaContents.length)" :key="`empty-${i}`" class="media-box">
          <div class="img-area"><img :src="nomedia" alt="" class="media-image" /></div>
          <div class="info">
            <p>등록된 게시글이 없습니다.</p>
          </div>
        </div>
      </div>
    </div>
    <div class="new-bodo">
      <div class="title mb-30">
        <h4>신규 스크랩 자료</h4>
        <router-link :to="{ name: 'NewsReleaseSearch' }" class="gopage">더보기</router-link>
      </div>
      <ul>
        <template v-for="(item, index) of bodoContents" :key="index">
          <li class="info" @click="fnMoveTo('NewsReleaseDetail', item.nesDtaId)">
            <p>{{ item.sj }}</p>
            <span>{{ $dotFormatDate(item.rgsde) }}</span>
          </li>
        </template>
        <!-- 게시글이 없는 경우 -->
        <li v-if="bodoContents.length < 1" class="info">
          <img :src="nobodo" alt="">
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
import { ref, onMounted } from 'vue';
import 'swiper/swiper-bundle.css';
import 'swiper/css/pagination';
import 'swiper/css/navigation';
import 'swiper/css';
import Swiper from 'swiper/bundle';

import { Autoplay, Pagination, Navigation } from 'swiper/modules';
import { CaretRightOutlined, PauseOutlined } from '@ant-design/icons-vue';

// 메인화면 조회
import { findAllSttusesProc } from "../../../resources/api/main";
import { getYouTubeThumbnail } from '../../../resources/js/youtubeUtils';

export default {
  components: {
    Swiper,
    PauseOutlined,
    CaretRightOutlined,
  },

  setup() {
    const swiperContainer = ref(null);
    const slides = [
      { img: 'client/resources/images/visual.png', alt: 'Slide 1' },
      { img: 'client/resources/images/visual.png', alt: 'Slide 2' },
      { img: 'client/resources/images/visual.png', alt: 'Slide 3' },
      // Add more slides as needed
    ];
    const isAutoplay = ref(true); // Tracks the autoplay state
    let swiperInstance = null;

    onMounted(() => {
      // Main Swiper with Fraction Pagination
      const mainSwiper = new Swiper(swiperContainer.value, {
        loop: true,
        navigation: {
          nextEl: '.swiper-button-next',
          prevEl: '.swiper-button-prev',
        },
        pagination: {
          el: '.swiper-pagination',
          type: 'progressbar',
        },
        autoplay: {
          delay: 3000, // 3초마다 슬라이드 전환
          disableOnInteraction: false, // Allow autoplay to continue after interaction
        },
      });
      swiperInstance = mainSwiper;
      // Secondary Swiper with Progressbar Pagination
      const pagingSwiper = new Swiper(swiperContainer.value, {
        loop: true,
        pagination: {
          el: '.swiper-pagination2',
          type: 'fraction',
        },
      });

      // Synchronize the two Swipers
      mainSwiper.controller.control = pagingSwiper;
      pagingSwiper.controller.control = mainSwiper;
    });
    const toggleAutoplay = () => {
      if (isAutoplay.value) {
        swiperInstance.autoplay.stop(); // Stop autoplay
      } else {
        swiperInstance.autoplay.start(); // Start autoplay
      }
      isAutoplay.value = !isAutoplay.value; // Toggle autoplay state
    };
    return {
      swiperContainer,
      slides,
      toggleAutoplay,
      isAutoplay,
    };
  },

  data() {
    return {
      noimg: "client/resources/images/no_img.png",
      nomedia: "client/resources/images/no_media.png",
      nobodo: "client/resources/images/no_bodo.png",
      direct: 'client/resources/images/direct-btn.png',
      search: 'client/resources/images/search_btn.png',
      selectedTab: "newPhoto", // Set initial tab index to 신규사진기록물 (first tab)
      tabs: [
        {
          id: "newPhoto",
          title: "신규 사진 기록물",
          contents: { list: [], search: 'PicHistorySearch', view: 'PicHistoryDetail' },
        },
        {
          id: "newVideo",
          title: "신규 영상 기록물",
          contents: { list: [], search: 'VideoHistorySearch', view: 'VideoHistoryDetail' },
        },
      ],
      mediaContents: [], // 신규 미디어 영상
      bodoContents: [], // 신규 스크랩 자료
      searchRecord: 'all', // 통합검색 Selectbox 내용
      isDropdownOpen: false,
      options: [
        { value: 'all', text: '전체' },
        { value: 'pic', text: '사진' },
        { value: 'video', text: '영상' },
        { value: 'media', text: '미디어 영상' },
        { value: 'bodo', text: '스크랩 자료' },
      ],
      searchText: null, // 통합검색 Input 내용
      icons: [
        {
          id: "TOTAL",
          name: "전체",
          url: 'client/resources/images/icon/icon1.png',
          routeName: 'TotalSearch',
        },
        {
          id: "dcry_photo",
          name: "사진",
          url: 'client/resources/images/icon/icon2.png',
          routeName: 'PicHistorySearch',
        },
        {
          id: "dcry_vido",
          name: "영상",
          url: 'client/resources/images/icon/icon3.png',
          routeName: 'VideoHistorySearch',
        },
        {
          id: "media_vido",
          name: "미디어",
          url: 'client/resources/images/icon/icon4.png',
          routeName: 'MediaVideoSearch',
        },
        {
          id: "nes_dta",
          name: "스크랩 자료",
          url: 'client/resources/images/icon/icon5.png',
          routeName: 'NewsReleaseSearch',
        },
      ],

      currentSlide: 1,   // To track the current slide
      totalSlides: 3,

      navigation: true, // Enable navigation buttons (prev/next)
    };
  },

  computed: {
    getSelectedText() {
      const selected = this.options.find(opt => opt.value === this.searchRecord);
      return selected ? selected.text : '';
    }
  },

  created() {
    this.fnFindAllSttuses();
  },

  methods: {
    toggleDropdown() {
      this.isDropdownOpen = !this.isDropdownOpen;
    },
    selectOption(option) {
      this.searchRecord = option.value;
      this.isDropdownOpen = false;
    },

    // 메인화면 정보 조회
    async fnFindAllSttuses() {
      try {
        const response = await findAllSttusesProc();
        if (response.data.status == 200) {
          let dcrySttuses = response.data.data.dcrySttuses;
          dcrySttuses.forEach(item => {
            const matchingIcon = this.icons.find(icon => icon.id === item.iemNm);
            if (matchingIcon) matchingIcon.rowCo = item.rowCo;
          });

          let photoDcrys = response.data.data.photoDcrys;
          this.tabs[0].contents = { id: 'newPhoto', list: photoDcrys, search: 'PicHistorySearch', view: 'PicHistoryDetail' };

          let vidoDcrys = response.data.data.vidoDcrys;
          this.tabs[1].contents = { id: 'newVideo', list: vidoDcrys, search: 'VideoHistorySearch', view: 'VideoHistoryDetail' };

          let mediaVidos = response.data.data.mediaVidos;
          this.mediaContents = this.onChangeList(mediaVidos);

          let nesDtas = response.data.data.nesDtas;
          this.bodoContents = this.onChangeList(nesDtas);
        } else {
          alert(response.data.message);
        }
      } catch (error) {
        alert("에러가 발생했습니다.\n시스템관리자에게 문의하세요.");
      }
    },
    // 목록 변환
    onChangeList(list) {
      for (let item of list) {
        let url = null;

        if (item.hasOwnProperty('files')) {
          if (item.files.length > 0) {
            url = item.thumbnail.filePath
          }
        } else {
          url = getYouTubeThumbnail(item.link);
        }

        item.url = url;
      }

      return list;
    },

    // 페이지 이동
    fnMoveTo(page, id) {
      if (page === 'TotalSearch') {
        this.$router.push({ name: page, query: { searchRecord: this.searchRecord, searchText: this.searchText }, });
      } else {
        if (this.$isEmpty(id)) {
          this.$router.push({ name: page });
        } else {
          this.$router.push({ name: page, query: { id: id } });
        }
      }
    },
  },
};
</script>