<script setup lang="ts">
import { ref } from 'vue'
import { api } from '@/tools/web.js'
import type { ReturnDto } from '@/types/response.js'
import { useMessage } from 'naive-ui'

const MESSAGE = useMessage()

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

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

function onCheck() {
  api
    .post('/aii/remote/provider/check/', JSON.stringify(addProviderForm.value))
    .then((res) => res.data as ReturnDto)
    .then((data) => {
      if (data.success) {
        MESSAGE.success(`模型提供商检测成功，探测到 ${data.result} 个可用模型。`)
      } else {
        MESSAGE.warning('模型提供商检测失败，请确认 Base URI 与 API key 是否正确。')
      }
    })
    .catch((err) => {
      MESSAGE.error(`检测模型提供商时遇到未知的异常，请检查后端业务：${err}`)
    })
}

function onConfirm() {
  api
    .post('/aii/provider/', JSON.stringify(addProviderForm.value))
    .then((res) => res.data as ReturnDto)
    .then((data) => {
      if (data.success) {
        MESSAGE.success(`已添加模型提供商 ${addProviderForm.value.name} 。`)
        showModal.value = false
      } else {
        throw TypeError('后端业务表示添加模型提供商失败，但未提供原因。')
      }
    })
    .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">
        <n-input v-model:value="addProviderForm.name" />
      </n-form-item>
      <n-form-item label="Base URL" path="base_url">
        <n-input v-model:value="addProviderForm.base_url" />
      </n-form-item>
      <n-form-item label="API Key" path="api_key">
        <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>
