<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">
        <div class="picture-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' }"
              @change="handleChange"
            >
              <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"
                  :preview-src-list="data.file_list.map((x) => x.file_url)"
                />
              </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 v-if="'list' === data.property.view_method && isEnable(data.property.view_memo)" class="memo-area">
          <div v-for="(file, i) in data.file_info_list" :key="i">
            <div v-if="curPictureMemoIndex === i" class="title-div">{{ file.title ?? file.title }}</div>
            <div v-if="curPictureMemoIndex === i" class="memo-div">{{ file.intro ?? file.intro }}</div>
          </div>
        </div>
      </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: {},
      curPictureMemoIndex: 0,
    };
  },
  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;
          const viewMemo = this.isEnable(this.data.property.view_memo);
          // 序号在左和右补齐序号高度，去掉padding(8*2)
          if (sn_position.includes('left') || sn_position.includes('right')) {
            this.elementWidth = viewMemo ? (ele.clientWidth - 16) * 0.8 : ele.clientWidth - 16;
            this.elementHeight = ele.clientHeight + 30;
          } else {
            this.elementWidth = viewMemo ? ele.clientWidth * 0.8 : 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() {
      this.isViewLeftRightBtn();
    },
  },
  mounted() {
    this.$nextTick(() => {
      const canvasElement = document.querySelector('.canvas');
      if (!canvasElement) {
        const ele = this.$refs.pictureAreaBox;
        const sn_position = this.data.property.sn_position;
        const viewMemo = this.isEnable(this.data.property.view_memo);
        // 序号在左和右补齐序号高度，去掉padding(8*2)
        if (sn_position.includes('left') || sn_position.includes('right')) {
          this.elementWidth = viewMemo ? (ele.clientWidth - 16) * 0.8 : ele.clientWidth - 16;
          this.elementHeight = ele.clientHeight + 30;
        } else {
          this.elementWidth = viewMemo ? ele.clientWidth * 0.8 : ele.clientWidth;
          this.elementHeight = ele.clientHeight;
        }
        this.fileLen = this.data.file_list.length;
        this.isViewLeftRightBtn();
        return;
      }
      const mainEle = this.$refs.pictureArea;
      // 检查元素是否包含已知的类名
      mainEle.classList.forEach((className) => {
        // 排除已知的类名
        if (className !== 'audio-area') {
          // 打印另一个类名
          this.elementID = className;
        }
      });

      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;
            const viewMemo = this.isEnable(this.data.property.view_memo);
            // 序号在上方和下方减去序号高度，在左右去掉padding(8*2)
            if (sn_position.includes('top') || sn_position.includes('bottom')) {
              this.elementWidth = viewMemo ? entry.contentRect.width * 0.8 : entry.contentRect.width;
              this.elementHeight = entry.contentRect.height - 30;
            } else {
              this.elementWidth = viewMemo ? (entry.contentRect.width - 16) * 0.8 : 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);
      this.curPictureMemoIndex = index;
    },
    handleChange(index) {
      this.curPictureMemoIndex = index;
    },
    // 滚动图片列表
    scroll(direction) {
      const container = this.$refs.container;
      const step = Number(this.data.min_width) + 13; // 每次滚动的距离
      this.scrollPosition += step * direction;
      container.scrollLeft += step * direction;
    },
    autoResize(entry) {
      window.requestAnimationFrame(() => {
        const sn_position = this.data.property.sn_position;
        const viewMemo = this.isEnable(this.data.property.view_memo);
        // 序号在上方和下方减去序号高度，在左右去掉padding(8*2)
        if (sn_position.includes('top') || sn_position.includes('bottom')) {
          this.elementWidth = viewMemo ? entry.contentRect.width * 0.8 : entry.contentRect.width;
          // this.elementHeight = entry.contentRect.height - 30;
        } else {
          this.elementWidth = viewMemo ? (entry.contentRect.width - 16) * 0.8 : entry.contentRect.width - 16;
          this.elementHeight = entry.contentRect.height;
        }
      });
    },
  },
};
</script>

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

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

    > span {
      display: flex;
    }
  }

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

    .view-area {
      .memo-area {
        float: left;
        width: 15%;
        padding-left: 5px;
        text-align: left;
        border-left: 1px solid #eee;

        .title-div {
          font-size: 16px;
          font-weight: 600;
        }

        .memo-div {
          color: #706f78;
          overflow-wrap: break-word;
        }
      }

      :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;

        .left {
          left: 0;
        }

        .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>
