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

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

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

const interval = ref<number>(1440) // 默认1天（1440分钟）
const startImmediately = ref(true)
const domains = ref('')
const formRef = ref<InstanceType<typeof NForm> | null>(null)

const rules: FormRules = {
  interval: [
    {
      required: true,
      type: 'number',
      message: '请输入采集间隔',
      trigger: ['blur', 'change'],
    },
    {
      type: 'number',
      min: 1,
      message: '采集间隔必须大于0',
      trigger: ['blur', 'change'],
    },
  ],
  domains: [
    {
      required: true,
      message: '请输入域名',
      trigger: ['blur', 'change'],
    },
    {
      validator: (_, value: string) => {
        if (!value.trim()) return true // 空值由 required 规则处理
        const domainList = value
          .split(/[\n,]/)
          .map((d) => d.trim())
          .filter((d) => d)
        if (domainList.length === 0) return false
        return true
      },
      message: '域名格式不正确',
      trigger: ['blur', 'change'],
    },
  ],
}

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

  try {
    // 处理域名输入，支持换行和逗号分隔
    const domainList = domains.value
      .split(/[\n,]/) // 同时支持换行和逗号分隔
      .map((domain) => domain.trim()) // 去除每个域名的前后空格
      .filter((domain) => domain) // 过滤空字符串

    const response = await axios.post('/api/domain/v1/add', {
      domains: domainList,
      crawl_interval: interval.value,
      crawl_now: startImmediately.value,
    })

    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
  domains.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, domains }" :rules="rules">
      <n-form-item path="interval" label="采集间隔（分钟）">
        <n-input-number v-model:value="interval" :min="1" />
      </n-form-item>

      <n-form-item path="domains" label="域名列表">
        <n-input
          v-model:value="domains"
          type="textarea"
          :rows="10"
          placeholder="请输入域名，支持换行或英文逗号分隔"
        />
      </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>
