<template>
    <div ref="chartRef" :style="{ height: height, width: width }" />
</template>

<script setup>
import { getCurrentInstance, watch, onMounted, ref } from 'vue'
import * as echarts from 'echarts'
import theme from '../theme/theme.json'
echarts.registerTheme('theme', theme)
import { CanvasRenderer } from 'echarts/renderers'
echarts.use([CanvasRenderer])
const { proxy } = getCurrentInstance()
const chartRef = ref(null)
const props = defineProps({
    width: {
        type: String,
        default: '100%'
    },
    height: {
        type: String,
        default: '350px'
    }
})
const options = {
    title: {
        text: '本月故障类型',
        left: 'left'
    },
    legend: {
        type: 'scroll',
        orient: 'vertical',
        bottom: 0,
        left: 0,
        height: 200,
        textStyle: {
            color: '#fff'
        }
    },
    grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
    },
    series: [
        {
            type: 'pie',
            data: [],
            label: {
                position: 'outside',
                formatter: '{b}-{c}\n{d}%',
                textBorderColor: '#fff',
                textBorderWidth: 0,
                color: '#fff'
            }
        }
    ]
}
const chart = ref(null)
function initChart() {
    chart.value = echarts.init(proxy.$refs.chartRef, 'theme')
    chart.value.setOption(options)
}
onMounted(() => {
    initChart()
    window.addEventListener('resize', () => {
        chart.value?.resize()
    })
})
/// ============ 修改数据 ===========
import { getFaultTypePie } from '@/api/smartScreen/DeviceScreen/index.js'
function updateData() {
    const param = {
        devicetTypeId: 1,
        searchTime: [proxy.dayjs().startOf('month'), proxy.dayjs().endOf('month')]
    }
    getFaultTypePie(param).then((res) => {
        if (res.code === 200) {
            // options.title = res.data.title
            // let _series = res.data.series
            // _series.forEach((item) => {
            //     item.label = {
            //         // 设置label在扇区内部
            //         position: 'inner',
            //         // 自定义显示格式，{b}表示名称，{d}表示百分比
            //         formatter: '{b}\n{d}%'
            //     }
            // })
            options.series = res.data
            chart.value.setOption(options)
            // console.log(res.data.title.text, res.data)
        }
    })
}
function handleQuery() {
    updateData()
}
handleQuery()
let timer1 = null
const clearSearchTimer = () => {
    clearInterval(timer1)
    timer1 = null
}
const createSearchTimer = () => {
    clearSearchTimer()
    timer1 = setInterval(() => {
        handleQuery()
    }, 1000 * 60 * 5)
}
onMounted(() => {
    createSearchTimer()
})
onUnmounted(() => {
    clearSearchTimer()
})
/// ==========================================
</script>
