<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>
    <div class="search-form form">
      <dl>
        <dd class="mb-15">
          <p>검색범위</p>
          <ul>
            <li>
              <input type="checkbox" id="allScope" v-model="isChkAllScope" @change="fnChkAllOptions" />
              <label for="allScope">전체</label>
            </li>
            <li>
              <input type="checkbox" id="searchSj" v-model="searchReqDTO.useSj" @change="fnChkOption" />
              <label for="searchSj">제목</label>
            </li>
            <li>
              <input type="checkbox" id="searchCn" v-model="searchReqDTO.useCn" @change="fnChkOption" />
              <label for="searchCn">내용</label>
            </li>
            <li>
              <input type="checkbox" id="searchAdres" v-model="searchReqDTO.useAdres" @change="fnChkOption" />
              <label for="searchAdres">주소</label>
            </li>
          </ul>
        </dd>
        <dd class="mb-15">
          <p>검색어</p>
          <div class="wfull"><input type="text" v-model="searchReqDTO.searchText" v-on:keyup.enter="fnChnageReqDTO"></div>
        </dd>
        <dd class="mb-15">
          <p>생산연도</p>
          <input type="date" v-model="searchReqDTO.startYear">
          <p class="mark">~</p>
          <input type="date" v-model="searchReqDTO.endYear">
        </dd>
        <dd class="mb-20 category-dd">
          <p>카테고리</p>
          <ul>
            <li v-for="(category, idx) of categorys" :key="idx">
              <input type="checkbox" :id="'ctgry_' + idx" name="categorys" :value="category.ctgryId" v-model="searchReqDTO.searchCtgries" />
              <label :for="'ctgry_' + idx">{{ category.ctgryNm }}</label>
            </li>
          </ul>
        </dd>
        <dd class="mb-15">
          <p>정렬</p>
          <ul>
            <li v-for="(order, idx) of orders" :key="idx">
              <input type="radio" :id="order.key" name="orders" :value="order.key" v-model="searchReqDTO.order" />
              <label :for="order.key">{{ order.value }}</label>
            </li>
          </ul>
        </dd>
        <div class="btn-group">
          <button type="button" class="reset" @click="init">
            <img :src="reseticon" alt="">
            <p>초기화</p>
          </button>
          <button type="button" class="search" @click="fnChnageReqDTO">
            <img :src="searchicon" alt="">
            <p>검색</p>
          </button>
        </div>
      </dl>
    </div>
    <div class="search-result">
      <div class="tabs">
        <div class="flex-sp-bw mb-20 align-center">
          <div class="resultext ">
            <img :src="resulticon" alt="">
            <p>총 <b>{{ searchReqDTO.totalRecordCount }}개</b>의 영상 기록물이 검색되었습니다. </p>
          </div>
          <div class="flex">
            <ul class="tab-box mb-20">
              <li v-for="(tab, idx) in tabs" :key="idx" class="tab-title" :class="{ active: selectedTabId === tab.id }" @click="selectTab(tab.id)">
                <img :src="selectedTabId === tab.id ? tab.activeImage : tab.inactiveImage" :alt="tab.title" class="tab-icon" />
                <p><b>{{ tab.title }}</b></p>
              </li>
            </ul>
            <div class="select-box">
              <select v-model="searchReqDTO.recordSize" @change="fnChnageReqDTO">
                <option :value="24">24개</option>
                <option :value="36">36개</option>
                <option :value="100">100개</option>
              </select>
            </div>
          </div>
        </div>
        <div class="tab-content">
          <div v-if="searchResult.length > 0">
            <CardStyleComponent v-if="selectedTabId === 'CARD'" :name="'V'" :list="searchResult" />
            <ListStyleComponent v-if="selectedTabId === 'LIST'" :name="'V'" :list="searchResult" />
          </div>
          <div v-else class="no-results">
            <p>등록된 게시물이 없습니다.</p>
          </div>
        </div>
      </div>
      <div class="btn-group flex-end mt-40"><button class="register"> <router-link :to="{ path: '/VideoHistoryInsert.page' }">등록</router-link></button></div>
      <DefaultPagination class="mt-40" :search="searchReqDTO" @onChange="fnChangeCurrentPage" />
    </div>
  </div>
</template>
<script>
// COMPONENT
import CardStyleComponent from '@/views/component/listLayout/CardStyleComponent.vue';
import ListStyleComponent from '@/views/component/listLayout/ListStyleComponent.vue';
import DefaultPagination from '@/views/component/listLayout/DefaultPagination.vue';
// API
import { findAllByNullProc } from "@/resources/api/category";
import { findDcrysProc } from "@/resources/api/dcry";

