<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, reactive, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { FormInst, InputInst, SelectOption, UploadFileInfo } from 'naive-ui'
import { useThrottleFn } from '@vueuse/core'
import CustomIcon from '@/components/custom-icon/custom-icon.vue'
import UploadPhoto from '@/components/upload-photo/upload-photo.vue'
import AutoConfigModal from './auto-config-modal.vue'
import OptimizeSystemModal from './optimize-system-modal.vue'
import { usePersonalAppConfigStore } from '@/store/modules/personal-app-config'
import { PersonalAppConfigState } from '@/store/types/personal-app-config'
import {
  fetchCreateAgentAvatar,
  fetchCreateAgentTitleAndDesc,
  fetchCreateFeaturedQuestions,
  fetchCreatePreamble,
  fetchGetDebugApplicationInfo,
  fetchGetLargeModelList,
  fetchSaveAgentApplication,
} from '@/apis/agent-application'
import { fetchCustomEventSource } from '@/composables/useEventSource'

const router = useRouter()

const personalAppConfigStore = usePersonalAppConfigStore()

const defaultPrompt = `#角色设定
作为一个____，你的任务是____。

#组件能力
你具备____能力。

#要求与限制
1.输出内容的风格要求____
2.输出结果的格式为____
3.输出内容的字数限制不超过____
......`

const questionSettingOptions = [
  {
    label: '默认',
    value: 'default',
    style: { fontSize: '12px' },
  },
  {
    label: '关闭',
    value: 'close',
    style: { fontSize: '12px' },
  },
]

let modalListOptions = reactive<SelectOption[]>([])

const commConfigExpandedNames = ref<string[]>(['continuousQuestion'])

const isInitGetAgentAppDetail = ref(false)

const isFullScreenLoading = ref(false) // 是否全面加载中

const isShowAutoConfigModal = ref(false) // 是否显示自动配置对话框
const autoConfigBtnLoading = ref(false) // 自动配置按钮加载状态
const isShowOptimizeAgentSystemModal = ref(false) // 是否显示优化角色指令对话框

const generateAgentAvatarLoading = ref(false) // 是否正在生成图片
const generatePreambleLoading = ref(false) // 是否正在生成开场白
const generateFeaturedQuestionsLoading = ref(false) // 是否正在生成推荐词

const personalAppFormRef = ref<FormInst | null>(null)
const agentSystemInputRef = ref<InputInst | null>(null)

const personalAppRules = {
  baseInfo: {
    agentTitle: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
  },
}

let generateAgentTitleAndDescController: AbortController | null = null
let generateAgentAvatarController: AbortController | null = null
let generatePreambleController: AbortController | null = null
let generateFeaturedQuestionsController: AbortController | null = null
let generateAgentSystemController: AbortController | null = null

const personalAppConfig = computed(() => {
  return personalAppConfigStore.$state
})

const continuousQuestionStatusText = computed(() => {
  return personalAppConfig.value.commConfig.continuousQuestionStatus === 'default' ? '默认' : '关闭'
})

const isUpdatePersonalAgentConfig = computed(() => {
  return !isInitGetAgentAppDetail.value
})

watch(
  () => personalAppConfig.value,
  () => {
    isUpdatePersonalAgentConfig.value && handleUpdatePersonalAppId()
  },
  { deep: true, once: true },
)

watch(
  () => personalAppConfig.value,
  () => {
    isUpdatePersonalAgentConfig.value && handleSavePersonalAppConfig()
  },
  { deep: true },
)

onMounted(async () => {
  if (router.currentRoute.value.params.agentId) {
    isInitGetAgentAppDetail.value = true
    await handleGetAgentApplicationDetail(router.currentRoute.value.params.agentId as string)
    isInitGetAgentAppDetail.value = false
  }
  await handleGetLargeModelList()
})

onUnmounted(() => {
  handleStopGenerate()
})

const handleSavePersonalAppConfig = useThrottleFn(
  async () => {
    personalAppConfig.value.baseInfo.agentId && (await handleSaveAgentApplication())
  },
  () => (isFullScreenLoading.value ? 6000 : 2000),
  true,
)

