<template>
    <!-- 能源实时数据监控 -->
    <div class="nyjkbz">
        <div class="box">
            <el-tabs v-model="activeName" >
                <el-tab-pane label="能源监控实时数据" name="first">
                    <div class="box-top">
                        <div class="box-top-gjl">
                            <span style="font-size:14px;">数据获取时间：{{ getDataTime }}</span>
                            <el-checkbox
                                v-show="tableData.length > 0"
                                v-model="autoGetData"
                                style="margin-left: 10px;"
                            >自动更新数据</el-checkbox>
                            <el-checkbox
                                v-show="tableData.length > 0"
                                v-model="warnFlag"
                                style="margin-left: 10px;"
                            >开启语音播报</el-checkbox>
                        </div>
                    </div>
                    <div class="box-bottom">
                        <el-form
                            size="mini"
                            ref="dialog_form_arr"
                            label-width="0px"
                            :model="tableFormDataObj"
                        >
                            <el-table
                                stripe
                                id="singleTable"
                                ref="singleTable"
                                :data="tableData"
                                v-loading="tableLoading"
                                style="width: 100%;"
                                :height="singleTableHeight"
                                border
                                size="mini"
                                highlight-current-row
                                :span-method="arraySpanMethod"
                                :cell-style="setColor"
                            >
                                <el-table-column
                                    prop="TABLE_NAME"
                                    label="能源"
                                    width="120px"
                                    align="center"
                                    :show-overflow-tooltip="true">
                                    <template slot-scope="scope">
                                        <span>{{ nameObj.nyObj[scope.row.TABLE_NAME] }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="COMMENTS"
                                    label="监测因子"
                                    width="400px"
                                    :show-overflow-tooltip="true"
                                ></el-table-column>
                                <el-table-column
                                    prop="FLAG"
                                    label="启用报警"
                                    width="120px"
                                    :show-overflow-tooltip="true"
                                >
                                    <template slot-scope="scope">
                                        <span>{{ nameObj.flagObj[scope.row.FLAG] }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="ST"
                                    label="报警开始时间"
                                    width="135px"
                                    :show-overflow-tooltip="true"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="VAL"
                                    label="实时数据"
                                    min-width="120px"
                                    :show-overflow-tooltip="true"
                                >
                                    <template slot-scope="scope">
                                        <span :class="{'nydata-error-warning' :
                                            scope.row.VAL && scope.row.VALU && scope.row.VALD &&
                                            (Number(scope.row.VAL) > Number(scope.row.VALU)|| Number(scope.row.VAL) < Number(scope.row.VALD))}">
                                            {{ scope.row.VAL }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="标准">
                                    <el-table-column
                                    prop="VALD"
                                    label="最小值"
                                    min-width="90px"
                                    :show-overflow-tooltip="true">
                                    </el-table-column>
                                    <el-table-column
                                    prop="VALU"
                                    label="最大值"
                                    min-width="90px"
                                    :show-overflow-tooltip="true">
                                    </el-table-column>
                                </el-table-column>
                            </el-table>
                        </el-form>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="能源监控超标数据" name="second">
                    <div class="box-top">
                        <div class="box-top-gjl">
                            <span style="font-size:14px;">数据获取时间：{{ getDataTime }}</span>
                            <el-checkbox
                                v-show="tableData.length > 0"
                                v-model="autoGetData"
                                style="margin-left: 10px;"
                            >自动更新数据</el-checkbox>
                            <el-checkbox
                                v-show="tableData.length > 0"
                                v-model="warnFlag"
                                style="margin-left: 10px;"
                            >开启语音播报</el-checkbox>
                        </div>
                    </div>
                    <div class="box-bottom">
                        <el-form
                            size="mini"
                            ref="dialog_form_arr"
                            label-width="0px"
                            :model="tableFormDataObj"
                        >
                            <el-table
                                stripe
                                ref="exTable"
                                :data="exTableData"
                                v-loading="tableLoading"
                                style="width: 100%;"
                                :height="singleTableHeight"
                                border
                                size="mini"
                                highlight-current-row
                                :span-method="arraySpanMethod2"
                                :cell-style="setColor"
                            >
                                <el-table-column
                                    prop="TABLE_NAME"
                                    label="能源"
                                    width="120px"
                                    align="center"
                                    :show-overflow-tooltip="true">
                                    <template slot-scope="scope">
                                        <span>{{ nameObj.nyObj[scope.row.TABLE_NAME] }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="COMMENTS"
                                    label="监测因子"
                                    width="400px"
                                    :show-overflow-tooltip="true"
                                ></el-table-column>
                                <el-table-column
                                    prop="FLAG"
                                    label="启用报警"
                                    width="120px"
                                    :show-overflow-tooltip="true"
                                >
                                    <template slot-scope="scope">
                                        <span>{{ nameObj.flagObj[scope.row.FLAG] }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="ST"
                                    label="报警开始时间"
                                    width="135px"
                                    :show-overflow-tooltip="true"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="VAL"
                                    label="实时数据"
                                    min-width="120px"
                                    :show-overflow-tooltip="true"
                                >
                                    <template slot-scope="scope">
                                        <span class="nydata-error-warning">
                                            {{ scope.row.VAL }}
                                        </span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="标准">
                                    <el-table-column
                                    prop="VALD"
                                    label="最小值"
                                    min-width="90px"
                                    :show-overflow-tooltip="true">
                                    </el-table-column>
                                    <el-table-column
                                    prop="VALU"
                                    label="最大值"
                                    min-width="90px"
                                    :show-overflow-tooltip="true">
                                    </el-table-column>
                                </el-table-column>
                            </el-table>
                        </el-form>
                    </div>
                </el-tab-pane>
                <el-tab-pane label="能源监控历史超标数据" name="third">
                    <div class="box-top">
                        <el-form
                            style="overflow: hidden;padding-top:15px;"
                            :style="filterForm.show ? null : { height: '0px' }"
                            size="mini"
                            label-width="60px"
                        >
                            <el-row>
                                <el-col :span="6">
                                    <el-form-item label="日期选择">
                                        <el-date-picker
                                            v-model="filterForm.ranges"
                                            type="datetimerange"
                                            range-separator="至"
                                            start-placeholder="开始日期"
                                            end-placeholder="结束日期"
                                            format="yyyy-MM-dd HH:mm:ss"
                                            value-format="yyyy-MM-dd HH:mm:ss"
                                            :default-time="['00:00:00', '23:59:59']">
                                        </el-date-picker>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </el-form>
                        <div class="box-top-gjl">
                            <div style="float:right; text-align: right;">
                                <el-button
                                    class="button"
                                    type="primary"
                                    size="mini"
                                    icon="el-icon-search"
                                    @click="getHistoryData()"
                                >查询</el-button>
                                <el-button
                                    size="mini"
                                    :icon="filterForm.show ? 'el-icon-caret-top' : 'el-icon-caret-bottom'"
                                    :title="filterForm.show ? '收起搜索区' : '展开搜索区'"
                                    @click="filterForm.show = !filterForm.show;
                                        $nextTick(() => {
                                            singleTableHeight = getRoleHeight($refs['singleTable'].$el) - 45;
                                        }
                                    );"
                                >{{ filterForm.show ? '收起' : '展开' }}</el-button>
                            </div>
                        </div>
                    </div>
                    <div class="box-bottom">
                        <el-table stripe
                                ref="singleTable2"
                                :data="rangeTableData"
                                v-loading="tableLoading"
                                style="width: 100%;"
                                :height="singleTableHeight1"
                                border
                                size="mini"
                                highlight-current-row
                            >
                                <el-table-column
                                    label="能源"
                                    width="120px"
                                    sortable
                                    align="center"
                                    :show-overflow-tooltip="true">
                                    <template slot-scope="scope">
                                        <span>{{ nameObj.nyObj[scope.row.tabCol.split(".")[0]] }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="colName"
                                    label="监测因子"
                                    sortable
                                    width="400px"
                                    :show-overflow-tooltip="true"
                                ></el-table-column>
                                <el-table-column
                                    prop="dateS"
                                    label="监测时间"
                                    sortable
                                    width="130px"
                                    :show-overflow-tooltip="true"
                                ></el-table-column>
                                <el-table-column
                                    prop="overStandard"
                                    label="超标类型"
                                    sortable
                                    width="100px"
                                    :show-overflow-tooltip="true"
                                ></el-table-column>
                                <el-table-column
                                    prop="dataS"
                                    label="监控值"
                                    sortable
                                    min-width="100px"
                                    :show-overflow-tooltip="true"
                                >
                                </el-table-column>
                                <el-table-column label="标准">
                                    <el-table-column
                                    prop="dataDown"
                                    label="最小值"
                                    min-width="90px"
                                    :show-overflow-tooltip="true">
                                    </el-table-column>
                                    <el-table-column
                                    prop="dataUp"
                                    label="最大值"
                                    min-width="90px"
                                    :show-overflow-tooltip="true">
                                    </el-table-column>
                                </el-table-column>
                            </el-table>
                            <el-pagination
                                    layout="total, sizes, prev, pager, next, jumper"
                                    :total="rangeTableInfo.total"
                                    :page-sizes="[10, 20, 50, 100, 500, 1000]"
                                    :page-size="rangeTableInfo.pageSize"
                                    :current-page.sync="rangeTableInfo.pageNum"
                                    @size-change="historyTableSizeChange"
                                    @current-change="pageChage"
                                    style="text-align: right;margin-top: 10px;"
                            ></el-pagination>
                    </div>
                </el-tab-pane>
            </el-tabs>
        </div>
    </div>
</template>

<script>
import { formatDate } from '@/utils/util.js';
import { zCheckNumber1 } from '@/utils/validator.js'
export default {
    name: 'nydata',
    data () {
        return {
            activeName: 'first',
            getDataTime: '',
            autoGetData: false,
            tableFormDataObj: {},
            activeMenu: '',
            start: new Date(),
            filterForm: {
                show: true,
                ranges: ['', ''],
                data: {
                    wrType: '',
                    checkEle: '',
                    drainName: '', // 排放口名称
                    location: ''
                },
                rules: {
                }
            },
            pageNum: 1,
            pageSize: 500,
            total: 0,
            singleTableHeight: 100,
            singleTableHeight1: 145,
            tableData: [],
            exTableData: [],
            rangeTableData: [],
            warnData: [], // 播报数据
            warnNext: false, // 下一条播报数据
            warnFlag: true, // 语音播报开关
            speaking: false, // 播报中
            nameObj: {
                nyObj: {
                    'COREDAS_AR': '氩气',
                    'COREDAS_BFG': '高炉煤气',
                    'COREDAS_CLD': '转炉煤气',
                    'COREDAS_COG': '焦炉煤气',
                    'COREDAS_N2': '氮气',
                    'COREDAS_O2': '氧气'
                },
                flagObj: {
                    '0': '否',
                    '1': '是'
                }
            },
            rangeTableInfo: {
                    pageNum: 1,
                    pageSize: 20,
                    total: 0,
                    tableData: []
            },
            loading: false,
            autoSize: 0,
            tableLoading: false
        }
    },
    created () {
        this.activeMenu = window.localStorage.getItem('activeMenu');
        this.filterForm.ranges = [this.getYNM(new Date()) + ' 00:00:00', this.getYNM(new Date()) + ' 23:59:59']
    },
    watch: {
        'autoGetData': function (newVal, oldVal) {
           let that = this;
            window.clearInterval(that.autoTimeId);
            that.autoSize = 0;
            if (that.autoGetData) {
                console.log('on')
                that.autoTimeId = setInterval(function () {
                    if (that.autoSize < 1000) {
                        that.getNyData();
                        that.autoSize++;
                    } else {
                        that.autoGetData = false;
                    }
                }, 5000);
            } else {
                console.log('off')
            }
        },
        'warnNext': function (newVal, oldVal) {
            let that = this;
            if (that.warnData.length > 0 && that.warnFlag) {
                that.speakWarning(that.warnData[0].COMMENTS + '数据异常');
            }
        }
    },
    mounted () {
        let that = this;
        window.PEDataObj = {
            // 将数据绑定到window上，供main页面使用
            vm: that,
            // tableArr：用于导出成Excel的表格的信息
            tableArr: [
                {
                    name: '',
                    id: 'singleTable'
                },
                {
                    name: '',
                    id: 'singleTable2'
                }
            ]
        };
        that.$nextTick(() => {
            // 立即获取的height有一定偏差，通过setTimeout延迟来解决
            setTimeout(() => {
                that.singleTableHeight = that.getRoleHeight(that.$refs['singleTable'].$el) - 45;
                that.singleTableHeight1 = that.getRoleHeight(that.$refs['singleTable2'].$el) - 185;
            }, 1);
        });
        that.getTableData();
        that.getHistoryData();
    },
    methods: {
        getYNM (date) {
            let year = date.getFullYear().toString();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            month = month < 10 ? '0' + month : month;
            day = day < 10 ? '0' + day : day;
            return `${year}-${month}-${day}`;
        },
        //  计算树区域高度
        getRoleHeight (dom) {
            return window.innerHeight - dom.offsetTop;
        },
        // 获取表格中的数据
        getTableData () {
            let that = this,
                params = {};
            that.tableLoading = true;
            let url = 'pass/ems/v1/coredasabnormalinfos/getCoredasData';
            that.axios.get(url, {
                params: params
            })
                .then(function (res) {
                    if (res.code === '0') {
                        that.getDataTime = res.data.time;
                        that.tableData = res.data.data;
                        that.exTableData = res.data.dataWarn;
                        that.autoGetData = true;
                        setTimeout(() => {
                            that.getNyData();
                        }, 1000);
                    } else {
                        that.$message.error(res.message);
                    }
                    that.tableLoading = false;
                }).catch(function () {
                    that.tableLoading = false;
                });
        },
        // 获取监控值
        getNyData () {
            let that = this;
            that.axios.get('pass/ems/v1/coredasabnormalinfos/nyData')
                .then(function (res) {
                    if (res.code === '0') {
                        that.exTableData = [];
                        let arr = [];
                        let obj = res.data.data;
                        that.getDataTime = res.data.time;
                        let now = new Date();
                        for (let i = 0; i < that.tableData.length; i++) {
                            that.tableData[i].VAL = obj[that.tableData[i].col];
                            if (that.tableData[i].VAL && that.tableData[i].VALU && that.tableData[i].VALD &&
                                (Number(that.tableData[i].VAL) > Number(that.tableData[i].VALU) || Number(that.tableData[i].VAL) < Number(that.tableData[i].VALD))) {
                                arr.push(that.tableData[i]);
                            }
                        }
                        // 添加语音播报内容
                        if (that.warnData.length < 20 && arr.length > 0) {
                            for (let item of arr) {
                                if (item.FLAG === '1' && item.ST && new Date(item.ST) < now) {
                                    that.warnData.push(item);
                                }
                            }
                        }
                        // 语音播报
                        if (that.warnFlag && that.warnData.length > 0 && !that.speaking) {
                            that.warnNext = !that.warnNext
                        }
                        that.exTableData = arr;
                    } else {
                        that.$message.error(res.message);
                    }
                }).catch(function () {});
        },
        // 语音播报
        speakWarning (test) {
            let that = this;
            that.speaking = true;
            const synth = window.speechSynthesis;
            const msg = new SpeechSynthesisUtterance();
            msg.text = test;
            msg.lang = 'zh-CN';
            msg.volume = 1;
            msg.rate = 1;
            msg.pitch = 1;
            synth.speak(msg);
            // 语音播报结束，去除已经播报内容（第一条）
            msg.addEventListener('end', function (event) {
                that.speaking = false;
                if (that.warnData.length > 0) {
                    that.warnData.splice(0, 1);
                }
            });
        },
        speakStop () {
            const synth = window.speechSynthesis;
            synth.cancel();
        },
        // 获取历史数据
        getHistoryData () {
            let that = this;
            // that.speakWarning('测试一下，语音正常');
            if (!that.filterForm.ranges) {
                that.$message.error('请选择日期');
                return true;
            }
            let params = {
                clock: that.filterForm.ranges[0],
                clocke: that.filterForm.ranges[1]
            };
            let url = 'pass/ems/v1/coredasabnormalinfos/getCoredasDataHis?pageNum=' + that.rangeTableInfo.pageNum + '&pageSize=' + that.rangeTableInfo.pageSize;
            that.axios.get(url, {
                params: params
            })
                .then(function (res) {
                    if (res.code === '0') {
                        that.rangeTableData = res.data.list;
                        that.rangeTableInfo.total = res.data.total;
                    } else {
                        that.$message.error(res.message);
                    }
                    that.tableLoading = false;
                }).catch(function () {
                    that.tableLoading = false;
                });
        },
        historyTableSizeChange (val) {
            let that = this;
            that.rangeTableInfo.pageSize = val;
            that.rangeTableInfo.pageNum = 1;
            that.getHistoryData();
        },
        pageChage (val) {
            this.rangeTableInfo.pageNum = val;
            this.getHistoryData();
        },
        // 表格合并单元格
        arraySpanMethod ({ row, column, rowIndex, columnIndex }) {
            let tableData = this.$refs.singleTable.tableData
            let rowsPan = 1;
            let thisColomnData = row[column['property']];
            // 能源列 合并
            if (column['property'] === 'TABLE_NAME' && thisColomnData) {
                if (rowIndex > 0 && thisColomnData === tableData[rowIndex - 1][column['property']]) {
                    return {
                        rowspan: 0,
                        colspan: 0
                    };
                }
                while (tableData[rowIndex + rowsPan] && thisColomnData === tableData[rowIndex + rowsPan][column['property']]) {
                    rowsPan += 1
                }
                return {
                    rowspan: rowsPan,
                    colspan: 1
                };
            }
        },
        arraySpanMethod2 ({ row, column, rowIndex, columnIndex }) {
            let tableData = this.$refs.exTable.tableData
            let rowsPan = 1;
            let thisColomnData = row[column['property']];
            // 能源列 合并
            if (column['property'] === 'TABLE_NAME' && thisColomnData) {
                if (rowIndex > 0 && thisColomnData === tableData[rowIndex - 1][column['property']]) {
                    return {
                        rowspan: 0,
                        colspan: 0
                    };
                }
                while (tableData[rowIndex + rowsPan] && thisColomnData === tableData[rowIndex + rowsPan][column['property']]) {
                    rowsPan += 1
                }
                return {
                    rowspan: rowsPan,
                    colspan: 1
                };
            }
        },
        setColor ({row, column, rowIndex, columnIndex}) {
            if (column['property'] === 'TABLE_NAME' || columnIndex === 0) {
                return 'background-color:#fff'
            }
        }
    }
}
</script>

<style lang="less">
.nyjkbz {
    min-width: 700px;
    height: 100%;
    .box {
        height: 100%;
        padding: 15px 15px 0 15px;
        .box-top {
            .el-form-item {
                margin-bottom: 7px;
            }
            .box-top-gjl {
                overflow: hidden;
                // margin-top: -7px;
                padding: 7px 0;
                border-top: 1px solid #ccc;
                // border-bottom: 1px solid #ccc;
                // margin-bottom: 6px;
            }
        }
        .el-table .el-table__row {
            height: 35px;
        }
        .el-table__body .el-form-item--mini.el-form-item {
            margin: 0px;
            .error {
                overflow: hidden;
                color: #f56c6c;
                font-size: 12px;
                line-height: 1;
            }
        }
    }
    .color_no {
        color: #7a7a7a;
    }
    .color_yes {
        color: #1a9f17;
    }
    @keyframes myfirst
    {
        from {
            color: #fff;
            font-weight: normal;
            }
        to {
            color: #ec3219;
            font-weight: bold;
            }
    }

    @-webkit-keyframes myfirst /* Safari and Chrome */
    {
        from {
            color: #fff;
            font-weight: normal;
            }
        to {
            color: #ec3219;
            font-weight: bold;
            }
    }
    .nydata-error-warning {
        animation: myfirst 0.4s infinite;
    }
}
</style>
