<template>
    <div class="component_box">
        <div ref="chart" style="width: 100%; height: 100%;" @mouseenter="handleMouseEnter"
            @mouseleave="handleMouseLeave"></div>
    </div>
</template>
<script>
import { alarmTrend } from '@/api/iot/board'
export default {
    props: {
        orgId: {
            type: String,
            isRequired: true,
        },
    },
    data() {
        return {
            data: {
                date: [], //x轴的日期
                total: [], //报警总数
                countByType: [],//按分类统计的报警总数
            },
            isMouseOver: false,
            // activeName: types[0].value,
        };
    },

    components: {},

    computed: {},

    watch: {
        orgId: {
            deep: true,
            handler(val) {
                this.resetTimer();
                this.getData();
            },
        },
        data: {
            deep: true,
            handler() {
                this.initMap();
            },
        },
    },

    created() {
        this.types = types;
        this.maxDisplay = 16;
        this.refreshTime = 1 * 10 * 1000;
        this.isMouseOver = false;
    },

    async mounted() {
        window.addEventListener("resize", this.windowResize);
    },
    beforeDestroy() {
        this.timer && clearInterval(this.timer);
        this.timer = null;

        window.removeEventListener("resize", this.windowResize);
    },

    methods: {
        // handleClick() {
        //     this.resetTimer();
        //     this.getData();
        // },
        handleMouseEnter() {
            this.isMouseOver = true;
        },
        handleMouseLeave() {
            this.isMouseOver = false;
        },
        async getData() {
            let r = (await alarmTrend(this.orgId))
                .data;
            let data = {
                date: [], //x轴的日期
                total: [], //报警总数
                countByType: [],//按分类统计的报警总数
            };

            let monitorCount = [];
            let fireCount = [];
            let environmentCount = [];
            for (let item of r) {
                data.total.push(item.total);
                monitorCount.push(item.monitorCount);
                fireCount.push(item.fireCount);
                environmentCount.push(item.environmentCount);

                data.date.push(item.orgName);
            }

            data.countByType.push(monitorCount)
            data.countByType.push(fireCount)
            data.countByType.push(environmentCount);
            this.data = data;
        },

        windowResize() {
            this.myChart && this.myChart.resize();
        },
        initMap() {
            this.myChart && this.myChart.dispose();
            let c = this.$refs["chart"];

            // 基于准备好的dom，初始化echarts实例
            this.myChart = echarts.init(
                c
            );
            var data = {
                id: "multipleBarsLines",
                title: "近7天告警趋势",
                legendBar: ["报警总数"],
                symbol: "", //数值是否带百分号        --默认为空 ''
                legendLine: ["监控设备", "消防设备", "环境监测"],
                // xAxis: ["9月19", "9月20", "9月21", "9月22", "9月23", "9月24", "9月25"],
                // yAxis: [[8, 10, 10, 11, 4, 13, 8]],
                // lines: [
                //     [4, 3, 2, 4, 2, 1, 1],
                //     [2, 1, 4, 2, 3, 2, 4],
                //     [1, 0, 2, 1, 1, 2, 1],
                // ],
                barColor: ["#3FA7DC", "#7091C4", "#5170A2"], //柱子颜色 必填参数
                lineColor: ["#D9523F"], // 折线颜色
            };
            /////////////end/////////

            var myData = (function test() {
                var yAxis = this.data.total || [];
                var lines = this.data.countByType || [];
                var legendBar = data.legendBar || [];
                var legendLine = data.legendLine || [];
                var symbol = data.symbol || " ";
                var seriesArr = [];
                var legendArr = [];
                yAxis &&
                    yAxis.forEach((item, index) => {
                        legendArr.push({
                            name: legendBar && legendBar.length > 0 && legendBar[index],
                        });
                        seriesArr.push({
                            name: legendBar && legendBar.length > 0 && legendBar[index],
                            type: "bar",
                            barGap: "0.5px",
                            data: item,
                            barWidth: data.barWidth || 12,
                            label: {
                                normal: {
                                    show: true,
                                    formatter: "{c}" + symbol,
                                    position: "top",
                                    textStyle: {
                                        color: "#fff",
                                        fontStyle: "normal",
                                        fontFamily: "微软雅黑",
                                        textAlign: "left",
                                        fontSize: 11,
                                    },
                                },
                            },
                            itemStyle: {
                                //图形样式
                                normal: {
                                    barBorderRadius: 4,
                                    color: data.barColor[index],
                                },
                            },
                        });
                    });

                lines &&
                    lines.forEach((item, index) => {
                        legendArr.push({
                            name: legendLine && legendLine.length > 0 && legendLine[index],
                        });
                        seriesArr.push({
                            name: legendLine && legendLine.length > 0 && legendLine[index],
                            type: "line",
                            data: item,
                            itemStyle: {
                                normal: {
                                    color: data.lineColor[index],
                                    lineStyle: {
                                        width: 3,
                                        type: "solid",
                                    },
                                },
                            },
                            label: {
                                normal: {
                                    show: false, //折线上方label控制显示隐藏
                                    position: "top",
                                },
                            },
                            symbol: "circle",
                            symbolSize: 10,
                        });
                    });

                return {
                    seriesArr,
                    legendArr,
                };
            })();

            option = {
                title: {
                    show: true,
                    top: "10%",
                    left: "3%",
                    text: data.title,
                    textStyle: {
                        fontSize: 18,
                        color: "#fff",
                    },
                    subtext: data.subTitle,
                    link: "",
                },
                tooltip: {
                    trigger: "axis",
                    formatter: function (params) {
                        var time = "";
                        var str = "";
                        for (var i of params) {
                            time = i.name.replace(/\n/g, "") + "<br/>";
                            if (i.data == "null" || i.data == null) {
                                str += i.seriesName + "：无数据" + "<br/>";
                            } else {
                                str += i.seriesName + "：" + i.data + symbol + "%<br/>";
                            }
                        }
                        return time + str;
                    },
                    axisPointer: {
                        type: "none",
                    },
                },
                legend: {
                    right: data.legendRight || "30%",
                    top: "12%",
                    right: "5%",
                    itemGap: 16,
                    itemWidth: 10,
                    itemHeight: 10,
                    data: myData.legendArr,
                    textStyle: {
                        color: "#fff",
                        fontStyle: "normal",
                        fontFamily: "微软雅黑",
                        fontSize: 12,
                    },
                },
                grid: {
                    x: 30,
                    y: 80,
                    x2: 30,
                    y2: 60,
                },
                xAxis: {
                    type: "category",
                    data: this.data.date,
                    axisTick: {
                        show: false,
                    },

                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: "#1AA1FD",
                        },
                        symbol: ["none", "arrow"],
                    },
                    axisLabel: {
                        show: true,
                        interval: "0",
                        textStyle: {
                            lineHeight: 16,
                            padding: [2, 2, 0, 2],
                            height: 50,
                            fontSize: 12,
                        },
                        rich: {
                            Sunny: {
                                height: 50,
                                // width: 60,
                                padding: [0, 5, 0, 5],
                                align: "center",
                            },
                        },
                        formatter: function (params, index) {
                            var newParamsName = "";
                            var splitNumber = 5;
                            var paramsNameNumber = params && params.length;
                            if (paramsNameNumber && paramsNameNumber <= 4) {
                                splitNumber = 4;
                            } else if (paramsNameNumber >= 5 && paramsNameNumber <= 7) {
                                splitNumber = 4;
                            } else if (paramsNameNumber >= 8 && paramsNameNumber <= 9) {
                                splitNumber = 5;
                            } else if (paramsNameNumber >= 10 && paramsNameNumber <= 14) {
                                splitNumber = 5;
                            } else {
                                params = params && params.slice(0, 15);
                            }

                            var provideNumber = splitNumber; //一行显示几个字
                            var rowNumber = Math.ceil(paramsNameNumber / provideNumber) || 0;
                            if (paramsNameNumber > provideNumber) {
                                for (var p = 0; p < rowNumber; p++) {
                                    var tempStr = "";
                                    var start = p * provideNumber;
                                    var end = start + provideNumber;
                                    if (p == rowNumber - 1) {
                                        tempStr = params.substring(start, paramsNameNumber);
                                    } else {
                                        tempStr = params.substring(start, end) + "\n";
                                    }
                                    newParamsName += tempStr;
                                }
                            } else {
                                newParamsName = params;
                            }
                            params = newParamsName;
                            return "{Sunny|" + params + "}";
                        },
                        color: "#1AA1FD",
                    },
                },
                yAxis: {
                    axisLine: {
                        show: true,
                        lineStyle: {
                            color: "#1AA1FD",
                        },
                        symbol: ["none", "arrow"],
                    },
                    type: "value",
                    axisTick: {
                        show: false,
                    },
                    axisLabel: {
                        show: false,
                    },
                    splitLine: {
                        show: false,
                        lineStyle: {
                            color: "#1AA1FD",
                            type: "solid",
                        },
                    },
                },
                series: myData.seriesArr,
            };
            // 使用刚指定的配置项和数据显示图表。
            if (option && typeof option === "object") {
                this.myChart.setOption(option);
            }
        },

        resetTimer() {
            this.timer && clearInterval(this.timer);
            this.timer = setInterval(() => {
                if (this.isMouseOver) {
                    return;
                }
                this.activeName = getNextPeriod(this.types, this.activeName);
                this.getData();
            }, this.refreshTime);
        },
    },
};
</script>
<style scoped src="./../css/index.css"></style>