<script setup>
import { NSlider } from "naive-ui";
import { ref, watch, onUnmounted } from "vue";
import { useStore } from "vuex";
import pubsub from 'pubsub-js'

const store = useStore();
const vol = ref(store.state.settings.volume);
const muted = ref(store.state.settings.muted);

const { primaryColor } = store.state.theme.themeOverrides.common;
const stySlider = () => {
  return {
    backgroundColor: primaryColor,
    height: (muted.value ? 0: vol.value) + "px",
  };
};
const styDot = () => {
  return {
    backgroundColor: primaryColor,
    bottom: (muted.value ? 0: vol.value) - 6 + "px",
  };
};

const setSlider = (e) => {
  vol.value = 100 - e.offsetY;
  muted.value = vol.value <= 0
};

watch(
  () => [vol.value, muted.value],
  ([v, m], [oldV, oldM]) => {
    // m = v <= 0
    if(v>=0 && v<=100){
      store.commit('saveSettings',{
        volume: v,
        muted: m,
      })
    }
  }
);

const setVol = (step) => {
  vol.value += step;
  if (vol.value > 100) vol.value = 100;
  if (vol.value < 0) vol.value = 0;
  muted.value = vol.value <= 0
};

const token = pubsub.subscribe("zp", (msg, data) => {
  switch (msg) {
    case "zp.setVolume":
      setVol(data.step);
      break;
    case "zp.setMuted":
      muted.value = !muted.value
      break;
  }
});

//卸载组件
onUnmounted(() => {
  pubsub.unsubscribe(token);
});
</script>
<template>
  <div class="wp z-slider">
    <div class="bg">
      <div class="bg-line"></div>
      <div class="content" :style="stySlider()"></div>
      <div class="dot" :style="styDot()"></div>
      <div class="mask" @click="setSlider"></div>
    </div>
  </div>
</template>

<script>
export default {};
</script>

<style lang="less" scoped>
.z-slider.wp {
  position: relative;
  padding: 6px;
  padding-top: 10px;
  width: 30px;
  // height: 100px;
  // border: 1px #eee solid;
  .bg {
    height: 100px;
    position: relative;
    .bg-line{
      position: absolute;
      top: 0;
      left: 8px;
      // right: 0;
      bottom: 0;
      width: 2px;
      background-color: #ddd;
    }
    .content {
      position: absolute;
      border-radius: 2px;
      bottom: 0px;
      left: 7px;
      width: 4px;
      height: 70px;
    }
    .dot {
      position: absolute;
      width: 10px;
      height: 10px;
      border-radius: 20px;
      bottom: 67px;
      left: 4px;
    }
    .mask {
      position: absolute;
      // width: 30px;
      // height: 100px;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
    }
  }
}
</style>
