<template>
  <div class="content pt50 pb50">
    <div class="w1400">
      <div class="search-bar mb30">
        <input
          type="text"
          class="full-input search-input"
          placeholder="검색어를 입력하세요."
          v-model="search.searchText"
          @keyup.enter="totalSearch"
        />
        <button class="icon-button search-button" @click="totalSearch">
          <svg-icon
            type="mdi"
            :path="this.$iconPath()"
            class="search-icon"
          ></svg-icon>
        </button>
      </div>
      <div class="chart-zone mb30">
        <div class="box">
          <div class="tab-nav mb15">
            <ul class="flex justify-between align-center">
              <li
                v-for="(item, idx) in codeList"
                :key="idx"
                :value="item.cd"
                :class="{
                  'point-font gd-4': true,
                  activeTab: activeTab === item.cd,
                }"
                @click="showTab(item.cd)"
              >
                <p class="pd15">{{ item.cdNm }}</p>
              </li>
            </ul>
          </div>
          <div class="tab-content">
            <div>
              <div class="flex justify-end align-center no-gutters mb15">
                <div class="select-label gd-1 text-rg mr10">기간</div>
                <div class="gd-2">
                  <select
                    class="full-select"
                    v-model="searchKeyword"
                    @change="fnCompanyInfo"
                  >
                    <option value="day">일별</option>
                    <option value="month">월별</option>
                    <option value="year">연도별</option>
                  </select>
                </div>
              </div>
              <div class="chart-wrap" ref="chartdiv">
                <ClusteredColumnChart
                  :chartData="chartData"
                  columnX="stats_date"
                />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="community-zone flex">
        <div class="gd-6 pl0">
          <div class="box">
            <div class="box-inner-title flex justify-between align-center">
              <p>공지사항</p>
              <router-link
                to="/government/BBS_MNG_000000000000027/list.page"
                class="shortcuts flex align-center"
              >
                <p class="mr5">바로가기</p>
                <svg-icon
                  type="mdi"
                  :width="15"
                  :height="15"
                  :path="this.$iconPath('mdiArrowRight')"
                ></svg-icon>
              </router-link>
            </div>
            <ul class="item-list" v-if="noticeTop5.length > 0">
              <li
                v-for="(notice, idx) in noticeTop5"
                :key="idx"
                class="flex justify-between align-center pt5 pl15 cursor"
                @click="fnNoticeViewDetail(notice.bbsId)"
              >
                <p>{{ notice.bbsNm }}</p>
                <p>{{ notice.regDt }}</p>
              </li>
            </ul>
            <div v-else>
              <p class="data-none text-ct">등록된 정보가 존재하지 않습니다.</p>
            </div>
          </div>
        </div>
        <div class="gd-6 pr0">
          <div class="box">
            <div class="box-inner-title flex justify-between align-center">
              <p>기업정보</p>
              <router-link
                to="/government/companyInfo/list.page"
                class="shortcuts flex align-center"
              >
                <p class="mr5">바로가기</p>
                <svg-icon
                  type="mdi"
                  :width="15"
                  :height="15"
                  :path="this.$iconPath('mdiArrowRight')"
                ></svg-icon>
              </router-link>
            </div>
            <ul class="item-list" v-if="companyInfoList.length > 0">
              <li
                v-for="(item, idx) in companyInfoList"
                :key="idx"
                class="flex justify-between align-center pt5 pl15 cursor"
                @click="fnCompanyInfoViewDetail(item.entId)"
              >
                <p>{{ item.entNm }}</p>
                <p>{{ item.regDt }}</p>
              </li>
            </ul>
            <div v-else>
              <p class="data-none text-ct">등록된 정보가 존재하지 않습니다.</p>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import ClusteredColumnChart from "../../../../component/chart/ClusteredColumnChart.vue";
import store from "../../../AppStore";

// 통합검색 관련
import queryParams from "../../../../../resources/js/queryParams";
import { defaultTotalSearchParams } from "../../../../../resources/js/defaultTotalSearchParams.js";

// API
import { governmentMainProc } from "../../../../../resources/api/main";
import { sysListByPageProc } from "../../../../../resources/api/popup";
import { findFiveNotice } from "../../../../../resources/api/bbsCn";

