import { Button, Card, Drawer, Input, Modal, Space, Spin, Tag } from 'antd'
import React, {  useCallback, useEffect, useMemo, useState } from 'react'
import style from './index.less'
import './index.less'
import Checkbox from 'antd/lib/checkbox/Checkbox';
import { useModel } from 'umi';
const { CheckableTag } = Tag;

/**标签管理*/
function TagManage() {
    const [selectedTags, setSelectedTags] = useState<{createTime: string, id: number, label: string, updateTime: string}[]>([])
    const [visible, setVisible] = useState<boolean>(false)
    const [inputKey, setInputKey] = useState<string>('')
    const [inputValue, setInputValue] = useState<string>('')

    const [addVisible, setAddVisible] = useState<boolean>(false)  // 新增标签
    const [query, setQuery] = useState<{label: string, id?: number}>({label: ''})  // 新增修改参数

    const [tagsData, setTagsData] = useState<{createTime: string, id: number, label: string, updateTime: string}[]>([])  // tages 列表

    const { labelAdd, LabelEdit, getLabels, delLabel } = useModel('useLaunch.useMaterial')

    useEffect(() => {
        getLabels.run({pageNum: 1, pageSize: 200}).then(res => {
            setTagsData(res?.records)
        })
    }, [])

    const getList = () => {
        setSelectedTags([])
        getLabels?.refresh().then(res => {
            setTagsData(res?.records)
        })
    }

    /**单选选中取消*/
    const handleChange = useCallback((tag: any, checked: boolean) => {
        let nextSelectedTags = checked ? [...selectedTags, tag] : selectedTags.filter(t => t !== tag);
        setSelectedTags(nextSelectedTags)
    }, [selectedTags])
    /**随机色 */
    const colors = useMemo(() => {
        return tagsData?.map((tag) => {
            let c1 = Math.floor(Math.random() * 210) + 1
            let c2 = Math.floor(Math.random() * 210) + 1
            let c3 = Math.floor(Math.random() * 210) + 1
            return `rgba(${c1},${c2},${c3},1)`
        })
    }, [tagsData])
    /**全选/反选 */
    const all = useCallback(() => {
        let newSelectedTags = tagsData?.filter((key) => selectedTags?.every(a => a !== key))
        setSelectedTags(newSelectedTags)
    }, [selectedTags, tagsData])
    /**删除*/
    const del = useCallback(() => {
        delLabel.run({id: selectedTags[0]?.id}).then(res => {
            getList()
            setSelectedTags([])
            setVisible(false)
        })
    }, [selectedTags])
    /**编辑 */
    const edit = useCallback((val: string) => {
        console.log('编辑', val)
        setInputValue('')
        setInputKey('')
    }, [])
    /** 新增标签 确定 */
    const handleOk = useCallback(()=> {
        if(selectedTags.length === 1) { // 修改
            console.log(query);
            let {id, label} = query
            LabelEdit.run({id, label}).then(res => {
                getList()
                setAddVisible(false)
                setQuery({label: ''})
            })
        }else{ // 新增
            labelAdd.run(query).then(res => {
                getList()
                setAddVisible(false)
                setQuery({label: ''})
            })
        }
    }, [selectedTags, query])
    /** 新增按钮 */
    const AddModal = useCallback(()=> {
        setQuery({label: ''})
        setAddVisible(true)
        if(selectedTags.length > 0) {
            setQuery(selectedTags[0])
        }
    }, [addVisible, query, selectedTags])
    /** 输入标签 */
    const labelChange = useCallback((e: any)=>{
        setQuery({...query, label: e.target?.value})
    },[query])
    return <Card
        title='标签管理'

    >
        <div className='tag_manage action' style={{ height: 'calc(100vh - 200px)' }}>
            <div className={style.header}>
                <Space>
                    <Button size='small' type='dashed' onClick={AddModal} disabled={selectedTags.length > 1}>{selectedTags.length > 0 ? '修改' : '新增'}</Button>
                    <Button size='small' type='dashed' onClick={all}>全选/反选</Button>
                    {
                        selectedTags.length > 0 && <Button size='small' type='dashed' onClick={() => { setSelectedTags([]) }}>清空</Button>
                    }
                    {
                        selectedTags.length === 1 && <Button size='small' type='dashed' danger onClick={() => { setVisible(true) }}>删除</Button>
                    }
                </Space>
            </div>
            {
                getLabels?.loading ? <div className={style.example}>
                    <Spin />
                </div> :
                tagsData?.map((tag: {createTime: string, id: number, label: string, updateTime: string}, index: number) => {
                    return < CheckableTag
                        key={tag.id}
                        checked={selectedTags.indexOf(tag) > -1}
                        // onChange={checked => { handleChange(tag, checked) }}//handleChange(tag, checked)
                    >
                        {
                            inputKey === tag.label ?
                                <Input.Search
                                    enterButton="Ok"
                                    size='small'
                                    style={{ width: 100 }}
                                    value={inputValue}
                                    loading={false}
                                    onChange={(e) => { setInputValue(e.target.value) }}
                                    onSearch={(value, e) => { e?.stopPropagation(); edit(value) }}
                                />
                                :
                                <Checkbox checked={selectedTags.indexOf(tag) > -1} onChange={() => { handleChange(tag, !(selectedTags.indexOf(tag) > -1)) }}>
                                    <span
                                        style={{ color: `${colors[index]}`, display: 'inline-block' }}
                                        className={style.tag}
                                    >
                                        {tag.label}
                                    </span>
                                </Checkbox>
                        }
                        {/* {
                            selectedTags.indexOf(tag) > -1 && inputKey !== tag && <div className={style.cz}>
                                <Space>
                                    <Popconfirm title={<span>确定要删除<b style={{ color: `${colors[index]}` }}>{tag}</b>标签吗?</span>} onConfirm={(e) => { e?.stopPropagation() }}>
                                        <DeleteOutlined onClick={(e) => { e.stopPropagation() }} />
                                    </Popconfirm>
                                    <EditOutlined onClick={(e) => { e.stopPropagation(); setInputKey(tag); setInputValue(tag) }} />
                                </Space>
                            </div>
                        } */}
                        {/* <span style={{ background: `${colors[index]}`, display: 'inline-block' }} className={style.tag}>{tag}</span> */}
                    </CheckableTag>
                })
            }
            <Drawer
                title="当前选中的标签"
                placement='top'
                closable={true}
                onClose={() => { setVisible(false) }}
                visible={visible}
                footer={<div style={{ display: 'flex', justifyContent: 'center' }}>
                    <Space>
                        <Button onClick={() => { setVisible(false) }}>取消</Button>
                        <Button onClick={del} type='primary' loading={delLabel?.loading}>确定</Button>
                    </Space>
                </div>}
            >
                <div className='tag_manage'>
                    {selectedTags.map((tag: {createTime: string, id: number, label: string, updateTime: string}, index: number) => {
                        return < CheckableTag
                            key={tag.id}
                            checked={selectedTags.indexOf(tag) > -1}
                            onChange={checked => { handleChange(tag, checked) }}//handleChange(tag, checked)
                        >
                            {/* <span style={{ background: `${colors[index]}`, display: 'inline-block' }} className={style.tag}>{tag}</span> */}
                            <span style={{ color: `${colors[index]}`, display: 'inline-block' }} className={style.tag}>{tag.label}</span>
                        </CheckableTag>
                    })
                    }
                </div>
            </Drawer>
        </div>
        
        {addVisible && <Modal visible={addVisible} title={`${selectedTags.length > 0 ? '修改' : '新增'}标签`} onCancel={()=>{setAddVisible(false)}} footer={
            <>
                <Space>
                    <Button onClick={()=>{setAddVisible(false)}}>取消</Button>
                    <Button type="primary" onClick={handleOk} loading={labelAdd?.loading || LabelEdit?.loading}>确定</Button>
                </Space>
            </>
        }>
            <Input placeholder="输入标签" value={query.label} onChange={labelChange}/>
        </Modal>}
    </Card >
}
export default TagManage
