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

class FocusButton extends Component {
  constructor(props) {
    super(props);
    this.state = {
      is_watch: false,
      id: "",
      isSpin: false,
    };
  }

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

  set_watch = () => {
    this.setState({
      is_watch: this.props.is_watch,
      id: this.props.id,
      isSpin: false,
    });
  };

  // 关注和取消关注
  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) => {
        console.log(error);
      });
  };

  render() {
    const { is_watch, isSpin } = this.state;
    return (
      <Button 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="font-12">已关注</span>
          </span>
        ) : (
          <span className="">
            <i className="iconfont icon-kongxing font-15"></i>
            <span className="font-12">关注</span>
          </span>
        )}
      </Button>
    );
  }
}

export default FocusButton;
