<template>
    <div>
        <div style="position: absolute; right: 20px; top: 50px; font-weight: bold; z-index: 200000">
            <el-button type="text" icon="el-icon-download" title="生成图片" @click="download">下载</el-button>
        </div>
        <div style="position: absolute; right: 10px; top: 80px; font-weight: bold; z-index: 200000">
            <el-tag
                style="
                    background: #cc0000;
                    width: 30px;
                    height: 15px;
                    border: 1px solid #cc0000;
                    float: left;
                    margin-top: 2px;
                "
            ></el-tag>
            <span style="color: #cc0000; font-weight: 400; float: left">&nbsp&nbspX<60% &nbsp&nbsp</span>
            <el-tag
                size="mini"
                style="
                    background: #ffcc33;
                    width: 30px;
                    height: 15px;
                    border: 1px solid #ffcc33;
                    float: left;
                    margin-top: 2px;
                "
            ></el-tag>
            <span style="color: #ffcc33; font-weight: 400; float: left">&nbsp&nbsp60%≤X<90% &nbsp&nbsp</span>
            <el-tag
                style="
                    background: #339966;
                    width: 30px;
                    height: 15px;
                    border: 1px solid #339966;
                    float: left;
                    margin-top: 2px;
                "
            ></el-tag>
            <span style="color: #339966; font-weight: 400; float: left; margin-right: 10px">&nbsp&nbspX≥90%</span>
        </div>
        <el-row id="echarts" :style="'height:' + vh + 'px;overflow: hidden;'">
            <el-col :span="12">
                <div id="left">
                    <div id="runstatus" ref="runstatus"></div>
                </div>
            </el-col>
            <el-col :span="12">
                <div id="right">
                    <div id="onlinRate" ref="onlinRate"></div>
                </div>
            </el-col>
        </el-row>
    </div>
