<template>
  <div class="box">
    <a-row :gutter="5">
      <a-col
        class="gutter-row"
        :span="24 / config.dashboard.length"
        v-for="(item, index) in config.dashboard"
        :key="index"
      >
        <div class="text-xs pt-4.5" :style="labelColorStyle">{{ item.name }}</div>
        <div class="text-2xl" :style="numColorStyle">
          <CountTo prefix="" :startVal="0" :endVal="getVal(item.field)" class="text-2xl" />
        </div>
      </a-col>
    </a-row>
  </div>
</template>

<script setup lang="ts">
  import { dashboardProperties } from '../config/properties';
  import { CountTo } from '/@/components/CountTo/index';
  import { DesktopComponent } from '/@/enums/desktop';
  import { DashboardConfig } from '/@/model/mobileDesign/designer';

  import { computed, nextTick, watch } from 'vue';
  import { isNumber } from 'lodash-es';
  import useApiRequest from '/@/hooks/event/useApiRequest';
  const { changeApiOptions } = useApiRequest();
  const props = withDefaults(
    defineProps<{
      type: DesktopComponent;
      title: string;
      config: DashboardConfig;
    }>(),
    {
      type: DesktopComponent.DEFAULT,
      title: '',
      config: () => {
        return dashboardProperties;
      },
    },
  );
  const emit = defineEmits(['update:config']);
  watch(
    () => props.config.renderKey,
    (val) => {
      val && resizeLayout();
    },
    {
      deep: true,
    },
  );
  async function resizeLayout() {
    await nextTick();
    await changeData();
  }
  const numColorStyle = computed(() => {
    return 'color:' + (props.config.numColor ? props.config.numColor : '#666666');
  });
  const labelColorStyle = computed(() => {
    return 'color:' + (props.config.labelColor ? props.config.labelColor : '#999999');
  });

  async function changeData() {
    let config = props.config;
    if (config.apiConfig.path) {
      let res = await changeApiOptions(config.apiConfig);
      config.apiData = res;
      config.apiColumns = [];
      for (let [key, value] of Object.entries(config.apiData)) {
        if (isNumber(value)) {
          config.apiColumns.push(key);
        }
      }
      emit('update:config', config);
    }
  }
  function getVal(key) {
    let num = props.config.apiData[key];
    return isNaN(parseFloat(num)) ? 0 : Number(parseFloat(num).toFixed(2));
  }
</script>

<style lang="less" scoped>
  .box {
    border-left: 5px solid @primary-color;
    text-align: center;
    height: 75px;
  }
</style>
