<!--  -->
<template>
  <div
    class="pic-box"
    :class="{ show: viewer }"
    :style="metasHeight ? `height:${metasHeight}px;` : ''"
  >
    <div>
      <div class="ctrl-btn left-btn" v-if="imageNum != 0" @click.stop="changeImage('pre')">
        <i class="iconfont ui-kankan-icon icon tip-h-center tip-v-bottom icon-left"></i>
      </div>
      <div
        class="ctrl-btn right-btn"
        v-if="imageNum < imageList.length - 1"
        @click.stop="changeImage('next')"
      >
        <i class="iconfont ui-kankan-icon icon tip-h-center tip-v-bottom icon-right"></i>
      </div>
    </div>
    <div class="over-box" ref="containerRef">
      <div
        v-show="!loading"
        class="image-list"
        :style="`transform:translateX(${-100 * imageNum}%);`"
      >
        <!-- <div
                    @click="openScale(i.src)"
                    :style="`transform:translateX(${100 * index}%);background-image:url(${changeUrl(i.src)});`"
                    class="image-item"
                    v-for="(i, index) in imageList"
                ></div> -->
        <div
          @click="openScale(i.src)"
          :style="`transform:translateX(${100 * index}%);`"
          class="image-item"
          :key="i.sid"
          v-for="(i, index) in imageList"
        >
          <img :id="`domImg${index}`" :src="changeUrl(i.src)" alt="" />
        </div>

        <!-- <div v-else :style="`transform:translateX(${100 * index}%);`" class="image-item" v-for="(i, index) in imageList">
                    <img @error="filesError(index)" :src="changeUrl(i.src)" alt="" />
                </div> -->
      </div>
      <!-- <ui-icon v-show="loading" class="loading-icon" type="_loading_"></ui-icon> -->
    </div>
    <div class="continue" v-if="imageList.length > 1">
      <span class="pic-num">
        <span class="cur">{{ imageNum + 1 }}</span>
        <span><span>&nbsp;</span>/<span>&nbsp;</span></span>
        <span>{{ imageList.length }}</span>
      </span>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { onMounted, nextTick, ref, computed, defineProps } from 'vue';
  import { tagType } from '/@/store/modules/scene';
  import { changeUrl } from '../common';
  // import { useApp } from '/@/hooks/userApp';
  import browser from '/@/utils/browser';
  const isMobile = ref(false);
  // const type = ref('image');
  // const emit = defineEmits(['close']);

  const props = defineProps({
    data: {
      type: Object,
      default: {} as any as tagType,
    },
    metasHeight: {
      type: Number,
      default: null,
    },
    viewer: {
      type: Boolean,
      default: false,
    },
    scale: {
      type: Boolean,
      default: false,
    },
  });

  const imageList = computed(() => {
    return props.data.media.image;
  });
  const loading = ref(true);
  const imageNum = ref(0);

  const changeImage = (type) => {
    if (type == 'pre') {
      imageNum.value--;
    } else {
      imageNum.value++;
    }
    if (props.viewer && !isMobile.value) {
      resetScale();
    }
  };
  // const hanlderFiles = (data) => {
  //   // store.commit('tag/setImageList', data[0])
  //   setImageList(data[0]);
  //   // if (imageNum.value < imageList.value.length + data[0].length - 1) {
  //   //     imageNum.value = imageList.value.length + data[0].length - 1
  //   // }
  //   imageNum.value = imageList.value.length - 1;
  // };

  // const setImageList = (data) => {
  //   let picLength = 0;
  //   let list = JSON.parse(JSON.stringify(imageList.value));
  //   if (list.length > 0) {
  //     picLength = list.length;
  //   }

  //   for (let i = 0; i < data.length; i++) {
  //     if (list.length < 9) {
  //       list.push('');
  //       var index = i + picLength;
  //       list[index] = { src: URL.createObjectURL(data[i]), file: data[i] };
  //     } else {
  //       break;
  //     }
  //   }
  //   // store.commit('tag/setImageList', list);
  // };
  let result = { width: 0, height: 0 },
    x,
    y,
    scale = 1,
    minScale = 0.5,
    maxScale = 4,
    isPointerdown = false, // 按下标识
    diff = { x: 0, y: 0 }, // 相对于上一次pointermove移动差值
    lastPointermove = { x: 0, y: 0 }; // 用于计算diff
  // transform = { x: 0, y: 0 };

  const drag = (image) => {
    // 绑定 pointerdown
    image.addEventListener('pointerdown', function (e) {
      isPointerdown = true;
      image.setPointerCapture(e.pointerId);
      lastPointermove = { x: e.clientX, y: e.clientY };
    });
    // 绑定 pointermove
    image.addEventListener('pointermove', function (e) {
      if (isPointerdown) {
        const current = { x: e.clientX, y: e.clientY };
        diff.x = current.x - lastPointermove.x;
        diff.y = current.y - lastPointermove.y;
        lastPointermove = { x: current.x, y: current.y };
        x += diff.x;
        y += diff.y;

        image.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0) scale(' + scale + ')';
        // log.innerHTML = `x = ${x.toFixed(0)}<br>y = ${y.toFixed(0)}<br>scale = ${scale.toFixed(5)}`
      }
      e.preventDefault();
    });
    // 绑定 pointerup
    image.addEventListener('pointerup', function (_) {
      if (isPointerdown) {
        isPointerdown = false;
      }
    });
    // 绑定 pointercancel
    image.addEventListener('pointercancel', function (_) {
      if (isPointerdown) {
        isPointerdown = false;
      }
    });
  };
  const containerRef = ref<HTMLElement | null>(null);

  const zoomFun = (e) => {
    let ratio = 1.1;
    // 缩小
    if (e.deltaY > 0) {
      ratio = 1 / 1.1;
    }
    const _scale = scale * ratio;
    if (_scale > maxScale) {
      ratio = maxScale / scale;
      scale = maxScale;
    } else if (_scale < minScale) {
      ratio = minScale / scale;
      scale = minScale;
    } else {
      scale = _scale;
    }
    // 目标元素是img说明鼠标在img上，以鼠标位置为缩放中心，否则默认以图片中心点为缩放中心
    console.log(e.target.tagName);
    if (e.target.tagName === 'IMG') {
      const origin = {
        x: (ratio - 1) * result.width * 0.5,
        y: (ratio - 1) * result.height * 0.5,
      };
      // 计算偏移量
      x -= (ratio - 1) * (e.clientX - x) - origin.x;
      y -= (ratio - 1) * (e.clientY - y) - origin.y;
    }
    imgEle.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0) scale(' + scale + ')';
    // log.innerHTML = `x = ${x.toFixed(0)}<br>y = ${y.toFixed(0)}<br>scale = ${scale.toFixed(5)}`
    e.preventDefault();
  };

  // 滚轮缩放
  const initWheelZoom = () => {
    containerRef.value?.addEventListener('wheel', zoomFun);
  };
  const removeWheelZoom = () => {
    containerRef.value?.removeEventListener('wheel', zoomFun);
  };

  const resetScale = () => {
    result = { width: 0, height: 0 };
    x = null;
    y = null;
    scale = 1;
    minScale = 0.5;
    maxScale = 4;
    isPointerdown = false; // 按下标识
    diff = { x: 0, y: 0 }; // 相对于上一次pointermove移动差值
    lastPointermove = { x: 0, y: 0 }; // 用于计算diff

    nextTick(() => {
      removeWheelZoom();
      initScale();
    });
  };
  let imgEle: HTMLImageElement;
  const initScale = () => {
    imgEle = document.getElementById(`domImg${imageNum.value}`) as HTMLImageElement;

    x = 0;
    y = 0;
    if (imgEle) {
      imgEle.style.transform = 'translate3d(' + x + 'px, ' + y + 'px, 0) scale(1)';

      result.width = imgEle.width;
      result.height = imgEle.height;
    }

    nextTick(() => {
      // 拖拽查看
      drag(imgEle);

      // 滚轮缩放
      initWheelZoom();
    });
  };
  onMounted(async () => {
    // const app = await useApp();
    isMobile.value = browser.isMobile();

    nextTick(() => {
      let img = new Image();
      img.onload = () => {
        loading.value = false;
        if (props.viewer && !isMobile.value) {
          //pc端缩放
          nextTick(() => {
            initScale();
          });
        }
      };
      img.src = changeUrl(imageList.value[0].src);

      if (props.scale) {
        if (imageList.value.length == 1) {
          openScale(imageList.value[0].src);
        }
      }
    });
  });

  const zoomInImg = ref(null);

  const openScale = (src) => {
    if (isMobile.value) {
      zoomInImg.value = changeUrl(src);
      let img: HTMLImageElement = new Image();
      img.onload = () => {
        loading.value = false;
      };
      img.src = zoomInImg.value || '';
      // nextTick(() => {
      //     zoomElement(topology.value)
      // })
    }
  };
