import { PlusOutlined } from '@ant-design/icons';
import { Tag, Input, Tooltip } from 'antd';

import { useEffect, useRef, useState } from 'react';
import { useRequest } from 'umi';
import { queryTagList, saveTag,deleteTag } from '../service';
import styles from '../style.less';
//const { Paragraph } = Typography;
/*
const tags = [
  {tag_id: 1, tag_name: 'Tag1'},
  {tag_id: 2, tag_name: 'Tag2'}
];*/

const Tags = () => {
  const [inputVisible, setInputVisible] = useState<boolean>(false);
  const [items, setItems] = useState([]);
  const [count, setCount] = useState(0);
  const inputRef = useRef<any>();;

  /** 显示输入框 */
  const showInput = async () => {
    await setInputVisible(true)
    console.log('inputRef', inputRef)
    inputRef.current.focus({
      cursor: 'start',
    });
  }

  /** 获取标签数据 */
  const { data } = useRequest(queryTagList);

  useEffect(() => {
    setItems(data || []);
    console.log('tags', data)
  }, [ data, count]);

  // 添加标签
  const handleInputConfirm = async (e: any) => {
    console.log(items)

    const res = await saveTag({ tag_name: e.target.value })
    const { data: tags } = await queryTagList({})
    setItems(tags)
    setInputVisible(false)
  }


  return (
    <div className={styles.tags}>
      {items.map((tag: any, index: number) => {
        return (
          <Tag
            className="edit-tag"
            closable={true}
            title={tag.tag_name}

            key={tag.tag_id.toString()}
            onClose={async()=>{
              const result= await deleteTag({
                tag_id:tag.tag_id
              })
              console.log('result----',result)
            }}
          //rowKey={index.toString()}
          >
            <div key={index.toString()}
                  style={{float:'left',maxWidth:'150px',overflow:'hidden',whitespace:'nowrap',textOverflow:'ellipsis'}}

            >{tag.tag_name}</div>
          </Tag>
        )
      })}
      {inputVisible && (
        <Input
          //ref={saveInputRef}
          type="text"
          size="small"
          className="tag-input"
          ref={inputRef}
          //value={inputValue}
          // onChange={handleInputChange}
          onBlur={handleInputConfirm}
          onPressEnter={handleInputConfirm}
        />
      )}
      {!inputVisible && (<Tag className="site-tag-plus" key={''} onClick={showInput}>
        <PlusOutlined /> 新建标签
      </Tag>)}
    </div>
  );
};

export default Tags;
