<template>
  <div class="content-zone">
    <div class="content">
       <div class="scroll">
        <div class="top-zone">
          <div class="popup-table tbl-wrap">
            <div class="section-title">
              <p>팝업관리</p>
            </div>
            <ListTable
              :colgroup="colgroup"
              :thead="thead"
              :tbody="tbody"
              :className="'data'"
              @listClick="fnPopupViewDetail"
            />
          </div>
          <div class="new-table tbl-wrap">
            <div class="section-title">
              <p>최근 등록 글</p>
            </div>
            <ListTable
              :colgroup="colgroup2"
              :thead="thead2"
              :tbody="tbody2"
              :className="'data'"
              @listClick="fnBbsCnViewDetail"
            />
          </div>
        </div>
        <div class="middle-zone">
          <div class="first-box">
            <div class="box">
              <p class="box-title">오늘 방문자 수</p>
              <p class="box-content text-rg">
                {{ cntnStats.dayCnt.toLocaleString("ko-KR") }}
              </p>
            </div>
          </div>
          <div class="two-box">
            <div class="box">
              <p class="box-title">이번달 방문자 수</p>
              <p class="box-content text-rg">
                {{ cntnStats.mmCnt.toLocaleString("ko-KR") }}
              </p>
            </div>
          </div>
          <div class="three-box">
            <div class="box">
              <p class="box-title">총 방문자 수</p>
              <p class="box-content text-rg">
                {{ cntnStats.totalCnt.toLocaleString("ko-KR") }}
              </p>
            </div>
          </div>
        </div>
        <div class="chart-zone">
          <div  class="section-title">
            <p >방문자 접속 통계</p>
          </div>
          <div class="box" style="height: 320px">
            <div class="chart-wrap" ref="chartdiv" style="height: 100%">
              <ClusteredColumnChart :chartData="chartData" columnX="date" />
            </div>
          </div>
        </div>
       </div>
    </div>
  </div>
</template>

<script>
import ListTable from "../../../component/table/ListTable.vue";
import ClusteredColumnChart from "../../../component/chart/ClusteredColumnChart.vue";
import { defaultSearchParams } from "../../../../resources/js/defaultSearchParams";
import queryParams from "../../../../resources/js/queryParams";
import cntnStatsSave from "../../../../resources/js/cntnStatsSave";

// API
import {
  adminMainProc
} from "../../../../resources/api/main";
import { findBySysMenu } from "../../../../resources/api/menu";

