<template>
    <div class="box">
        <div :id="id" class="pie-charts"></div>
        <div class="levelbox">
            <div
                class="levelItem"
                @click="dispatchSel('在线设备')"
                @mouseover="dispatchHov('在线设备', 'highlight')"
                @mouseout="dispatchHov('在线设备', 'downplay')"
            >
                <span class="online-dot"></span>
                <span class="level">在线设备</span>
                <span class="online-rate">{{ onlineRate + '%' }}</span>
            </div>
            <div
                class="levelItem"
                @click="dispatchSel('离线设备')"
                @mouseover="dispatchHov('离线设备', 'highlight')"
                @mouseout="dispatchHov('离线设备', 'downplay')"
            >
                <span class="offline-dot"></span>
                <span class="level">离线设备</span>
                <span class="offline-rate">{{ offlineRate + '%' }}</span>
            </div>
        </div>
    </div>
</template>

<script>
import * as echarts from 'echarts' // 引入charts
export default {
    name: 'pieCharts',
    props: {
        id: {
            type: String,
            require: true,
        },
        data: {
            type: Array,
            require: true,
        },
        config: {
            type: Object,
            default: () => {},
        },
        key_: {
            type: Number,
            default: 0,
        },
    },
    data() {
        return {
            myChart: null,
            option: null,
            timerPie: null,
            curIndex: 0,
            offlineRate: 0,
            onlineRate: 0,
        }
    },
    mounted() {
        if (this.data && this.data[0].value) {
            this.init()
        }
    },
    watch: {
        data: {
            deep: true,
            handler(val) {
                if (val[0].value != undefined) {
                    const total = val[0].value + val[1].value
                    if (total != 0) {
                        this.offlineRate = ((val[1].value / total) * 100).toFixed(2)

                        this.onlineRate = ((val[0].value / total) * 100).toFixed(2)
                    } else {
                        this.offlineRate = 0
                        this.onlineRate = 0
                    }
                    if (this.option) {
                        this.option.series[0].data = val
                        this.myChart.setOption(this.option)
                    } else {
                        this.init()
                    }
                }
            },
        },
    },
    methods: {
        init() {
            let chartDom = document.getElementById(this.id)
            this.myChart = echarts.init(chartDom)
            this.option = {
                color: this.color,
                tooltip: {
                    trigger: 'item',
                    formatter: function (params) {
                        // params 包含了关于当前鼠标悬停的数据项的所有信息
                        return `${params.name}: ${params.value}`
                    },
                },
                title: {
                    text: this.data[0].value,
                    subtext: this.data[0].name + '个',
                    left: '23%',
                    x: 'center',
                    y: '35%',
                    textAlign: 'center',
                    textStyle: {
                        color: '#fff',
                        fontSize: 16,
                    },
                    subtextStyle: {
                        color: '#fff',
                        fontSize: 14,
                        lineHeight: 18,
                    },
                },
                // graphic: {
                //   type: 'text',
                //   left: 'center',
                //   top: '48%',
                //   style: {
                //     text: '74.5%',
                //     textAlign: 'center',
                //     fill: '#fff',
                //     fontSize: 12,
                //   },
                // },
                legend: {
                    show: false,
                    bottom: '40%',
                    left: '50%',
                    icon: 'circle',
                    formatter: (name) => {
                        // 添加
                        let total = 0
                        let target
                        let color = '#55EDB0'
                        for (let i = 0; i < this.data.length; i++) {
                            total += this.data[i].value
                            if (this.data[i].name === name) {
                                target = this.data[i].value
                            }
                            if (name === '在线设备') {
                                color = '#55EDB0'
                            }
                            if (name == '离线设备') {
                                color = '#00D4F'
                            }
                        }
                        var arr = [
                            '{a|' + name + '}',
                            '{b|' + ((target / total) * 100).toFixed(2) + '%}',
                        ]
                        return arr.join('')
                    },
                    textStyle: {
                        // 添加
                        // padding: [8, 0, 0, 0],
                        rich: {
                            a: {
                                fontSize: 14,
                                width: 70,
                                color: '#fff',
                            },
                            b: {
                                fontSize: 16,
                                width: 50,
                                color: ['#55EDB0', '#00D4FF'],
                            },
                        },
                    },
                },
                ...this.config,
                series: [
                    {
                        name: '设备信息',
                        type: 'pie',

                        radius: ['40%', '50%'],
                        center: ['25%', '46%'],
                        avoidLabelOverlap: false,
                        label: {
                            show: false,
                            // show: true,
                            // position: 'center',
                            // formatter: (a) => {
                            //     // if (this.key_ == 1) {
                            //     //     return a.percent.toFixed(2) + '%'
                            //     // } else {
                            //     //     return (100 - a.percent).toFixed(2) + '%'
                            //     // }
                            //     return a.value + '个'
                            // }, //'{d}%',
                            // color: '#fff',
                            // fontSize: 16,
                        },
                        emphasis: {
                            label: {
                                show: false,
                            },
                        },
                        labelLine: {
                            show: false,
                        },
                        ...this.config.series,
                        data: this.data,
                    },
                ],
            }

            this.option && this.myChart.setOption(this.option)
            window.addEventListener('resize', () => this.myChart.resize())

            if (this.data.length) {
                this.intervalPie()
            }
            this.myChart.on('click', this.handleClick)
        },
        // 饼图动效
        intervalPie() {
            if (this.timerPie) clearInterval(this.timerPie)

            this.timerPie = setInterval(() => {
                if (!this.data.length) return

                this.highLightPie(this.curIndex)
                this.curIndex++
                if (this.curIndex >= this.data.length) {
                    this.curIndex = 0
                }
            }, 3000)
        },

        highLightPie(index) {
            const dataIndexes = this.data.map((_, i) => i) // 获取所有数据索引

            // 对所有项执行downplay动作
            dataIndexes.forEach((idx) => {
                this.myChart.dispatchAction({
                    type: 'downplay',
                    seriesIndex: 0,
                    dataIndex: idx,
                })
            })

            // 对当前项执行highlight动作
            this.myChart.dispatchAction({
                type: 'highlight',
                seriesIndex: 0,
                dataIndex: index,
            })

            // 更新标题文本
            this.option.title.text = this.data[index].value
            this.option.title.subtext = this.data[index].name

            this.myChart.setOption(this.option)
        },
        //弹窗数据传递
        handleClick(params) {
            // params 包含了关于点击事件的信息，包括点击的是哪个数据项
            if (params.seriesType === 'pie') {
                // 根据点击的扇区名称或值决定展示哪个弹窗
                let popupContent
                switch (params.name) {
                    case '在线设备':
                        popupContent = this.getOnlineDevices()
                        break
                    case '离线设备':
                        popupContent = this.getOfflineDevices()
                        break
                    default:
                        return // 如果不是预期的扇区，则不执行任何操作
                }

                // 展示弹窗
                // this.showPopup(popupContent);
            }
        },
        //在线设备获取
        getOnlineDevices() {
            // 获取并返回在线设备信息

            this.$emit('getDevicesDetail', 1)
            return /* 在线设备信息 */
        },
        //离线设备获取
        getOfflineDevices() {
            // 获取并返回离线设备信息
            this.$emit('getDevicesDetail', 0)
            return /* 离线设备信息 */
        },
        //仿图例

        dispatchSel(name) {
            switch (name) {
                case '在线设备':
                    break
                case '离线设备':
                    break
                    this.nameD = !this.nameD
                    break
                default:
                    break
            }
            this.myChart.dispatchAction({
                type: 'legendToggleSelect',
                // 图例名称
                name,
            })
        },
        dispatchHov(name, type) {
            this.myChart.dispatchAction({
                type,
                // 数据项的 index，如果不指定也可以通过 name 属性根据名称指定数据项
                // dataIndex?: number | number[],
                // 可选，数据项名称，在有 dataIndex 的时候忽略
                name,
            })
        },
    },
    beforeDestroy() {
        if (this.timerPie) clearInterval(this.timerPie)
    },
}
</script>

<style lang="scss" scoped>
.box {
    height: 100%;
    width: 100%;
    position: relative;
}
.pie-charts {
    width: 100%;
    height: 100%;
}
.online-dot {
    display: inline-block;
    width: 14px;
    height: 14px;
    border-radius: 14px;
    background: #00d4ff;
}
.offline-dot {
    display: inline-block;
    width: 14px;
    height: 14px;
    border-radius: 14px;
    background: #55edb0;
}
.offline-rate {
    display: inline-block;
    width: 50px;
    height: 21px;
    font-weight: 600;
    font-size: 14px;
    color: #55edb0;
    line-height: 21px;
    text-align: center;
    font-style: normal;
    text-transform: none;
}
.online-rate {
    display: inline-block;
    width: 50px;
    height: 21px;
    font-weight: 600;
    font-size: 14px;

    color: #00d4ff;
    line-height: 21px;
    text-align: center;
    font-style: normal;
    text-transform: none;
}
.level {
    display: inline-block;
    text-align: center;
    width: 80px;
    height: 18px;
}
.levelbox {
    position: absolute;
    top: 40%;
    right: 48px;
    .levelItem {
        margin-bottom: 10px;
        cursor: pointer;
    }
}
</style>
