<template>
  <div class="navbar">
    <audio v-show="false" id="audio" ref="audio" />

    <hamburger id="hamburger-container" :is-active="sidebar.opened" class="hamburger-container" @toggleClick="toggleSideBar" />

    <breadcrumb id="breadcrumb-container" class="breadcrumb-container" />

    <div class="right-menu">
      <template v-if="device!=='mobile'">
        <!-- <search id="header-search" class="right-menu-item" /> -->

        <!-- <el-tooltip content="项目文档" effect="dark" placement="bottom">
          <Doc class="right-menu-item hover-effect" />
        </el-tooltip> -->
        <div style="display: inline-block; overflow: hidden;vertical-align: -4px;">
          <el-select size="mini" v-model="currentCompany" placeholder="" @change="handleChange">
            <el-option
              v-for="item in companyList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </div>

        <el-tooltip content="打开数据大屏" effect="dark" placement="bottom">
          <div class="right-menu-item hover-effect" @click="gotoDatav">返回首页</div>
        </el-tooltip>

        <!-- <el-tooltip v-if="showNotice" :content="playNotice?'通知公告':'打开声音权限，新消息可以播放提示音'" effect="dark" placement="bottom">
          <router-link :to="noticeUrl">
            <div class="right-menu-item hover-effect">
              <el-badge :value="undoNotice.totle" :hidden="!undoNotice.totle" :max="99" class="item">
                <div style="line-height: 30px;">
                  <i class="el-icon-message" />
                </div>
              </el-badge>
            </div>
          </router-link>
        </el-tooltip> -->

        <el-tooltip content="全屏缩放" effect="dark" placement="bottom">
          <screenfull id="screenfull" class="right-menu-item hover-effect" />
        </el-tooltip>

        <!-- <el-tooltip content="布局设置" effect="dark" placement="bottom">
          <size-select id="size-select" class="right-menu-item hover-effect" />
        </el-tooltip> -->

      </template>

      <el-dropdown class="avatar-container right-menu-item hover-effect" trigger="click">
        <div class="avatar-wrapper">
          <img :src="user.avatarName ? baseApi + '/avatar/' + user.avatarName : Avatar" class="user-avatar">
          <i class="el-icon-caret-bottom" />
        </div>
        <el-dropdown-menu slot="dropdown">
          <span style="display:block;" @click="show = true">
            <el-dropdown-item>
              布局设置
            </el-dropdown-item>
          </span>
          <router-link to="/user/center">
            <el-dropdown-item>
              个人中心
            </el-dropdown-item>
          </router-link>
          <span style="display:block;" @click="open">
            <el-dropdown-item divided>
              退出登录
            </el-dropdown-item>
          </span>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
  </div>
</template>

<script>
 import request from '@/utils/request'
import { mapGetters } from 'vuex'
import Breadcrumb from '@/components/Breadcrumb'
import Hamburger from '@/components/Hamburger'
// import Doc from '@/components/Doc'
import Screenfull from '@/components/Screenfull'
import SizeSelect from '@/components/SizeSelect'
// import Search from '@/components/HeaderSearch'
import Avatar from '@/assets/images/avatar.png'
import noticeAPI from '@/api/kd/noticeApi'

