import React, { useState } from "react";
import classnames from "classnames";
import { Input } from "antd";
import styles from "./PriceOptions.less";

interface Props {
  price: number;
  onPriceChange: (v: number) => void;
  size: "small" | "normal" | "large";
  focusScroll: boolean;
  withTitle: boolean;
  titleText?: string | JSX.Element[] | JSX.Element;
  inputPlaceholderText?: string;
  priceOptions?: Array<any>;
  priceRender?: Function;
  inputPriceRender?: Function;
  inputRef: React.RefObject<any>;
}

const PriceOptions = ({
  price,
  onPriceChange,
  size = "normal",
  focusScroll = true,
  withTitle = true,
  titleText = "Price",
  inputPlaceholderText = "Others",
  priceOptions = [100, 600, 800],
  priceRender = (i: any) => i / 100,
  inputPriceRender = (i: any) => (i ? i / 100 : ""),
  inputRef
}: Props) => {
  const defaultOptions = priceOptions;
  // 控制是否为其他金额输入情况
  const [inputStatus, setInputStatus] = useState(false);

  return (
    <div className={classnames(styles.options)}>
      {withTitle ? (titleText || null) : null}
      <div className={styles.infoItem}>
        <span className={styles.priceBtn}>
          {defaultOptions.map(item => (
            <span
              className={classnames({
                [styles.priceItem]: true,
                [styles.active]: price === item && !inputStatus
              })}
              key={item}
              onClick={() => {
                onPriceChange(item);
                setInputStatus(false);
              }}
            >
              {priceRender(item)}
            </span>
          ))}
        </span>
        <Input
          ref={inputRef}
          onMouseEnter={() => {
            if (inputStatus && inputRef && inputRef.current) {
              inputRef.current.focus();
              inputRef.current.select();
            }
          }}
          suffix="¥"
          className={styles.priceInput}
          value={inputStatus ? inputPriceRender(price) : ""}
          placeholder={inputPlaceholderText}
          onChange={e => {
            const n = +e.target.value;
            if (Number.isNaN(n)) {
              return;
            }
            // 测试暂时改成1分
            onPriceChange(n * 100);
          }}
          onClick={e => {
            onPriceChange(0);
            setInputStatus(true);
          }}
          onFocus={e => {
            e.target.placeholder = "";
            setInputStatus(true);
            if (focusScroll) {
              e.target.scrollIntoView();
            }
          }}
          onBlur={e => {
            e.target.placeholder = inputPlaceholderText;
            if (price) {
              setInputStatus(true);
            } else {
              setInputStatus(false);
            }
          }}
        />
      </div>
    </div>
  );
};

export default PriceOptions;