async function handleGetAgentApplicationDetail(agentId: string) {
  const res = await fetchGetDebugApplicationInfo<PersonalAppConfigState>(agentId)

  if (res.code === 0) {
    personalAppConfigStore.updatePersonalAppConfigState({
      ...res.data,
      baseInfo: {
        ...res.data.baseInfo,
        agentAvatar:
          res.data.baseInfo.agentAvatar || 'https://gsst-poe-sit.gz.bcebos.com/data/20240911/1726041369632.webp',
      },
    })
    ;['preamble', 'featuredQuestions']
      .filter((property) => personalAppConfig.value.commConfig[property as keyof PersonalAppConfigState['commConfig']])
      .forEach((property) => {
        commConfigExpandedNames.value.push(property)
      })
  }
}

async function handleGetLargeModelList() {
  modalListOptions = []
  const res = await fetchGetLargeModelList<{ owner: string; models: string[] }[]>()

  res.data.forEach((item) => {
    modalListOptions.push({
      type: 'group',
      label: item.owner,
      key: item.owner,
      children: item.models.map((model) => ({
        label: model,
        value: model,
        style: { fontSize: '12px' },
      })),
    })
  })
}

// 保存应用配置
async function handleSaveAgentApplication() {
  await fetchSaveAgentApplication<PersonalAppConfigState>(personalAppConfigStore.$state)
}

// 更新保存应用ID
async function handleUpdatePersonalAppId() {
  const res = await fetchSaveAgentApplication<PersonalAppConfigState>(personalAppConfigStore.$state)

  if (res.code === 0) {
    personalAppConfigStore.updatePersonalAppConfigState({
      baseInfo: { ...personalAppConfigStore.baseInfo, agentId: res.data.baseInfo.agentId },
    })
  }
}

function handleShowAutoConfigModal() {
  isShowAutoConfigModal.value = true
  autoConfigBtnLoading.value = false
}

function handleShowOptimizeAgentSystemModal() {
  if (!personalAppConfig.value.baseInfo.agentSystem) return

  isShowOptimizeAgentSystemModal.value = true
}

function handleSettingDefaultPrompt() {
  personalAppConfig.value.baseInfo.agentSystem = defaultPrompt
}

function handleUploadAppAvatar(file: UploadFileInfo[]) {
  personalAppConfig.value.baseInfo.agentAvatar = file?.[0]?.url || ''
}

function handleRemoveAppAvatar() {
  personalAppConfig.value.baseInfo.agentAvatar = ''
}

function handleUpdateCommConfigExpandedNames(expandedNames: string[]) {
  commConfigExpandedNames.value = expandedNames
}

async function handleAIGenerateAgentAvatar() {
  generateAgentAvatarLoading.value = true
  generateAgentAvatarController = new AbortController()

  const res = await fetchCreateAgentAvatar(
    {
      agentTitle: personalAppConfig.value.baseInfo.agentTitle,
      agentDesc: personalAppConfig.value.baseInfo.agentDesc,
    },
    generateAgentAvatarController,
  ).finally(() => (generateAgentAvatarLoading.value = false))

  if (res.code === 0) {
    personalAppConfig.value.baseInfo.agentAvatar = res.data as string
  }
}

async function handleAIGeneratePreamble() {
  !commConfigExpandedNames.value.includes('preamble') && commConfigExpandedNames.value.push('preamble')

  generatePreambleLoading.value = true

  generatePreambleController = new AbortController()

  const res = await fetchCreatePreamble<string>(
    {
      agentTitle: personalAppConfig.value.baseInfo.agentTitle,
      agentDesc: personalAppConfig.value.baseInfo.agentDesc,
      agentSystem: personalAppConfig.value.baseInfo.agentSystem,
    },
    generatePreambleController,
  ).finally(() => (generatePreambleLoading.value = false))

  if (res.code === 0) {
    try {
      const content = res.data.replace(/^```json|```$/g, '')
      const preamble = JSON.parse(content)['output']
      personalAppConfig.value.commConfig.preamble = preamble
    } catch (error) {
      window.$message.error('生成内容格式出错啦')
    }
  }
}

