<script setup>
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'

import { useLinksStore } from '@/stores/links'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
})

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

const linksStore = useLinksStore()
const uploadRef = ref()

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value),
})

const isImporting = ref(false)

async function handleImport(uploadFile) {
  const file = uploadFile?.raw
  if (!file) return

  isImporting.value = true
  try {
    const text = await file.text()
    const payload = JSON.parse(text)
    const links = Array.isArray(payload?.links) ? payload.links : []
    if (!links.length) {
      throw new Error('所选文件中没有可导入的书签数据。')
    }
    await linksStore.importLinks(links)
    ElMessage.success(`已导入 ${links.length} 条书签`)
    visible.value = false
  } catch (error) {
    console.error(error)
    ElMessage.error(error.message ?? '导入失败')
  } finally {
    isImporting.value = false
    uploadRef.value?.clearFiles()
  }
}

async function handleExport() {
  await linksStore.ensureLoaded()
  const payload = await linksStore.exportLinks()
  const blob = new Blob([JSON.stringify(payload, null, 2)], {
    type: 'application/json',
  })
  const url = URL.createObjectURL(blob)
  const anchor = document.createElement('a')
  anchor.href = url
  anchor.download = `bookmark-export-${new Date().toISOString().split('T')[0]}.json`
  anchor.click()
  URL.revokeObjectURL(url)
  ElMessage.success('已开始导出')
}
</script>

<template>
  <el-dialog v-model="visible" title="导入 / 导出数据" width="520px">
    <section>
      <h3>从 JSON 导入</h3>
      <p>上传由本应用导出的 JSON 文件，用于恢复本地书签。</p>
      <el-upload
        ref="uploadRef"
        drag
        accept="application/json"
        :show-file-list="false"
        :auto-upload="false"
        :disabled="isImporting"
        @change="handleImport"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">拖拽文件到此处或<em>点击上传</em></div>
      </el-upload>
    </section>

    <el-divider />

    <section>
      <h3>导出当前数据</h3>
      <p>下载当前浏览器中所有书签的 JSON 备份。</p>
      <el-button type="primary" @click="handleExport">导出 JSON</el-button>
    </section>
  </el-dialog>
</template>

