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

import { aiiModelRules, check_remote_model } from '@/tools/avaliable-check.ts'
import { api } from '@/tools/web.ts'
import type { AiiModelPublic } from '@/types/aii.ts'

const MESSAGE = useMessage()

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

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

const provider = computed(() => {
  return `[${model.provider_id}] ${model.provider_name}`
})

async function onCheck() {
  if (await check_remote_model(model.provider_id, model.model_name)) {
    MESSAGE.success(`提供商的模型 ${model.model_name} 可用。`)
  } else {
    MESSAGE.warning(`提供商的模型 ${model.model_name} 不可用。`)
  }
}

function onSave() {
  api
    .post(
      `/aii/model/${model.id}`,
      JSON.stringify({
        model_name: model.model_name,
        max_context_length: model.max_context_length,
        reasonable: model.reasonable,
        aii_provider_id: model.provider_id,
      }),
    )
    .then((res) => res.data as AiiModelPublic)
    .then((data) => {
      MESSAGE.success(
        `提供商 [${model.provider_id}] ${model.provider_name} 的模型 ${data.model_name} 已更新。`,
      )
      showModal.value = false
    })
    .catch((err) => {
      MESSAGE.error(`更新模型失败：${err}`)
    })
}
</script>

<template>
  <n-modal v-model:show="showModal" preset="card" title="修改模型">
    <n-alert type="warning" class="in-form-alert">
      不支持更换 API Key。如果需要更换 Key，请移除并重新添加模型提供商与模型。
    </n-alert>
    <n-form
      label-width="auto"
      label-align="right"
      label-placement="left"
      :model="model"
      :rules="aiiModelRules"
    >
      <n-form-item label="模型提供商">
        <n-input v-model:value="provider" readonly />
      </n-form-item>
      <n-form-item label="模型名称" path="model_name">
        <n-input v-model:value="model.model_name" />
      </n-form-item>
      <n-form-item label="最大上下文长度" path="max_context_length">
        <n-input-number v-model:value="model.max_context_length">
          <template #suffix>k</template>
        </n-input-number>
      </n-form-item>
      <n-form-item label="支持思考" path="reasonable">
        <n-switch v-model:value="model.reasonable" />
      </n-form-item>
      <n-form-item label="操作">
        <n-flex>
          <n-button type="info" secondary @click="onCheck()">检测</n-button>
          <n-button type="primary" secondary @click="onSave()">确认</n-button>
        </n-flex>
      </n-form-item>
    </n-form>
  </n-modal>
</template>

<style scoped></style>
