<template>
  <el-dialog
    width="90%"
    @open="opened"
    @closed="closed"
    :fullscreen="true"
    :show-close="true"
    class="dialogs"
  >
    <template #title>
      <div class="showTitles currentShowTitles">
        <div class="titles">升压站</div>
      </div>
    </template>
    <div class="bodyy">
        <el-tabs
            type="border-card"
            stretch
            lazy
            style="width: 100%; height: 100%"
            v-model="activeTab"
            @tab-click="tabClick"
        >
            <el-tab-pane
            class="syzDetailsPaneItem"
            v-for="(item, index) in syzArray"
            :key="index"
            :name="item.id"
            >
            <template #label>
                <span v-if="pageshowMode % 2">
                <el-badge is-dot v-if="item.isWarning === '1'">
                    <span>{{ item.name }}</span>
                </el-badge>
                <span v-else>{{ item.name }}</span>
                </span>
                <span v-else>
                <el-badge is-dot v-if="item.isWarning === '1'">
                    <span>{{ item.name }}</span>
                </el-badge>
                <span v-else>{{ item.name }}</span>
                </span>
            </template>
            <div class="buttonGroup" v-if="item.id === 'all'" >
                <el-button-group>
                    <el-button type="plain" size="small" @click="changeHeight('D')" :class="allHeight === 'D' ? 'showSty' : ''">大图标</el-button>
                    <el-button type="plain" size="small" @click="changeHeight('Z')" :class="allHeight === 'Z' ? 'showSty' : ''">中图标</el-button>
                    <el-button type="plain" size="small" @click="changeHeight('X')" :class="allHeight === 'X' ? 'showSty' : ''">小图标</el-button>
                </el-button-group>
            </div>
            <div v-if="item.id === 'all'" :style="allpageHeight" style="width: 100%;display: inline-block;overflow-y:auto">
                <div v-for="(item, index) in allSvgMsgData" :key="index" :style="getStyle(allHeight)">
                    <div class="showAllSvgMsg" @dblclick="dblgetSvgDataFn(item.id)" :class="getWarnstyle(item)">
                        <div class="showAllSvgMsg_top" v-html="item.msg"></div>
                        <div class="showAllSvgMsg_bot">
                            <span>{{item.name}}</span>
                        </div>
                    </div>
                </div>
            </div>
            <div id="svg" :style="pageHeight" v-if="item.id !== 'all' && item.id === activeTab" v-html="svgMsg" v-loading="loading"></div>
            <!-- <Mhs ref="svgRef" v-if="item.id === 'MHS_BT'" />
            <Nss ref="svgRef" v-if="item.id === 'NSS_FDC'" />
            <Qs ref="svgRef" v-if="item.id === 'QS_FDC'" />
            <Sbq ref="svgRef" v-if="item.id === 'SBQ_FDC'" />
            <Xs ref="svgRef" v-if="item.id === 'XS_FDC'" /> -->
            <!-- <Pl1 ref="svgRef" v-if="item.id === 'PL1_GDC'" />
            <Pl2 ref="svgRef" v-if="item.id === 'PL2_GDC'" />
            <Dwk ref="svgRef" v-if="item.id === 'DWK_GDC'" />
            <Mch ref="svgRef" v-if="item.id === 'MCH_GDC'" />
            <Xh ref="svgRef" v-if="item.id === 'XH_GDC'" />
            <Sbdl ref="svgRef" v-if="item.id === 'QS3_FDC'" /> -->
            <div class="alarmIconBox" v-if="item.id !== 'all'" @click="switchAlarmSound(index)">
                <el-tooltip
                v-if="item.isMute"
                effect="light"
                :content="`当前${item.name}升压站报警已消音，请注意`"
                placement="left"
                >
                <i
                    class="el-icon-close-notification"
                    style="color: orangered"
                ></i>
                </el-tooltip>
                <i v-else class="el-icon-bell" style="color: rgb(219, 215, 0)"></i>
            </div>
            </el-tab-pane>
        </el-tabs>
        <CurrentWarningCard
            :currentClass="$store.state.currentWarningCardClass"
            :activeTab="activeTab || 'MHS_FDC'"
            v-if="activeTab !== 'all'"
        />
    </div>
  </el-dialog>
