import type {NodeProps} from '@xyflow/react'
import React, {useCallback, useEffect} from 'react'
import {commonInfo} from '../../../util/amis.tsx'
import {useContextStore} from '../store/ContextStore.ts'
import {useDataStore} from '../store/DataStore.ts'
import {useFlowStore} from '../store/FlowStore.ts'
import AmisNode, {inputsFormColumns, NormalNodeHandler, outputsFormColumns} from './AmisNode.tsx'

const KnowledgeNode = (props: NodeProps) => {
  const {getNodes, getEdges} = useFlowStore()
  const {getData, mergeDataById} = useDataStore()
  const {getInputSchema} = useContextStore()

  useEffect(() => {
    mergeDataById(
      props.id,
      {
        outputs: {
          result: {
            type: 'array-string',
          },
        },
      },
    )
  }, [props.id])

  const columnsSchema = useCallback(() => [
    ...inputsFormColumns(props.id, getInputSchema(), getNodes(), getEdges(), getData()),
    {
      type: 'divider',
    },
    {
      type: 'select',
      name: 'knowledgeId',
      label: '知识库',
      required: true,
      options: [],
      source: {
        method: 'get',
        url: `${commonInfo.baseAiUrl}/knowledge/list`,
        // @ts-ignore
        adaptor: (payload, response, api, context) => {
          return {
            ...payload,
            data: {
              items: payload.data.items.map((item: any) => ({value: item['id'], label: item['name']})),
            },
          }
        },
      },
    },
    {
      type: 'input-text',
      name: 'query',
      label: '查询文本',
      required: true,
    },
    {
      type: 'input-range',
      name: 'count',
      label: '返回数量',
      required: true,
      value: 3,
      max: 10,
    },
    {
      type: 'input-range',
      name: 'score',
      label: '匹配阀值',
      required: true,
      value: 0.6,
      max: 1,
      step: 0.05,
    },
    {
      type: 'divider',
    },
    ...outputsFormColumns(false, true),
  ], [props.id])
  return (
    <AmisNode
      nodeProps={props}
      columnSchema={columnsSchema}
      handler={<NormalNodeHandler/>}
    />
  )
}

export default React.memo(KnowledgeNode)