import { CloseOutlined, PlusOutlined } from "@ant-design/icons"
import { Button, Form, Input, message, Modal, Space, Spin, Tabs, Tooltip, Typography } from "antd"
import React, { useEffect, useState } from "react"
import { LABEL_TYPE_ENUM } from "../../const"
import style from './index.less'
import '../../index.less'
import { useAjax } from "@/Hook/useAjax"
import { getAdLabelApi } from "@/services/adqV3/global"
const { Text } = Typography;


interface Props {
    arrayProperty: { maxNumber: number, minNumber: number }
    putInType?: 'NOVEL' | 'GAME'
    value?: { content: string, type: LABEL_TYPE_ENUM }[]
    onChange?: (value?: { content: string, type: LABEL_TYPE_ENUM }[]) => void
}

/**
 * 选择标签
 * @returns 
 */
const SelectLabel: React.FC<Props> = ({ value, onChange, arrayProperty, putInType }) => {

    /************************************/
    const [visible, setVisible] = useState<boolean>(false)
    const [activeKey, setActiveKey] = useState<string>('1')
    const [oldValue, setOldValue] = useState<{ content: string, type: LABEL_TYPE_ENUM }[]>([])
    const [isFocus, setIsFocus] = useState<boolean>(false)
    const [customizetext, setCustomizetext] = useState<string>()

    const getAdLabel = useAjax((params) => getAdLabelApi(params))
    /************************************/

    useEffect(() => {
        if (visible && value) {
            setOldValue(value)
        }
    }, [visible, value])

    useEffect(() => {
        if (visible) {
            getAdLabel.run({ taskType: putInType })
        }
    }, [visible, putInType])

    const handleOk = () => {
        onChange?.(oldValue)
        setVisible(false)
    }

    return <>
        {(value && value?.length > 0) ? <div className={style.toggleLabels}>
            {value?.map((item, tIndex) => <div
                key={tIndex}
                className={`${style.toggleLabel} ${style.showLabel}}`}
            >
                <Space>
                    <span>{item.content}</span>
                    <CloseOutlined className={style.clearLable} onClick={() => onChange?.(value.filter((_, index) => tIndex !== index))} />
                </Space>
            </div>)}
            <a onClick={() => setVisible(true)}>修改</a>
        </div> : <a className={style.selectLabelBtn} onClick={() => setVisible(true)}><PlusOutlined /><span>选择标签</span></a>}
        {visible && <Modal
            title={<strong>选择标签</strong>}
            open={visible}
            className="modalResetCss"
            width={900}
            onCancel={() => setVisible(false)}
            bodyStyle={{ padding: '0px 32px' }}
            footer={<div className={style.showLabel}>
                <div style={{ textAlign: 'left' }}>
                    <Tooltip
                        title={`${(oldValue?.length || 0) > arrayProperty.maxNumber ? `最多可选 ${arrayProperty.maxNumber} 个标签` : ''}，${oldValue.reduce((pre: number, cur) => pre + cur.content.length, 0) > 16 ? '标签总字数上限不超过 16 个字，中英文均算 1 个字' : ''}`}
                        open={((oldValue?.length || 0) > arrayProperty.maxNumber || oldValue.reduce((pre: number, cur) => pre + cur.content.length, 0) > 16)}
                    >
                        <Text strong>文字标签 ({oldValue?.length || 0}/{arrayProperty.maxNumber})</Text>
                    </Tooltip>
                    <div className={style.toggleLabels}>
                        {oldValue?.map((item, tIndex) => <div
                            key={tIndex}
                            className={`${style.toggleLabel} ${style.showLabel} ${((oldValue?.length || 0) > arrayProperty.maxNumber || oldValue.reduce((pre: number, cur) => pre + cur.content.length, 0) > 16) ? style.errorSHowLabel : ''}`}
                        >
                            <Space>
                                <span>{item.content}</span>
                                <CloseOutlined className={style.clearLable} onClick={() => setOldValue(oldValue.filter((_, index) => tIndex !== index))} />
                            </Space>
                        </div>)}
                    </div>
                </div>
                <Space>
                    <Button onClick={() => setVisible(false)}>取消</Button>
                    <Button type="primary" onClick={handleOk}>确定</Button>
                </Space>
            </div>}
        >
            <Tabs
                accessKey={activeKey}
                onChange={(e) => setActiveKey(e)}
                tabBarExtraContent={<Text type="secondary" style={{ fontSize: 12 }}>最多可选 {arrayProperty.maxNumber} 个标签，且标签总字数上限不超过 16 个字，中英文均算 1 个字</Text>}
                items={[
                    {
                        label: '选择已有', key: '1', children: <Spin spinning={getAdLabel.loading}>
                            <div className={style.labelContent}>
                                <div className={style.tips}>
                                    <strong>行业通用</strong>
                                </div>
                                <Form
                                    name="basicSelectLabel"
                                    labelCol={{ span: 3 }}
                                    wrapperCol={{ span: 21 }}
                                    labelAlign="left"
                                    colon={false}
                                >
                                    {getAdLabel.data?.map((item: { labelCategory: string, label: string[], labelTypeName: string }, index: number) => <Form.Item className={style.toggleLabelForm} label={<strong>{item.labelCategory}</strong>} key={index}>
                                        <div className={style.toggleLabels}>
                                            {item.label.map((text, tIndex) => {
                                                let activeIndex = oldValue?.findIndex(i => i.content === text)
                                                return <div
                                                    key={tIndex}
                                                    className={`${style.toggleLabel} ${(activeIndex !== -1) ? style.active : ''}`}
                                                    onClick={() => {
                                                        let newValue: { content: string, type: LABEL_TYPE_ENUM }[] = JSON.parse(JSON.stringify(oldValue))
                                                        if (activeIndex !== -1) {
                                                            newValue = newValue.filter((_, index) => activeIndex !== index)
                                                        } else {
                                                            newValue.push({ content: text, type: (item.labelTypeName === '普通文本标签' ? 'LABEL_TYPE_COMMON' : 'LABEL_TYPE_UNKNOWN') as LABEL_TYPE_ENUM })
                                                        }
                                                        setOldValue(newValue)
                                                    }}
                                                >{text}</div>
                                            })}
                                        </div>
                                    </Form.Item>)}
                                </Form>
                            </div>
                        </Spin>
                    },
                    {
                        label: '新建标签', key: '2', children: <div className={style.spauiInputGroup} style={{ borderColor: isFocus ? '#296bef' : '#dfe1e6' }}>
                            {oldValue?.filter(item => item.type === 'LABEL_TYPE_CUSTOMIZETEXT' as LABEL_TYPE_ENUM)?.map((item, tIndex) => <div
                                key={tIndex}
                                className={`${style.toggleLabel} ${style.customizeLabel}`}
                            >
                                <Space>
                                    <span>{item.content}</span>
                                    <CloseOutlined className={style.clearLable} onClick={() => setOldValue(oldValue.filter((_, index) => tIndex !== index))} />
                                </Space>
                            </div>)}
                            <div className={style.divInput}>
                                <Input
                                    placeholder="请输入自定义标签文案，按回车键生成标签，单标签 2-7 字"
                                    bordered={false}
                                    onFocus={() => setIsFocus(true)}
                                    onBlur={() => setIsFocus(false)}
                                    value={customizetext}
                                    maxLength={7}
                                    minLength={2}
                                    onChange={(e) => setCustomizetext(e.target.value)}
                                    onPressEnter={() => {
                                        if (customizetext) {
                                            if (oldValue.some(item => item.content === customizetext)) {
                                                message.error('存在相同名称标签')
                                                return
                                            }
                                            let yyLables = getAdLabel?.data?.reduce((pre: any, cur: { label: any }) => [...pre, ...(cur.label || [])], [])
                                            if (yyLables.some((item: string) => item === customizetext)) {
                                                message.warn(`标签【${customizetext}】为已有标签，已为您自动选择`)
                                                return
                                            }
                                            let newValue: { content: string, type: LABEL_TYPE_ENUM }[] = JSON.parse(JSON.stringify(oldValue))
                                            newValue.push({ content: customizetext, type: 'LABEL_TYPE_CUSTOMIZETEXT' as LABEL_TYPE_ENUM })
                                            setOldValue(newValue)
                                            setCustomizetext(undefined)
                                        } else {
                                            message.error('请填写内容')
                                        }
                                    }}
                                />
                            </div>
                        </div>
                    }
                ]}
            />
        </Modal>}
    </>
}

export default React.memo(SelectLabel)