<script setup>
import { Plus, UploadFilled, Picture, MagicStick } from '@element-plus/icons-vue'
import { useFileDialog } from '@vueuse/core'
import { upload } from '@/utils/upload'
import dayjs from 'dayjs'
const ImageDesign = defineAsyncComponent(() => import('./ImageDesign.vue'))
const ImageChat = defineAsyncComponent(() => import('@/components/ImageChat.vue'))

const props = defineProps({
  modelValue: { type: [Array, String], default: () => [] },
  multiple: { type: Boolean, default: false },
  accept: { type: String, default: '' },
  limit: { type: Number, default: 1 },
  title: { type: String },
  firstTitle: { type: String },
  tips: { type: String, default: '' },
  firstTips: { type: String },
  itemHeight: { type: String, default: '100px' },
  isVideo: { type: Boolean, default: false },
})

const emit = defineEmits(['update:modelValue'])

const index = ref(0)

const { open, onChange, reset } = useFileDialog({
  accept: props.accept,
  multiple: props.multiple,
})

onChange(async (files) => {
  if (!files) return
  const [file] = files
  const res = await upload(file)
  const nowTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  const result = { name: file.name, size: file.size, type: file.type, url: res, upload_time: nowTime }
  if (typeof props.modelValue === 'string') {
    emit('update:modelValue', result.url)
  } else {
    const updatedValue = [...props.modelValue]
    updatedValue[index.value] = result
    emit('update:modelValue', updatedValue)
  }
  reset()
})

const handleOpen = (i = 0) => {
  index.value = i
  open()
}

const getTitle = (i) => (i === 0 && props.firstTitle) || props.title
const getTips = (i) => (i === 0 && props.firstTips) || props.tips

const designVisible = ref(false)
const handleOpenDesign = (i = 0) => {
  index.value = i
  designVisible.value = true
}
const handleDesignSave = (url) => {
  const nowTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  const result = { name: '未命名', size: '未知', type: 'image/png', url, upload_time: nowTime }
  const updatedValue = [...props.modelValue]
  updatedValue[index.value] = result
  emit('update:modelValue', updatedValue)
}

const chatVisible = ref(false)
const handleOpenChat = (i = 0) => {
  index.value = i
  chatVisible.value = true
}
const handleChatSave = (url) => {
  const nowTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
  const result = { name: '未命名', size: '未知', type: 'image/png', url, upload_time: nowTime }
  const updatedValue = [...props.modelValue]
  updatedValue[index.value] = result
  emit('update:modelValue', updatedValue)
}
</script>
<template>
  <div class="upload-wrapper">
    <template v-if="Array.isArray(props.modelValue)">
      <div v-for="(item, i) in props.limit" :key="i">
        <el-popover placement="top" width="220px" trigger="hover">
          <ul class="upload-popover">
            <li @click="handleOpen(i)">
              <i class="el-icon"><UploadFilled /></i>本地上传
            </li>
            <li @click="handleOpenDesign(i)" v-if="!isVideo">
              <i class="el-icon"><Picture /></i>图库选择
            </li>
            <li @click="handleOpenChat(i)" v-if="!isVideo">
              <i class="el-icon"><MagicStick /></i>AI辅助
            </li>
          </ul>
          <template #reference>
            <div class="upload-item">
              <template v-if="props.modelValue[i]">
                <a :href="props.modelValue[i]?.url" target="_blank">
                  <img :src="props.modelValue[i]?.url" />
                </a>
              </template>
              <template v-else>
                <div class="upload-item-uploader" @click="handleOpen(i)">
                  <div class="upload-item__title">{{ getTitle(i) }}</div>
                  <i class="el-icon"><Plus /></i>
                  <div class="upload-item__tips">{{ getTips(i) }}</div>
                </div>
              </template>
            </div>
          </template>
        </el-popover>
      </div>
    </template>

    <template v-else>
      <el-popover placement="top" width="160px" trigger="hover">
        <ul class="upload-popover">
          <li @click="handleOpen">
            <i class="el-icon"><UploadFilled /></i>本地上传
          </li>
          <li @click="handleOpenDesign" v-if="!isVideo">
            <i class="el-icon"><Picture /></i>图库选择
          </li>
          <li @click="handleOpenChat" v-if="!isVideo">
            <i class="el-icon"><MagicStick /></i>AI辅助
          </li>
        </ul>
        <template #reference>
          <div class="upload-item">
            <template v-if="props.modelValue">
              <a :href="props.modelValue" target="_blank">
                <video :src="props.modelValue" v-if="isVideo"></video>
                <img :src="props.modelValue" v-else />
              </a>
            </template>
            <template v-else>
              <div class="upload-item-uploader" @click="handleOpen">
                <div class="upload-item__title">{{ props.firstTitle || props.title }}</div>
                <i class="el-icon"><Plus /></i>
                <div class="upload-item__tips">{{ props.firstTips || props.tips }}</div>
              </div>
            </template>
          </div>
        </template>
      </el-popover>
    </template>
    <ImageDesign v-model="designVisible" :kindId="29" @update="handleDesignSave" v-if="designVisible"></ImageDesign>
    <ImageChat v-model="chatVisible" @update="handleChatSave" v-if="chatVisible"></ImageChat>
  </div>
</template>

<style lang="scss">
.upload-wrapper {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
}
.upload-popover {
  display: flex;
  justify-content: space-around;
  li {
    display: flex;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
    .el-icon {
      font-size: 20px;
    }
  }
}
.upload-item {
  position: relative;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  text-align: center;
  width: 100px;
  height: v-bind(itemHeight);
  border: 1px dashed var(--el-border-color-darker);
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  a,
  video,
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
  &__title {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    background-color: var(--main-color);
    font-size: 12px;
    color: #fff;
    text-align: center;
    line-height: 20px;
  }
  &__tips {
    font-size: 12px;
  }
  &-uploader {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
  }
}
</style>