export default {
  components: {
    Breadcrumb,
    Hamburger,
    Screenfull,
    // Search,
    // Doc,
    SizeSelect
  },
  data() {
    return {
      currentCompany: '',
      companyList: [],
      selectedMine: {},
      undoNotice: {}, // 未处理的通知
      playNotice: true,
      noticeTimer: null,
      Avatar: Avatar,
      dialogVisible: false,
      showNotice: false,
      showDatav: false
    }
  },
  computed: {
    ...mapGetters([
      'sidebarRouters',
      'sidebar',
      'device',
      'user',
      'baseApi'
    ]),
    show: {
      get() {
        return this.$store.state.settings.showSettings
      },
      set(val) {
        this.$store.dispatch('settings/changeSetting', {
          key: 'showSettings',
          value: val
        })
      }
    },
    noticeUrl() {
      if (this.user.enterpriseId === 0) {
        return '/c/noticeMix/index'
      } else {
        return '/e/noticeMix/index'
      }
    }
  },
  mounted() {
    this.getCompanyList()
    // // 当前选择的矿山
    // const selectedMineJson = window.localStorage.getItem('kd.selected.mine')
    // if (selectedMineJson) {
    //   const selectedMine = JSON.parse(selectedMineJson)
    //   if (selectedMine && selectedMine.enterpriseId === this.user.enterpriseId) {
    //     this.selectedMine = selectedMine
    //   }
    // }
    // this.$refs.audio.src = require('@/assets/audio/notice.wav')
    // // 是否有通知权限
    // this.sidebarRouters.forEach(r => {
    //   if (this.user.enterpriseId === 0 && r.path === '/c/noticeMix') {
    //     this.showNotice = true
    //     this.bindNoticeTimer()
    //   }
    //   if (this.user.enterpriseId !== 0 && r.path === '/e/noticeMix' && this.selectedMine.hasEnable) {
    //     this.showNotice = true
    //     this.bindNoticeTimer()
    //   }
    // })
    // // 是否有大屏功能
    // if (this.user.enterpriseId === 0) {
    //   this.showDatav = true
    // } else {
    //   if (this.selectedMine.hasEnable) {
    //     this.showDatav = true
    //   }
    // }
  },
  beforeDestroy() { // 组件卸载，关闭通知
    if (this.noticeTimer) {
      clearInterval(this.noticeTimer)
    }
  },
  methods: {
    getCompanyList(){
      request({
        url: 'api/enterprise/auth/enterpriseList',
        method: 'get',
        params:{
        }
      }).then((res)=>{
        this.companyList = res.body || []
        this.currentCompany = this.companyList[0].id
      })
        
    },
    handleChange(value) {
      console.log('被选择的值:', value);
     
      request({
        url: 'api/enterprise/change/default/enterprise',
        method: 'post',
        data:{
          id: value
        }
      }).then((res)=>{
        Message({
          message: '操作成功,正在重新加载页面',
          type: 'success',
          duration: 3000 // 消息显示的时间，单位为 ms
        });
        // window.location.reload()
      })
    },
    // 跳转到大屏
    gotoDatav() {
        // window.open(location.protocol + '//' + window.location.host + '/datav/index.html', '_self')
        // window.open('http://192.168.3.226:8057/datav/index.html', '_self')
        this.$router.push('/login4Index')

      // if (this.user.enterpriseId === 0) { // 应急局用户
      //   window.open(location.protocol + '//' + window.location.host + '/datav/index.html', '_self')
      // } else { // 企业用户
      //   if (this.selectedMine.hasEnable) {
      //     this.$message.error('当前未选择矿山')
      //     this.$router.replace('/dashboard')
      //   }
      //   if (this.selectedMine.mineType === 1) {
      //     window.open(location.protocol + '//' + window.location.host + '/datav/underground.html', '_self')
      //   }
      //   if (this.selectedMine.mineType === 2) {
      //     window.open(location.protocol + '//' + window.location.host + '/datav/open-air.html', '_self')
      //   }
      //   if (this.selectedMine.mineType === 3) {
      //     window.open(location.protocol + '//' + window.location.host + '/datav/tailings.html', '_self')
      //   }
      // }
    },
    bindNoticeTimer() { // 为页面绑定通知的定时任务
      const searchFunction = () => {
        noticeAPI.undo({
          mineId: this.selectedMine.id,
          mineType: this.selectedMine.mineType
        }).then(response => {
          if (response && response.totle && response.totle > 0 &&
            (typeof this.undoNotice.totle !== 'number' || response.totle > this.undoNotice.totle)) { // 以总数判断是否有新通知
            this.undoNotice = {}
            setTimeout(() => { // 消失半秒后出现，营造闪烁效果
              this.undoNotice = response
            }, 500)
            if (this.playNotice) {
              this.$refs.audio.play().catch(() => {
                this.playNotice = false
              })
            }
          } else {
            this.undoNotice = response
          }
        })
      }
      searchFunction() // 立刻执行，并增加10秒一次的定时请求
      this.noticeTimer = setInterval(searchFunction(), 10 * 1000) // 10秒请求一次（假推送）
    },
    toggleSideBar() {
      this.$store.dispatch('app/toggleSideBar')
    },
    open() {
      this.$confirm('确定注销并退出系统吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.logout()
      })
    },
    logout() {
      window.localStorage.removeItem('kd.selected.mine')
      this.$store.dispatch('LogOut').then(() => {
        location.reload()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-badge__content {
  border: 0px;
}
.navbar {
  height: 50px;
  overflow: hidden;
  position: relative;
  background: #fff;
  box-shadow: 0 1px 4px rgba(0,21,41,.08);

  .hamburger-container {
    line-height: 46px;
    height: 100%;
    float: left;
    cursor: pointer;
    transition: background .3s;
    -webkit-tap-highlight-color:transparent;

    &:hover {
      background: rgba(0, 0, 0, .025)
    }
  }

  .breadcrumb-container {
    float: left;
  }

  .errLog-container {
    display: inline-block;
    vertical-align: top;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 50px;

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      color: #5a5e66;
      vertical-align: text-bottom;

      &.hover-effect {
        cursor: pointer;
        transition: background .3s;

        &:hover {
          background: rgba(0, 0, 0, .025)
        }
      }
    }

    .avatar-container {
      margin-right: 30px;

      .avatar-wrapper {
        margin-top: 5px;
        position: relative;

        .user-avatar {
          cursor: pointer;
          width: 40px;
          height: 40px;
          border-radius: 10px;
        }

        .el-icon-caret-bottom {
          cursor: pointer;
          position: absolute;
          right: -20px;
          top: 25px;
          font-size: 12px;
        }
      }
    }
  }
}
</style>
