<template>
  <div class="vtk-img-container">
    <v-card 
      :class="['vtk-img-card', { 'vtk-img-card--preview': preview }]"
      @click="openPreview"
    >
      <v-img 
        v-bind="$attrs" 
        :src="srcWithToken"
        class="vtk-img"
        :aspect-ratio="aspectRatio"
        cover
      >
        <template v-slot:placeholder>
          <div class="d-flex align-center justify-center fill-height">
            <v-progress-circular indeterminate color="grey-lighten-1"></v-progress-circular>
          </div>
        </template>
      </v-img>
      
      <!-- 图片标题和描述 -->
      <div class="vtk-img-info" v-if="showTitle || showDescription">
        <v-card-title v-if="showTitle" class="vtk-img-title text-subtitle-2 pa-2">
          {{ title }}
        </v-card-title>
        <v-card-subtitle v-if="showDescription" class="vtk-img-description text-caption pa-2">
          {{ description }}
        </v-card-subtitle>
      </div>
    </v-card>
    
    <!-- 使用 v-dialog 的图片预览 -->
    <v-dialog 
      v-model="showPreview" 
      max-width="90%" 
      fullscreen
      @click:outside="closePreview"
    >
      <v-card class="image-viewer-card">
        <v-toolbar dark color="primary">
          <v-btn icon dark @click="closePreview">
            <v-icon>mdi-close</v-icon>
          </v-btn>
          <v-toolbar-title>{{ currentImageTitle }}</v-toolbar-title>
          <v-spacer></v-spacer>
          <v-toolbar-items>
            <v-btn icon dark @click="rotateImage(-90)">
              <v-icon>mdi-rotate-left</v-icon>
            </v-btn>
            <v-btn icon dark @click="rotateImage(90)">
              <v-icon>mdi-rotate-right</v-icon>
            </v-btn>
          </v-toolbar-items>
        </v-toolbar>
        
        <div class="image-viewer-content">
          <v-btn 
            v-if="hasPrev" 
            icon 
            class="nav-button prev-button" 
            @click="prevImage"
          >
            <v-icon>mdi-chevron-left</v-icon>
          </v-btn>
          
          <div class="image-container">
            <v-img
              :src="currentImageUrl"
              class="viewer-image"
              :style="{ transform: `rotate(${imageRotation}deg)` }"
            />
          </div>
          
          <v-btn 
            v-if="hasNext" 
            icon 
            class="nav-button next-button" 
            @click="nextImage"
          >
            <v-icon>mdi-chevron-right</v-icon>
          </v-btn>
        </div>
        
        <div class="image-info">
          <p class="text-center">{{ currentImageDescription }}</p>
          <p class="text-center text--secondary">{{ currentIndex + 1 }} / {{ imageList.length }}</p>
        </div>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue';

defineOptions({
  name: 'VtkImg',
  inheritAttrs: true
});

const props = defineProps({
  src: {
    type: String,
    default: null,
  },
  error: {
    type: String,
    default: new URL('../../assets/img/wxsq.png', import.meta.url).href,
  },
  preview: {
    type: Boolean,
    default: true
  },
  title: {
    type: String,
    default: ''
  },
  description: {
    type: String,
    default: ''
  },
  // 图片列表，用于导航功能
  imageList: {
    type: Array,
    default: () => []
  },
  // 当前图片索引
  index: {
    type: Number,
    default: 0
  },
  // 是否显示标题
  showTitle: {
    type: Boolean,
    default: true
  },
  // 是否显示描述
  showDescription: {
    type: Boolean,
    default: true
  },
  // 图片宽高比
  aspectRatio: {
    type: [String, Number],
    default: 16/9
  }
});

// 预览状态
const showPreview = ref(false);
// 图片旋转角度
const imageRotation = ref(0);
// 当前图片索引（预览模式下使用）
const currentIndex = ref(0);

// 使用计算属性处理带token的URL
const srcWithToken = computed(() => {
  if (!props.src) return props.src;
  
  try {
    // 首先尝试使用 $vtk.storage
    if (window.$vtk && typeof window.$vtk.storage?.get === 'function') {
      const token = window.$vtk.storage.get('token');
      return token ? `${props.src}?stoken=${token}` : props.src;
    }
    // 如果 $vtk 不存在，尝试从 localStorage 获取 token
    else {
      const token = localStorage.getItem('token');
      return token ? `${props.src}?stoken=${token}` : props.src;
    }
  } catch (error) {
    // 发生错误时返回原始src
    console.warn('VtkImg: Failed to get token, using src without token', error);
    return props.src;
  }
});

