<template>
  <div ref="dashboardRef" class="dashboard" :style="{ height: (props.record?.itemHeight || 400) + 'px' }"></div>
</template>

<script setup name="FormDashboard">
import * as echarts from 'echarts';
import { ref, onMounted, watch, nextTick } from 'vue';

const props = defineProps({
  value: {
    type: Number,
    default: 0
  },
  //是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  record: {
    type: Object,
    default: {}
  },
  // 是否只读
  readonly: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['update:value', 'onChange']);

// 选中的值
const dataValue = ref(0);

// 仪表盘配置
const option = ref({
  series: [
    {
      type: 'gauge',
      min: props.record?.formItemNumber?.minValue || 0,
      max: props.record?.formItemNumber?.maxValue || 100,
      zlevel: 9,
      z: 9,
      progress: {
        show: true,
        width: 10
      },
      axisLine: {
        lineStyle: {
          width: 10
        }
      },
      axisTick: {
        show: true
      },
      // 指针
      pointer: {
        show: false
      },
      splitLine: {
        length: 15,
        lineStyle: {
          width: 2,
          color: '#999'
        }
      },
      axisLabel: {
        distance: 25,
        color: '#999',
        fontSize: 20
      },
      title: {
        show: true
      },
      detail: {
        valueAnimation: true,
        offsetCenter: [0, 0],
        formatter: '{value} %',
        color: 'inherit'
      },
      data: [
        {
          value: dataValue.value,
          name: props.record?.itemLabelName,
          title: {
            offsetCenter: ['0%', '30%']
          }
        }
      ]
    }
  ]
});

// ref
const dashboardRef = ref(null);

const myChart = ref(null);

onMounted(() => {
  if (props.record?.formItemNumber?.defaultValue) {
    dataValue.value = props.record?.formItemNumber?.defaultValue;
    dataValueChange();
  } else {
    dataValue.value = props.value;
  }
  initEcharts();
});

//初始化仪表盘
const initEcharts = () => {
  nextTick(() => {
    myChart.value = echarts.getInstanceByDom(dashboardRef.value);
    if (myChart.value == null) {
      myChart.value = echarts.init(dashboardRef.value);
    }
    option.value.series[0].data[0].value = dataValue.value;
    myChart.value.setOption(option.value);
  });
};

// 更改值
const dataValueChange = () => {
  emits('update:value', dataValue.value);
  emits('onChange', props.record);
};

watch(
  () => props.value,
  val => {
    dataValue.value = val;
    initEcharts();
  },
  { deep: true }
);
</script>

<style>
.dashboard {
  width: 100%;
}
</style>
