<script setup lang="ts">
import { ref, inject } from 'vue'
import {
  NModal,
  NForm,
  NFormItem,
  NInputNumber,
  NCheckbox,
  NUpload,
  NButton,
  NButtonGroup,
  useMessage,
} from 'naive-ui'
import type { FormRules } from 'naive-ui'
import type { AxiosInstance } from 'axios'
import type { UploadFileInfo } from 'naive-ui'

const model = defineModel<boolean>('show', { required: true })
const emit = defineEmits(['success'])

const axios = inject('axios') as AxiosInstance
const message = useMessage()

const interval = ref(1440) // 默认1天（1440分钟）
const startImmediately = ref(true)
const fileList = ref<UploadFileInfo[]>([])
const formRef = ref<InstanceType<typeof NForm> | null>(null)

const rules: FormRules = {
  interval: [
    {
      type: 'number',
      required: true,
      message: '请输入采集间隔',
      trigger: ['blur', 'change'],
    },
    {
      type: 'number',
      min: 1,
      message: '采集间隔必须大于0',
      trigger: ['blur', 'change'],
    },
  ],
  fileList: [
    {
      type: 'array',
      required: true,
      message: '请选择文件',
      trigger: ['change'],
    },
    {
      validator: (_, value: UploadFileInfo[]) => {
        if (!value || value.length === 0) return false
        return !!value[0].file
      },
      message: '文件无效',
      trigger: ['change'],
    },
  ],
}

const handleConfirm = async () => {
  try {
    await formRef.value?.validate()
  } catch (errors) {
    return
  }

  try {
    const formData = new FormData()
    const file = fileList.value[0].file
    if (!file) {
      message.error('文件无效')
      return
    }
    formData.append('file', file)
    formData.append('crawl_interval', interval.value.toString())
    formData.append('crawl_now', startImmediately.value.toString())

    const response = await axios.post('/api/domain/v1/import', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })

    if (response.data.code === 20000) {
      message.success('导入成功')
      emit('success')
      handleClose()
    } else {
      message.error(`导入失败：${response.data.message}`)
    }
  } catch (error) {
    console.error('导入失败', error)
    message.error(`导入失败：${error}`)
  }
}

const handleClose = () => {
  // 清空表单
  interval.value = 1440
  startImmediately.value = true
  fileList.value = []
  formRef.value?.restoreValidation()
  model.value = false
}
</script>

<template>
  <n-modal
    v-model:show="model"
    preset="card"
    title="通过文件导入"
    :mask-closable="false"
    style="width: 600px"
  >
    <n-form
      size="small"
      ref="formRef"
      :model="{ interval, fileList }"
      :rules="rules"
      label-placement="left"
      label-width="200"
    >
      <n-form-item path="interval" label="采集间隔（分钟）">
        <n-input-number v-model:value="interval" :min="1" />
      </n-form-item>
      <n-form-item path="fileList" label="选择文件">
        <n-upload v-model:file-list="fileList" :max="1" accept=".txt,.csv">
          <n-button>选择文件</n-button>
        </n-upload>
      </n-form-item>
      <n-form-item label="采集选项">
        <n-checkbox v-model:checked="startImmediately"> 立即开始采集 </n-checkbox>
      </n-form-item>
    </n-form>
    <template #action>
      <n-button-group size="small">
        <n-button type="primary" @click="handleConfirm">确认</n-button>
        <n-button @click="handleClose">关闭</n-button>
      </n-button-group>
    </template>
  </n-modal>
</template>
