<template>
  <div class="core--component--wrap user--list">
    <div>
      <div class="inner--header--wrap">
        <h2 class="inner--component--title none--after">
          가입자
        </h2>
        <span class="inner--component--date">{{ current }}</span>
      </div>  
      <div class="inner--content">
        <div class="oper--stat">
          <div class="card--title">
            <h3>테넌트 현황</h3>
          </div>
          <div class="card--alarm mb--1rem">
            <div class="card tenant1">
              <div class="ico" />
              <div class="alarm--txt">
                <p>Total</p>
                <span>{{ objCount.total }}</span>
              </div>
            </div>
            <div class="card tenant2 gray--alarm">
              <div class="ico" />
              <div class="alarm--txt">
                <p>대내</p>
                <span>{{ objCount.customer0 }}</span>
              </div>
            </div>
          </div>
          <div class="card--alarm">
            <div class="card tenant3 gray--alarm">
              <div class="ico" />
              <div class="alarm--txt">
                <p>대외</p>
                <span>{{ objCount.customer1 }}</span>
              </div>
            </div>
            <div class="card tenant4 gray--alarm">
              <div class="ico" />
              <div class="alarm--txt">
                <p>공용</p>
                <span>{{ objCount.customer2 }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="oper--stat">
          <div class="card--title">
            <h3>라이선스 인증 현황</h3>
          </div>
          <div class="card--alarm gap--0">
            <div class="card license1">
              <div class="ico" />
              <div class="alarm--txt">
                <p>인증</p>
                <span>{{ objCount.licentVerified }}</span>
              </div>
            </div>
            <div class="card license2 no--alarm">
              <div class="ico" />
              <div class="alarm--txt">
                <p>미인증</p>
                <span>{{ objCount.licentNotVerified }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 위젯 영역 -->
    <WidgetM
      v-if="isLoaded && widgetSize === 'M'"
      :items="userItems"
      :total-cnt="objCount.total"
    />
    <WidgetS
      v-if="isLoaded && widgetSize === 'S'"
      :items="userItems"
      :total-cnt="objCount.total"
    />
  </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 WidgetM from "@/components/home/dashboard/layout03/user/layout03UserWidgetM.vue"
  import WidgetS from '@/components/home/dashboard/layout03/user/layout03UserWidgetS.vue'
  import dayjs from "#build/dayjs.imports.mjs";
  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
   ************************/
  // TenantName
  const tenantName = computed(() => useAuthStore().getTenantName);

  // 설정된 위젯 사이즈 : M or S
  const widgetSize = computed(() => props.config?.widgetSize || 'M');
  
  // Swiper 표시 slide 갯수
  const slideItemSize = computed(() => widgetSize.value == 'M' ? 8 : 14)

  // 현재 일시
  const current = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'));

  // 카운트 정보
  const objCount = ref({
    total: 0,
    customer0: 0,
    customer1: 0,
    customer2: 0,
    licentVerified: 0,
    licentNotVerified: 0,
  })

  // 가입자 리스트
  const userItems = ref([]);

  // 데이터 조회 여부
  const isLoaded = ref(false);
  /***********************
   *     Methods
   ************************/
  const fnInit = () => {
    fnGetUserList();
  }

  const fnReset = () => {
    objCount.value.total = 0;
    objCount.value.customer0 = 0;
    objCount.value.customer1 = 0;
    objCount.value.customer2 = 0;
    objCount.value.licentVerified = 0;
    objCount.value.licentNotVerified = 0;

    current.value = dayjs().format('YYYY-MM-DD HH:mm:ss');
  }

  /** 가입자 목록 조회 */
  function fnGetUserList() {

    isLoaded.value = false;

    const params = {
      tenantName: tenantName.value,
    }

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

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

        fnParseData(data.items || [])

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

      $log.debug("[dashboard][fnGetUserList][error]", error)
      useErrorHandler().fnSetCommErrorHandle(error, fnGetUserList)
      // 테스트 데이터 파싱
    }).finally(()=>{
      $log.debug("[dashboard][fnGetUserList][finished]")
      isLoaded.value = true;
    }) 
  }

  /**
   * 데이터 가공
   */
  function fnParseData(items = []) {
    userItems.value = [];
    objCount.value.total = 0;
    objCount.value.customer0 = 0;
    objCount.value.customer1 = 0;
    objCount.value.customer2 = 0;
    objCount.value.licentVerified = 0;
    objCount.value.licentNotVerified = 0;

    let temp = [];

    // 정렬 적용
    temp = items.sort((a, b) => {
      const perA = fnGetPercentValue(a.maxSubscriber, a.curSubscriber);
      const perB = fnGetPercentValue(b.maxSubscriber, b.curSubscriber);
      return +perA < +perB ? 1 : (+perA > +perB ? -1 : 0);
    })


    // 데이터 가공
    temp = temp.map((item) => {

      //카운트 셋팅
      const { customerType, licenseKey } = item;

      objCount.value.total = objCount.value.total+1;

      if(customerType == 0) objCount.value.customer0 = objCount.value.customer0 + 1;
      else if(customerType == 1) objCount.value.customer1 = objCount.value.customer1 + 1;
      else if(customerType == 2) objCount.value.customer2 = objCount.value.customer2 + 1;

      if(licenseKey) objCount.value.licentVerified = objCount.value.licentVerified + 1;
      else objCount.value.licentNotVerified = objCount.value.licentNotVerified + 1;

      //percent 
      const { maxSubscriber, curSubscriber } = item;
      const perSubscriber = fnGetPercentValue(maxSubscriber, curSubscriber);

      //심각도 
      const level = fnGetLevel(perSubscriber);

      //차트 데이터 
      const chartData = {
        datasets: [
            {
              data: [curSubscriber , maxSubscriber - curSubscriber],
              backgroundColor: fnGetChartColorSet(level),
              borderWidth: 0,
            }
          ]
      }

      return {
        ...item,
        level,
        perSubscriber,
        chartData,
      }
    });

    userItems.value = splitIntoChunk(temp, slideItemSize.value)
  }

  /** Array Spliter */
  function splitIntoChunk(arr, chunk) {
    // 빈 배열 생성
    const result = [];
    
    for (let index=0; index < arr.length; index += chunk) {
      // slice() 메서드를 사용하여 특정 길이만큼 배열을 분리함
      const tempArray = arr.slice(index, index + chunk);
      // 빈 배열에 특정 길이만큼 분리된 배열을 추가
      result.push(tempArray);
    }
    
    return result;
  }

  /** make percent data */
  const fnGetPercentValue = (max, curr) => {
    return useUtil.toRoundFix((curr / max) * 100, 0);
  }

  const fnGetLevel = (per) => {
    if(per >= 95) return 'critical';        //critical
    else if(per >= 90) return 'major';      //major
    else if(per >= 85) return 'minor';      //minor
    else return '';                         //normal
  }

  /** 차트 데이터 > 컬러셋  */
  const fnGetChartColorSet = (level) => {
    if(level == 'critical') return ['#f00','#EAEAEA'];       //critical
    else if(level == 'major') return ['#C96103','#EAEAEA'];     //major
    else if(level == 'minor') return ['#DDA405','#EAEAEA'];     //minor
    else return ['#2D8CFA','#EAEAEA'];                          //normal
  }


  onMounted(() => fnInit());
  // 위젯사이즈 변경 watch
  watch(() => widgetSize.value, (v) => {
    fnReset();
    fnInit();
  }, {deep: true})
</script>

