<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: [` ${props.color[1]}`, ` ${props.color[0]}`],
      waveAnimation: true,
      animationEasingUpdate: 'cubicOut',
      outline: {
        show: true,
        borderDistance: 2,          // 第一层边框
        itemStyle: {
          shadowBlur: 0,        // 同样设为 0
          borderWidth: 1,
          borderColor: `${props.color[0]}`,
          shadowColor: 'transparent'
        }
      },
      // 1. 关掉波浪的阴影
      itemStyle: {
        shadowBlur: 0,          // 关键：阴影范围设为 0
        shadowColor: 'transparent'
      },

      backgroundStyle: {
        color: `${props.color[2]}`,
        borderWidth: 1,
        borderColor: `${props.color[1]}`, // 中间区域保持透明
        shadowBlur: 0
      },
      label: {
        show: true,
        formatter: `${props.data.text}` + `${props.data.unit}`,
        fontSize: 24,
        color: `${props.color[3]}`,
        insideColor: `${props.color[3]}`,
      }
    }]
  }
}

/* 初始化 */
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>