<template>
  <div class="content">
    <div class="sub-title-area mb-30">
      <h2>통합검색</h2>
      <div class="breadcrumb-list">
        <ul>
          <!-- Bind the image source dynamically for homeicon -->
          <li>
            <img :src="homeicon" alt="Home Icon">
            <p></p>
          </li>
          <li><img :src="righticon" alt=""></li>
          <li>통합검색</li>
        </ul>
      </div>
    </div>
    <form action="search" class="search-form mb-40">
      <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 v-for="(record, idx) in searchRecord" :key="idx">
              <input type="checkbox" :id="idx" :name="searchRecord" :value="record.key" v-model="searchReqDTO.searchRecord" @change="fnChkOption('record')" />
              <label :for="idx">{{ record.value }}</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 v-for="(scope, idx) in searchType" :key="idx">
              <input type="checkbox" :id="idx" :name="searchType" :value="scope.key" v-model="searchReqDTO.searchType" @change="fnChkOption('scope')" />
              <label :for="idx">{{ scope.value }}</label>
            </li>
          </ul>
        </dd>
        <dd class="mb-15">
          <p>검색어</p>
          <div class="wfull"><input type="text" v-model="searchReqDTO.searchText"></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">
          <p>카테고리</p>
          <ul>
            <li v-for="(category, idx) of categorys" :key="idx">
              <input type="checkbox" :id="category.ctgryId" name="categorys" :value="category.ctgryId" v-model="searchReqDTO.searchCtgry" />
              <label :for="category.ctgryId">{{ 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="fnFindAllDatas">
            <img :src="searchicon" alt="">
            <p>검색</p>
          </button>
        </div>
      </dl>
    </form>
    <div class="search-result">
      <ul>
        <li v-for="(resultItem, idx) of searchResult" :key="idx" class="mb-30">
          <div class="flex-sp-bw mb-20">
            <div class="resultext">
              <img :src="resulticon" alt="">
              <p>총 <b>{{ resultItem.count }}개</b>의 {{ searchRecord[idx].value }}{{ resultItem.key === 'N' ? '가' : '이' }} 검색되었습니다.</p>
            </div>
            <router-link :to="{ path: '/' + resultItem.id }" class="gopage">모두보기</router-link>
          </div>
          <div v-for="(item, idx2) of resultItem.list" :key="idx2" class="result-box">
            <div class="main-img">
              <img v-if="item.hasOwnProperty('files') && item.files.length > 0" :src="item.files[0].filePath" alt="">
              <img v-else src="client/resources/images/img6.png" alt="">
            </div>
            <div class="text-box">
              <h5>{{ item.sj }}</h5>
              <p v-if="resultItem.key === 'P' || resultItem.key === 'V'" class="address">{{ item.adres }}</p>
              <p class="text">{{ item.cn }}</p>
              <div class="mb-20">
                <ul class="category">
                  <li v-for="(ctgry, idx3) of item.ctgrys" :key="idx3" class="category1">{{ ctgry.ctgryNm }}</li>
                </ul>
              </div>
              <div class="date">
                <ul>
                  <li>생산연도 <b>{{ item.prdctnYear }}</b></li>
                  <li>|</li>
                  <li>등록 <b>{{ item.rgsde }}</b></li>
                </ul>
              </div>
            </div>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>
<script>
// 통합 검색
import { findAllDatas } from "../../../resources/api/main";
import { findAllByNullProc } from "../../../resources/api/category"; // 카테고리 목록 검색

export default {
  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: {
        searchRecord: ["P", "V", "M", "N"],
        searchType: ["sj", "cn", "adres"],
        searchText: null,
        startYear: null,
        endYear: null,
        searchCtgry: [],
        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.fnFindAllDatas(); // 통합검색
  },

  methods: {
    // 초기화
    init() {
      if (this.isInitialLoad) {
        this.isInitialLoad = false;
      } else {
        if (!confirm('검색 조건을 초기화하시겠습니까?')) {
          return;
        }
      }
      this.searchReqDTO = Object.assign({}, this.searchDefault); // 검색객체 초기화
      this.searchResult = []; // 검색결과 초기화
    },
    // 카테고리 목록 조회
    async fnFindCategorys() {
      try {
        const response = await findAllByNullProc();
        this.categorys = response.data.data.ctgry;
      } catch (error) {
        this.categorys = []; // 카테고리 목록 초기화

        if (error.response) {
          console.log("에러 응답:", error.response.data);
        }
        console.error("Error:", error);
      }
    },

    // 통합검색
    async fnFindAllDatas() {
      if (this.searchReqDTO.searchRecord == null || this.searchReqDTO.searchRecord.length < 1) {
        alert('검색 유형은 최소 한 개 이상 선택해주세요.');
        return;
      }

      try {
        let params = {};
        if (this.searchReqDTO.searchRecord.length > 0) {
          params.searchRecords = this.searchReqDTO.searchRecord.join(',');
        }
        if (this.searchReqDTO.searchType.length > 0) {
          params.searchTypes = this.searchReqDTO.searchType.join(',');
        }
        if (this.searchReqDTO.searchCtgry.length > 0) {
          params.searchCtgries = this.searchReqDTO.searchCtgry.join(',');
        }
        params.searchText = this.searchReqDTO.searchText;
        params.startYear = this.searchReqDTO.startYear;
        params.endYear = this.searchReqDTO.endYear;
        params.order = this.searchReqDTO.order;

        // 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':
          if (this.isChkAllRecord) {
            this.searchReqDTO.searchRecord = this.searchRecord.map(item => item.key);
          } else {
            this.searchReqDTO.searchRecord = [];
          }
          break;
        case 'scope':
          if (this.isChkAllScope) {
            this.searchReqDTO.searchType = this.searchType.map(item => item.key);
          } else {
            this.searchReqDTO.searchType = [];
          }
          break;
      }
    },

    // 기록유형 선택 여부 변경
    fnChkOption(type) {
      switch (type) {
        case 'record':
          this.isChkAllRecord = this.searchReqDTO.searchRecord.length === this.searchRecord.length;
          break;
        case 'scope':
          this.isChkAllScope = this.searchReqDTO.searchType.length === this.searchType.length;
          break;
      }
    },
  },
};
</script>
