import useNewToken from "@/Hook/useNewToken"
import { Button, Empty, Input, Popover, Space, Spin, Typography } from "antd"
import React, { useEffect, useRef, useState } from "react"
import style from './index.less'
import { DownOutlined, SearchOutlined, SettingOutlined, CloseCircleOutlined } from '@ant-design/icons';
import { useDebounce, useHover, useUpdateEffect } from "ahooks";
import { getMedaiTagListApi, GetMedaiTagListProps } from "../../API/weMaterial/weMaterial";
import { useAjax } from "@/Hook/useAjax";
import ManageTag from "./manageTag";

interface QueryProps {
    tagName: string,
    tagId: number
}

interface Props {
    value?: number
    onChange?: (value?: any) => void
    isPopup?: boolean
}
/**
 * 选择标签
 * @returns 
 */
const SelectTag: React.FC<Props> = ({ value, onChange, isPopup = true }) => {

    /*************************/
    const { token } = useNewToken()
    const ref = useRef(null);
    const isHovering = useHover(ref)
    const [open, setOpen] = useState<boolean>(false)
    const [visible, setVisible] = useState<boolean>(false)
    const [isHovering1, setIsHovering1] = useState<boolean>(false)
    const [queryForm, setQueryForm] = useState<GetMedaiTagListProps>({})
    const [searchValue, setSearchValue] = useState<string>('') // 控制搜索文本
    const debouncedValue = useDebounce(searchValue, { wait: 500 });
    const [selectQuery, setSelectQuery] = useState<QueryProps>()

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

    useEffect(() => {
        if (value && getMedaiTagList?.data?.data) {
            setSelectQuery(getMedaiTagList.data.data.find((item: QueryProps) => Number(item.tagId) === Number(value)))
        }
    }, [value, getMedaiTagList?.data?.data])

    useUpdateEffect(() => {
        setQueryForm({ ...queryForm, tagName: debouncedValue })
    }, [debouncedValue])

    useEffect(() => {
        getMedaiTagList.run(queryForm)
    }, [queryForm])

    const xzTag = (value?: { tagName: string, tagId: number }) => {
        setSelectQuery(value)
        onChange?.(value?.tagId)
    }

    return <div>
        <Popover
            zIndex={1000}
            placement="bottomRight"
            arrow={false}
            open={visible}
            onOpenChange={(e) => { setVisible(e) }}
            styles={{ body: { maxWidth: 450, width: 450, minHeight: 86 } }}
            content={
                <div className={style.selectTagDow} onMouseOver={() => { setIsHovering1(true) }} onMouseOut={() => { setIsHovering1(false) }} onClick={(e) => { e.stopPropagation() }}>
                    <div className={style.selectTagDow_head}>
                        <Typography.Paragraph strong style={{ margin: 0 }}><span>选择标签（{getMedaiTagList?.data?.data?.length}）</span></Typography.Paragraph>
                        <Space align="center">
                            <Input suffix={<SearchOutlined />} placeholder="搜索标签" value={searchValue} onChange={(e) => setSearchValue(e.target.value)} />
                            {isPopup && <Button style={{ padding: '0 5px' }} type="text" onClick={() => setOpen(true)}><SettingOutlined /></Button>}
                        </Space>
                    </div>
                    <Spin spinning={getMedaiTagList.loading}>
                        {getMedaiTagList?.data?.data?.length > 0 ? <Space wrap>
                            {getMedaiTagList?.data?.data?.map((item: QueryProps) => <Button key={item.tagId} onClick={() => xzTag({ tagName: item.tagName, tagId: item.tagId })}>{item.tagName}</Button>)}
                        </Space> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description='暂无标签' />}

                    </Spin>
                </div>
            }
            trigger={['click']}
            color={token.colorBgElevated}
        >
            <div
                ref={ref}
                className={style.selectTag}
                style={{
                    height: token.controlHeight,
                    border: `1px solid ${(isHovering || isHovering1) ? token.colorPrimaryBorderHover : token.colorBorder}`,
                    borderRadius: token.borderRadius,
                    padding: token.padding,
                    backgroundColor: token.colorBgContainer,
                    color: token.colorTextPlaceholder,
                    boxSizing: 'border-box'
                }}
            >
                {selectQuery && Object.keys(selectQuery).length > 0 ? <>
                    <Typography.Paragraph style={{ margin: 0 }}>{selectQuery.tagName}</Typography.Paragraph>
                    <Typography.Paragraph style={{ margin: 0, cursor: 'pointer' }} onClick={() => xzTag()}><CloseCircleOutlined /></Typography.Paragraph>
                </> : <>
                    <span>点击选择标签</span>
                    <DownOutlined />
                </>}

            </div>
        </Popover>
        {/* 标签管理 */}
        {open && <ManageTag onClose={() => setOpen(false)} onChange={() => { getMedaiTagList.refresh() }} visible={open} />}
    </div>
}

export default React.memo(SelectTag)