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

    <div ref="pictureAreaBox" class="main">
      <div class="view-area">
        <template v-if="'list' === data.property.view_method">
          <el-carousel
            ref="pictureCarousel"
            class="view-list"
            indicator-position="none"
            :autoplay="false"
            :style="{ height: elementHeight - 144 - 17 + 'px' }"
          >
            <el-carousel-item v-for="(file, i) in data.file_list" :key="i">
              <el-image :id="file.file_id" :src="file.file_url" fit="contain" />
            </el-carousel-item>
          </el-carousel>
          <div class="container-box">
            <button v-if="viewLeftRightBtn" class="arrow left" @click="scroll(-1)">
              <i class="el-icon-arrow-left"></i>
            </button>
            <ul ref="container" class="view-list-bottom" :style="{ width: elementWidth + 'px' }">
              <li v-for="(file, i) in data.file_list" :key="i" @click="handleIndicatorClick(i)">
                <el-image :id="file.file_id" :src="file.file_url" fit="contain" />
              </li>
            </ul>
            <button v-if="viewLeftRightBtn" class="arrow right" @click="scroll(1)">
              <i class="el-icon-arrow-right"></i>
            </button>
          </div>
        </template>
        <ul v-else class="view-independent">
          <li v-for="(file, i) in data.file_list" :key="i" @click="handleIndicatorClick(i)">
            <el-image :id="file.file_id" :src="file.file_url" fit="contain" />
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { getPictureData } from '@/views/book/courseware/data/picture';
import PreviewMixin from '../common/PreviewMixin';

export default {
  name: 'PicturePreview',
  mixins: [PreviewMixin],
  inject: ['getDragStatus'],
  data() {
    return {
      data: getPictureData(),
      curImgIndex: 0,
      elementWidth: 0,
      elementHeight: 0,
      viewLeftRightBtn: false,
      fileLen: 0,
      elementID: '',
      pictureObserversMap: {},
    };
  },
  watch: {
    data: {
      handler(val) {
        this.fileLen = val.file_list.length;
        if (this.fileLen > 0 && this.data.property.view_method === 'list') {
          const ele = this.$refs.pictureAreaBox;
          // 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.pictureArea;
          // 检查元素是否包含已知的类名
          mainEle.classList.forEach((className) => {
            // 排除已知的类名
            if (className !== 'audio-area') {
              // 打印另一个类名
              this.elementID = className;
            }
          });
        }
      },
      deep: true,
    },
    elementWidth(newWidth) {
      this.elementWidth = newWidth;
      this.isViewLeftRightBtn();
    },
    elementHeight(newHeight) {
      this.elementHeight = newHeight;
    },
  },
  mounted() {
    this.$nextTick(() => {
      const canvasElement = document.querySelector('.canvas');
      if (!canvasElement) return;
      const instanceName = `observer_${this.elementID}`;
      this.pictureObserversMap[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.pictureObserversMap[instanceName].observe(this.$el);
    });
  },
  beforeDestroy() {
    Object.values(this.pictureObserversMap).forEach((observer) => {
      observer.disconnect();
    });
  },
  methods: {
    handleResize() {
      const width = this.$refs.pictureAreaBox.clientWidth;
      if (width !== this.elementWidth) {
        this.elementWidth = width;
      }
    },
    // 是否显示左右箭头
    isViewLeftRightBtn() {
      // 计算底部列表图片宽度
      let listWidth = this.fileLen * this.data.min_width + 13 * (this.fileLen - 1);
      if (listWidth > this.elementWidth) {
        this.viewLeftRightBtn = true;
      } else {
        this.viewLeftRightBtn = false;
      }
    },
    handleIndicatorClick(index) {
      // 获取 Carousel 实例
      const carousel = this.$refs.pictureCarousel;
      // 切换到对应索引的图片
      carousel.setActiveItem(index);
    },
    // 滚动图片列表
    scroll(direction) {
      const container = this.$refs.container;
      const step = Number(this.data.min_width) + 13; // 每次滚动的距离
      this.scrollPosition += step * direction;
      container.scrollLeft += step * direction;
    },
  },
};
</script>

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

  > .main {
    display: flex;
    margin: 4px auto;

    > span {
      display: flex;
    }
  }

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

    .view-area {
      width: 100%;

      :deep .el-carousel {
        margin-bottom: 17px;
        background-color: #d9d9d9;

        &__container::before {
          display: inline-block;
          padding-bottom: 55%;
          content: '';
        }

        &__container {
          height: 100%;
        }

        &__item {
          display: flex;
          justify-content: center;
          text-align: center;
        }
      }

      .container-box {
        position: relative;

        .arrow {
          position: absolute;
          top: 0;
          z-index: 10;
          height: 144px;
          text-align: center;
          background-color: rgba(0, 0, 0, 10%);
          border-radius: 0;
        }

        .arrow:hover {
          background-color: rgba(0, 0, 0, 30%);
        }

        .right {
          right: 0;
        }

        .view-list-bottom {
          display: flex;
          flex-wrap: nowrap;
          column-gap: 13px;
          min-width: 144px;
          overflow: hidden;

          li {
            display: flex;
            align-items: center;
            justify-content: center;
            background-color: #d9d9d9;
          }

          .el-image {
            width: 144px;
            height: 144px;
            cursor: pointer;
          }
        }
      }

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

        li {
          display: flex;
          align-items: center;
          justify-content: center;
          background-color: #d9d9d9;
        }

        .el-image {
          width: 144px;
          height: 144px;
        }
      }
    }
  }
}
</style>
