<template>
  <div class="core--component--wrap">
    <div class="inner--header--wrap">
      <h2 class="inner--component--title none--after">
        RAN
      </h2>
      <!--<div class="pagenation--wrapper">
         <div class="total--wrapper">
           Total : <span class="total--count">18</span>
         </div>
         <div class="pager--btn--wrap">
           <v-btn flat class="page--btn prev--btn"></v-btn>
           <div class="page--numb">
             <span class="current">1</span>/<span>3</span>
           </div>
           <v-btn flat class="page--btn next--btn"></v-btn>

           <div class="user--type">
            <v-select
              v-model="sltModel1"
              :items="slt1"
              variant="outlined"
              style="width:9.5rem"
              class="custom-select"
              >
              </v-select>

            <v-select
              v-model="sltModel2"
              :items="slt2"
              variant="outlined"
              style="width:9.5rem"
              class="custom-select"
              >
              </v-select>

              <v-btn class="custom-btn mini lgd--btn"></v-btn>
           </div>
         </div>
       </div>-->
    </div>  
    <div class="inner--content">
      <ul class="ran--card">
        <li v-for="(item, idx) in cardRanInfo" :key="idx" :class="item.cls">
          <div class="ran--title">
            <span class="ran--area">{{item.areaName}}</span>
            <v-btn class="more--btn" flat @click="fnClickCardDetail(item)"></v-btn>
          </div>
          <div class="ran--stat">
            <p>
              <span>테넌트 수</span><span>{{item.tenantCnt}}</span>
            </p>
            <p>
              <span>NE그룹 수</span><span>{{item.neGroupCnt}}</span>
            </p>
            <p>
              <span>NE 수</span><span>{{item.neCnt}}</span>
            </p>
          </div>
        </li>
      </ul>
    </div>

    <RanCardGroupDetailModal v-if="isShowRanCardGroupDetailModal" :propsObj="propsCardObj" :centerPosition="centerPosition" @closeModal="isShowRanCardGroupDetailModal = false"/>
  </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 RanCardGroupDetailModal from '@/components/home/dashboard/common/ranCardGroupDetailModal.vue';
  /***********************
   *     plugins inject
   ************************/
  const { $toast, $log, $dayjs, $eventBus } = useNuxtApp()

  // props
  const props = defineProps({})

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

  // 발신 이벤트 선언
  const emit = defineEmits([""]);
  const i18n = useI18n();

  /***********************
   *     data & created
   ************************/
  const isShowRanCardGroupDetailModal = ref(false)
  // 카카오맵 센터좌표
  const centerPosition = ref({
    lat: 33.450701,
    lng: 126.570667
  })
  const ranInterval = ref(null)
  const sidoCode = ref([])
  const cardRanInfo = ref([])       // 카드형 데이터

  const propsCardObj = ref({})
  onMounted(() => {
    console.log('%c 대시보드 레이아웃2 RAN 카드형 24*12' ,'color:#bada55','')
    fnGeoTenantNeInfo()

    ranInterval.value = setInterval(() => {
      fnGeoTenantNeInfo()
    }, 1000 * 60 * 5)
  })
  onUnmounted(() => {
    clearInterval(ranInterval.value)
    ranInterval.value = null
  })
  watchEffect(() =>{
    fnGetEnumCode(useLangStore().getLang)
  })
  /**
   * ENUM 업데이트
   * @param lang
   */
  function fnGetEnumCode(lang){
    let objEnum = useEnumCode.getEnumCode(lang)
    // ...objEnum.sidoCode
    sidoCode.value = _cloneDeep(objEnum.sidoCode.slice(1))
    fnSetInitMapData()
  }

  const getCardAllRan = computed(() => {
    let result = {
      areaName: '전국현황', areaCode: 0, cls: 'ran--all', criCnt: 0, majCnt: 0, minCnt: 0, tenantCnt: 0, neGroupCnt: 0, neCnt: 0, tenantList:[], neGroupList: []
    }
    cardRanInfo.value.forEach((item, idx) => {
      if(idx !== 0) {
        result.criCnt += item.criCnt
        result.majCnt += item.majCnt
        result.minCnt += item.minCnt
        result.tenantCnt += item.tenantCnt
        result.neGroupCnt += item.neGroupCnt
        result.neCnt += item.neCnt
        result.tenantList.push(...item.tenantList)
        result.neGroupList.push(...item.neGroupList)
      }
    })

    return result
  })
  /***********************
   *     Methods
   ************************/
  // 초기 데이터 세팅
  function fnSetInitMapData(){
    let tempCardRanData = [{areaName: '전국현황', areaCode: 0, cls: 'ran--all', criCnt: 0, majCnt: 0, minCnt: 0, tenantCnt: 0, neGroupCnt: 0, neCnt: 0, tenantList:[], neGroupList: []}]
    sidoCode.value.forEach((item) => {
      let cardRanObj = {}
      cardRanObj.areaName = item.title[0]
      cardRanObj.areaCode = item.value
      cardRanObj.cls = ''
      cardRanObj.criCnt = 0
      cardRanObj.majCnt = 0
      cardRanObj.minCnt = 0
      cardRanObj.tenantCnt = 0
      cardRanObj.neGroupCnt = 0
      cardRanObj.neCnt = 0
      cardRanObj.tenantList = []
      cardRanObj.neGroupList = []
      tempCardRanData.push(cardRanObj)
    })
    cardRanInfo.value = _cloneDeep(tempCardRanData)
  }
  /**
   * P5G RAN
   */
  function fnGeoTenantNeInfo() {
    let _req = {
      tenantName: useAuthStore().getTenantName
    }
    useAxios().post(useApi.tenantNeInfo, _req).then((res) => {
      $log.debug("[dashboard][fnGeoTenantNeInfo][success]")
      let datas = res.data.data.items
      fnMakeNeData(datas)
    }).catch((error)=>{
      $log.debug("[dashboard][fnGeoTenantNeInfo][error]")
      useErrorHandler().fnSetCommErrorHandle(error, fnGeoTenantNeInfo)
    }).finally(()=>{
      $log.debug("[dashboard][fnGeoTenantNeInfo][finished]")
    })
  }
  /**
  * 지도 데이터 및 모든 데이터 가공
  */
  function fnMakeNeData(arr){
    // 데이터 초기화
    fnSetInitMapData()

    arr.forEach((item, idx) => {
      // 카드형 데이터 세팅
      let cardFindIndex = cardRanInfo.value.findIndex((obj => obj.areaCode === item.areaCode))
      if(cardFindIndex !== -1) {
        // 테넌트 리스트 세팅
        cardRanInfo.value[cardFindIndex].minCnt += item.minCnt
        cardRanInfo.value[cardFindIndex].majCnt += item.majCnt
        cardRanInfo.value[cardFindIndex].criCnt += item.criCnt
    
        if(!cardRanInfo.value[cardFindIndex].tenantList.includes(item.tenantName)) {
          cardRanInfo.value[cardFindIndex].tenantList.push(item.tenantName)
          cardRanInfo.value[cardFindIndex].tenantCnt++
        }
        // 그룹 및 NE 세팅
        if(!_isEmpty(_find(cardRanInfo.value[cardFindIndex].neGroupList, {neGroup: item.neGroup}))) {
          let groupFindIndex = cardRanInfo.value[cardFindIndex].neGroupList.findIndex((obj => obj.neGroup === item.neGroup))
          cardRanInfo.value[cardFindIndex].neGroupList[groupFindIndex].minCnt += item.minCnt
          cardRanInfo.value[cardFindIndex].neGroupList[groupFindIndex].majCnt += item.majCnt
          cardRanInfo.value[cardFindIndex].neGroupList[groupFindIndex].criCnt += item.criCnt
          cardRanInfo.value[cardFindIndex].neGroupList[groupFindIndex].neCnt++
          cardRanInfo.value[cardFindIndex].neGroupList[groupFindIndex].tenantName = item.tenantName
          cardRanInfo.value[cardFindIndex].neGroupList[groupFindIndex].neList.push(item)
          cardRanInfo.value[cardFindIndex].neCnt++
        }else{
          cardRanInfo.value[cardFindIndex].neGroupList.push({neGroup: item.neGroup, tenantName: item.tenantName, neCnt: 1, minCnt: item.minCnt, majCnt: item.majCnt, criCnt: item.criCnt, neList: [item]})
          cardRanInfo.value[cardFindIndex].neGroupCnt++
          cardRanInfo.value[cardFindIndex].neCnt++
        }
      }
    })
    
    // 카드형 데이터 > 전국현황 데이터 세팅
    cardRanInfo.value[0] = _cloneDeep(getCardAllRan.value)
    console.log('%c 카드형 전국현황 데이터 [cardRanInfo]' ,'color:#bada55', cardRanInfo.value)
  }
  /**
   * 카드형 UI 상세보기 클릭
   */
  function fnClickCardDetail(item) {
    console.log('%c 클릭 item' ,'color:#bada55', item)
    propsCardObj.value = item
    isShowRanCardGroupDetailModal.value = true
  }
</script>

