import styles from './style.module.css'
import { useEffect, useContext, useState } from 'react'
import { getTags } from '@/pages/api/base'
import { ItagsRes } from '@/pages/api/base/type'
import CustomTag from '@/components/CustomTag'
import AppContext from '@/components/hooks/createContext'
import { ItabsRes } from '@/pages/api/base/type'

interface IProps {
    agentName: string | null
}

const Tags = ({ agentName }: IProps) => {
    const {
        taskId: [taskId],
        taskResult: [taskResult],
        handleTaskResult,
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
    } = useContext(AppContext)!

    const [tagList, setTagList] = useState<ItabsRes[]>([])

    useEffect(() => {
        const getTaglist = async () => {
            if (!taskId) return
            const value =
                (await getTags({ agentName, agentVersion: taskResult?.agentVersion })) || []
            const list = value.map((item: ItagsRes) => {
                return { key: item.id, value: item.name }
            })
            setTagList(list)
        }
        getTaglist()
    }, [agentName, taskResult?.agentVersion])

    // 多选tags
    const changeTags = (value: number) => {
        const tagIds = taskResult.tagIds || []
        if (tagIds?.includes(value)) {
            const index = tagIds.indexOf(value)
            tagIds?.splice(index, 1)
        } else {
            tagIds?.push(value)
        }
        handleTaskResult('tagIds', tagIds)
    }
    return (
        <div className={styles.tagList}>
            {tagList.length ? (
                <CustomTag
                    value={taskResult.tagIds || []}
                    options={tagList}
                    onChange={(value) => {
                        changeTags(value)
                    }}
                ></CustomTag>
            ) : null}
        </div>
    )
}
export default Tags