export default {
  components: {
    DefaultPagination,
    CardStyleComponent,
    ListStyleComponent,
  },

  data() {
    return {
      // ICON
      resulticon: "client/resources/images/icon/r-check.png",
      homeicon: 'client/resources/images/icon/home.png',
      searchicon: 'client/resources/images/icon/search.png',
      reseticon: 'client/resources/images/icon/reset.png',
      righticon: 'client/resources/images/icon/right.png',

      // 검색용 객체
      isChkAllScope: true, // 검색범위 전체 체크 여부
      searchType: [
        { key: "sj", value: "제목" },
        { key: "cn", value: "내용" },
        { key: "adres", value: "주소" },
      ], // 검색범위 목록
      categorys: [], // 카테고리 목록
      orders: [
        { key: "rgsde", value: "최신" },
        { key: "rdcnt", value: "인기" },
      ], // 정렬 목록

      // 검색용 객체 초기값
      searchDefault: {
        useSj: true,
        useCn: true,
        useAdres: true,
        searchText: null,
        startYear: null,
        endYear: null,
        searchTy: "V",
        searchCtgries: [],
        order: "rgsde",
        // 페이지네이션
        currentPage: 1, // 현재 페이지
        recordSize: 24, // 한 페이지에 표시할 데이터 개수
      },
      searchReqDTO: {}, // 실제 검색에 사용되는 객체

      searchResult: [], // 검색결과

      // 목록 레이아웃
      selectedTabId: null,
      tabs: [
        {
          id: "CARD",
          title: "카드형",
          activeImage: "client/resources/images/list_icon01_on.png", // Active tab image
          inactiveImage: "client/resources/images/list_icon01_off.png",
        },
        {
          id: "LIST",
          title: "리스트형",
          activeImage: "client/resources/images/list_icon02_on.png", // Active tab image
          inactiveImage: "client/resources/images/list_icon02_off.png",
        },
      ],

      isInitialLoad: true // 초기 로드 여부
    };
  },

  created() {
    this.init(); // 초기화
    this.fnFindCategorys(); // 카테고리 목록 조회 (검색조건 없음)
  },

  methods: {
    // 초기화
    init() {
      if (this.isInitialLoad) {
        this.isInitialLoad = false;

        this.queryParamsToSearch();
      } else {
        if (!confirm('검색 조건을 초기화하시겠습니까?')) {
          return;
        }
      }

      this.searchReqDTO.searchTy = "V"; // 영상 기록물 고정
      this.selectedTabId = this.tabs[0].id;

      this.searchReqDTO = JSON.parse(JSON.stringify(this.searchDefault));
      this.searchResult = []; // 검색결과 초기화

      this.fnChnageReqDTO(); // 통합검색
    },

    queryParamsToSearch() {
      let query = this.$route.query;
      if (!this.$isEmpty(query)) {
        const typeConverters = {
          useSj: val => val === 'true',
          useCn: val => val === 'true',
          useAdres: val => val === 'true',
          searchCtgries: val => Array.isArray(val) ? val : (val ? val.split(',') : [])
        };
        Object.entries(query).forEach(([key, value]) => {
          if (key in this.searchDefault) {
            this.searchDefault[key] = key in typeConverters ? typeConverters[key](value) : value;
          }
        });
      }
    },

    // 카테고리 목록 조회
    async fnFindCategorys() {
      try {
        const response = await findAllByNullProc();
        this.categorys = response.data.data.ctgry;
      } catch (error) {
        this.categorys = []; // 카테고리 목록 초기화

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

    // 페이지 이동
    fnChangeCurrentPage(currentPage) {
      this.searchReqDTO.currentPage = Number(currentPage);
      this.$nextTick(() => {
        this.fnSearch();
      });
    },

    // 검색 조건이 변경된 경우
    fnChnageReqDTO() {
      this.searchReqDTO.currentPage = 1;
      this.$nextTick(() => {
        this.fnSearch();
      });
    },

    // 통합검색
    async fnSearch() {
      try {
        const params = JSON.parse(JSON.stringify(this.searchReqDTO));

        // 카테고리 목록 처리
        if (this.searchReqDTO.searchCtgries && this.searchReqDTO.searchCtgries.length > 0) {
          params.searchCtgries = this.searchReqDTO.searchCtgries.join(',');
        } else {
          delete params.searchCtgries;
        }

        // API 호출
        const response = await findDcrysProc(params);
        this.searchResult = response.data.data.dcrys;
        this.searchReqDTO = response.data.data.search;
      } catch (error) {
        this.searchResult = []; // 검색결과 초기화

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

    // 기록유형 전체 선택 여부 변경
    fnChkAllOptions() {
      this.searchReqDTO.useSj = this.isChkAllScope;
      this.searchReqDTO.useCn = this.isChkAllScope;
      this.searchReqDTO.useAdres = this.isChkAllScope;
    },

    // 기록유형 선택 여부 변경
    fnChkOption() {
      this.isChkAllScope = this.searchReqDTO.useSj && this.searchReqDTO.useCn && this.searchReqDTO.useAdres;
    },

    selectTab(tabId) {
      this.selectedTabId = tabId;
    },
  },
};
</script>