<template>
    <div class="fenceChart">
        <div class="fenceChart-header">
            <div>
                <span class="fenceChart-header-title">{{ title }}</span>
                <i v-if="isShowTable" @click="dialogVisible = true" class="el-icon-menu marginLeft" style="cursor: pointer"></i>
            </div>
            <span v-if="isDownload" @click="download" class="fenceChart-header-download">
                下载
            </span>
        </div>
        <div v-loading="chartLoading" class="fenceChart-main">
            <div :style="{visibility: isNotEmpty ? 'visible' : 'hidden'}" :class="['chart-'+id, 'chart']"></div>
            <div v-show="!isNotEmpty" class="empty"></div>
        </div>

        <dialog-table :visible.sync="dialogVisible" :title="title" width="60%" @close="dialogVisible = false">
            <template v-slot:btns>
                <el-button type="primary" plain size="mini" icon="el-icon-download" @click="download">下载</el-button>
            </template>

            <template v-slot:table>
                <el-table v-loading="loading" :data="tableData" max-height="500px">
                    <el-table-column type="index" width="50"></el-table-column>
                    <el-table-column v-for="(item, index) in colsList" :label="item.label" :prop="item.prop" :key="index"></el-table-column>
                </el-table>
            </template>
        </dialog-table>
    </div>
</template>

<script>
import resize from './mixins/resize'
import echarts from 'echarts3'
import { parseTime, deepClone } from '../../utils'
import dialogTable from '../dialogTableComponents/dialogTable.vue'
import { getFieldAggregate, exportSeverityAgg } from '../../api/fence.js'
export default {
    mixins: [resize],
    props: {
        title: {
            type: String,
            require: true
        },
        type: {
            type: String,
            require: true
        },
        id: {
            type: String,
            require: true
        },
        isDownload: {
            type: Boolean,
            default: true
        },
        isShowTable: {
            type: Boolean,
            default: true
        },
        colsList: {
            type: Array,
            default: () => []
        },
        time: {
            type: Array,
            require: true
        },
        queryStatements: {
            type: String,
            require: true
        }
    },
    components: {
        dialogTable,
    },
    data() {
        return {
            chart: null,
            dialogVisible: false,
            tableData: [
                // {field: "2", percent: 50, aggregate: 4},
                // {field: "4", percent: 37.5, aggregate: 3},
                // {field: "1", percent: 12.5, aggregate: 1},
            ],
            loading: false,
            chartLoading: false,
            options: {},
            isNotEmpty: true
        }
    },
    methods: {
        getList(field) {
            let params = {
                field: field,
                startTime: parseTime(this.time[0]),
                endTime: parseTime(this.time[1]),
                filterString: this.queryStatements
            }
            this.chartLoading = true
            getFieldAggregate(params).then(res => {
                if (res.data.returnCode == 0) {
                    let { data } = res.data
                    let options = deepClone(this.options)
                    if (field == 'severity') {
                        options.series.data = []
                        data.forEach(el => {
                            switch(+el.field) {
                                case 1:
                                    options.series.data.push({
                                        value: +el.aggregate,
                                        name: '低危',
                                        itemStyle: {
                                            normal: {
                                                color: 'rgb(88,161,247)'
                                            }
                                        }
                                    })
                                    break
                                case 2:
                                case 3: {
                                    let index = options.series.data.findIndex(el => el.name == '中危')
                                    if (index == -1) {
                                        options.series.data.push({
                                            value: +el.aggregate, 
                                            name: '中危',
                                            itemStyle: {
                                                normal: {
                                                    color: 'rgb(255,223,67)'
                                                }
                                            }
                                        })
                                    } else options.series.data[index].value += +el.aggregate
                                    break
                                }
                                case 4:
                                    options.series.data.push({
                                        value: +el.aggregate,
                                        name: '高危',
                                        itemStyle: {
                                            normal: {
                                                color: 'rgb(255,167,53)'
                                            }
                                        }
                                    })
                                    break
                                case 5:
                                    options.series.data.push({
                                        value: +el.aggregate,
                                        name: '危急',
                                        itemStyle: {
                                            normal: {
                                                color: 'rgb(236,87,89)'
                                            }
                                        }
                                    })
                                    break
                            }
                        })
                        options.legend.formatter = function(name) {
                            let data = options.series.data;
                            let total = 0;
                            let tarValue = 0;
                            for (let i = 0, l = data.length; i < l; i++) {
                                total += data[i].value;
                                if (data[i].name == name) {
                                    tarValue = data[i].value;
                                }
                            }
                            let p = (tarValue / total * 100).toFixed(2);
                            if (+p < 1) return `${name} [<1%]`;
                            else return `${name} [${+p}%]`;
                        }
                        this.tableData = options.series.data
                        this.isNotEmpty = !!this.tableData.length
                    } else if (field == 'timestamp') {
                        options.xAxis.data = []
                        options.series.data = []
                        data.sort((a, b) => a.field - b.field)
                        data.forEach(el => {
                            options.xAxis.data.push(parseTime(el.field))
                            options.series.data.push(el.aggregate)
                        })
                        this.isNotEmpty = !!options.series.data.length
                    }
                    this.chart.setOption(options)
                } else {
                    this.isNotEmpty = false
                }
                this.chartLoading = false
            }).catch(() => {
                this.chartLoading = false
            })
        },
        download() {
            let params = {
                field: this.id,
                startTime: parseTime(this.time[0]),
                endTime: parseTime(this.time[1]),
                filterString: this.queryStatements
            }
            this.$message.info("正在生成导出文件,请稍等");
          exportSeverityAgg(params).then(res => {
                if (res.data.returnCode == 0) {
                    this.$message.success('已加入离线任务队列，请在离线任务栏进行查看')
                    // window.open(`${this.$util.getAjaxUrl('analyse')}/${res.data.data.url}`, '_blank')
                }

            }).catch(() => {

            })
        }
    },
    mounted() {
        this.options = require(`./${this.type}.js`).options
        this.chart = echarts.init(document.querySelector(`.chart-${this.id}`), 'infographic')
        this.getList(this.id)
    },
    beforeDestroy() {
        if (!this.chart) return
        this.chart.dispose()
        this.chart = null
    },
}
</script>

<style lang="scss" scoped>
    .fenceChart {
        display: flex;
        flex-direction: column;
        background: white;
        height: 100%;
        &-header {
            display: flex;
            justify-content: space-between;
            height: 41px;
            line-height: 41px;
            padding: 0 20px;
            border-bottom: 1px solid #ebeef5;
            &-title {
                font-size: 16px;
                color: #000000CC;
            }
            .el-icon-menu {
                color: #409EFF;
                font-size: 16px;
                line-height: 41px;
            }
            &-download {
                color: #409EFF;
                font-size: 12px;
                cursor: pointer;
            }
        }
        &-main {
            flex: 1;
            padding: .6vw;
            position: relative;
            .chart {
                width: 100%;
                height: 220px;
            }
            .empty {
                &::after {
                    content: '暂无数据';
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translate(-50%, -50%);
                    display: flex;
                    justify-content: center;
                    align-items: flex-end;
                    width: 90px;
                    height: 80px;
                    background: url('../../images/empty.png') top/90px 60px no-repeat;
                    opacity: 0.4;
                    font-size: 14px;
                }
            }
        }
    }
</style>
