<script setup lang="ts">
import { useMessage } from 'naive-ui'
import { ref } from 'vue'

import { check_remote_provider } from '@/tools/avaliable-check.ts'
import { api } from '@/tools/web.js'
import type { AiiProviderPublicWithoutKey } from '@/types/aii.ts'

const MESSAGE = useMessage()

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

const { reload } = defineProps<{
  reload?: () => void
}>()

const addProviderForm = ref({
  id: 0,
  name: '',
  base_url: '',
  api_key: '',
})

async function onCheck() {
  if (await check_remote_provider(addProviderForm.value)) {
    MESSAGE.success(`检查模型提供商 ${addProviderForm.value.name} 可用性成功。`)
  } else {
    MESSAGE.success(`检查模型提供商 ${addProviderForm.value.name} 可用性失败？`)
  }
}

function onConfirm() {
  api
    .post('/aii/provider/', JSON.stringify(addProviderForm.value))
    .then((res) => res.data as AiiProviderPublicWithoutKey)
    .then(() => {
      MESSAGE.success(`已添加模型提供商 ${addProviderForm.value.name} 。`)
      showModal.value = false
      if (reload) reload()
    })
    .catch((err) => {
      MESSAGE.error(`添加模型提供商失败：${err}`)
    })
}
</script>

<template>
  <n-modal v-model:show="showModal" preset="card" title="添加模型提供商">
    <n-form :model="addProviderForm" label-placement="left" label-width="auto" label-align="right">
      <n-form-item label="名称" path="name" :rule="{ required: true, trigger: 'blur' }">
        <n-input v-model:value="addProviderForm.name" />
      </n-form-item>
      <n-form-item label="Base URL" path="base_url" :rule="{ required: true, trigger: 'blur' }">
        <n-input v-model:value="addProviderForm.base_url" />
      </n-form-item>
      <n-form-item label="API Key" path="api_key" :rule="{ required: true, trigger: 'blur' }">
        <n-input v-model:value="addProviderForm.api_key" />
      </n-form-item>
      <n-form-item label="添加完成">
        <n-flex>
          <n-button secondary type="info" @click="onCheck()">检测</n-button>
          <n-button secondary type="primary" @click="onConfirm()">确认</n-button>
        </n-flex>
      </n-form-item>
    </n-form>
  </n-modal>
</template>

<style scoped></style>
