import { useAjax } from "@/Hook/useAjax";
import useNewToken from "@/Hook/useNewToken";
import { useDebounce, useUpdateEffect } from "ahooks";
import { App, Card, Select, Space, Typography } from "antd";
import React, { useEffect, useState } from "react"
import { addMedaiTagApi, getMedaiTagListApi } from "../../API/weMaterial/weMaterial";
import style from './index.less'
import { CloseCircleOutlined } from '@ant-design/icons';


export interface TagProps {
    tagName: string,
    tagId: number
}
interface Props {
    value?: TagProps[]
    onChange?: (value?: TagProps[]) => void
}

const InputTag: React.FC<Props> = ({ value, onChange }) => {

    /**************************************/
    const { message } = App.useApp()
    const { token } = useNewToken()
    const [searchValue, setSearchValue] = useState<string>('') // 控制搜索文本
    const debouncedValue = useDebounce(searchValue, { wait: 500 });
    const [tag, setTag] = useState<string>()
    const [isHovering, setIsHovering] = useState<number>(-1)
    const [tagValue, setTagValue] = useState<TagProps[]>([])

    const addMedaiTag = useAjax((params) => addMedaiTagApi(params))
    const getMedaiTagList = useAjax((params) => getMedaiTagListApi(params))
    /**************************************/

    useEffect(() => {
        if (tag) {
            setTimeout(() => {
                let newTagValue = JSON.parse(JSON.stringify(tagValue))
                let [tagName, tagId] = tag.split('_')
                newTagValue.push({ tagName, tagId })
                setTagValue(newTagValue)
                setTag(undefined)
                onChange?.(newTagValue)
            }, 200)
        }
    }, [tag])

    useEffect(() => {
        setTagValue(value || [])
    }, [value])

    useUpdateEffect(() => {
        getMedaiTagList.run({ tagName: debouncedValue })
    }, [debouncedValue])

    /** 标签搜索 */
    const handleSearch = (value: any) => {
        setSearchValue(value)
    }
    return <>
        <Space direction="vertical" style={{ width: '100%' }}>
            <Select
                allowClear
                showSearch
                placeholder='新建或搜索标签，回车键确认'
                value={tag}
                onChange={(e) => { setTag(e) }}
                filterOption={false}
                onSearch={handleSearch}
                searchValue={searchValue}
                loading={addMedaiTag.loading || getMedaiTagList.loading}
                notFoundContent={null}
                options={getMedaiTagList?.data?.data
                    ?.filter((item: TagProps) => !tagValue.some(item1 => item.tagId == item1.tagId))
                    ?.map((item: { tagName: string, tagId: number }) => ({ value: item.tagName + '_' + item.tagId, label: item.tagName }))}
                onInputKeyDown={(e: any) => {
                    if (e.code === "NumpadEnter" || e.code === "Enter") { // 按键endter
                        if (e?.target?.value && !getMedaiTagList?.data?.data?.some((item: { tagName: string, tagId: number }) => item.tagName === e?.target?.value)) {
                            const hide = message.loading('新增中..', 0)
                            addMedaiTag.run({ tagName: e?.target?.value }).then(res => {
                                if (res) {
                                    message.success('新增成功')
                                    getMedaiTagList.refresh()
                                    hide()
                                }
                                hide()
                            }).catch(() => hide())
                        }
                    }
                }}
            />
            {tagValue.length > 0 && <Card>
                <div className={style.flexStartWrap} style={{ gap: 10 }}>
                    {tagValue?.map((item: TagProps) => <div
                        onMouseOver={() => { setIsHovering(item.tagId) }}
                        onMouseOut={() => { setIsHovering(-1) }}
                        key={item.tagId}
                        className={style.selectTag}
                        style={{
                            height: token.controlHeight,
                            border: `1px solid ${isHovering === item.tagId ? token.colorPrimaryBorderHover : token.colorBorder}`,
                            borderRadius: token.borderRadius,
                            padding: token.padding,
                            backgroundColor: token.colorBgContainer,
                            color: token.colorTextPlaceholder,
                            boxSizing: 'border-box',
                            width: 'auto',
                            minWidth: 'auto',
                            gap: 5
                        }}
                    >
                        <Typography.Paragraph strong style={{ margin: 0 }}>{item.tagName}</Typography.Paragraph>
                        <CloseCircleOutlined onClick={() => { setTagValue(tagValue.filter(item1 => item1.tagId !== item.tagId)) }} style={{ color: `${isHovering === item.tagId ? token.colorPrimaryBorderHover : token.colorBorder}`, cursor: 'pointer' }} />
                    </div>)}
                </div>
            </Card>}
        </Space>
    </>
}


export default React.memo(InputTag)