async function handleAIGenerateFeaturedQuestions() {
  !commConfigExpandedNames.value.includes('featuredQuestions') &&
    commConfigExpandedNames.value.push('featuredQuestions')

  generateFeaturedQuestionsLoading.value = true
  generateFeaturedQuestionsController = new AbortController()

  const res = await fetchCreateFeaturedQuestions<string[]>(
    {
      agentTitle: personalAppConfig.value.baseInfo.agentTitle,
      agentDesc: personalAppConfig.value.baseInfo.agentDesc,
    },
    generateFeaturedQuestionsController,
  ).finally(() => (generateFeaturedQuestionsLoading.value = false))

  if (res.code === 0) {
    personalAppConfig.value.commConfig.featuredQuestions = res.data
  }
}

async function handleSettingAgent(autoConfigInputValue: string) {
  autoConfigBtnLoading.value = true
  isShowAutoConfigModal.value = false
  isFullScreenLoading.value = true

  await handleCreateAgentTitleAndDesc(autoConfigInputValue)
    .then(() => {
      Promise.all([
        handleAIGenerateAgentAvatar(),
        handleAIGeneratePreamble(),
        handleAIGenerateFeaturedQuestions(),
        handleAIGenerateAgentSystem(),
      ]).finally(() => {
        isFullScreenLoading.value = false
      })
    })
    .catch(() => {
      isFullScreenLoading.value = false
    })
}

async function handleCreateAgentTitleAndDesc(input: string) {
  generateAgentTitleAndDescController = new AbortController()
  const res = await fetchCreateAgentTitleAndDesc<{ agentTitle: string; agentDesc: string }>(
    { input },
    generateAgentTitleAndDescController,
  )

  if (res.code === 0) {
    personalAppConfig.value.baseInfo.agentTitle = res.data.agentTitle
    personalAppConfig.value.baseInfo.agentDesc = res.data.agentDesc
  }
}

function handleSettingAgentSystem(agentSystem: string) {
  personalAppConfig.value.baseInfo.agentSystem = agentSystem
  isShowOptimizeAgentSystemModal.value = false
}

function handleAIGenerateAgentSystem() {
  return new Promise((resolve, reject) => {
    personalAppConfig.value.baseInfo.agentSystem = ''
    generateAgentSystemController = new AbortController()

    fetchCustomEventSource({
      path: '/api/rest/agentApplicationInfoRest/createAgentSystem.json',
      payload: {
        input: personalAppConfigStore.baseInfo.agentSystem,
      },
      controller: generateAgentSystemController,
      onMessage: (data: any) => {
        if (data === '[DONE]') {
          blockAnswerResponse()
          resolve(data)
          return
        }

        if (data) {
          useThrottleFn(
            () => {
              nextTick(() => {
                personalAppConfig.value.baseInfo.agentSystem += data
                agentSystemInputRef.value!.textareaElRef!.scrollTop =
                  agentSystemInputRef.value?.textareaElRef?.scrollHeight || 0
              })
            },
            1000,
            true,
          )()
        }
      },
      onRequestError: () => {
        reject()
        blockAnswerResponse()
      },
      onError: () => {
        reject()
        blockAnswerResponse()
      },
      onFinally: () => {
        generateAgentSystemController = null
      },
    })
  })
}

function blockAnswerResponse() {
  generateAgentSystemController?.abort()
}

function handleStopGenerate() {
  generateAgentTitleAndDescController?.abort()
  generateAgentAvatarController?.abort()
  generatePreambleController?.abort()
  generateFeaturedQuestionsController?.abort()
  generateAgentSystemController?.abort()
  isFullScreenLoading.value = false
}
</script>

