<template>
  <div ref="ballDom" class="ball-box" :style="{ width: size + 'px', height: size + 'px' }" />
</template>

<script setup>
/**
 * Vue3 水波进度球
 * 用法：<WaterBall :percent="67" :size="200" />
 */
import { ref, watch, onMounted } from 'vue'
import * as echarts from 'echarts'
import 'echarts-liquidfill'

/* props */
const props = defineProps({
  percent: { type: Number, default: 60 },   // 0~100
  size: { type: Number, default: 200 },   // 画布宽高
  data: { type: Object, default: {} },
  color: { type: Array, default: [] },
})

/* dom */
const ballDom = ref(null)
let instance = null
// const color = ref([0, 0, 0])
// const makeColors = () => {
//   props.color[0] = Math.floor(Math.random() * 360)   // 随机色相
//   props.color[1] = 70                                   // 固定饱和度
//   props.color[2] = 50                                   // 固定亮度

// }
/* 颜色映射 */

/* 配置项 */
const makeOption = () => {
  const p = Math.min(100, Math.max(0, props.percent)) / 100
  console.log(props.color, 'colorcolorcolor')
  return {
    series: [{
      type: 'liquidFill',
      radius: '90%',
      data: [
        { value: p, direction: 'right' },
        { value: p, direction: 'left' }   // 两层波浪反向
      ],
      color: [`hsla(${props.color[0]}, ${props.color[1]}%, ${props.color[2]}%, ${1})`, `hsla(${props.color[0]}, ${props.color[1]}%, ${props.color[2]}%, ${0.8})`],
      waveAnimation: true,
      animationEasingUpdate: 'cubicOut',
      outline: {
        show: true,
        borderDistance: 4,          // 第一层边框
        itemStyle: {
          borderWidth: 3,
          borderColor: `hsla(${props.color[0]}, ${props.color[1]}%, ${props.color[2]}%, ${0.5})`
        }
      },
      backgroundStyle: {
        color: '#ffffff',
        shadowColor: '#fff', //阴影
        shadowBlur: 0, //阴影模糊

      },
      label: {
        show: true,
        formatter: `${props.data.text}` + `${props.data.unit}`,
        fontSize: 24,
        color: `hsla(${props.color[0]}, ${props.color[1]}%, ${props.color[2]}%, ${1})`,
        // insideColor: '#fff'
      }
    }]
  }
}

/* 初始化 */
const init = () => {
  if (instance) instance.dispose()
  instance = echarts.init(ballDom.value)
  instance.setOption(makeOption())
}

/* 自动更新 */
watch(() => props.percent, () => {
  instance?.setOption(makeOption())
})

onMounted(init)
</script>

<style scoped>
.ball-box {
  margin: 0 auto;
}
</style>