// 当前预览图片的URL
const currentImageUrl = computed(() => {
  if (props.imageList.length > 0 && currentIndex.value < props.imageList.length) {
    const currentImage = props.imageList[currentIndex.value];
    if (currentImage && currentImage.url) {
      try {
        // 为图片列表中的图片也添加token
        if (window.$vtk && typeof window.$vtk.storage?.get === 'function') {
          const token = window.$vtk.storage.get('token');
          return token ? `${currentImage.url}?stoken=${token}` : currentImage.url;
        } else {
          const token = localStorage.getItem('token');
          return token ? `${currentImage.url}?stoken=${token}` : currentImage.url;
        }
      } catch (error) {
        return currentImage.url;
      }
    }
  }
  return srcWithToken.value;
});

// 当前图片标题
const currentImageTitle = computed(() => {
  if (props.imageList.length > 0 && currentIndex.value < props.imageList.length) {
    const currentImage = props.imageList[currentIndex.value];
    return currentImage?.title || '';
  }
  return props.title;
});

// 当前图片描述
const currentImageDescription = computed(() => {
  if (props.imageList.length > 0 && currentIndex.value < props.imageList.length) {
    const currentImage = props.imageList[currentIndex.value];
    return currentImage?.description || '';
  }
  return props.description;
});

// 是否有上一张图片
const hasPrev = computed(() => {
  return props.imageList.length > 1 && currentIndex.value > 0;
});

// 是否有下一张图片
const hasNext = computed(() => {
  return props.imageList.length > 1 && currentIndex.value < props.imageList.length - 1;
});

// 监听预览状态变化
watch(showPreview, (newVal) => {
  if (newVal) {
    // 打开预览时重置旋转角度和当前索引
    imageRotation.value = 0;
    currentIndex.value = props.index;
  }
});

// 打开预览
const openPreview = () => {
  if (props.preview) {
    showPreview.value = true;
  }
};

// 关闭预览
const closePreview = () => {
  showPreview.value = false;
};

// 上一张图片
const prevImage = () => {
  if (hasPrev.value) {
    currentIndex.value--;
    imageRotation.value = 0; // 切换图片时重置旋转
  }
};

// 下一张图片
const nextImage = () => {
  if (hasNext.value) {
    currentIndex.value++;
    imageRotation.value = 0; // 切换图片时重置旋转
  }
};

// 旋转图片
const rotateImage = (degrees) => {
  imageRotation.value += degrees;
};
</script>

<style lang="scss" scoped>
.vtk-img-container {
  position: relative;
  display: inline-block;
  width: 100%;
  height: 100%;
}

.vtk-img-card {
  height: 100%;
}

.vtk-img-card--preview {
  cursor: pointer;
  transition: transform 0.2s ease-in-out;
}

.vtk-img-card--preview:hover {
  transform: translateY(-5px);
}

.vtk-img {
  width: 100%;
}

.vtk-img-info {
  padding: 0;
}

.vtk-img-title {
  word-break: break-word;
}

.vtk-img-description {
  word-break: break-word;
}

/* 图片查看器样式 */
.image-viewer-card {
  background-color: rgba(0, 0, 0, 0.9);
  color: white;
}

.image-viewer-content {
  display: flex;
  align-items: center;
  justify-content: center;
  height: calc(100vh - 150px);
  position: relative;
}

.image-container {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.viewer-image {
  max-width: 90%;
  max-height: 80vh;
  transition: transform 0.3s ease;
}

.nav-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  width: 50px;
  height: 50px;
}

.prev-button {
  left: 20px;
}

.next-button {
  right: 20px;
}

.image-info {
  padding: 20px;
  background-color: rgba(0, 0, 0, 0.7);
}

.image-info p {
  margin: 5px 0;
}

:deep(.v-img__img) {
  background: v-bind('props.error') no-repeat center;
  background-size: cover;
}

:deep(.v-img__placeholder) {
  filter: blur(0px);
}
</style>