<template>
  <el-card
    class="mb-12px"
    :body-class="!images.length ? 'hidden' : 'pr-0!'"
    :header-class="!images.length ? 'border-b-none!' : ''"
  >
    <template #header>
      <div class="flex items-center justify-between">
        <span>图片序列</span>
        <span class="flex gap-4px">
          <LuPlus class="cursor-pointer" size="14px" @click="handleAdd" />
          <LuTrash2 class="cursor-pointer" size="14px" @click="handleClear" />
        </span>
      </div>
    </template>
    <el-scrollbar height="180px">
      <div
        v-for="(item, index) in images"
        :key="`${item || 'empty'}-${index}`"
        class="flex items-center gap-8px pr-12px mb-8px"
      >
        <div class="flex-1">
          <ImageSelect v-model="images[index]" />
        </div>
        <span class="flex gap-4px shrink-0">
          <LuArrowUp
            class="cursor-pointer"
            size="14px"
            :style="{ opacity: index === 0 ? 0.4 : 1 }"
            @click="handleMove(index, index - 1)"
          />
          <LuArrowDown
            class="cursor-pointer"
            size="14px"
            :style="{ opacity: index === images.length - 1 ? 0.4 : 1 }"
            @click="handleMove(index, index + 1)"
          />
          <LuTrash2 class="cursor-pointer" size="14px" @click="handleDelete(index)" />
        </span>
      </div>
    </el-scrollbar>
  </el-card>
</template>

<script setup lang="ts">
import { computed, type Ref } from 'vue'
import { LuArrowDown, LuArrowUp, LuPlus, LuTrash2 } from 'vue-icons-plus/lu'
import { moveToPosition } from '@/utils'

import ImageSelect from '@/views/designer/config/property/components/ImageSelect.vue'

const props = defineProps<{
  values: Ref<{
    props: {
      images: string[]
    }
  }>
}>()

const images = computed({
  get: () => props.values.value.props.images || [],
  set: (value: string[]) => {
    props.values.value.props.images = value
  }
})

const handleAdd = () => {
  images.value.push('')
}

const handleDelete = (index: number) => {
  images.value.splice(index, 1)
}

const handleClear = () => {
  images.value = []
}

const handleMove = (fromIndex: number, toIndex: number) => {
  if (toIndex < 0 || toIndex >= images.value.length) return
  moveToPosition(images.value, fromIndex, toIndex)
}
</script>
