<script setup lang="ts">
import { Close, Download } from '@element-plus/icons-vue'
import { onKeyStroke } from '@vueuse/core'
import { saveAs } from 'file-saver'

interface FileItem {
  name: string
  url: string
  upload_time?: string
}
interface Props {
  modelValue: boolean
  index: number
  items: FileItem[]
}
withDefaults(defineProps<Props>(), {
  modelValue: false,
  index: 0
})
const emit = defineEmits<{
  (e: 'update:modelValue', visible: boolean): void
}>()

// esc 关闭
onKeyStroke('Escape', () => {
  emit('update:modelValue', false)
})
// 下载
function handleDownload(item: FileItem) {
  saveAs(item.url, item.name)
}
</script>

<template>
  <div class="image-viewer" v-if="modelValue">
    <div class="image-viewer__close" @click="$emit('update:modelValue', false)">
      <el-icon><Close /></el-icon>
    </div>
    <el-carousel :autoplay="false" :initial-index="index" arrow="always" height="100vh">
      <el-carousel-item v-for="item in items" :key="item.url">
        <div class="image-viewer__inner">
          <div class="image-viewer__pic">
            <div class="image-viewer__pic-header">
              <h1>{{ item.name }}</h1>
              <el-button :icon="Download" @click="handleDownload(item)">下载</el-button>
            </div>
            <img :src="item.url" />
          </div>
        </div>
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

<style lang="scss">
.image-viewer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 10000;
  background-color: rgba(0, 0, 0, 0.6);
}
.image-viewer__close {
  position: absolute;
  right: 40px;
  top: 40px;
  z-index: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  opacity: 0.8;
  cursor: pointer;
  box-sizing: border-box;
  user-select: none;
  width: 44px;
  height: 44px;
  font-size: 24px;
  color: #fff;
  background-color: var(--el-text-color-regular);
  border-color: #fff;
}
.image-viewer__inner {
  height: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.image-viewer__pic {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-top: 60px;
  max-height: calc(100vh - 60px);
  img {
    max-width: 100%;
    max-height: 100%;
  }
}
.image-viewer__pic-header {
  position: absolute;
  top: -40px;
  left: 0;
  right: 0;
  display: flex;
  align-items: center;
  justify-content: space-between;
  color: #fff;
}
</style>
