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


interface Props {
    value?: any,
    onChange?: (value: any) => void,
    style?: React.CSSProperties,
    placeholder?: string;
    maxTextLength?: number
}
/**
 * 带文案助手输入框
 * @returns 
 */
const TextAideInput: React.FC<Props> = (props) => {

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

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

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

    return <div className="textAideInput">
        <Space>
            <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={(e: any) => {
                            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={() => {
                        setDescriptionshow(true)
                        textList(value)
                    }}
                    onBlur={() => {
                        setTimeout(() => { setDescriptionshow(false) }, 500)
                    }}
                    onChange={(e) => {
                        let value = e.target.value
                        setText(value)
                        textList(value)
                        onChange && onChange(value)
                    }}
                    allowClear
                />
            </Popover>

            <span>{`${txtLength(text)}/${maxTextLength}`}</span>
        </Space>
    </div>
}


export default React.memo(TextAideInput)