<template>
  <div class="navbar">
    <div v-show="sidebar.opened" class="theTitle">后台管理</div>
    <hamburger :is-active="sidebar.opened" class="hamburger-container" @toggleClick="toggleSideBar" />
    <breadcrumb class="breadcrumb-container" />
    <div class="right-menu">
      <div style="display: flex;align-items: center;margin-right: 25px">

        <div style="display: flex; align-items: center; margin-right: 15px;margin-top: 6px">
          <i class="el-icon-bell" style="margin-right: 5px; font-size: 16px; color: #fff;" />
          <el-switch v-model="isSoundOn" active-color="#13ce66" @change="handleSoundChange" />
        </div>

        <el-popover placement="bottom" width="170" trigger="hover">
          <div style="padding: 10px 5px;">
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
              <el-badge :value="PendingData.usdtRecharge" :max="99" :hidden="PendingData.usdtRecharge <= 0">
                <span class="pending-text" @click="goPage('withdraw/topUp')">USDT充值订单</span>
              </el-badge>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
              <el-badge :value="PendingData.rgRecharge" :max="99" :hidden="PendingData.rgRecharge <= 0">
                <span class="pending-text" @click="goPage('ManualTopUp')">人工充值订单</span>
              </el-badge>

            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
              <el-badge :value="PendingData.rmbRecharge" :max="99" :hidden="PendingData.rmbRecharge <= 0">
                <span class="pending-text" @click="goPage('treePay')">人民币充值订单</span>
              </el-badge>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">

              <el-badge :value="PendingData.usdtWithdraw" :max="99" :hidden="PendingData.usdtWithdraw <= 0">
                <span class="pending-text" @click="goPage('listUSDT')">USDT提现订单</span>
              </el-badge>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">

              <el-badge :value="PendingData.rgWithdraw" :max="99" :hidden="PendingData.rgWithdraw <= 0">
                <span class="pending-text" @click="goPage('Manualwithdrawal')">人工提现订单</span>
              </el-badge>
            </div>
            <div style="display: flex; justify-content: space-between; align-items: center;">

              <el-badge :value="PendingData.rmbWithdraw" :max="99" :hidden="PendingData.rmbWithdraw <= 0">
                <span class="pending-text" @click="goPage('listRMB')">人民币提现订单</span>
              </el-badge>
            </div>
          </div>
          <div slot="reference" style="cursor: pointer; display: flex; align-items: center;margin-top: 6px">
            <el-badge :value="totalPending" :max="99" :hidden="totalPending <= 0"
              style="line-height: 1; margin-right: 5px;">
              <span style="font-size: 14px;">待处理 <i class="el-icon-arrow-down" /></span>
            </el-badge>
          </div>
        </el-popover>
      </div>
      <el-dropdown class="avatar-container" trigger="click">
        <div class="avatar-wrapper">
          <img src="../../assets/images/logo.webp" class="user-avatar">
          <i class="el-icon-caret-bottom" style="color: #fff;" />
        </div>
        <el-dropdown-menu slot="dropdown" class="user-dropdown">
          <el-dropdown-item @click.native="logout">
            <span style="display:block;">退出登陆</span>
          </el-dropdown-item>
          <el-dropdown-item @click.native="setPassword">
            <span style="display:block;">修改密码</span>
          </el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <setPassword ref="setPassword" />
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import { mapGetters } from 'vuex'
import Breadcrumb from '@/components/Breadcrumb'
import Hamburger from '@/components/Hamburger'
import setPassword from './setPassword.vue'
import { getPaymentOrderUnProcessed } from '@/api/data'