</template>
<script>
import Mhs from "../BoosterStation/mhs.vue";
import Nss from "../BoosterStation/nss.vue";
import Qs from "../BoosterStation/qs.vue";
import Sbq from "../BoosterStation/sbq.vue";
import Xs from "../BoosterStation/xs.vue";
import Dwk from "../BoosterStation/dwk.vue";
import Sbdl from "../BoosterStation/sbdl.vue";
import Pl1 from "../BoosterStation/pl1.vue";
import Pl2 from "../BoosterStation/pl2.vue";
import Mch from "../BoosterStation/mch.vue";
import Xh from "../BoosterStation/xh.vue";

import api from "api/index";

import CurrentWarningCard from "./currentWarningCard.vue";
export default {
    props: {
        activeTabStation: {
        type: String,
        default: "",
        },
    },
    components: {
        Mhs,
        Nss,
        Qs,
        Sbq,
        Xs,
        Dwk,
        Sbdl,
        Pl1,
        Pl2,
        Mch,
        Xh,
        CurrentWarningCard
    },
    data() {
        return {
            activeTab: this.$store.state.activeTab,
            svgVisible: true,
            audio: null,
            timmer: null,
            syzArray: [],
            pageshowMode: 0,
            svgMsg: '',
            loading: false,
            allTagidArr: [],
            starTimer: null,
            allTagsMS: {},
            allrefreshData: {},
            allConditions: {},
            onlytag: {},
            allSvgMsgData: [],
            allHeight: 'D',
            allWarnData: [],
            starTimerWarn: null,
            numm: 0
        };
    },
    computed: {
        pageHeight() {
            return {
                'height': document.documentElement.clientHeight-60 + 'px'
            }
        },
        allpageHeight() {
            return {
                'height': document.documentElement.clientHeight-200 + 'px'
            }
        },
    },
    mounted() {
    },
    updated() {},
    methods: {
        // 获取升压站报警数据
        getSyzWarnData() {
            api.alarmFault().then((res) => {
                if (res && res.data) {
                    let datas = res.data
                    let arr = []
                    datas.forEach(it =>{
                        if (it.rank === '5') {
                            if (it.stationName.indexOf('风电场') !== -1 ) {
                                str = it.stationName.substring(0, it.stationName.indexOf('风电场'))
                            } else if (it.stationName.indexOf('光伏电站') !== -1) {
                                str = it.stationName.substring(0, it.stationName.indexOf('光伏电站'))
                            }
                            arr.push(str)
                        }
                        let str = ''
                    })
                    this.allWarnData = this.unique(arr)
                }
            })
        },
        unique(arr) {
            let newArr = []
            for(let i=0; i<arr.length; i++) {
                if (newArr.indexOf(arr[i]) === -1) {
                    newArr.push(arr[i])
                }
            }
            return newArr
        },
        getWarnstyle(item) {
            let showWarn = ''
            this.allWarnData.forEach(it=> {
                if (it === item.name) {
                    showWarn = 'warningMaskNew'
                }
            })
            return showWarn
        },
        getStyle(type) {
            let num = null
            let num1 = null
            let num2 = null
            if (type === 'D') {
                return {
                    'width': '33.3%',
                    'float': 'left',
                    'height': '400px'
                }
            } else if (type === 'Z') {
                num = parseInt(this.allSvgMsgData.length / 4)
                num1 = this.allSvgMsgData.length % 4
                num2 = num1 > 0 ? num + 1 : num
                return {
                    'width': '25%',
                    'float': 'left',
                    'height': (document.documentElement.clientHeight-200) / num2 + 'px'
                }
            } else {
                num = parseInt(this.allSvgMsgData.length / 5)
                num1 = this.allSvgMsgData.length % 5
                num2 = num1 > 0 ? num + 1 : num
                return {
                    'width': '20%',
                    'float': 'left',
                    'height': (document.documentElement.clientHeight-200) / num2 + 'px'
                }
            }
            
        },
        changeHeight(type) {
            this.allHeight = type
        },
        getAllStationtab() {
            let obj = {
                id: 'all',
                name: '全部'
            }
            api.getAllStationTab().then((res) => {
                if (res && res.data) {
                    res.data.unshift(obj)
                    this.syzArray = res.data
                    this.activeTab = res.data[0].id
                    if (this.activeTab === 'all') {
                        let allMsg = res.data
                        this.allSvgMsgData = []
                        allMsg.forEach(it =>{
                            if (it.id !== 'all') {
                                this.getallSvgDataFn(it.id, it.name)
                            }
                        })
                        // window.sessionStorage.setItem('allSvgData', [])
                        console.log('allSvgMsgData', this.allSvgMsgData)
                    }
                    // this.getSvgDataFn(res.data[0].id)
                }
            })
        },
        // 获取所有升压站数据
        getallSvgDataFn(id, name) {
            let params = {
                id: id
            }
            api.getSvgData(params).then((res) => {
                let str = ''
                str = res.data.substring(res.data.indexOf('<svg'))
                str = str.replace('<svg', '<svg viewBox="0 -100 1900 1260"')
                let obj = {
                    id: id,
                    name: name,
                    msg: str
                }
                this.allSvgMsgData.push(obj)
            })
        },
        // 获取升压站数据
        getSvgDataFn(val) {
            this.svgMsg = ''
            this.loading = true
            let params = {
                id: val
            }
            api.getSvgData(params).then((res) => {
                if (res && res.data) {
                    let str = ''
                    str = res.data.substring(res.data.indexOf('<svg'))
                    str = str.replace('<svg', '<svg viewBox="0 0 1900 1260"')
                    this.svgMsg = str
                    let html = document.getElementById('svg')
                    let svg1 = document.getElementsByTagName('svg')
                    this.$nextTick(() =>{
                        if (svg1) {
                            let allTags = []
                            let allTagsxc = []
                            let status = ['g', 'text', 'rect', 'line', 'polyline', 'circle', 'ellipse', 'polygon']
                            status.forEach(it =>{
                                let allgs = []
                                allgs = document.querySelectorAll(it);
                                allTags.push(allgs)
                            })
                            allTags = [...allTags[0], ...allTags[1], ...allTags[2], ...allTags[3], ...allTags[4], ...allTags[5], ...allTags[6], ...allTags[7]]
                            allTags.forEach((it) => {
                                if (it.getAttribute("tagid")) {
                                    allTagsxc.push(it);
                                }
                            });
                            console.log('allTags222=>', allTagsxc)
                            this.allTagidArr = allTagsxc
                            this.getSvgInfo()
                        }
                        console.log('html111=>', html)
                    })
                    this.loading = false
                }
            })
        },
        // 获取触发器
        getSvgInfo() {
            let params = {
                id: this.activeTab
            }
            api.getAllStationSvgInfo(params).then((res) => {
                if (res && res.data) {
                    if (res.data.tags) {
                        let strarr = []
                        let str = ''
                        for(let i in res.data.tags) {
                            strarr.push(res.data.tags[i].tag)
                        }
                        str = strarr.join(',')
                        this.allTagsMS = res.data.tags
                        this.allConditions = res.data.conditions
                        // this.getrefreshData(str)
                        this.starTimer = setInterval(() =>{
                            this.getrefreshData(str)
                        }, 1000)
                    }
                    console.log('SvgInfo333=>', res)
                }
            })
        },
        // 获取根盾数据
        getrefreshData(val) {
            api.refreshData(val).then((res) => {
                if (res && res.data) {
                    this.allrefreshData = res.data
                    this.refreshDataFn(this.allTagsMS)
                }
                console.log('refreshData444=>', res)
            })
        },
        // 刷新数据
        refreshDataFn(datas) {
            for (let it in datas) {
                let tagId = datas[it];
                this.toRefreshFn(it, tagId);
            }
        },
        // 刷新自定义组件
        toRefreshFn(val, data) {
            var tag = this.allrefreshData[data.tag];
            if (!tag) return;
            this.allTagidArr.forEach(it =>{
                this.onlytag = {}
                if (it.attributes.tagid) {
                    if (val === it.attributes.tagid.value) {
                        this.onlytag = it
                        if (it.nodeName === 'polyline') {
                            console.log('onlyTag666', this.onlytag)
                        }
                        if (it.nodeName !== 'text') {
                            if (this.onlytag.attributes.csid) {
                                let csid = this.onlytag.attributes.csid.value.split(';')
                                csid.forEach(ic =>{
                                    if (ic) {
                                        if (!this.allConditions[ic].isBinding) {
                                            let num = parseInt(this.allConditions[ic].value) === 0 ? '0' : parseInt(this.allConditions[ic].value)
                                            if (num) {
                                                let num2 = tag.value === 0 ? '0' : tag.value
                                                if (num === num2) {
                                                    this.onlytag.setAttribute(this.allConditions[ic].property, this.allConditions[ic].propertyValue)
                                                    return 
                                                }
                                            }
                                        } else {
                                            this.onlytag.setAttribute(this.allConditions[ic].property, this.allConditions[ic].propertyValue)
                                        }
                                    }
                                })
                            }
                        } else {
                            this.onlytag.textContent = tag.value.toFixed(2)
                        }
                    }
                }
            })
            // console.log('onlyTag555', this.onlytag)
        },
        // '全部'界面双击事件
        dblgetSvgDataFn(name) {
            this.activeTab = name
            this.getSvgDataFn(name)
        },
        // 初始化第一次报警并判断是否播放声音
        initAlarm() {
        let syzAlarmArray = this.$store.getters.syzAlarmArray;

        const firstAlarmItem = syzAlarmArray.find((ele) => {
            return !ele.isConfirm && ele.rank === this.$store.state.syzAlarmRank;
        });

        firstAlarmItem &&
            this.audioPlay(this.getSound(firstAlarmItem.soundSource));

        firstAlarmItem &&
            this.$store.getters.syzAlarmArray.forEach((ele) => {
            if (ele.stationId === firstAlarmItem.stationId) {
                ele.isConfirm = true;
            }
            });

        this.activeTab = 
            this.activeTabStation ||
            firstAlarmItem?.stationId ||
            syzAlarmArray.find((ele) => {
            return ele.rank === this.$store.state.syzAlarmRank;
            })?.stationId ||
            this.$store.getters.syzArray[0].id;

        syzAlarmArray.forEach((ele) => {
            if (ele.stationId === firstAlarmItem?.stationId) {
            ele.isConfirm = true;
            this.clearWarningTag(ele.stationId);
            } else if (
            !ele.isConfirm &&
            ele.stationId !== firstAlarmItem?.stationId
            ) {
            this.renderWarningTag(ele.stationId);
            }
        });

        this.$store.commit("syzAlarmArray", syzAlarmArray);
        },

        // 定时器循环数据判断小红点渲染及是否播放声音
        renderAlarm(stationId = "", playSound = true) {
        let syzAlarmArray = this.$store.getters.syzAlarmArray;

        syzAlarmArray.forEach((ele) => {
            if (ele.stationId === stationId) {
            ele.isConfirm = true;
            this.clearWarningTag(ele.stationId);
            } else if (!ele.isConfirm && ele.stationId !== stationId) {
            this.renderWarningTag(ele.stationId);
            }
        });

        const res = syzAlarmArray.find((ele) => {
            return !ele.isConfirm;
        });

        if (playSound) {
            // this.audioPlay("./static/sound/syz.mp3");
        }

        this.$store.commit("syzAlarmArray", syzAlarmArray);
        },

        // 返回音频文件路径
        getSound(fileName) {
        return `./static/sound/${fileName}.mp3`;
        },

        // 播放音频
        audioPlay(audioPath) {
        let soundMuteSelf = [];
        let soundMuteOther = [];

        this.$store.getters.syzAlarmArray.forEach((ele) => {
            if (ele.stationId === this.activeTab) {
            soundMuteSelf.push(ele);
            } else {
            soundMuteOther.push(ele);
            }
        });

        let alarmSelfLock = soundMuteSelf.some((ele) => {
            return !ele.isConfirm;
        });

        let alarmOtherLock = soundMuteOther.some((ele) => {
            return !ele.isConfirm;
        });

        if (alarmOtherLock) {
            this.audio = new Audio(audioPath);
            this.audio.play();
        } else if (alarmSelfLock) {
            this.$store.getters.syzArray.forEach((ele) => {
            if (ele.stationId === this.activeTab) {
                ele.isMute = false;
                this.audio = new Audio(audioPath);
                this.audio.play();
            }
            });
        } else if (!alarmSelfLock) {
            this.$store.getters.syzArray.forEach((ele) => {
            if (ele.stationId === this.activeTab) {
                if (!ele.isMute) {
                this.audio = new Audio(audioPath);
                this.audio.play();
                }
            }
            });
        }
        },

        // 显示某个小红点
        renderWarningTag(stationId = "") {
        this.$store.getters.syzArray.forEach((ele) => {
            if (ele.id === stationId) {
            ele.isWarning = "1";
            }
        });
        this.pageshowMode++;
        },

        // 清除某个小红点
        clearWarningTag(stationId = "") {
        this.$store.getters.syzArray.forEach((ele) => {
            if (ele.id === stationId) {
            ele.isWarning = "0";
            }
        });
        this.pageshowMode++;
        },

        // 切换报警声音开关
        switchAlarmSound(index) {
        this.$store.getters.syzArray[index].isMute =
            !this.$store.getters.syzArray[index].isMute;
        },

        opened() {
            this.initAlarm();
            this.getAllStationtab()
            this.timmer = setInterval(() => {
                this.renderAlarm();
            }, 3000);
            
            let starTimerWarn = setInterval(() =>{
                this.getSyzWarnData()
            }, 2000)
        },

        closed() {
            // this.$refs.svgRef[0].closed()
            // this.$refs.svgRef[1].closed()
            // this.$refs.svgRef[2].closed()
            // this.$refs.svgRef[3].closed()
            // this.$refs.svgRef[4].closed()
            clearInterval(this.starTimer);
            clearInterval(this.starTimerWarn);
            clearInterval(this.timmer);
            this.starTimer = null
            this.starTimerWarn = null
            this.timmer = null;
            this.$store.commit("activeTab", "");
            this.$store.commit("syzDialogShow", false);
        },

        tabClick(res) {
            clearInterval(this.starTimer);
            this.starTimer = null;
            this.$store.commit("activeTab", res.props.name);
            this.renderAlarm(res.props.name, false);
            if (res.props.name !== 'all') {
                this.getSvgDataFn(res.props.name)
            }
        },
    },
    watch: {
        "$store.state.syzArray"(res) {
        this.syzArray = res;
        },
    },
};
</script>