</template>
<script>
import html2canvas from 'html2canvas'
import { getComFlagInfoData, getRunOnlineRateData } from '@/api/monitoringpointStatistics/echart'
import yan from '@/assets/commjs/color'
import { onLienRate1, onLienRate2, onLienRate3 } from '@/assets/commjs/color'
export default {
    components: {},
    props: {
        item: {
            default: ['', '']
        },
        timeFlag: {
            default: 0
        }
    },
    data() {
        return {
            zoom: '',
            isLoading: true,
            myChartes: '',
            myChartes1: '',
            //模拟在线率数据
            onlineReate: [],
            //run模拟数据
            ydata: {},
            vh: null
            //run模拟数据
        }
    },
    created() {},
    mounted() {
        this.setHeight()
        window.addEventListener('resize', this.setHeight)
        this.resizeEchartLeft()
        this.resizeEchartRight()
    },
    beforeDestroy() {
        window.removeEventListener('resize', this.setHeight)
    },
    methods: {
        setHeight() {
            this.vh = window.sessionStorage.getItem('appheight') - 100 + 'px'
            //   this.myChartes.resize();
            this.zoom = 1 / document.body.style.zoom
            if (this.myChartes !== '') {
                this.myChartes.resize()
            } else if (this.myChartes1 !== '') {
                this.myChartes1.resize()
            }
        },
        // dmo元素里的内容转换为canvas,并将canvas下载为图片
        download() {
            // 转换成canvas
            html2canvas(document.getElementById('echarts'), {
                scale: 2
            }).then(function (canvas) {
                // 创建a标签，实现下载
                var creatIMg = document.createElement('a')
                creatIMg.download = '图表.png' // 设置下载的文件名，
                creatIMg.href = canvas.toDataURL() // 下载url
                // document.body.appendChild(creatIMg);
                creatIMg.click()
                creatIMg.remove() // 下载之后把创建的元素删除
            })
        },
        query() {
            this.isLoading = true
            let form = {
                id: this.$store.state.user.lineID,
                periodBeginTime: '',
                periodEndTime: '',
                searchBeginTime: this.item[0],
                searchEndTime: this.item[1],
                timeFlag: this.timeFlag
            }

            getRunOnlineRateData(form).then(res => {
                this.onlineReate = res.data
                // this.ydata = res.data.integrityData;
                this.runManage()
                // this.runstatusEcharts();
            })
            getComFlagInfoData(form).then(res => {
                this.ydata = res.data
                // this.ydata = res.data.integrityData;
                // this.runManage();
                this.runstatusEcharts()
            })
            this.isLoading = false
        },
        //运行情况在线率表
        runManage() {
            var months = new Array()
            var handle = new Array()
            var year = this.onlineReate[0].year
            // for (var i = 0; i < items.length; i++) {
            //   if (i != 0) {
            //     i;
            //     items[i] = items[i].slice(11);
            //   } else if (i == 0) {
            //     let date = items[i].slice(11);
            //     let t = items[i].slice(0, 10);
            //     items[i] = "(" + date + ")" + "\n" + t;
            //   }
            // }

            for (var i = 0; i < this.onlineReate.length; i++) {
                if (this.timeFlag == 0) {
                    months[i] = this.onlineReate[i].month
                    months[0] = this.onlineReate[i].month + '\n' + '(' + year + ')'
                } else {
                    months[i] = this.onlineReate[i].month + '-' + this.onlineReate[i].day
                    months[0] = this.onlineReate[i].month + '-' + this.onlineReate[i].day + '\n' + '(' + year + ')'
                }
                handle.push(this.onlineReate[i].onlineRate)
            }
            // }
            const echarts = require('echarts')
            let domID1 = document.getElementById('onlinRate')

            this.myChartes = echarts.init(domID1, null, { renderer: 'svg' })
            setTimeout(() => {
                ;(domID1.style.width = (document.getElementById('right').offsetWidth - 40) / 2 + 'px'),
                    (domID1.style.height = window.sessionStorage.getItem('appheight') - 100 + 'px')
            }, 0)
            let echartsColor = JSON.parse(window.localStorage.echartsColor)
            this.myChartes.clear()
            var option = {
                // backgroundColor: canvasBG,//背景色,
                title: {
                    text: '在线率统计',
                    x: 'center',
                    textStyle: {
                        fontWeight: 'normal',
                        fontSize: yan.EchartObject.titleNamefontSize1
                    }
                },
                // legend: {
                //   data: ["在线率"],
                //   left: "5%",
                // },
                grid: yan.EchartObject.grid11,
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow',
                        label: {
                            color: '#fff',
                            fontSize: 16
                        }
                    },
                    textStyle: {
                        color: '#fff',
                        fontStyle: 'normal',
                        opacity: 0.35,
                        fontSize: 14
                    },
                    backgroundColor: 'rgba(0,0,0,0.35)',
                    formatter: function (params) {
                        var tips = ''
                        tips += '时间:' + year + '-' + params[0].name + '</br/>'
                        for (var i = 0; i < params.length; i++) {
                            if (params[i].value == 3.14159) {
                                tips += params[i].seriesName + ':暂无数据<br/>'
                            } else {
                                tips += params[i].seriesName + ':' + params[i].value + '%<br/>'
                            }
                        }
                        return tips
                    }
                },

                dataZoom: yan.EchartObject.dataZoom,

                xAxis: [
                    {
                        type: 'category',
                        data: months,
                        name: '时间',
                        nameTextStyle: {
                            color: echartsColor.WordColor,
                            verticalAlign: 'top', //标题位置
                            padding: [-5, 0, 0, -10]
                        },

                        splitLine: {
                            show: false
                        },
                        axisLabel: {
                            textStyle: {
                                fontFamily: yan.EchartObject.fontFamily,
                                color: echartsColor.WordColor,
                                fontSize: yan.EchartObject.xNamefontSize
                            }
                        },
                        axisLine: {
                            show: true,
                            // symbol: ["none", "arrow"],
                            // symbolOffset:5,//箭头距离x轴末端距离
                            lineStyle: {
                                //           shadowOffsetX:5,
                                color: echartsColor.thread
                                //           shadowColor:  echartsColor.thread,   //设置阴影的颜色
                            }
                        }
                    }
                ],
                yAxis: [
                    {
                        min: 0,
                        max: 100,
                        type: 'value',
                        name: yan.EchartObject.nuit1,
                        nameTextStyle: {
                            color: echartsColor.WordColor
                            // verticalAlign:'top',//标题位置
                            // padding: [-22, 0, 10, 0]
                        },
                        axisLine: {
                            show: true,
                            // symbol: ["none", "arrow"],
                            //symbolOffset:25,//箭头距离x轴末端距离
                            lineStyle: {
                                //shadowOffsetY:-25,
                                color: echartsColor.thread
                                //color: echartsColor.thread,
                                //shadowColor:  echartsColor.thread,   //设置阴影的颜色
                            }
                        },
                        axisLabel: {
                            color: echartsColor.WordColor,
                            fontSize: yan.EchartObject.xNamefontSize
                        },
                        splitLine: {
                            show: false,
                            lineStyle: {
                                // 使用深浅的间隔色
                                color: [echartsColor.thread],
                                type: 'dashed',
                                opacity: 0.5
                            }
                        }
                    }
                ],
                series: [
                    {
                        name: '在线率',
                        zlevel: -99,
                        type: 'bar',
                        data: handle,
                        barMaxWidth: yan.EchartObject.barMaxWidth,
                        label: {
                            normal: {
                                show: false,
                                position: 'top'
                            }
                        },
                        itemStyle: {
                            normal: {
                                // 随机显示
                                //color:function(d){return "#"+Math.floor(Math.random()*(256*256*256-1)).toString(16);}

                                // 定制显示（按顺序）
                                color: function (params) {
                                    if (params.value >= 90) {
                                        return new echarts.graphic.LinearGradient(
                                            0,
                                            1,
                                            0,
                                            0,
                                            [{ offset: 1, color: yan.ColorObject.Integrity1 }],
                                            false
                                        )
                                    } else if (params.value >= 60 && params.value <= 90) {
                                        return new echarts.graphic.LinearGradient(
                                            0,
                                            1,
                                            0,
                                            0,
                                            [{ offset: 1, color: yan.ColorObject.Integrity2 }],
                                            false
                                        )
                                    } else if (params.value <= 60 && params.value !== 3.14159 && params.value !== 1) {
                                        return new echarts.graphic.LinearGradient(
                                            0,
                                            1,
                                            0,
                                            0,
                                            [{ offset: 1, color: yan.ColorObject.Integrity3 }],
                                            false
                                        )
                                    } else if (params.value == 3.14159 || params.value == 1) {
                                        return new echarts.graphic.LinearGradient(
                                            0,
                                            1,
                                            0,
                                            0,
                                            [{ offset: 1, color: '#ccc' }],
                                            false
                                        )
                                    }
                                }
                            }
                        },

                        markLine: {
                            silent: false,
                            symbol: 'circle',
                            data: [
                                {
                                    // name: "在线率≥90%",
                                    yAxis: 100,
                                    lineStyle: {
                                        color: yan.ColorObject.Integrity1
                                    },
                                    label: {
                                        position: 'end',
                                        formatter: '{b}',
                                        textStyle: {
                                            color: yan.ColorObject.Integrity1
                                        }
                                    }
                                },
                                {
                                    // name: "60%≤在线率<90%",
                                    yAxis: 90,
                                    lineStyle: {
                                        color: yan.ColorObject.Integrity2
                                    },
                                    label: {
                                        position: 'end',
                                        formatter: '{b}',
                                        textStyle: {
                                            color: yan.ColorObject.Integrity2
                                        }
                                    }
                                },
                                {
                                    // name: "在线率<60%",
                                    yAxis: 60,
                                    lineStyle: {
                                        color: yan.ColorObject.Integrity3
                                    },
                                    label: {
                                        position: 'end',
                                        formatter: '{b}',
                                        textStyle: {
                                            color: yan.ColorObject.Integrity3
                                        }
                                    }
                                }
                            ]
                        }
                    }
                ]
            }
            this.myChartes.setOption(option)
            window.echartsArr.push(this.myChartes)
            // myChart.resize();
            let _this = this
            _this.$erd.listenTo(_this.$refs.onlinRate, element => {
                _this.$nextTick(() => {
                    //  domID1.style.width = document.getElementById("drag-dept-right").offsetWidth - 30 + "px",
                    ;(domID1.style.width = document.getElementById('right').offsetWidth - 0 + 'px'),
                        _this.myChartes.resize()
                })
            })
        },
        resizeEchartRight() {
            var elementResizeDetectorMaker = require('element-resize-detector')
            var erd = elementResizeDetectorMaker()
            erd.listenTo(document.getElementById('right'), element => {
                let domeId = document.getElementById('right')
                let domeId2 = document.getElementById('onlinRate')
                domeId2.style.width = domeId.offsetWidth - 0 + 'px'
                // this.$nextTick(() => {
                if (this.myChartes !== '') {
                    this.myChartes.resize()
                }
                // });
            })
        },
        //运行状态
        runstatusEcharts() {
            let echartsColor = JSON.parse(window.localStorage.echartsColor)
            let list = this.ydata.type
            let items = this.ydata.updateTime

            for (var i = 0; i < items.length; i++) {
                if (i != 0) {
                    i
                    items[i] = items[i].slice(11)
                } else if (i == 0) {
                    let date = items[i].slice(11)
                    let t = items[i].slice(0, 10)
                    items[i] = '(' + date + ')' + '\n' + t
                }
            }

            // this.ydata.forEach(item => {
            //   list.push(item.sbzt);
            //   items.push(item.time);
            // });
            const echarts = require('echarts')
            let domID1 = document.getElementById('runstatus')
            this.myChartes1 = echarts.init(domID1, null, { renderer: 'svg' })
            setTimeout(() => {
                ;(domID1.style.width = (document.getElementById('left').offsetWidth - 40) / 2 + 'px'),
                    (domID1.style.height = window.sessionStorage.getItem('appheight') - 100 + 'px')
            }, 0)
            this.myChartes1.clear()
            var option = {
                // title: {
                //     text: '运行状态'
                // },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: {
                        type: 'shadow',
                        label: {
                            color: '#fff',
                            fontSize: 16
                        }
                    },
                    textStyle: {
                        color: '#fff',
                        fontStyle: 'normal',
                        opacity: 0.35,
                        fontSize: 14
                    },
                    backgroundColor: 'rgba(0,0,0,0.35)',
                    formatter: function (params) {
                        var res = '时间: ' + params[0].name + '<br/>运行状态：'
                        var texts = ''
                        if (params[0].value === 2 || params[0].value === '2') {
                            texts = '退出'
                        } else if (params[0].value === 0 || params[0].value === '0') {
                            texts = '中断'
                        } else if (params[0].value === 1 || params[0].value === '1') {
                            texts = '正常'
                        }
                        res = res + texts
                        return res
                    }
                },
                legend: {
                    data: ['运行状态'],
                    left: '5%'
                },
                grid: yan.EchartObject.grid11,
                dataZoom: [
                    {
                        type: 'inside',
                        height: 13,
                        start: 0,
                        end: 100,
                        bottom: '25px'
                    },

                    { height: 13, start: 0, bottom: '25px', end: 100 }
                ],

                xAxis: {
                    name: '时间',
                    type: 'category',
                    data: items,
                    axisLine: {
                        lineStyle: {
                            color: echartsColor.thread
                        }
                    },
                    boundaryGap: false,
                    axisLabel: {
                        textStyle: {
                            fontFamily: yan.EchartObject.fontFamily,
                            color: echartsColor.WordColor,
                            fontSize: yan.EchartObject.xNamefontSize
                        }
                    }
                },
                yAxis: {
                    name: '状态',
                    type: 'value',
                    axisLine: {
                        show: true,

                        lineStyle: {
                            color: echartsColor.thread
                        }
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: 'blue'
                        },
                        // 这里重新定义就可以
                        formatter: function (value, index) {
                            var texts = []
                            if (value === 2) {
                                texts.push('退出')
                            } else if (value === 0) {
                                texts.push('中断')
                            } else if (value === 1) {
                                texts.push('正常')
                            }
                            return texts
                        }
                    }
                },
                series: [
                    {
                        name: '运行状态',
                        type: 'line',
                        step: 'end',
                        data: list
                    }
                ]
            }
            this.myChartes1.setOption(option)
            window.echartsArr.push(this.myChartes1)
            // myChart.resize();
            let _this = this
            _this.$erd.listenTo(_this.$refs.runstatus, element => {
                _this.$nextTick(() => {
                    //  domID1.style.width = document.getElementById("drag-dept-right").offsetWidth - 30 + "px",
                    ;(domID1.style.width = document.getElementById('left').offsetWidth - 0 + 'px'),
                        _this.myChartes1.resize()
                })
            })
        },
        resizeEchartLeft() {
            var elementResizeDetectorMaker = require('element-resize-detector')
            var erd = elementResizeDetectorMaker()
            erd.listenTo(document.getElementById('left'), element => {
                let domeId = document.getElementById('left')
                let domeId2 = document.getElementById('runstatus')
                domeId2.style.width = domeId.offsetWidth - 0 + 'px'
                // this.$nextTick(() => {
                if (this.myChartes !== '') {
                    this.myChartes1.resize()
                }
                // });
            })
        }
    },

    computed: {},

    watch: {}
}
</script>
<style lang="scss" scoped></style>