const App = {
  mixins: [queryParams, cntnStatsSave],
  components: {
    ListTable: ListTable,
    ClusteredColumnChart: ClusteredColumnChart,
  },
  data: () => {
    return {
      menuList: [],
      resetSearch: { ...defaultSearchParams },

      // 팝업관리
      colgroup: ["10%", "20%", "15%", "20%", "20%", "15%"],
      thead: ["NO", "제목", "사용여부", "시작일", "종료일", "작성자"],
      tbody: [],
      popupList: [],

      // 게시판
      colgroup2: ["10%", "50%", "10%", "20%"],
      thead2: ["NO", "제목", "작성자", "작성일"],
      tbody2: [],
      bbsCnList: [],

      // 통계
      cntnStats: {
        dayCnt: 0, // 오늘 방문자 수
        mmCnt: 0, // 이번달 방문자 수
        totalCnt: 0, // 총 방문자 수
      },
      chartData: [],
    };
  },
  created() {
    this.reSetMenu();
    this.fnMenuList();
    this.fnAdminMain();
  },
  methods: {
    // 메뉴 초기화
    reSetMenu() {
      this.$store.commit("setMenu", null);
    },

    // 전체 조회
    async fnAdminMain() {
      try {
        const response = await adminMainProc();
        this.popupList = response.data.data.popupMng;
        this.bbsCnList = response.data.data.bbsCnNew;
        this.cntnStats.dayCnt = response.data.data.cntnDayCnt;
        this.cntnStats.mmCnt = response.data.data.cntnMmCnt;
        this.cntnStats.totalCnt = response.data.data.cntnTotalCnt;

        // 팝업관리
        if (response.data.data.popupMng.length > 0) {
          this.tbody = [];
          this.tbody = this.popupList.map((popup, idx) => ({
            id: 5 - idx,
            popupTtl: popup.popupTtl,
            useYn:
              popup.popupUseYn == "Y"
                ? "사용"
                : popup.popupUseYn == "N"
                ? "미사용"
                : null,
            bgngDt: popup.bgngDt,
            endDt: popup.endDt,
            mbrNm: popup.mbrNm,
          }));
        }

        // 최근등록글
        if (response.data.data.bbsCnNew.length > 0) {
          this.tbody2 = [];
          this.tbody2 = this.bbsCnList.map((bbs, idx) => ({
            id: 5 - idx,
            ttl:
              bbs.type == "faq"
                ? this.fnFindBbsTitle(bbs)
                : "[" + bbs.nm + "] " + bbs.ttl,
            writer: bbs.writer,
            dt: bbs.dt,
          }));
        }

        // 차트 데이터
        let datas = [];
        for (let data of response.data.data.monthCntnStats) {
          let newData = {};
          newData["date"] = data["dates"];
          for (let i = 0; i < data["authrt_nm"].length; i++) {
            newData[data["authrt_nm"][i]] = data["cntn_nope"][i];
          }
          datas.push(newData);
        }
        this.chartData = datas;

      } catch (error) {
        alert("에러가 발생했습니다.\n시스템관리자에게 문의하세요.");
      }
    },
    // 게시판 제목 출력
    fnFindBbsTitle(data) {
      let cn = data.cn.replace(/<[^>]*>?/g, "");
      let isAnser = data.ans != null ? "응답" : "미응답";
      return "[" + data.nm + "] " + "[" + isAnser + "] " + cn;
    },

    // 메뉴 조회
    async fnMenuList() {
      try {
        const params = {
          roles: this.$store.state.roles.map((auth) => auth.authority),
          menuType: this.$store.state.userType,
        };
        const response = await findBySysMenu(params);
        if (response.status == 200) {
          this.menuList = response.data.data.menuList;
        }
      } catch (error) {
        alert("에러가 발생했습니다.\n시스템관리자에게 문의하세요.");
      }
    },

    // 팝업 최신글 상세 보기
    async fnPopupViewDetail(idx) {
      this.saveQueryParams("queryParams", this.resetSearch);
      this.$store.commit(
        "setMenu",
        this.findMenu(this.menuList, "MENU_000000000000011")
      );
      await this.cntnStatsSave("MENU_000000000000029");
      this.$router.push({
        name: "admPopupManagementSelectOne",
        query: {
          pageId: this.popupList[idx]["popupId"],
        },
      });
    },

    // 게시판 최신글 상세 보기
    async fnBbsCnViewDetail(idx) {
      this.saveQueryParams("queryParams", this.resetSearch);
      let depth1 = this.findMenu(this.menuList, "MENU_000000000000010");
      this.$store.commit("setMenu", depth1);
      for (let menu of depth1.childList) {
        if (menu.menuTypeCtgry == this.bbsCnList[idx]["id"]) {
          await this.cntnStatsSave(menu.menuId);
        }
      }
      if (this.bbsCnList[idx].type == "faq") {
        this.$router.push({
          path: "/adm/" + this.bbsCnList[idx]["mng_id"] + "/list.page",
        });
      } else {
        this.$router.push({
          path: "/adm/" + this.bbsCnList[idx]["mng_id"] + "/view.page",
          query: {
            pageId: this.bbsCnList[idx]["id"],
          },
        });
      }
    },

    // 메뉴 정보 찾기
    findMenu(menuList, menuId) {
      for (let menu of menuList) {
        if (menu.menuId == menuId) {
          return menu;
        }
      }
    },

  },
};

export default App;
</script>