</script>
<style lang="scss" scoped>
  .showPicBox {
    width: 100%;
    height: 100%;
    position: fixed;
    z-index: 10000;
    background: rgb(24, 22, 22);
    top: 0;
    left: 0;
    .close {
      position: absolute;
      top: 10px;
      right: 10px;
      width: 20px;
      height: 20px;
      z-index: 100;
      color: #fff;
      .iconfont {
        font-size: 20px;
      }
    }
    .loading {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }
    .imgbox {
      width: 100%;
      height: 100%;
      background-repeat: no-repeat;
      background-size: contain;
      background-position: center center;
      #eleImg {
        // position: absolute;

        // top: 50%;
        // left: 50%;
        // transform: translate(-50%, -50%);
        margin: 0 auto;
        display: block;
        &.s {
          height: 100%;
          width: auto;
        }
        &.h {
          height: auto;
          width: 100%;
        }
      }
    }
  }
  .del-btn {
    width: 24px;
    height: 24px;
    background: rgba(0, 0, 0, 0.3);
    border-radius: 50%;
    position: absolute;
    cursor: pointer;
    top: 10px;
    right: 10px;
    z-index: 10;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .loading-icon {
    color: var(--editor-main-color);
    animation: rotate 2s infinite linear;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    font-size: 30px;
  }
  .pic-box {
    width: 100%;
    height: 100%;
    position: absolute;
    border-radius: 4px;
    border: 1px solid rgba(255, 255, 255, 0.2);
    top: 0;
    left: 0;
    z-index: 10;

    @keyframes rotate {
      0% {
        transform: translate(-50%, -50%) rotate(0deg);
      }
      100% {
        transform: translate(-50%, -50%) rotate(360deg);
      }
    }
    .over-box {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    .continue {
      width: 100%;
      height: 32px;
      background: linear-gradient(180deg, rgba(0, 0, 0, 0.1) 0%, #000000 200%);
      border-radius: 0px 0px 4px 4px;
      position: absolute;
      bottom: 0;
      left: 0;

      .ui-input {
        width: 100%;
      }
      .continue-tips {
        font-size: 12px;
      }
      .pic-num {
        position: absolute;
        right: 10px;
        top: 50%;
        transform: translateY(-50%);
        font-size: 12px;
        .cur {
          color: var(--editor-main-color);
        }
      }
    }

    .ctrl-btn {
      width: 32px;
      height: 32px;
      background: rgba(0, 0, 0, 0.2);
      border-radius: 50%;
      position: absolute;
      cursor: pointer;
      top: 50%;
      transform: translateY(-50%);
      z-index: 10;
      display: flex;
      align-items: center;
      justify-content: center;
      .iconfont {
        font-size: 14px;
      }
      &.left-btn {
        left: 5px;
      }
      &.right-btn {
        right: 5px;
      }
    }
    .image-list {
      width: 100%;
      height: 100%;
      position: relative;
      transition: all 0.3s linear;
      .image-item {
        width: 100%;
        height: 100%;
        // background: red;
        position: absolute;
        transform: translateX(0);
        text-align: center;
        background-repeat: no-repeat;
        background-size: contain;
        background-position: center;
        overflow: hidden;
        img {
          height: 100%;
          width: 100%;
          object-fit: contain;
          touch-action: none;
        }
      }
    }
    &.show {
      .ctrl-btn {
        width: 40px;
        height: 80px;
        background: rgba(0, 0, 0, 0.6);
        .iconfont {
          font-size: 20px;
        }
        &.left-btn {
          left: 0px;
          border-radius: 0 40px 40px 0;
          .icon {
            margin-right: 5px;
          }
        }
        &.right-btn {
          right: 0px;
          border-radius: 40px 0 0 40px;
          .icon {
            margin-left: 8px;
          }
        }
      }
      .continue {
        width: 76px;
        height: 36px;
        background: rgba(0, 0, 0, 0.6);
        border-radius: 20px;
        position: absolute;
        bottom: -5%;
        left: 50%;
        transform: translateX(-50%);

        .pic-num {
          width: 76px;
          height: 36px;
          display: inline-block;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 20px;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          span {
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }
      }
    }
  }

  [is-mobile] {
    .pic-box {
      &.show {
        .ctrl-btn {
          width: 40px;
          height: 80px;
          background: rgba(0, 0, 0, 0.6);
          .iconfont {
            font-size: 20px;
          }
          &.left-btn {
            left: 0px;
            border-radius: 0 40px 40px 0;
            .icon {
              margin-right: 5px;
            }
          }
          &.right-btn {
            right: 0px;
            border-radius: 40px 0 0 40px;
            .icon {
              margin-left: 8px;
            }
          }
        }
        .continue {
          width: 76px;
          height: 36px;
          background: rgba(0, 0, 0, 0.6);
          border-radius: 20px;
          position: absolute;
          bottom: -6%;
          left: 50%;
          transform: translateX(-50%);

          .pic-num {
            width: 76px;
            height: 36px;
            display: inline-block;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 20px;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            span {
              display: flex;
              align-items: center;
              justify-content: center;
            }
          }
        }
      }
    }
  }
</style>
