import { useAjax } from "@/Hook/useAjax"
import { txtLength } from "@/utils/utils";
import { Input, List, Popover } from "antd";
import React, { useEffect } from "react"
import { useState } from "react";
import './index.less'
import { getTextApi } from "@/services/adqV3/global";


interface Props {
    value?: any,
    onChange?: (value: any) => void;
    style?: React.CSSProperties;
    placeholder?: string;
    maxTextLength?: number;
    isShowAjax?: boolean
}

/**
 * 文案助手输入框
 * @param props 
 * @returns 
 */
const TextAideInput: React.FC<Props> = (props) => {

    /************************/
    const { value, onChange, style, placeholder, maxTextLength = 10, isShowAjax = true } = props
    const [text, setText] = useState<any>(value)
    const [descriptionShow, setDescriptionshow] = useState(false)

    const getTextLsit = useAjax((params) => getTextApi(params))
    /************************/

    useEffect(() => {
        setText(value)
    }, [value])

    // 文案助手
    const textList = (keyword?: any) => {
        getTextLsit.run({ keyword, maxTextLength })
    }

    return <div style={{ display: 'inline-flex', alignItems: 'center', columnGap: 5 }}>
        <Popover
            placement="topLeft"
            overlayClassName="textAideInputPopover"
            style={{ minWidth: 600 }}
            visible={descriptionShow}
            content={<List
                loading={getTextLsit?.loading}
                size="small"
                style={{ maxHeight: 300, overflowX: 'auto', minWidth: 600 }}
                dataSource={getTextLsit?.data?.returnTexts}
                renderItem={(item: any) => <List.Item onClick={() => {
                    setText(item.text)
                    onChange && onChange(item.text)
                    setTimeout(() => { setDescriptionshow(false) }, 50)
                }}><span >{item.text}{item.tag && <span className="crt">{'CTR 高'}</span>}</span></List.Item>}
            />}
        >
            <Input
                placeholder={placeholder}
                style={style}
                value={text}
                onFocus={() => {
                    if (isShowAjax) {
                        setDescriptionshow(true)
                        textList(value)
                    } 
                }}
                onBlur={() => {
                    setTimeout(() => { setDescriptionshow(false) }, 500)
                }}
                onChange={(e) => {
                    let value = e.target.value
                    setText(value)
                    if (isShowAjax) {
                        textList(value)
                    }
                    onChange && onChange(value)
                }}
                allowClear
            />
        </Popover>
        <span>{`${txtLength(text)}/${maxTextLength}`}</span>
    </div>
}


export default React.memo(TextAideInput)