import React, { Component } from "react";

import Modal, { ModalProps } from "../../Common/Modal";
import WantedPublishView from "../WantedPublishView";
import styles from "./WantedPublishModal.less";

interface WantedPublishModalProps {
  modalConfig?: ModalProps;
  handleConfirm?: Function;
}

interface WantedPublishModalState {
  modalVisible: boolean;
  current_wanted: number | string | null;
}

export class WantedPublishModal extends Component<
  WantedPublishModalProps,
  WantedPublishModalState
> {
  constructor(props: WantedPublishModalProps) {
    super(props);
    this.state = {
      modalVisible: false,
      current_wanted: null
    };
  }

  handleModalShow = () => {};

  handleClose = () => {
    const { handleConfirm } = this.props;
    if (handleConfirm) {
      this.handleUpdateCurrentWanted(
        this.state.current_wanted,
        (value: string) => {
          handleConfirm(Number(value).toFixed(2));
        }
      );
    }
    this.setState({ modalVisible: false });
  };

  handleUpdateCurrentWanted = (
    value: string | number | null,
    afterUpdate?: Function
  ) => {
    if (!value) return;
    let result: string | number;
    result = value;
    if (parseInt(`${value}`, 10) === value) {
      // 无小数判断
      result = Number(value);
    }
    if (!result) return;
    if (result > 10000) result = 10000;
    if (result < 5) result = 5;
    this.setState(
      { current_wanted: result },
      () => afterUpdate && afterUpdate(result)
    );
  };

  clearCurrentWanted = (cb: Function) => {
    this.setState(
      {
        current_wanted: null
      },
      () => cb()
    );
  };

  renderMain() {
    const { current_wanted } = this.state;
    return (
      <WantedPublishView
        wrapperClass={styles.modalBg}
        current_wanted={current_wanted}
        InputWantedValueChange={(v: string) =>
          this.setState({ current_wanted: v })
        }
        InputWantedPressEnter={(v: string) =>
          this.handleUpdateCurrentWanted(v, this.handleClose)
        }
        InputWantedOnBlur={(v: string) => this.handleUpdateCurrentWanted(v)}
        InputWantedClear={() => this.clearCurrentWanted(this.handleClose)}
        CloseFunction={this.handleClose}
      />
    );
  }

  render() {
    return (
      <>
        <div onClick={() => this.setState({ modalVisible: true })}>
          {this.props.children}
        </div>
        <Modal visible={this.state.modalVisible} onCancel={this.handleClose} {...this.props.modalConfig}>
          {this.renderMain()}
        </Modal>
      </>
    );
  }
}

export default WantedPublishModal;