<template>
  <div class="flex h-full w-[800px] flex-col xl:w-[1000px]">
    <div
      class="flex h-[56px] w-full items-center justify-between border-r border-[#e8e9eb] px-5 text-[#333] shadow-[inset_0_-1px_#e8e9eb]"
    >
      <div class="flex items-center">
        <span class="font-600 mr-4 text-base">应用配置</span>

        <div
          class="text-theme-color flex cursor-pointer items-center rounded-md border border-[#d4e5ff] bg-[#eef3fe] px-[11px] py-[7px] text-xs hover:opacity-80"
          @click="handleShowAutoConfigModal"
        >
          <div class="mr-2 mt-[-4px] h-[16px] w-[16px] bg-[url(@/assets/svgs/star.svg)] bg-[length:100%_100%]" />
          <span>AI自动配置</span>
        </div>
      </div>

      <div>
        <NPopover placement="bottom" trigger="click" style="width: 420px">
          <template #trigger>
            <div
              class="hover:border-theme-color flex cursor-pointer items-center justify-between rounded-md border border-[#d4d6d9] px-3 py-[7px]"
            >
              <img src="@/assets/images/lingjing-icon.png" class="mr-1 h-4 w-4" />
              <span class="line-clamp-1 max-w-[100px] text-xs text-[#5c5f66]">
                {{ personalAppConfig.commModelConfig.largeModel }}
              </span>
              <CustomIcon icon="mingcute:down-line" class="ml-1.5 text-base outline-none" />
            </div>
          </template>
          <div class="mb-2 mt-[6px] flex items-center">
            <span class="font-500 mr-3 text-sm text-[#151b26]">问答模型</span>
            <span class="rounded bg-[#f2f5f9] px-1 text-xs text-[#5c5f66]">用于总结生成回复结果</span>
          </div>
          <NSelect
            v-model:value="personalAppConfig.commModelConfig.largeModel"
            class="model-select"
            :options="modalListOptions"
          />

          <div class="mt-4 text-xs">
            <div class="mb-2.5 flex h-[34px] items-center justify-between">
              <div class="flex w-[105px] items-center">
                <span>多样性：</span>
                <NPopover trigger="hover">
                  <template #trigger>
                    <CustomIcon
                      icon="mingcute:question-line"
                      class="cursor-pointer text-base text-[#999] outline-none"
                    />
                  </template>
                  <span class="text-xs">
                    用于控制模型输出的多样性。推荐值为 0，数值越大，模型每次输出内容的差异性越大
                  </span>
                </NPopover>
              </div>

              <div class="mx-5 flex flex-1">
                <NSlider
                  v-model:value="personalAppConfig.commModelConfig.topP"
                  :default-value="0"
                  :step="0.01"
                  :min="0"
                  :max="1"
                />
                <span class="ml-4 w-[30px]">{{ personalAppConfig.commModelConfig.topP }}</span>
              </div>

              <NInputNumber
                v-model:value="personalAppConfig.commModelConfig.topP"
                placeholder=""
                :step="0.01"
                :min="0"
                :max="1"
                size="small"
                class="w-[90px]! text-xs!"
              />
            </div>

            <div class="mb-2.5 flex h-[34px] items-center justify-between">
              <div class="flex w-[105px] items-center">
                <span>参考对话轮数：</span>
                <NPopover trigger="hover">
                  <template #trigger>
                    <CustomIcon
                      icon="mingcute:question-line"
                      class="cursor-pointer text-base text-[#999] outline-none"
                    />
                  </template>
                  <span class="text-xs">
                    传入大模型上下文的最大对话轮数。推荐值为2，数值越大，多轮对话中上下文相关性越强，但Tokens消耗越多
                  </span>
                </NPopover>
              </div>

              <div class="mx-5 flex flex-1">
                <NSlider
                  v-model:value="personalAppConfig.commModelConfig.communicationTurn"
                  :default-value="3"
                  :step="1"
                  :min="0"
                  :max="100"
                />
                <span class="ml-4 w-[30px]">{{ personalAppConfig.commModelConfig.communicationTurn }}</span>
              </div>
              <NInputNumber
                v-model:value="personalAppConfig.commModelConfig.communicationTurn"
                :step="1"
                :min="0"
                :max="100"
                size="small"
                class="w-[90px]!"
                placeholder=""
              />
            </div>
          </div>
        </NPopover>
      </div>
    </div>

    <div class="flex h-[calc(100vh-56px-56px)]">
      <div class="flex h-full flex-1 flex-col overflow-auto border-r border-[#e8e9eb] py-4">
        <div class="mb-1 flex h-6 items-center px-5 leading-6">
          <CustomIcon icon="mdi:user" class="mr-1.5 text-lg" />
          <span>应用设定</span>
        </div>

        <NCollapse :default-expanded-names="['1']" class="px-5">
          <template #arrow>
            <CustomIcon icon="gravity-ui:caret-right" />
          </template>
          <NCollapseItem title="基本信息" name="1" class="my-[13px]!">
            <div class="justify-left flex items-start pl-5">
              <div class="relative mr-2 w-[72px]">
                <UploadPhoto
                  :file-arr="[personalAppConfig.baseInfo.agentAvatar]"
                  @after-upload="handleUploadAppAvatar"
                  @remove="handleRemoveAppAvatar"
                />

                <div
                  v-show="generateAgentAvatarLoading"
                  class="absolute left-0 top-0 z-10 flex h-[72px] w-[72px] cursor-not-allowed items-center justify-center rounded-xl bg-[#151b2680]"
                >
                  <CustomIcon icon="eos-icons:bubble-loading" class="text-xl text-white" />
                </div>

                <div
                  class="text-theme-color mt-3 flex h-[28px] items-center justify-between rounded-md border border-[#d4d6d9] px-2"
                  :class="
                    generateAgentAvatarLoading
                      ? 'cursor-not-allowed opacity-50'
                      : 'cursor-pointer hover:border-[#d4e5ff] hover:bg-[#e6f0ff]'
                  "
                  @click="handleAIGenerateAgentAvatar"
                >
                  <div class="mt-[-2px] h-[14px] w-[14px] bg-[url(@/assets/svgs/star.svg)] bg-[length:100%_100%]" />
                  <span class="text-xs">AI生成</span>
                </div>
              </div>
              <div class="flex flex-1">
                <NForm
                  ref="personalAppFormRef"
                  :model="personalAppConfig"
                  :rules="personalAppRules"
                  label-placement="left"
                  class="flex-1"
                >
                  <NFormItem feedback-class="p-0.5! text-xs!" path="baseInfo.agentTitle">
                    <NInput
                      v-model:value="personalAppConfig.baseInfo.agentTitle"
                      :maxlength="50"
                      show-count
                      placeholder="请输入应用名称"
                      class="h-[32px]! text-xs! rounded-md!"
                    />
                  </NFormItem>
                  <NFormItem feedback-style="display:none">
                    <NInput
                      v-model:value="personalAppConfig.baseInfo.agentDesc"
                      type="textarea"
                      :maxlength="100"
                      :rows="3"
                      show-count
                      placeholder="请描述你的应用，该描述将在应用发布后固定展示"
                      class="not-resize rounded-md! text-xs!"
                      size="small"
                    />
                  </NFormItem>
                </NForm>
              </div>
            </div>
          </NCollapseItem>
        </NCollapse>

        <div class="flex flex-1 flex-col border-t border-[#e8e9eb] px-5">
          <div class="my-[13px] flex items-center justify-between">
            <div class="flex items-center pl-6">
              <span class="select-none">角色指令</span>
              <NPopover style="width: 520px" trigger="hover">
                <template #trigger>
                  <CustomIcon
                    icon="mingcute:question-line"
                    class="ml-1 cursor-pointer text-base text-[#999] outline-none"
                  />
                </template>
                <span class="text-xs">
                  通过角色指令（Instruction）功能，你能够精确设定Agent应用的作用范围。包括指定应用将扮演的角色、能够使用的组件以及输出结果的格式与风格。此外，你还可以规定应用不得执行哪些操作等。
                </span>
              </NPopover>
            </div>

            <div class="flex items-center justify-center">
              <NPopover trigger="hover">
                <template #trigger>
                  <div
                    class="text-theme-color flex items-center border-r border-[#e8e9eb] pr-[9px]"
                    :class="
                      personalAppConfig.baseInfo.agentSystem
                        ? 'cursor-pointer hover:opacity-80'
                        : 'cursor-not-allowed opacity-50'
                    "
                    @click="handleShowOptimizeAgentSystemModal"
                  >
                    <div
                      class="mr-3 mt-[-2px] h-[16px] w-[16px] bg-[url(@/assets/svgs/star.svg)] bg-[length:100%_100%]"
                    />
                    <span class="text-xs">优化</span>
                  </div>
                </template>
                <p class="text-xs">AI优化</p>
              </NPopover>

              <NPopover style="width: 200px" content-style="padding: 10px 0;" trigger="hover">
                <template #trigger>
                  <div
                    class="text-theme-color flex cursor-pointer items-center pl-[9px] hover:opacity-80"
                    @click="handleSettingDefaultPrompt"
                  >
                    <CustomIcon icon="solar:book-2-broken" class="mr-3 text-base" />
                    <span class="text-xs">模板</span>
                  </div>
                </template>
                <p class="text-xs" style="white-space: pre-wrap">{{ defaultPrompt }}</p>
              </NPopover>
            </div>
          </div>

          <div class="flex flex-1 p-1 pl-6">
            <NInput
              ref="agentSystemInputRef"
              v-model:value="personalAppConfig.baseInfo.agentSystem"
              type="textarea"
              class="prompt-input not-resize text-xs! flex-1"
              :maxlength="1400"
              show-count
              placeholder="请输入希望角色完成的任务目标、具备的组件能力以及对输出答案的要求与限制等"
            />
          </div>
        </div>
      </div>

      <div class="h-full flex-1 overflow-auto border-r border-[#e8e9eb] py-4">
        <div class="flex h-6 items-center px-5 leading-6">
          <CustomIcon icon="streamline:decent-work-and-economic-growth-solid" class="mr-1.5 text-base" />
          <span>能力扩展</span>
        </div>

        <section class="border-b border-[#e8e9eb] px-5">
          <div class="pt-4">
            <h2 class="my-3 text-[#84868c]">知识</h2>
            <NCollapse :trigger-areas="['main', 'arrow']">
              <template #arrow>
                <CustomIcon icon="gravity-ui:caret-right" />
              </template>

              <NCollapseItem title="知识库" name="1" class="my-[13px]!">
                <span class="text-xs text-[#84868c]">
                  引用文本数据、表格型知识数据（含FAQ问答，多列索引问答）以及网页数据，实现知识库问答，应用最多可关联5个知识库，请详细填写知识库描述信息以提高问答准确率
                </span>
              </NCollapseItem>
            </NCollapse>
          </div>
        </section>

        <section class="border-b border-[#e8e9eb] px-5">
          <div class="pt-4">
            <h2 class="my-3 text-[#84868c]">对话</h2>
            <NCollapse
              :expanded-names="commConfigExpandedNames"
              :trigger-areas="['main', 'arrow']"
              @update:expanded-names="handleUpdateCommConfigExpandedNames"
            >
              <template #arrow>
                <CustomIcon icon="gravity-ui:caret-right" />
              </template>
              <NCollapseItem title="开场白" name="preamble" class="my-[13px]!">
                <template #header-extra>
                  <NTooltip trigger="hover">
                    <template #trigger>
                      <div
                        class="h-4 w-4 bg-[length:100%_100%]"
                        :class="
                          generatePreambleLoading
                            ? 'bg-[url(@/assets/images/loading.gif)]'
                            : 'bg-[url(@/assets/svgs/star.svg)]'
                        "
                        @click="handleAIGeneratePreamble"
                      />
                    </template>
                    AI生成
                  </NTooltip>
                </template>
                <NInput
                  v-model:value="personalAppConfig.commConfig.preamble"
                  type="textarea"
                  :rows="5"
                  :disabled="generatePreambleLoading"
                  class="text-xs! rounded-md!"
                  placeholder="请输入开场白"
                />
              </NCollapseItem>

              <NCollapseItem title="推荐问" name="featuredQuestions" class="my-[13px]!">
                <template #header-extra>
                  <NTooltip trigger="hover">
                    <template #trigger>
                      <div
                        class="h-4 w-4 bg-[length:100%_100%]"
                        :class="
                          generateFeaturedQuestionsLoading
                            ? 'bg-[url(@/assets/images/loading.gif)]'
                            : 'bg-[url(@/assets/svgs/star.svg)]'
                        "
                        @click="handleAIGenerateFeaturedQuestions"
                      />
                    </template>
                    AI生成
                  </NTooltip>
                </template>
                <NDynamicInput
                  v-model:value="personalAppConfig.commConfig.featuredQuestions"
                  placeholder="请输入推荐问"
                  class="rounded-md"
                  :min="1"
                  :max="3"
                  :disabled="generateFeaturedQuestionsLoading"
                />
              </NCollapseItem>

              <NCollapseItem name="continuousQuestion" class="my-[13px]!">
                <template #header>
                  <div class="flex items-center">
                    <span>追问</span>
                    <NPopover trigger="hover">
                      <template #trigger>
                        <CustomIcon
                          icon="mingcute:question-line"
                          class="ml-1 cursor-pointer text-base text-[#999] outline-none"
                        />
                      </template>
                      <span class="text-xs"> 大模型根据对话内容自动生成的追加问题 </span>
                    </NPopover>
                  </div>
                </template>

                <template #header-extra>
                  <NPopselect
                    v-model:value="personalAppConfig.commConfig.continuousQuestionStatus"
                    :options="questionSettingOptions"
                    trigger="click"
                    content-class="text-xs"
                  >
                    <div class="text-theme-color flex cursor-pointer items-center justify-between text-xs">
                      <span> {{ continuousQuestionStatusText }}</span>
                      <CustomIcon icon="mingcute:down-line" class="ml-1 text-base" />
                    </div>
                  </NPopselect>
                </template>

                <div>
                  <span
                    v-show="personalAppConfig.commConfig.continuousQuestionStatus === 'default'"
                    class="text-xs text-[#84868c]"
                  >
                    根据用户最近一轮对话，在回复后自动提供3个提问建议。
                  </span>

                  <span
                    v-show="personalAppConfig.commConfig.continuousQuestionStatus === 'close'"
                    class="text-xs text-[#84868c]"
                  >
                    在每轮回复后，不会提供用户任何提问建议
                  </span>
                </div>
              </NCollapseItem>
            </NCollapse>
          </div>
        </section>
      </div>
    </div>
  </div>

  <div
    v-show="isFullScreenLoading"
    class="z-999 fixed bottom-0 left-0 right-0 top-0 flex items-center justify-center bg-[#151b2680]"
  >
    <div class="flex h-14 w-[300px] items-center justify-between rounded-xl bg-white px-5">
      <div class="flex items-center">
        <div class="mr-2 h-4 w-4 bg-[url(@/assets/images/loading.gif)] bg-[length:100%_100%]" />
        <span class="text-theme-color">配置信息生成中...</span>
      </div>
      <div class="cursor-pointer text-[#5c5f66] hover:opacity-80" @click="handleStopGenerate">停止生成</div>
    </div>
  </div>

  <AutoConfigModal
    v-model:is-show-modal="isShowAutoConfigModal"
    :btn-loading="autoConfigBtnLoading"
    modal-title="AI生成配置信息"
    @comfirm="handleSettingAgent"
  />

  <OptimizeSystemModal
    v-model:is-show-modal="isShowOptimizeAgentSystemModal"
    :btn-loading="false"
    modal-title="角色指令优化"
    @comfirm="handleSettingAgentSystem"
  />
</template>

<style lang="scss" scoped>
:deep(.n-form-item-feedback-wrapper) {
  --n-feedback-height: 14px;
}

:deep(.not-resize .n-input-wrapper) {
  resize: none !important;
}

:deep(.prompt-input.n-input--textarea) {
  --n-border: none !important;
  --n-border-focus: none !important;
  --n-border-hover: none !important;
  --n-box-shadow-focus: none !important;
}

:deep(.prompt-input .n-input-wrapper) {
  padding: 0;
}

.model-select {
  :deep(.n-base-selection) {
    font-size: 12px;
    border-radius: 6px;
  }
}

:deep(.n-input__suffix),
:deep(.n-input-word-count) {
  font-size: 13px !important;
}

:deep(.prompt-input .n-input-word-count) {
  bottom: -10px !important;
  background: white !important;
}

:deep(.n-input--stateful) {
  --n-border-radius: 6px !important;

  font-size: 12px;
}

:deep(.n-upload-trigger.n-upload-trigger--image-card) {
  width: 70px;
  height: 70px;
  border-radius: 12px;
}

:deep(.n-upload-file-list .n-upload-file.n-upload-file--image-card-type) {
  width: 72px;
  height: 72px;
  border-radius: 12px;
}
</style>
