<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="allRecord" v-model="isChkAllRecord" @change="fnChkAllOptions('record')" />
              <label for="allRecord">전체</label>
            </li>
            <li>
              <input type="checkbox" id="photoRecord" v-model="searchReqDTO.usePhoto" @change="fnChkOption('record')" />
              <label for="photoRecord">사진</label>
            </li>
            <li>
              <input type="checkbox" id="videoRecord" v-model="searchReqDTO.useVideo" @change="fnChkOption('record')" />
              <label for="videoRecord">영상</label>
            </li>
            <li>
              <input type="checkbox" id="mediaVideo" v-model="searchReqDTO.useMedia" @change="fnChkOption('record')" />
              <label for="mediaVideo">미디어영상</label>
            </li>
            <li>
              <input type="checkbox" id="newsData" v-model="searchReqDTO.useNews" @change="fnChkOption('record')" />
              <label for="newsData">보도자료</label>
            </li>
          </ul>
        </dd>
        <dd class="mb-15">
          <p>검색범위</p>
          <ul>
            <li>
              <input type="checkbox" id="allScope" v-model="isChkAllScope" @change="fnChkAllOptions('scope')" />
              <label for="allScope">전체</label>
            </li>
            <li>
              <input type="checkbox" id="searchSj" v-model="searchReqDTO.useSj" @change="fnChkOption('scope')" />
              <label for="searchSj">제목</label>
            </li>
            <li>
              <input type="checkbox" id="searchCn" v-model="searchReqDTO.useCn" @change="fnChkOption('scope')" />
              <label for="searchCn">내용</label>
            </li>
            <li>
              <input type="checkbox" id="searchAdres" v-model="searchReqDTO.useAdres" @change="fnChkOption('scope')" />
              <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="fnSearch()"></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="fnSearch">
            <img :src="searchicon" alt="">
            <p>검색</p>
          </button>
        </div>
      </dl>
    </div>
    <div class="search-result">
      <CardViewList v-for="(item, idx) of searchResult" :key="idx" :name="item.key" :count="item.count" :list="item.list" />
    </div>
  </div>
</template>
<script>
// COMPONENT
import CardViewList from "../../component/listLayout/CardViewList.vue";
// API
import { findAllDatas } from "../../../resources/api/main"; // 통합 검색
import { findAllByNullProc } from "../../../resources/api/category"; // 카테고리 목록 검색

export default {
  components: {
    CardViewList
  },
  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',

      // 검색용 객체 초기값
      searchDefault: {
        usePhoto: true,
        useVideo: true,
        useMedia: true,
        useNews: true,
        useSj: true,
        useCn: true,
        useAdres: true,
        searchText: null,
        startYear: null,
        endYear: null,
        searchCtgries: [],
        order: "rgsde",
      },
      searchReqDTO: {},

      isChkAllRecord: true, // 기록유형 전체 체크 여부
      searchRecord: [
        { key: "P", value: "사진" },
        { key: "V", value: "영상" },
        { key: "M", value: "미디어영상" },
        { key: "N", value: "보도자료" },
      ], // 기록유형 목록
      isChkAllScope: true, // 검색범위 전체 체크 여부
      searchType: [
        { key: "sj", value: "제목" },
        { key: "cn", value: "내용" },
        { key: "adres", value: "주소" },
      ], // 검색범위 목록
      categorys: [], // 카테고리 목록
      orders: [
        { key: "rgsde", value: "최신" },
        { key: "rdcnt", value: "인기" },
      ], // 정렬 목록

      searchResult: [], // 검색결과

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

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

  mounted() {
    let searchText = this.$route.query.searchText;
    if (searchText !== null) {
      this.searchReqDTO.searchText = searchText;
    }

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

  methods: {
    // 초기화
    init() {
      if (this.isInitialLoad) {
        this.isInitialLoad = false;
      } else {
        if (!confirm('검색 조건을 초기화하시겠습니까?')) {
          return;
        }
      }

      this.searchReqDTO = JSON.parse(JSON.stringify(this.searchDefault));
      this.isChkAllRecord = true;
      this.isChkAllScope = true;

      this.searchResult = []; // 검색결과 초기화
    },

    // 카테고리 목록 조회
    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);
      }
    },

    // 통합검색
    async fnSearch() {
      // 유효성 검사
      if (!this.searchReqDTO.usePhoto && !this.searchReqDTO.useVideo && !this.searchReqDTO.useMedia && !this.searchReqDTO.useNews) {
        alert('검색 유형은 최소 한 개 이상 선택해주세요.');
        return;
      }

      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 findAllDatas(params);
        this.searchResult = response.data.data.searchResult;
      } catch (error) {
        this.searchResult = []; // 검색결과 초기화

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

    // 기록유형 전체 선택 여부 변경
    fnChkAllOptions(type) {
      switch (type) {
        case 'record':
          this.searchReqDTO.usePhoto = this.isChkAllRecord;
          this.searchReqDTO.useVideo = this.isChkAllRecord;
          this.searchReqDTO.useMedia = this.isChkAllRecord;
          this.searchReqDTO.useNews = this.isChkAllRecord;
          break;
        case 'scope':
          this.searchReqDTO.useSj = this.isChkAllScope;
          this.searchReqDTO.useCn = this.isChkAllScope;
          this.searchReqDTO.useAdres = this.isChkAllScope;
          break;
      }
    },

    // 기록유형 선택 여부 변경
    fnChkOption(type) {
      switch (type) {
        case 'record':
          this.isChkAllRecord = this.searchReqDTO.usePhoto && this.searchReqDTO.useVideo && this.searchReqDTO.useMedia && this.searchReqDTO.useNews;
          break;
        case 'scope':
          this.isChkAllScope = this.searchReqDTO.useSj && this.searchReqDTO.useCn && this.searchReqDTO.useAdres;
          break;
      }
    }
  },
};
</script>