<!--
  - Copyright (c) 2024 LangChat. TyCoding All Rights Reserved.
  -
  - Licensed under the GNU Affero General Public License, Version 3 (the "License");
  - you may not use this file except in compliance with the License.
  - You may obtain a copy of the License at
  -
  -     https://www.gnu.org/licenses/agpl-3.0.html
  -
  - Unless required by applicable law or agreed to in writing, software
  - distributed under the License is distributed on an "AS IS" BASIS,
  - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  - See the License for the specific language governing permissions and
  - limitations under the License.
  -->

<script lang="ts" setup>
import { onMounted, ref, toRaw } from 'vue'
import { ModelApi } from '@/api/new-ai/model'
import { LLMProviders } from '@/views/ai/model/chatModel/composables/consts'
import { ModelTypeEnum } from '@/api/models'
import { useChatStore } from '@/views/ai/chat/new-chat/store/useChatStore'

const chatStore = useChatStore()
const props = defineProps<{
  id: any
  size?: 'large' | 'default' | 'small'
}>()
const size = props.size || 'default'
const emit = defineEmits(['update', 'load'])
const options = ref([])
const modelId = ref('')

onMounted(async () => {
  const providers = await ModelApi.getModelList({ type: ModelTypeEnum.CHAT })
  if (chatStore.modelId === '' || chatStore.modelId === null) {
    if (providers != null && providers.length != 0) {
      const item = providers[0]
      chatStore.modelId = item.id
      chatStore.modelName = item.model
      chatStore.modelProvider = item.provider

      if (props.id == null) {
        modelId.value = item.id
        emit('load', item)
      } else {
        modelId.value = props.id
      }
    }
  }
  const data: any = []
  LLMProviders.forEach((i) => {
    const children = providers.filter((m) => m.provider == i.model)
    if (children.length === 0) {
      return
    }
    data.push({
      label: i.name,
      value: i.id,
      children: children.map(child => ({
        label: child.name,
        value: child.id,
        raw: child
      }))
    })
  })
  options.value = data
  modelId.value = chatStore.modelId
})

function onUpdate(val: any) {
  const group = options.value.find(g => g.children.some(c => c.value === val))
  if (!group) return
  
  const option = group.children.find(c => c.value === val)
  if (!option) return

  const obj = option.raw
  emit('update', {
    id: obj.id,
    modelName: obj.model,
    modelProvider: obj.provider,
  })
  chatStore.modelId = obj.id
  chatStore.modelName = obj.model
  chatStore.modelProvider = obj.provider
}
</script>

<template>
  <el-cascader
    v-model="modelId"
    :options="options"
    :size="size"
    :props="{
      expandTrigger: 'hover'
    }"
    placeholder="请选择关联模型"
    @change="onUpdate"
  />
</template>

<style lang="scss" scoped>
:deep(.el-cascader) {
  width: 100%;
}
</style>
