<script setup lang="ts">
import { computed, onMounted, useTemplateRef } from 'vue';

interface Props {
  text?: string | number;
  percent: number;
  height?: number;
}

const props = withDefaults(defineProps<Props>(), {
  text: '',
  height: 20,
});

const barText = computed(() => {
  if (props.percent === 0) {
    return '""';
  }

  return `"${props.text}"`;
});

const isTextInProgress = computed(() => {
  return props.percent > 50;
});

const progressRef = useTemplateRef('progress');

onMounted(() => {
  if (progressRef.value) {
    const el = progressRef.value.$el as HTMLElement;
    const { paramCode } = el.dataset;

    // 若该组件设置了参数编码作为数据属性，则同样使其内部元素也设置相同的属性和值。当在设备工况的卡片中使用时，点击该组件可以查看该参数的历史数据
    if (paramCode) {
      const progressInnerEl = el.querySelector<HTMLElement>('.ant-progress-inner');
      const progressBgEl = el.querySelector<HTMLElement>('.ant-progress-bg');
      progressInnerEl?.setAttribute('data-param-code', paramCode);
      progressBgEl?.setAttribute('data-param-code', paramCode);
    }
  }
});
</script>

<template>
  <AProgress
    ref="progress"
    :class="['progress-text-bar', { 'progress-inner-text': isTextInProgress }]"
    :percent="percent"
    :size="height"
    :show-info="false"
    :stroke-color="{
      '0%': 'var(--antd-color-primary-border-hover)',
      '100%': 'var(--antd-color-primary)',
    }"
  />
</template>

<style lang="scss" scoped>
.progress-text-bar {
  margin: 0;
  line-height: unset;

  :deep(.ant-progress-outer) {
    .ant-progress-inner {
      background-color: #f0f2f5;
    }

    .ant-progress-inner,
    .ant-progress-success-bg,
    .ant-progress-bg {
      border-radius: 4px;
    }

    .ant-progress-bg {
      display: flex;
      align-items: center;
      background-color: var(--antd-color-primary-border-hover);
    }

    .ant-progress-bg::before {
      position: absolute;
      left: calc(100% + 8px);
      font-family: DINAlternate;
      font-size: 12px;
      font-weight: bold;
      line-height: 16px;
      color: #000;
      content: v-bind(barText);
    }
  }
}

.progress-inner-text {
  :deep(.ant-progress-outer) {
    .ant-progress-bg::before {
      right: 8px;
      left: unset;
      color: #fff;
    }
  }
}
</style>
