import React, { Component } from "react";
import axios from "axios";
import { Button } from "antd";
import "./list.css";

class FocusButton extends Component {
  constructor(props) {
    super(props);
    this.state = {
      is_watch: false,
      id: "",
      isSpin: false,
      fontClass: "font-12",
      starText: "关注",
      is_block: false
    };
  }

  componentDidMount = () => {
    this.set_watch();
  };

  set_watch = () => {
    this.setState({
      is_watch: this.props.is_watch,
      id: this.props.id,
      isSpin: false,
      fontClass: this.props.fontClass ? this.props.fontClass : "font-12",
      starText: this.props.starText ? this.props.starText : "关注",
      is_block: this.props.is_block === undefined ? false : this.props.is_block
    });
  };

  // 关注和取消关注
  focusFunc = (flag) => {
    const { id } = this.state;
    this.setState({ isSpin: true });
    axios({
      method: flag ? "delete" : "post",
      url: `/watchers/${flag ? "unfollow" : "follow"}.json`,
      params: {
        target_type: "user",
        id: id,
      },
    })
      .then((result) => {
        if (result && result.data.status === 0) {
          this.setState({
            is_watch: result.data.watched,
            isSpin: false,
          });
        }
      })
      .catch((error) => {
        this.setState({ isSpin: false })
      });
  };

  render() {
    const { is_watch, isSpin, fontClass, starText, is_block } = this.state;

    return (
      <Button type={is_watch ? "default" : "primary"} ghost={!is_watch} block={is_block} loading={isSpin} onClick={() => this.focusFunc(is_watch)}>
        {is_watch ? (
          <span className="">
            <i className="iconfont icon-shixing font-15 text-yellow mr-4"></i>
            <span className={fontClass}>已关注</span>
          </span>
        ) : (
            <span className="">
              <i className="iconfont icon-kongxing font-15"></i>
              <span className={fontClass}>{starText}</span>
            </span>
          )}
      </Button>
    );
  }
}

export default FocusButton;
