/*
 * @Author: Nian Yi
 * @Date: 2022-05-24 12:17:13
 * @LastEditTime: 2022-05-31 18:17:44
 * @LastEditors: Nian Yi
 * @Description:
 * @FilePath: /easyvadmin/src/scripts/components/PriceTages/index.tsx
 * 奥利给
 */
import { PlusOutlined } from '@easyv/react-icons';
import styles from './index.less';
import React, { useState, useRef, useEffect } from 'react';
import { Input, Tag, Tooltip, Row, Col } from '@easyv/antd';
import { useLocalStorage } from '../easyUse';
import message from '@/components/message';
const defaultTages = ['500', '800', '1000'];

function PriceTages({ setFieldsValue, Form, value: priceValue = 0 }) {
  const [tages, setTages] = useLocalStorage('adminPanelPriceTages');
  const [editInputIndex, setEditInputIndex] = useState(-1);
  const [editInputValue, setEditInputValue] = useState('');
  const [tags, setTags] = useState<string[]>(tages || defaultTages);
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const inputRef = useRef(null);
  const editInputRef = useRef(null);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value.trim());
  };

  useEffect(() => {
    setTages(tags);
  }, [tags]);

  const handleInputConfirm = () => {
    if (Number(inputValue) && /^[0-9]+(\.[0-9]{1,2})?$/.test(inputValue)) {
      const value = Number(inputValue).toFixed(2).toString();
      if (value && tags.indexOf(value) === -1) {
        setTags([...tags, value]);
      }
    }else if(inputValue){
      message.warning('请输入正确价格')
    }
    setInputVisible(false);
    setInputValue('');
  };

  const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEditInputValue(e.target.value.trim());
  };

  const handleEditInputConfirm = () => {
    if (Number(editInputValue) && /^[0-9]+(\.[0-9]{1,2})?$/.test(editInputValue )) {
      const newTags = [...tags];
      if (editInputValue && +editInputValue > 0 && +editInputIndex != priceValue) {
        newTags[editInputIndex] = Number(editInputValue).toFixed(2).toString();
        setTags(newTags);
      }
    }else if(inputValue){
      message.warning('请输入正确价格')
    }
    setEditInputIndex(-1);
    setInputValue('');
    setEditInputValue(priceValue + '');
  };
  useEffect(() => {
    if (inputVisible) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);

  useEffect(() => {
    editInputRef.current?.focus();
  }, [inputValue]);

  const handleClose = (removedTag: string) => {
    const newTags = tags.filter((tag) => tag !== removedTag);
    setTags(newTags);
  };

  const onTagClick = (tag) => {
    setFieldsValue({ price: Number(tag) });
  };

  const showInput = () => {
    setInputVisible(true);
  };

  const validatePrice = (rule, value) => {
    if (value > 0) {
      const result = /^[0-9]+(\.[0-9]{1,2})?$/.test(value + '');
      if (result) {
        return Promise.resolve();
      } else {
        return Promise.reject(new Error('请输入正确价格，小数点后2位'));
      }
    } else if (value === '0') {
      return Promise.reject(new Error('不允许小于等于0'));
    } else {
      return Promise.reject(new Error('请输入价格'));
    }
  };

  return (
    <>
      <Form.Item
        label="价格"
        name={'price'}
        className={styles.price}
        rules={[{ required: true }, { validator: validatePrice }]}>
        <Input type="number" placeholder="请输入自定义价格" />
      </Form.Item>
      <span className={styles.priceTages}>
        <Row style={{ marginTop: -14 }}>
          <Col span={19} offset={5}>
            <div style={{ display: 'flex', flexWrap: 'wrap' }}>
              {tags.map((tag, index) => {
                if (editInputIndex === index) {
                  return (
                    <div className={styles.inputTag} key={tag}>
                      <Input
                        ref={editInputRef}
                        placeholder="价格"
                        type="number"
                        size="small"
                        autoFocus
                        className="tag-input"
                        value={editInputValue}
                        onChange={handleEditInputChange}
                        onBlur={handleEditInputConfirm}
                        onPressEnter={handleEditInputConfirm}
                      />
                    </div>
                  );
                }

                const isLongTag = tag.length > 10;

                const tagElem = (
                  <Tag
                    className="edit-tag"
                    key={tag}
                    onClick={() => {
                      onTagClick(tag);
                    }}
                    closable={true}
                    onClose={() => handleClose(tag)}>
                    <span
                      onDoubleClick={(e) => {
                        setEditInputIndex(index);
                        setEditInputValue(tag);
                        e.preventDefault();
                      }}>
                      {isLongTag ? `${tag.slice(0, 10)}...` : tag}
                    </span>
                  </Tag>
                );
                return isLongTag ? (
                  <Tooltip title={tag} key={tag}>
                    {tagElem}
                  </Tooltip>
                ) : (
                  tagElem
                );
              })}
              {inputVisible && (
                <div className={styles.inputTag}>
                  <Input
                    ref={inputRef}
                    type="number"
                    size="small"
                    placeholder="价格"
                    className="tag-input"
                    value={inputValue}
                    onChange={handleInputChange}
                    onBlur={handleInputConfirm}
                    onPressEnter={handleInputConfirm}
                  />
                </div>
              )}

              {!inputVisible && (
                <Tag className={styles.siteTagPlus} onClick={showInput}>
                  <PlusOutlined />
                </Tag>
              )}
            </div>
          </Col>
        </Row>
      </span>
    </>
  );
}

export default PriceTages;
