<template>
    <hc-charts :option="setOption" />
</template>

<script setup>
import { nextTick, onMounted, ref, watch } from 'vue'

const props = defineProps({
    datas: {
        type: Array,
        default: () => ([]),
    },
})

//初始变量
const setOption = ref({})

//深度监听数据变化
const datas = ref(props.datas)
watch(() => props.datas, (data) => {
    datas.value = data
    setDataFormat()
}, { deep: true })

//处理数据
const setDataFormat = () => {
    let data = datas.value, names = []
    for (let i = 0; i < data.length; i++) {
        const { projectName, contractor, supervision, owner } = data[i]
        if (projectName) {
            names.push([projectName, contractor ? contractor : 0, supervision ? supervision : 0, owner ? owner : 0])
        }
    }
    setOptions(names)
}

//设置图表
const setOptions = (datas = []) => {
    setOption.value = {
        color: ['#5B8FF9', '#5AD8A6', '#5D7092'],
        legend: {},
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
            },
        },
        dataset: {
            source: [
                ['product', '施工方', '监理方', '指挥部'],
                ...datas,
            ],
        },
        grid: {
            top: '20px',
            left: '0',
            right: '4px',
            bottom: '0',
            containLabel: true,
        },
        xAxis: {
            type: 'category',
            axisLabel: {
                overflow: 'breakAll',
                interval: 0,
                rotate: -50,
                formatter: function (value) {
                    return value.length > 5 ? value.slice(0, 3) + '...' : value
                },
            },
        },
        yAxis: {},
        series: [{ type: 'bar' }, { type: 'bar' }, { type: 'bar' }],
    }
}

//渲染完成
onMounted(() => {
    nextTick(() => {
        setDataFormat()
    })
})
</script>