<style lang="less" scoped>
.bodyy {
  display: flex;
  flex-direction: row;
  background-color: black;
  width: 98%;
  margin-top: -30px;
  height: 90vh;
  position: relative;
  overflow: hidden;
  margin-left: 44px;

  .syzDetailsPaneItem {
    position: relative;
    .buttonGroup{
        margin-bottom: 10px;
        display: flex;
        // justify-content: end;
        float: right;
        .el-button-group{
            .el-button{
                min-height: 30px !important;
            }
            .showSty{
                color: #409eff;
                border-color: #c6e2ff;
                background-color: #ecf5ff;
                outline: 0;
            }
        }
    }
    .warningMaskNew {
        background-color: rgba(186, 50, 55, 0.5);
        animation: fade 2000ms infinite;
        -webkit-animation: fade 2000ms infinite;
    }

    @keyframes fade {
    from {
        opacity: 0.7;
    }

    50% {
        opacity: 0.3;
    }

    to {
        opacity: 0.7;
    }
    }

    @-webkit-keyframes fade {
    from {
        opacity: 0.7;
    }

    50% {
        opacity: 0.3;
    }

    to {
        opacity: 0.7;
    }
    }
    .showAllSvgMsg{
        width: calc(100% - 15px);
        height: calc(100% - 15px);
        // padding: 20px;
        // margin-bottom: 20px;
        // background: #3a3a3a;
        // border: 3px solid #3a3a3a;
        border: 3px solid #646464;
        border-radius: 10px;
        .showAllSvgMsg_top{
            border-radius: 10px 10px 0 0;
            height: calc(100% - 40px);
            width: 100%;
            // background: #fff;
        }
        .showAllSvgMsg_bot{
            background: #3a3a3a;
            border-radius: 0 0 8px 8px;
            height: 40px;
            text-align: center;
            span{
                position: relative;
                top: 10px;
                font-weight: bold;
                color: #fff;
            }
        }
    }

    .alarmIconBox {
      position: absolute;
      right: 0;
      top: 0;
      cursor: pointer;

      i {
        font-size: 20px;
      }
    }
  }
}
</style>
<style lang="less">
.bodyy {
  .pop-up-main,
  .paln-box {
    width: 100%;
    height: 90vh;
    overflow: hidden;
    position: relative;
  }
  .movableItem {
    // width: 1920PX !important;
    // height: 800PX !important;

    .svg {
    //   width: 100%;
    //   height: 92%;
      margin-left: 0;
      margin-top: 8%;
    }
  }

  .el-badge__content.is-fixed.is-dot {
    right: 0;
    top: 10px;
    background: #f25656;
    animation: twinkle 0.75s infinite;
    border-color: transparent;
  }

  @keyframes twinkle {
    0% {
      opacity: 0;
    }
    50% {
      opacity: 1;
    }
    100% {
      opacity: 0;
    }
  }
}

.currentShowTitles {
  width: 100%;
  position: relative;
  .alarIcon {
    position: absolute;
    right: 50px;
    top: 5;
    font-size: 20px;
    cursor: pointer;
  }
}

</style>