<template>
  <div
    class="core--component--wrap"
    :class="widgetSize === 'S' ? 'small' : ''"
  >
    <div class="inner--header--wrap">
      <h2 class="inner--component--title none--after">
        CORE
      </h2>
      <pagination
        :page-obj="pageObj"
        @chg_page="fnChgPage"
      >
        <template #rightArea>
          <div class="search--box">
            <v-select
              v-model="objSltSearch.neType"
              :items="objSlt.neTypeList"
              variant="outlined"
              style="width:9.0625rem;"
              class="custom-select"
            />
            <v-select
              v-model="objSltSearch.customerType"
              :items="objSlt.customerTypeList"
              variant="outlined"
              style="width:9.0625rem;"
              class="custom-select"
            />
            <v-btn
              class="custom-btn mini sort-btn"
              flat
              @click="isSortShow ? isSortShow = false : isSortShow = true"
            />
            <div
              v-if="isSortShow == true"
              class="sort--atv"
            >
              <ul>
                <li
                  v-for="(sort, index) in objSlt.sortTypeList"
                  :key="`sort-option-${index}`"
                  :class="{atv: objSltSearch.sortType == sort.value}"
                  @click="fnOnclickSortType(sort.value)"
                >
                  {{ sort.title }}
                </li>
              </ul>
            </div>
          </div>
        </template>
      </pagination>
    </div>  

    <!-- 위젯 영역 -->
    <WidgetM
      v-if="widgetSize === 'M'"
      :items="coreItems"
      @more="fnCoreDetailClick"
    />
    <WidgetS
      v-if="widgetSize === 'S'"
      :items="coreItems"
      @more="fnCoreDetailClick"
    />
    
    <!-- 코어 상세보기 Modal  -->
    <CoreDetailModal
      ref="refCoreDetailModal"
      :is-core-detail-modal="isCoreDetailModal"
      @close-modal="fnCloseCoreDetailModal"
    />
  </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 CoreDetailModal from "@/components/home/dashboard/common/coreDetailModal.vue"
  import WidgetM from "@/components/home/dashboard/layout02/core/layout02CoreWidgetM.vue"
  import WidgetS from "@/components/home/dashboard/layout02/core/layout02CoreWidgetS.vue"
  import pagination from "@/components/home/dashboard/common/pagination.vue"
  import testJson from "../../test.json"

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

  // props
  const props = defineProps({
    config: {
      type: Object,
      default: () => {}
    },
    intervalTime: {
      type: Number,
      default: 5000
    }
  })

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

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

  /***********************
   *     data & created
   ************************/
  // 코어 상세보기 모달
  const refCoreDetailModal = ref(null);
  const isCoreDetailModal = ref(false);

  // TenantName
  const tenantName = computed(() => useAuthStore().getTenantName);

  // 설정된 위젯 사이즈 : M or S
  const widgetSize = computed(() => props.config?.widgetSize || 'M');
  // 위젯 사이즈별 표시 갯수
  const widgetListLimit = ref({
    S: 12, M: 6
  });

  // 페이징 정보
  const pageObj = ref( {
    page: 1, // 현재 페이지
    pageSize: widgetListLimit.value[widgetSize.value],
    totalCnt: 0, // 전체 페이지
  })

  const objSltSearch = ref({
    neType: '', 
    customerType: '',
    sortType: '',
  })
  // 검색조건
  const objSlt = ref({
    neTypeList: [], 
    customerTypeList: [],
    sortTypeList: [
      {title: '위험도순', value: 0},
      {title: '이름순(오름차순)', value: 1},
      {title: '이름순(내림차순)', value: 2}
    ],
  })

  // 코어 리스트
  const coreItems = ref([]);

  // 정렬 옵션 open 여부
  const isSortShow = ref(false);
   
  /***********************
   *     Methods
   ************************/
  /**
   * 리셋
   */
   const fnReset = () => {
    objSltSearch.value.neType = '';
    objSltSearch.value.customerType = '';
    objSltSearch.value.sortType = '';

    pageObj.value.page = 1;
    pageObj.value.pageSize = widgetListLimit.value[widgetSize.value],
    pageObj.value.totalCnt = 0;
  }

  /**
   * 코어 리스트 조회
   */
  function fnGetCoreList() {
    const params = {
      tenantName: tenantName.value,
    }

    useAxios().post(apiUrl.getCoreInfoList, params).then((res) => {
      const {resCode, resMsg,  data} = res.data;

      if(resCode == 200) {
        // 테스트를 위한 테스트 코드 (삭제 필수)
        // fnParseData([...(data?.items || []), ...testJson.core.data.items])

        fnParseData(data.items || [])

        $log.debug("[dashboard][fnGetCoreList][success]")
      } else {
        $log.debug("[dashboard][fnGetCoreList][error]", `[${resCode}] ${resMsg}`);
      }
    }).catch((error)=>{
      // 테스트를 위한 테스트 코드 (삭제 필수)
      // fnParseData([...testJson.core.data.items])

      $log.debug("[dashboard][fnGetCoreList][error]", error)
      useErrorHandler().fnSetCommErrorHandle(error, fnGetCoreList)
    }).finally(()=>{
      $log.debug("[dashboard][fnGetCoreList][finished]")
    }) 

  }

  /**
   * 데이터 가공
   */
   function fnParseData(items = []) {
    // {neType: 'AMF', neName: 'neName1', emsStatus: 0, mcmStatus: 0, psmStatus: 0, criCnt: 3,majCnt: 1, minCnt: 1,customerType: 1,CPU: {AVG_CPU_L: 14,PEAK_CPU_L: 15, }, MEM: {AVG_MEM_L: 6,PEAK_MEM_L: 95,}},
    // {id: 14, customerType: '1', level: 'MINOR', isDisconnect: false, neType: 'AMF', status: 'ACTIVE', cpu: Math.random() * 100, memory: Math.random() * 100, disk: Math.random() * 100}, 

    coreItems.value = [];

    if(!items || items.length < 1) {
      pageObj.value.totalCnt = 0;
      return;
    }

    let temp = [];

    // 검색 조건 적용
    const { neType, customerType} = objSltSearch.value;
    temp = items.filter((data) => (useUtil.isNull(neType) || neType == data.neType) && (useUtil.isNull(customerType) || customerType == data.customerType));

    // 정렬 조건 적용
    const { sortType } = objSltSearch.value;
    temp = temp.sort((a, b) => {
      // 위험도순
      if(sortType == 0) {
        return a.criCnt < b.criCnt ? 1 : a.criCnt > b.criCnt ? -1 : (a.majCnt < b.majCnt ? 1 : a.majCnt > b.majCnt ? -1 : (a.minCnt < b.minCnt ? 1 : a.minCnt > b.minCnt ? -1 : 0));
      } 
      //이름순 오름차순
      else if(sortType == 1) {
        return a.neName < b.neName ? -1 : a.neName > b.neName ? 1 : 0;
      }
      //이름순 내림차순 
      else if(sortType == 2) {
        return a.neName > b.neName ? -1 : a.neName < b.neName ? 1 : 0;
      }
    })

    // 페이징 적용
    pageObj.value.totalCnt = temp.length;
    temp = temp.filter((data, index) =>(index >= ((pageObj.value.page - 1) * pageObj.value.pageSize) && index < (pageObj.value.page * pageObj.value.pageSize)));

    // 데이터 가공
    coreItems.value = temp.map((item) => {
      // KPI 정보 셋팅 - TODO: CPU, MEM 외의 값이 추가되면 여기에 추가
      const { cpu, mem } = item;
      const kpiItems = [];

      if(cpu) {
        const objCpu = typeof cpu === 'string' ? JSON.parse(cpu) : cpu;
        if(objCpu && objCpu[`AVG_CPU_L(%)`]){
          kpiItems.push({label: 'CPU', val: objCpu[`AVG_CPU_L(%)`] || 0})
          item.cpu = objCpu;
        }

      }
      if(mem) {
        const objMem = typeof mem === 'string' ? JSON.parse(mem) : mem ; 
        if(objMem && objMem['AVG_MEM_L(%)']){
          kpiItems.push({label: 'MEMORY', val: objMem['AVG_MEM_L(%)'] || 0})
          item.mem = objMem;
        }
      }

      //고객 유형명 셋팅
      const { customerType } = item;
      let customerTypeName = '';

      if(customerType) {
        const type = objSlt.value.customerTypeList.find((t) => t.value == customerType)
        if(type) customerTypeName = type.title;
      }

      // disconected 셋팅
      const { emsStatus, mcmStatus, psmStatus } = item;
      const connect = {
        isConnected: false,
        reason: [],
      }

      if([emsStatus, mcmStatus, psmStatus].every((status) => status == 0)) {
        connect.isConnected = true;
      } else {
        connect.isConnected = false;
        if(emsStatus != 0 ) connect.reason.push(`emsSatats: ${emsStatus}`);
        if(mcmStatus != 0 ) connect.reason.push(`mcmStatus: ${mcmStatus}`);
        if(psmStatus != 0 ) connect.reason.push(`psmStatus: ${psmStatus}`);
      }

      // 심각도 level 셋팅
      const { criCnt ,majCnt, minCnt } = item;
      let level = '';
      if(criCnt > 0) level = 'CRITICAL';
      else if(majCnt > 0) level = 'MAJOR';
      else if(minCnt > 0) level = 'MINOR';


      return {
        ...item, 
        kpiItems,   // kpi 정보
        customerTypeName,   // 고객유형명
        connect,    // 연결 상태
        level,      // 심각도 레벨
      }
    });
  }

  /**
  * 페이지 변경
  */
  function fnChgPage(page){
    pageObj.value.page = page;
    fnGetCoreList();
    // gridApi.value.paginationGoToPage(page-1)
  }

  /** 코어 상세보기 open */
  function fnCoreDetailClick(item) {
    isCoreDetailModal.value = true
    refCoreDetailModal.value.fnInit(item)
  }
  /** 코어 상세보기 Close */
  function fnCloseCoreDetailModal() {
    isCoreDetailModal.value = false
  }

  
  /** 검색조건 > 정렬 변경 */
  function fnOnclickSortType(type) {
    objSltSearch.value.sortType = type;
    isSortShow.value = false;
  }

  /**
   * ENUM 업데이트
   * @param lang
   */
   function fnGetEnumCode(lang){
    lang = useUtil.nvl(lang, 'kr')
    const objEnum = useEnumCode.getEnumCode(lang)
    objSlt.value.neTypeList = [{title: i18n.t('common.all'), value: ''},...objEnum.neType]
    objSlt.value.customerTypeList = [{title: i18n.t('common.all'), value: ''},...objEnum.customerType]
  }

  onMounted(() => fnGetCoreList())
  watchEffect(() => fnGetEnumCode(useLangStore().getLang))
  // 검색 조건 변경 watch
  watch(() => objSltSearch.value, () => {
    pageObj.value.page = 1;
    fnGetCoreList();
  }, {deep: true})
  // 위젯사이즈 변경 watch
  watch(() => widgetSize.value, () => {
    fnReset();
    fnGetCoreList();
  }, {deep: true})
</script>

