import React, { RefObject } from "react";
import { Input, Button, Popover, Tooltip } from "antd";
import { Modal } from "@/components/Common/Modal/index.tsx";

import CloseButtonIcon from "../assets/icon/close.png";

import styles from "./AllocWantedModal.less";

interface AllocWantedModalProps {
  allocValue: string | number | null;
  sendValueRange: Array<string | number>;
  sendRequest: Function;
  sendGiftData: {
    answerId: string | number;
    questionId: string | number;
    toUserId: string | number;
  };
  handleVisibleChange: (visible: boolean) => void;
}
interface AllocWantedModalState {
  visible: boolean;
  outRangeTip: boolean;
  sendValue: string | number;
}

class AllocWantedModal extends React.Component<
  AllocWantedModalProps,
  AllocWantedModalState
> {
  ModalInputRef: RefObject<Input>;
  ModalContentRef: RefObject<any>;

  constructor(props: AllocWantedModalProps) {
    super(props);
    this.state = {
      visible: false,
      sendValue: 0,
      outRangeTip: false
    };
    this.ModalContentRef = React.createRef();
    this.ModalInputRef = React.createRef();
  }

  handleSendValueChange = (v: string | number) => {
    if (this.state.outRangeTip) {
      this.setState({
        outRangeTip: !this.checkSendValue()
      });
    }
    this.setState({
      sendValue: v
    });
  };

  checkSendValue = () => {
    const { sendValueRange } = this.props;
    const { sendValue } = this.state;
    let min = 0;
    let max = Number(this.props.allocValue);
    if (sendValueRange) {
      min = Number(sendValueRange[0]);
      max = Number(sendValueRange[1]);
    }
    if (sendValue > max) {
      this.setState({
        // sendValue: max,
        outRangeTip: true
      });
      return false;
    } else if (sendValue < min) {
      this.setState({
        // sendValue: max,
        outRangeTip: true
      });
      return false;
    }
    return true;
  };

  handleCloseAction = () => {
    this.setState(
      {
        visible: false,
        sendValue: 0,
        outRangeTip: false
      },
      () => {
        this.props.handleVisibleChange(false);
      }
    );
  };

  handleShowAction = () => {
    this.setState(
      {
        visible: true
      },
      () => {
        this.props.handleVisibleChange(true);
      }
    );
  };

  handleConfirm = () => {
    const { sendGiftData } = this.props;
    const checkResult = this.checkSendValue();
    if (!checkResult) {
      // 未通过验证
      return null;
    }
    // 进行分配请求
    Promise.resolve(
      this.props.sendRequest({
        business_type: 14, // 表示悬赏答案
        ref_id: sendGiftData.answerId.toString(), // 对应回答的id
        origin_id: sendGiftData.questionId, // 对应问题的id
        to_user: sendGiftData.toUserId, // 悬赏给谁
        goods_id: 2, // 礼物id 帮币的话为2
        num: Number(this.state.sendValue) // 礼物数量
      })
    ).then((res: any) => {
      if (res) {
        this.handleCloseAction();
      } else {
        this.handleCloseAction();
      }
    });
  };

  renderCloseButton = () => {
    return (
      <div
        role="button"
        tabIndex={-1}
        className={styles.closeButton}
        onClick={() => {
          this.handleCloseAction();
        }}
      >
        <img src={CloseButtonIcon} alt="close button for send wanted" />
      </div>
    );
    // return null;
  };

  renderModalContent = () => {
    return (
      <div className={styles.wantedModalContent} ref={this.ModalContentRef}>
        {this.renderCloseButton()}
        <h4 className={styles.title}>分配悬赏奖金</h4>
        <div
          className={styles.wantedValueText}
        >{`剩余可分配 ${this.props.allocValue}元`}</div>
        <Tooltip
          visible={this.state.outRangeTip}
          title="超过范围值"
          placement="bottom"
          overlayClassName={styles.outRangeTextTip}
          getTooltipContainer={() =>
            this.ModalContentRef && this.ModalContentRef.current
          }
        >
          <Input
            ref={this.ModalInputRef}
            className={styles.wantedInputNumber}
            suffix="元"
            value={this.state.sendValue}
            onChange={e => this.handleSendValueChange(e.target.value)}
            onFocus={e =>
              e.target.setSelectionRange(0, String(this.state.sendValue).length)
            }
          />
        </Tooltip>
        <div className={styles.wantedValueTipBottom}>
          需要在悬赏时间结束前将奖金分配完成, 否则将按照规则自动分配
        </div>
        <div className={styles.buttonRow}>
          <div className={styles.tipsButton} />
          <Button className={styles.confirmButton} onClick={this.handleConfirm}>
            确认
          </Button>
          <div className={styles.tipsButton}>
            <Popover
              placement="bottom"
              trigger="click"
              getPopupContainer={() =>
                this.ModalContentRef && this.ModalContentRef.current
              }
              overlayStyle={{
                width: "320px"
              }}
              content={
                <div className={styles.tipsView}>
                  <h6>1、如何参与悬赏？</h6>
                  <div>
                    悬赏问题皆有有效期，默认为120小时（5天），在有效期内回复的答案，才有资格被选为最佳答案，以及分得赏金。
                  </div>
                  <h6>2、赏金如何分？</h6>
                  <div>
                    悬赏时间结束前，提问者可随时选出最优答案，并对赏金进行分配，直至赏金被分完或时间到期为止。若悬赏时间到期，悬赏者仍未分配赏金，且回答数大于等于2，系统则默认将赏金平分给点赞数前3名的回答。
                  </div>
                  <h6>3、赏金能退款吗？</h6>
                  <div>
                    赏金只会在以下2种情况进行退款：一、悬赏时间到期，回答数小于2，赏金将自动退还至提问者的钱包；二、悬赏时间到期，悬赏者未分配完赏金，系统自动将剩余的赏金退还至提问者的钱包。
                  </div>
                </div>
              }
            >
              <i className="schedule schedule-icon_rewardtips" />
            </Popover>
          </div>
        </div>
      </div>
    );
  };

  render() {
    const { children } = this.props;
    return (
      <>
        <div className={styles.wrapper} onClick={() => this.handleShowAction()}>
          {children}
        </div>
        <Modal
          visible={this.state.visible}
          onCancel={() => this.handleCloseAction()}
        >
          {this.renderModalContent()}
        </Modal>
      </>
    );
  }
}

export default AllocWantedModal;
