<script setup lang="ts">
import { type SelectOption, useMessage } from 'naive-ui'
import { computed, onMounted, ref } from 'vue'

import AiiModelAddModal from '@/components/chatroom/AiiModelAddModal.vue'
import ChatPromptQuicker from '@/components/chatroom/ChatPromptQuicker.vue'
import ChatroomEditorModal from '@/components/chatroom/ChatroomEditorModal.vue'
import ScriptDrawer from '@/components/chatroom/ScriptDrawer.vue'
import { useNowUser } from '@/stores/now-user.ts'
import { api } from '@/tools/web.js'
import type { AiiModelPublic } from '@/types/aii.js'
import type { Chatroom, ChatroomPublic } from '@/types/chatroom.ts'
import type { ReturnDto } from '@/types/response.js'

const NOWUSER = useNowUser()
const MESSAGE = useMessage()

const selectedModel = defineModel<number | null>('selectModel', { required: true })
const quickerPrompt = defineModel<string>('quickerPrompt', { required: true })

const { chatroom, loadPage } = defineProps<{
  chatroom: Chatroom
  loadPage: () => void
}>()

const showAddModelModal = ref(false)
const models = ref<AiiModelPublic[]>([])
const showScriptDrawer = ref(false)

const modelOptions = computed(() => {
  const options = [] as SelectOption[]
  for (const model of models.value) {
    options.push({
      value: model.id,
      label: `[${model.provider_name}] ${model.model_name}`,
    })
  }
  return options
})

function loadModels() {
  api
    .get('/aii/model')
    .then((res) => res.data as ReturnDto)
    .then((data) => {
      if (data.success) {
        models.value = data.result as AiiModelPublic[]
      } else {
        throw TypeError('获取模型列表失败……')
      }
    })
    .catch((err) => {
      MESSAGE.error(`加载模型列表失败：${err}`)
    })
}

onMounted(() => {
  loadModels()
  if (chatroom.default_model_id) {
    selectedModel.value = chatroom.default_model_id
  } else {
    MESSAGE.info(
      '此聊天室还未设置默认模型。你需要选择一个模型然后开始聊天，或者现在就保存一个默认模型嘛？',
    )
  }
})

const showChatroomInfoModal = ref(false)
const chatroomInfo = ref<ChatroomPublic>({
  id: chatroom.id,
  name: chatroom.name,
  description: chatroom.description,
  feature_image: chatroom.feature_image,
  default_model_id: chatroom.default_model_id,
  script_template_id: chatroom.script_template_id,
  script_template_version: chatroom.script_template_version,
})

function saveDefaultModel() {
  if (selectedModel.value) {
    chatroomInfo.value.default_model_id = selectedModel.value
    api
      .post(`/chatroom/${chatroom.id}/`, JSON.stringify(chatroomInfo.value))
      .then(() => {
        MESSAGE.success('默认模型设置成功~')
      })
      .catch((err) => {
        MESSAGE.error(`设置默认模型失败：${err}`)
      })
  } else {
    MESSAGE.warning('请先选择一个模型哦~')
  }
}
</script>

<template>
  <n-flex vertical>
    <n-card title="模型">
      <template #header-extra>
        <n-flex>
          <n-button secondary type="info" size="small" round @click="loadModels()">刷新</n-button>
          <n-button
            v-if="NOWUSER.is_admin"
            secondary
            type="warning"
            size="small"
            round
            @click="showAddModelModal = true"
          >
            添加
          </n-button>
          <n-button-group>
            <n-button secondary type="primary" size="small" round @click="saveDefaultModel()">
              保存
            </n-button>
            <n-popover>
              <template #trigger>
                <n-button secondary type="tertiary" size="small" round>?</n-button>
              </template>
              <n-h4>有哪些模型？</n-h4>
              <n-p>NyaHome 管理员可以添加模型，然后所有用户都可以使用这些模型。</n-p>
              <n-p>NyaHome 不提供模型调用。</n-p>
              <n-h4>默认模型？切换模型？</n-h4>
              <n-p>可以针对聊天室保存一个默认模型。</n-p>
              <n-p>你也可以在这里切换其他的模型。但在保存之前，默认模型不会修改。</n-p>
            </n-popover>
          </n-button-group>
        </n-flex>
      </template>
      <n-select v-model:value="selectedModel" :options="modelOptions" />
      <aii-model-add-modal v-model:show-modal="showAddModelModal" />
    </n-card>

    <chat-prompt-quicker v-model:prompt-prefix="quickerPrompt" />

    <n-card title="剧本">
      <template #header-extra>故事设定 · 世界书</template>
      <n-flex vertical>
        <n-alert type="info">剧本模板功能仍在开发中，暂不支持分享哦~</n-alert>
        <n-button secondary type="info" @click="showScriptDrawer = true">
          故事设定 · 世界书
        </n-button>
      </n-flex>
      <script-drawer :script="chatroom.script" v-model:show-drawer="showScriptDrawer" />
    </n-card>

    <n-card title="设置">
      <template #header-extra>也许你不需要修改这里</template>
      <n-flex vertical>
        <n-button secondary type="primary" @click="showChatroomInfoModal = true">
          聊天室信息
        </n-button>
        <n-button secondary type="info">系统设置</n-button>
      </n-flex>
      <chatroom-editor-modal
        :chatroom="chatroomInfo"
        v-model:show-modal="showChatroomInfoModal"
        :reload="loadPage"
      />
    </n-card>
  </n-flex>
</template>

<style scoped></style>
