<script setup lang="ts">
import { ref, defineProps, defineEmits, inject, defineModel, computed, watch } from 'vue'
import { useMessage } from 'naive-ui'
import type { AxiosInstance } from 'axios'
import type { DataTableRowKey } from 'naive-ui'

const show = defineModel<boolean>('show')
const props = defineProps<{
  // 要修改的域名 ID 列表
  domainIds: DataTableRowKey[] | null
}>()

const emit = defineEmits<{
  (e: 'success'): void
  (e: 'close'): void
}>()

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

// 采集间隔需要用户输入
const crawlInterval = ref<number | null>(null)
const loading = ref(false)

// 动态计算弹窗标题
const dialogTitle = computed(() => {
  const count = props.domainIds?.length || 0
  if (count > 1) {
    return `批量修改 ${count} 个域名的采集间隔`
  } else if (count === 1) {
    return '修改域名采集间隔'
  }
  return '修改采集间隔' // 应该不会出现，但作为备用
})

// 弹窗显示时，重置 crawlInterval
watch(show, (newShow) => {
  if (newShow) {
    crawlInterval.value = null // 每次打开都清空，强制用户输入
  }
})

const handleSubmit = async () => {
  if (crawlInterval.value === null || crawlInterval.value < 1) {
    message.error('请输入有效的采集间隔（大于等于1的整数）')
    return
  }

  if (!props.domainIds || props.domainIds.length === 0) {
    message.error('没有指定要修改的域名')
    return
  }

  try {
    loading.value = true

    const response = (
      await axios.post('/api/domain/v1/update', {
        domain_ids: props.domainIds, // 直接使用传入的 ID
        crawl_interval: crawlInterval.value,
      })
    ).data

    if (response.code !== 20000) {
      message.error(`更新失败：${response.message}`)
      return
    }

    message.success('更新成功')
    emit('success')
    show.value = false // 关闭弹窗
  } catch (error) {
    console.error('更新失败', error)
    message.error(`更新失败：${error}`)
  } finally {
    loading.value = false
  }
}

const handleClose = () => {
  show.value = false
  emit('close') // 触发 close 事件
}
</script>

<template>
  <n-modal
    v-model:show="show"
    preset="dialog"
    :title="dialogTitle"
    :loading="loading"
    @close="handleClose"
  >
    <!-- 批量编辑提示 -->
    <div v-if="(domainIds?.length || 0) > 1" class="mb-4 text-orange-500">
      你正在批量修改 {{ domainIds?.length }} 个域名的采集间隔。
    </div>

    <n-form>
      <n-form-item label="采集间隔（分钟）" required>
        <n-input-number
          v-model:value="crawlInterval"
          :min="1"
          :step="1"
          style="width: 100%"
          placeholder="请输入采集间隔"
        />
      </n-form-item>
    </n-form>
    <template #action>
      <n-button @click="handleClose">取消</n-button>
      <n-button type="primary" @click="handleSubmit" :loading="loading">确定</n-button>
    </template>
  </n-modal>
</template>