export default {
  components: {
    Breadcrumb,
    Hamburger,
    setPassword
  },
  data() {
    return {
      // 新增：读取缓存状态，默认开启(true)
      isSoundOn: localStorage.getItem('isSoundOn') !== 'false',
      isShow: Cookies.get('sidebarStatus'),
      PendingData: {
        'usdtRecharge': 0, // USDT充值订单
        'rgRecharge': 0, // 人工充值订单
        'rmbRecharge': 0, // 人民币充值订单

        'usdtWithdraw': 0, // USDT提现订单
        'rgWithdraw': 0, // 人工提现订单
        'rmbWithdraw': 0 // 人民币提现订单
      },
      intervalSeconds: 3, // 轮询秒数变量
      timer: null, // 定时器
      audi: require('@/assets/masg.mp3')
    }
  },
  computed: {
    ...mapGetters([
      'sidebar',
      'avatar'
    ]),
    // 统计所有待处理数量总和
    totalPending() {
      const p = this.PendingData
      return (p.usdtRecharge || 0) +
        (p.rgRecharge || 0) +
        (p.rmbRecharge || 0) +
        (p.usdtWithdraw || 0) +
        (p.rgWithdraw || 0) +
        (p.rmbWithdraw || 0)
    }
  },
  created() {
    // 初始化调用一次
    this.fetchPendingData()
    // 开启定时器
    this.timer = setInterval(() => {
      this.fetchPendingData()
    }, this.intervalSeconds * 1000)
  },
  beforeDestroy() {
    // 组件销毁前清除定时器
    if (this.timer) {
      clearInterval(this.timer)
    }
  },
  methods: {
    goPage(pagePath) {
      this.$router.push({ name: pagePath })
    },
    // 新增：监听开关状态变化并写入缓存
    handleSoundChange(val) {
      localStorage.setItem('isSoundOn', val)
    },
    // 提取接口请求逻辑以便复用
    fetchPendingData() {
      getPaymentOrderUnProcessed().then(res => {
        Object.assign(this.PendingData, res.data)
        console.log(this.PendingData, 67)

        // 修改：数量大于0 且 声音开关为开启状态时，才播放声音
        if (this.totalPending > 0 && this.isSoundOn) {
          this.playSound()
        }
      })
    },
    playSound() {
      const audio = new Audio(this.audi)
      audio.currentTime = 0 // 重置播放位置
      audio.play().catch(e => console.error('播放失败:', e))

      // const AudioContext = window.AudioContext || window.webkitAudioContext
      // if (!AudioContext) return
      //
      // const ctx = new AudioContext()
      //
      // const playTone = (frequency, startTime, duration) => {
      //   const osc = ctx.createOscillator()
      //   const gainNode = ctx.createGain()
      //
      //   osc.type = 'sine' // 正弦波，声音比较柔和圆润
      //   osc.frequency.setValueAtTime(frequency, ctx.currentTime)
      //
      //   // 设置声音淡入淡出效果，模拟自然的回声衰减
      //   gainNode.gain.setValueAtTime(0, startTime)
      //   gainNode.gain.linearRampToValueAtTime(1, startTime + 0.05)
      //   gainNode.gain.exponentialRampToValueAtTime(0.001, startTime + duration)
      //
      //   osc.connect(gainNode)
      //   gainNode.connect(ctx.destination)
      //
      //   osc.start(startTime)
      //   osc.stop(startTime + duration)
      // }
      //
      // // 叮 (高音)
      // playTone(659.25, ctx.currentTime, 0.5)
      // // 咚 (低音，稍微延迟0.2秒播放)
      // playTone(523.25, ctx.currentTime + 0.2, 0.8)
    },
    setPassword() {
      this.$refs.setPassword.openClose()
    },
    toggleSideBar() {
      console.log(Cookies.get('sidebarStatus'))
      this.isShow = Cookies.get('sidebarStatus')
      this.$store.dispatch('app/toggleSideBar')
    },
    async logout() {
      await this.$store.dispatch('user/logout')
      this.$router.push(`/login?redirect=${this.$route.fullPath}`)
    }
  }
}
</script>

<style lang="scss" scoped>
.navbar {
  height: 60px;
  margin-top: -10px;
  overflow: hidden;
  position: relative;
  background: #2B5198;
  box-shadow: 0 1px 4px rgba(0, 21, 41, .08);
  color: #fff;

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

  .breadcrumb-container {
    float: left;
  }

  .right-menu {
    float: right;
    height: 100%;
    line-height: 80px;
    display: flex;

    &:focus {
      outline: none;
    }

    .right-menu-item {
      display: inline-block;
      padding: 0 8px;
      height: 100%;
      font-size: 18px;
      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;
        }
      }
    }
  }
}


.remind {
  width: 24px;
  height: 24px;
  margin: 24px 12px 24px 0;
}

.theTitle {
  width: 210px;
  height: 72px;
  line-height: 72px;
  text-align: center;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 1;
  background-color: #2B5198;
  font-weight: 800;
  font-size: 14px;
  color: #FFFFFF;
}

.pending-text {
  transition: .3s;
  cursor: pointer;
  user-select: none;
}

.pending-text:hover {
  color: #409eff;
}
</style>
