<template>
  <div ref="audioArea" class="audio-area" :style="getAreaStyle()">
    <SerialNumberPosition v-if="isEnable(data.property.sn_display_mode)" :property="data.property" />

    <div ref="audioAreaBox" class="main">
      <ul v-if="'independent' === data.property.view_method" class="view-independent">
        <li v-for="(file, i) in data.file_list" :key="i">
          <AudioPlay
            view-size="middle"
            :file-id="file.file_id"
            :file-name="file.file_name.slice(0, file.file_name.lastIndexOf('.'))"
            :audio-index="i"
          />
        </li>
      </ul>
      <ul v-else-if="'icon' === data.property.view_method" class="view-icon">
        <li v-for="(file, i) in data.file_list" :key="i">
          <AudioPlay view-size="small" :file-id="file.file_id" :audio-index="i" />
        </li>
      </ul>
      <div v-else class="view-list">
        <el-carousel
          ref="audio_carousel"
          indicator-position="none"
          direction="vertical"
          :autoplay="false"
          :interval="0"
        >
          <el-carousel-item v-for="(file, i) in data.file_list" :key="i">
            <AudioPlay
              view-size="big"
              :file-id="file.file_id"
              :file-name="file.file_name.slice(0, file.file_name.lastIndexOf('.'))"
              :show-slider="true"
              :cur-audio-index="curAudioIndex"
              @changeFile="changeFile"
            />
          </el-carousel-item>
        </el-carousel>
        <div :style="{ height: elementHeight - 140 + 'px', overflowY: viewScroll }">
          <ul class="view-list-bottom">
            <li v-for="(file, i) in data.file_list" :key="i" @click="handleAudioClick(i)">
              <AudioPlay
                view-size="list"
                :file-id="file.file_id"
                :file-name="file.file_name.slice(0, file.file_name.lastIndexOf('.'))"
                :show-slider="false"
                :audio-index="i"
                :cur-audio-index="curAudioIndex"
              />
            </li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { getAudioData } from '@/views/book/courseware/data/audio';

import PreviewMixin from '../common/PreviewMixin';
import AudioPlay from '../common/AudioPlay.vue';

export default {
  name: 'AudioPreview',
  components: { AudioPlay },
  mixins: [PreviewMixin],
  inject: ['getDragStatus'],
  data() {
    return {
      data: getAudioData(),
      curAudioIndex: 0,
      elementWidth: 0,
      elementHeight: 0,
      fileLen: 0,
      viewScroll: 'hidden',
      elementID: '',
      audioObserversMap: {},
    };
  },
  watch: {
    data: {
      handler(val) {
        this.fileLen = val.file_list.length;
        if (this.fileLen > 0 && this.data.property.view_method === 'list') {
          const ele = this.$refs.audioAreaBox;
          // this.elementWidth = ele.clientWidth;
          // this.elementHeight = ele.clientHeight;

          const sn_position = this.data.property.sn_position;
          // 序号在左和右补齐序号高度，去掉padding(8*2)
          if (sn_position.includes('left') || sn_position.includes('right')) {
            this.elementWidth = ele.clientWidth - 16;
            this.elementHeight = ele.clientHeight + 30;
          } else {
            this.elementWidth = ele.clientWidth;
            this.elementHeight = ele.clientHeight;
          }

          const mainEle = this.$refs.audioArea;
          // 检查元素是否包含已知的类名
          mainEle.classList.forEach((className) => {
            // 排除已知的类名
            if (className !== 'audio-area') {
              // 打印另一个类名
              this.elementID = className;
            }
          });
        }
      },
      deep: true,
    },
    elementWidth(newWidth) {
      if (this.data.property.view_method === 'list') this.elementWidth = newWidth;
    },
    elementHeight(newHeight) {
      if (this.data.property.view_method === 'list') {
        this.elementHeight = newHeight;
        this.isViewScroll();
      }
    },
  },
  mounted() {
    this.$nextTick(() => {
      const canvasElement = document.querySelector('.canvas');
      if (!canvasElement) return;
      const instanceName = `observer_${this.elementID}`;
      this.audioObserversMap[instanceName] = new ResizeObserver((entries) => {
        if (!this.getDragStatus()) return;
        for (let entry of entries) {
          window.requestAnimationFrame(() => {
            const sn_position = this.data.property.sn_position;
            // 序号在上方和下方减去序号高度，在左右去掉padding(8*2)
            if (sn_position.includes('top') || sn_position.includes('bottom')) {
              this.elementWidth = entry.contentRect.width;
              this.elementHeight = entry.contentRect.height - 30;
            } else {
              this.elementWidth = entry.contentRect.width - 16;
              this.elementHeight = entry.contentRect.height;
            }
          });
        }
      });
      this.audioObserversMap[instanceName].observe(this.$el);
    });
  },
  beforeDestroy() {
    Object.values(this.audioObserversMap).forEach((observer) => {
      observer.disconnect();
    });
  },
  methods: {
    handleAudioClick(index) {
      // 获取 Carousel 实例
      const carousel = this.$refs.audio_carousel;
      // 切换到对应索引的文件
      carousel.setActiveItem(index);
      this.curAudioIndex = index;
    },
    changeFile(type) {
      // 获取 Carousel 实例
      const carousel = this.$refs.audio_carousel;
      // 切换到对应索引的文件
      if (type === 'prev') {
        carousel.prev();
        this.curAudioIndex += -1;
      } else {
        carousel.next();
        this.curAudioIndex += 1;
      }
      if (this.curAudioIndex >= this.data.file_id_list.length) {
        this.curAudioIndex = 0;
      }
      if (this.curAudioIndex < 0) {
        this.curAudioIndex = this.data.file_id_list.length - 1;
      }
    },
    isViewScroll() {
      const ulHeight = this.fileLen * 44;
      if (ulHeight > this.elementHeight - 140) {
        this.viewScroll = 'scroll';
      } else {
        this.viewScroll = 'hidden';
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.audio-area {
  display: grid;
  gap: 6px;
  padding: 8px;

  > .main {
    margin: 0 auto;

    > span {
      display: flex;
    }
  }

  .main {
    grid-area: main;
    width: 100%;

    .view-independent {
      display: flex;
      flex-wrap: wrap;
      gap: 16px;

      > li {
        min-width: 280px;
      }
    }

    .view-icon {
      display: flex;
      flex-wrap: wrap;
      gap: 16px 50px;
    }

    .view-list {
      display: flex;
      flex-direction: column;

      :deep .el-carousel {
        flex: 1;
        background-color: #f8f8f8;
        border-radius: 4px;

        &__container {
          height: 128px;
        }

        &__item {
          transition: none !important;
        }
      }

      .view-list-bottom {
        display: flex;
        flex-direction: column;

        li {
          border-top: 1px solid #ccc;
        }
      }
    }
  }
}
</style>
