<template>
  <div class="content--r--b">
    <div class="content--inner">
      <div class="content--inner--title">
        <p>Trend<!--<i class="ico"></i>--></p>
        <div class="select--wrap">
          <v-select
            v-model="objSltSearch.neFamilyName"
            :items="objSltOptions.neFamilyNameList"
            variant="outlined"
            style="width:12.875rem"
            class="custom-select"
            hide-details
          />
          <!-- <v-btn class="custom-btn btn-blue mid">
            적용
          </v-btn> -->
        </div>
        <div class="btn-wrap">
          <!-- <v-btn class="custom-btn mini btn-white btn-pip">
            <i class="ico" />전체보기
          </v-btn> -->
        </div>
      </div>
      <div
        v-if="chartItem && Object.keys(chartItem).length > 0"
        class="chart--con"
      >
        <div class="chart--in">
          <trendBar :chart-item="chartItem" />
        </div>
      </div>
      <!-- 데이터 없을 경우 -->
      <div
        v-else
        class="content--inner--content no--data"
      >
        <i class="ico" />데이터가 없습니다.
      </div>
    </div>
  </div>
</template>

<script setup>
  /***********************
   *     import
   ************************/
  import { useI18n } from "vue-i18n"
  import apiUrl from '@/composables/useApi';
  import useAxios from '@/composables/useAxios';
  import useUtil from '@/composables/useUtil';
  import dayjs from "#build/dayjs.imports.mjs";
  import trendBar from '@/components/home/tenant/chart/trendBar.vue'
  import testJson from '../dashboard/test.json'

  /***********************
   *     plugins inject
   ************************/
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp()

  // props
  const props = defineProps({})

  // 참조가능 데이터 설정
  defineExpose({
    fnInit,
  })

  // 발신 이벤트 선언
  const emit = defineEmits([""]);
  const i18n = useI18n();
  /***********************
   *     data & created
   ************************/
  // 차트데이터 조회 간격
  const chartInterval = ref(15);
  // 차트데이터 시작 시간
  const chartDiffHour = ref(-6);

  // 검색 option List object
  const objSltOptions = ref({
    neFamilyNameList: [],
  });
  // 검색 조건 Object
  const objSltSearch = ref({
    neFamilyName: '',
  })

  // 선택된 테넌트명
  const selectedTenantName = ref('');

  // chartdata
  const chartItem = ref({});

  /***********************
   *     Methods
   ************************/
  function fnInit(tenantName) {
    console.log('::::::: tenantTrend init ::::' , tenantName)
    fnReset();
    selectedTenantName.value = tenantName;
    fnGetTrendList()
  }

  const fnReset = () => {
    chartItem.value = {};
    objSltSearch.value.neFamilyName = '';
    objSltOptions.value.neFamilyNameList = [];
  }

  /**
   * 트렌드 목록 조회 : familyName 목록
   */
  const fnGetTrendList = (neFamilyName = '') => {

    return new Promise((resolve, reject) => {
      const params = {
        tenantName: selectedTenantName.value, 
        intv: chartInterval.value,
        start: dayjs().add(chartDiffHour.value, 'hours').format('YYYY-MM-DD HH:mm:ss'),
        end: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      }


      useAxios().get(useApi.getTrendHomeList, {params: params}).then((res) => {
        const {resCode, resMsg, data} = res.data;
        
        if(resCode == 200) {

          fnSetData(data, neFamilyName);

          $log.debug("[tenantDashboard][fnGetTrendList][success]")
        } else {
          $log.debug("[tenantDashboard][fnGetTrendList][error]", `[${resCode}] ${resMsg}`);
        }

        resolve();
        console.log('::::::::: 트렌드 목록 조회 ::', data)
      }).catch((error)=>{
        // 데이터가 없는 경우 204로 넘어온다...
        if(error?.response?.data?.status == 204) {
          fnSetData(null, neFamilyName);
          resolve();
          $log.debug("[tenantDashboard][fnGetTrendList][success empty]")
        } else {
          reject();
          $log.debug("[tenantDashboard][fnGetTrendList][error]", error)
          useErrorHandler().fnSetCommErrorHandle(error, fnGetTrendList)
        }
      }).finally(()=>{
        $log.debug("[tenantDashboard][fnGetTrendList][finished]")
      }) 
    })
  }

  const fnSetData = (data, neFamilyName) => {
    if(data && data.length > 0) {

      if(neFamilyName) {

        // 테스트 데이터 - 삭제 필수 : Todo: items가 어떻게 전달되는지 확인 후 적용 필요
        // const findData = data.find((nf) => nf.neFamilyName == neFamilyName) || {};
        // if(neFamilyName == 'nename001_RRC_ESTAB' || neFamilyName == 'nename001_RRC_REESTAB' || neFamilyName == 'nename001_UE_NUM_PER_GNB') {
        //   findData.items = [...testJson.tenantTrendItems1]
        // } else {
        //   findData.items = [...testJson.tenantTrendItems2]
        // }

        chartItem.value = data.find((nf) => nf.neFamilyName == neFamilyName) || {};
      } else {
        objSltOptions.value.neFamilyNameList = data.map((f) => {
          return {title: f.neFamilyName, value: f.neFamilyName} 
        });

        objSltSearch.value.neFamilyName = objSltOptions.value.neFamilyNameList[0].value;

        chartItem.value = data.find((nf) => nf.neFamilyName == objSltOptions.value.neFamilyNameList[0].value) || {};
      }
    } else {
      fnReset();
    }
  }

  /***********************
  *     Watch Computed
  ************************/
  watch(
    () => objSltSearch.value.neFamilyName, 
    async (neFamilyName) => {
      await fnGetTrendList(neFamilyName);
      console.log("chart neFamily change :::::::" , neFamilyName)
    }
  )
</script>