<script setup lang="ts">
import { ref, watch } from 'vue'

import SelectFileModal from '@/components/file/SelectFileModal.vue'
import UploadFileModal from '@/components/file/UploadFileModal.vue'
import { api } from '@/tools/web.ts'
import type { UploadFileDto } from '@/types/user.ts'

const value = defineModel('value', { required: true })

const showSelectModal = ref(false)
const showUploadModal = ref(false)
const selectFiles = ref<UploadFileDto[]>([])

async function loadFiles() {
  return await api.get('/file/').then((res) => res.data as UploadFileDto[])
}

watch(
  () => selectFiles.value,
  () => {
    value.value = selectFiles.value[0]?.download_url
  },
)
</script>

<template>
  <n-flex style="width: 100%" :wrap="false">
    <n-input v-model:value="value" placeholder="留空以使用默认图像" />
    <n-button secondary type="info" @click="showSelectModal = true">选择</n-button>
    <n-button secondary type="warning" @click="showUploadModal = true">上传</n-button>
  </n-flex>

  <select-file-modal
    :max="1"
    :extensions="['png', 'jpeg', 'jpg']"
    :load-files="loadFiles"
    v-model:show-modal="showSelectModal"
    v-model:select-files="selectFiles"
  />
  <upload-file-modal v-model:show-modal="showUploadModal" />
</template>

<style scoped></style>
