<template>
  <div class="content--l">
    <div class="content--inner">
      <div class="content--inner--title">
        <h3>사용 현황</h3>
      </div>
      <div class="content--inner--content">
        <div class="db--chart--wrap">
          <userDoughnut
            :max-subscriber="userInfo?.maxSubscriber || 0"
            :cur-subscriber="userInfo?.curSubscriber || 0"
          />
        </div>
      </div>
    </div>
    <div class="content--inner">
      <div class="content--inner--title">
        <h3>테넌트 정보</h3>
        <p
          v-if="dday != '' && dday > 0"
          class="d--day"
        >
          D-{{ dday }}일
        </p>
        <p
          v-else-if="dday != '' && dday < 1"
          class="d--day"
        >
          만료
        </p>
      </div>
      <div class="content--inner--content">
        <div class="db--table">
          <table>
            <colgroup>
              <col style="width:7.5rem">
              <col>
            </colgroup>
            <tbody>
              <tr>
                <th>테넌트명</th>
                <td>{{ userInfo?.tenantName }}</td>
              </tr>
              <tr>
                <th>테넌트 고유번호</th>
                <td>{{ userInfo?.tenantCode }}</td>
              </tr>
              <tr>
                <th>고객 유형</th>
                <td>{{ customerTypeName }}</td>
              </tr>
              <tr>
                <th>라이선스 키</th>
                <td>{{ userInfo?.licenseKey }}</td>
              </tr>
              <tr>
                <th>라이선스 유형</th>
                <td>{{ licenseTypeName }}</td>
              </tr>
              <tr>
                <th>라이선스 발급일</th>
                <td>{{ issueDate }}</td>
              </tr>
              <tr>
                <th>라이선스 만료일</th>
                <td>{{ expirationDate }}</td>
              </tr>
              <tr>
                <th>계정 현황</th>
                <td>
                  <span>사용 : {{ userInfo?.currentAccountCount || 0 }}</span> / 최대 : {{ userInfo?.maxAccount || 0 }}
                </td>
              </tr>
              <tr>
                <th>접속 현황</th>
                <td>
                  <span>사용 : {{ userInfo?.currentConnectingCount || 0 }}</span> / 최대 : {{ userInfo?.maxSession || 0 }}
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
  /***********************
  *     import
  ************************/
  import { useI18n } from 'vue-i18n'
  import userDoughnut from '@/components/home/tenant/chart/userDoughnut.vue'
  import dayjs from '#build/dayjs.imports.mjs';
  import testJson from '../dashboard/test.json'
  /***********************
  *     plugins inject
  ************************/
  const {$toast, $log, $dayjs, $eventBus } = useNuxtApp()
  const i18n = useI18n()

  const props = defineProps({})

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

  /***********************
  *     data & created
  ************************/
  
  // 사용 현황 정보
  const userInfo = ref({});

  
  /***********************
   *     Watch Computed
   ************************/
  const licenseTypeList = computed(() => {
    return useEnumCode.getEnumCode(useUtil.nvl(useLangStore().getLang, 'kr')).licenseType;
  })
  const customerTypeList = computed(() => {
    return useEnumCode.getEnumCode(useUtil.nvl(useLangStore().getLang, 'kr')).customerType;
  })

  const licenseTypeName = computed(() => fnGetLicenseTypeName(userInfo.value?.licenseType));
  const customerTypeName = computed(() => fnGetCustomerTypeName(userInfo.value?.customerType));
  const issueDate = computed(() => fnGetDateStr(userInfo.value?.issueDate));
  const expirationDate = computed(() => fnGetDateStr(userInfo.value?.expirationDate));
  const dday = computed(() => fnGetDayDiff(userInfo.value?.expirationDate));

  
  /***********************
  *     Methods
  ************************/
  function fnInit(tenantName) {
    fnGetUserInfo(tenantName)
  }

  /**
   * 사용 현황 정보 조회
   */
  const fnGetUserInfo = (tenantName) => {
    const params = {
      tenantName: tenantName
    }

    userInfo.value = {};

    useAxios().post(useApi.getUserList, params).then((res) => {

      const {resCode, resMsg, data} = res.data;

      if(resCode == 200) {

        userInfo.value = data.items.find((i) => i.tenantName == params.tenantName);

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

      console.log('::::::::: 사용자 정보 조회 ::', userInfo.value)
    }).catch((error)=>{
      $log.debug("[tenantDashboard][fnGetUserList][error]", error)
      useErrorHandler().fnSetCommErrorHandle(error, fnGetUserInfo)
      // 테스트 데이터 파싱
    }).finally(()=>{
      $log.debug("[tenantDashboard][fnGetUserList][finished]")
    }) 
  }

  // 라이선스 유형명
  const fnGetLicenseTypeName = (licenseType) => {
    if(useUtil.isNull(licenseType)) return '';
    const licenseTypeObj = licenseTypeList.value.find((l) => l.value == licenseType)
    return licenseTypeObj ? licenseTypeObj.title : ''
  }
  // 고객 유형명
  const fnGetCustomerTypeName = (customerType) => {
    if(useUtil.isNull(customerType)) return '';
    const customerTypeObj = customerTypeList.value.find((c) => c.value == customerType)
    return customerTypeObj ? customerTypeObj.title : ''
  }
  // 날짜
  const fnGetDateStr = (date) => {
    try {
      if(!date) return '';
      return dayjs(date).format('YYYY-MM-DD')
    } catch(e) {
      return date;
    }
  }
  // DDay
  const fnGetDayDiff = (date) => {
    try {
      if(!date) return '';
      return Math.floor(dayjs(date).diff(dayjs(), 'days') + 1);
    } catch(e) {
      return ''
    }
  }

</script>