<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 = () => {
    const data = datas.value
    let names = [], personalCount = [], enterpriseCount = []
    for (let i = 0; i < data.length; i++) {
        const item = data[i]
        if (item.projectName) {
            names.push(item.projectName)
            personalCount.push(item.personalCount ? item.personalCount : '0')
            enterpriseCount.push(item.enterpriseCount ? item.enterpriseCount : '0')
        }
    }
    setOptions(names, personalCount, enterpriseCount)
}

//设置图表
const setOptions = (names = [], personalCount = [], enterpriseCount = []) => {
    setOption.value = {
        color: ['#5B8FF9', '#5AD8A6'],
        tooltip: {
            trigger: 'axis',
            axisPointer: {
                type: 'cross',
            },
        },
        legend: {
            data: ['个人证书', '企业证书'],
        },
        grid: {
            top: '40px',
            left: '0',
            right: '10px',
            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
                    },
                },
                boundaryGap: false,
                data: names,
            },
        ],
        yAxis: [
            {
                type: 'value',
                interval: 30,
            },
        ],
        series: [
            {
                name: '个人证书',
                type: 'line',
                areaStyle: {},
                data: personalCount,
            },
            {
                name: '企业证书',
                type: 'line',
                areaStyle: {},
                data: enterpriseCount,
            },
        ],
    }
}

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