export default {
  mixins: [queryParams],
  components: {
    ClusteredColumnChart: ClusteredColumnChart,
  },
  data() {
    return {
      search: { ...defaultTotalSearchParams },
      mbrId: store.state.mbrId || null, // 사용자 아이디
      roles: store.state.roles.map((auth) => auth.authority) || [], // 사용자 권한
      menuType: store.state.userType || null, // 메뉴 타입

      // 공지사항 top5
      noticeTop5: [],

      // 검색조건
      codeList: [],
      activeTab: "categoryTab",
      searchKeyword: "day",

      // 통계
      chartData: [],

      popupList: [],

      // 기업정보
      companyInfoList: [],
    };
  },
  created() {
    // 쿠키 초기화
    const today = new Date();
    let tomorrow = new Date(today.setDate(today.getDate() + 1));
    tomorrow.setHours(0, 0, 0, 0);
    tomorrow = new Date(tomorrow);
    if (this.$cookies.get("popup") == null) {
      this.$cookies.set("popup", [], tomorrow);
    }

    this.fnPopupList();
    this.fnCompanyInfo();
    this.fnFiveNotice();
  },
  methods: {
    showTab: function (tabName) {
      this.activeTab = tabName;
      this.searchKeyword = "day";
      this.fnCompanyInfo();
    },

    // 통합검색
    totalSearch() {
      if (this.search.searchText === "") {
        alert("검색어를 입력해주세요.");
        return;
      }
      this.search.mbrId = this.mbrId;
      this.search.roles = this.roles;
      this.search.menuType = this.menuType;
      this.saveQueryParams("totalSearchQueryParams", this.search); // 검색조건 저장
      this.$router.push({
        path: "/government/search.page",
      });
    },

    // 통계 조회
    async fnCompanyInfo() {
      let data = {
        activeTab: this.activeTab,
        searchKeyword: this.searchKeyword,
      };
      try {
        const response = await governmentMainProc(data);
        this.codeList = response.data.data.codeList;
        this.chartData = response.data.data.governmentStats;
        this.companyInfoList = response.data.data.companyInfo;
      } catch (error) {
        alert("에러가 발생했습니다.\n시스템관리자에게 문의하세요.");
      }
    },

    // 기업정보 상세 조회
    fnCompanyInfoViewDetail(entId) {
      this.$router.push({
        path: "/government/companyInfo/view.page",
        query: { pageId: entId },
      });
    },

    // 팝업조회(상세)
    async fnPopupList() {
      let data = {
        pageType: this.$store.state.userType,
      };
      try {
        const response = await sysListByPageProc(data);
        let popupList = response.data.data;
        if (popupList != null && popupList.length > 0) {
          this.fnShowPopup(popupList);
        }
      } catch (error) {
        alert("에러가 발생했습니다.\n시스템관리자에게 문의하세요.");
      }
    },
    // 팝업 표시
    fnShowPopup(popupList) {
      for (let popup of popupList) {
        let count = false;
        const popupCookies = this.$cookies.get("popup");
        if (popupCookies.length > 0) {
          for (let cookie of popupCookies) {
            if (popup.popupId == cookie) {
              count = true;
            }
          }
        }
        if (!count) {
          let size = "width=" + popup.wdthLen + ", height=" + popup.vrtcLen;
          window.open(
            "/cmmn/popup.page?popupId=" + popup.popupId,
            "_blank",
            size + ", scrollbars=no, resizable=no, toolbars=no, menubar=no"
          );
        }
      }
    },

    // 공지사항 최신 5개 조회
    async fnFiveNotice() {
      try {
        const params = {
          bbsMngId: "BBS_MNG_000000000000004",
        };
        const response = await findFiveNotice(params);
        this.noticeTop5 = response.data.data;
      } catch (error) {
        alert("에러가 발생했습니다.\n시스템관리자에게 문의하세요.");
      }
    },
    // 공지사항 상세페이지 이동
    fnNoticeViewDetail(bbsId) {
      this.$router.push({
        path: "/government/BBS_MNG_000000000000004/view.page",
        query: {
          pageId: bbsId,
        },
      });
    },
  },
};
</script>
