import React from "react";
import axios from "axios";
import { AlignCenter, FlexAJ } from "../Component/layout";
import { Popover, Button, Input } from "antd";
import { Link } from "react-router-dom";
import { getImageUrl } from "educoder";
import "./claim.scss";
const { TextArea } = Input;

class claims extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      claimerData: new Array(),
      currentUserClaimed: 0,
      issue_id: this.props.issue_id,
      claimNoteBody: "",
      claimNoteBodyChanged: false,
      claimNotePop: false,
      claimNoteBodyError: undefined,
      // 原声明信息
      currentUserClaimedContent: undefined
    };
  }

  getClaimers = () => {
    const { issue_id } = this.state;
    const { current_user } = this.props;
    axios
      .get(`/issues/${issue_id}/claims.json`)
      .then((result) => {
        if (result) {
          this.setState({
            claimerData: result.data.claimers,
            currentUserClaimed: result.data.currentUserclaimed,
          });
          // 如果用户有声明此issue，则赋值currentUserClaimedContent、claimNoteBody
          if(result.data.currentUserclaimed){
            const map = result.data.claimers.filter(item =>{return item.user_login === current_user.login});
            this.setState({
              currentUserClaimedContent: map[0],
              claimNoteBody: map[0] && map[0].note_body
            })
          }
        }
      })
      .catch(function (error) {
        console.log(error);
      });
  };

  delClaim = () => {
    if (this.props.checkIfLogin() === false) {
      this.props.showLoginDialog();
      return;
    } else {
      const { issue_id } = this.state;
      axios({
        method: "delete",
        url: `/issues/${issue_id}/claims.json`,
      })
        .then((result) => {
          this.setState({
            claimerData: result.data.claimers,
            currentUserClaimed: result.data.currentUserclaimed,
            claimNotePop: false,
            claimNoteBody: "",
            currentUserClaimedContent: undefined
          });
          const { refreshFunc } = this.props;
          refreshFunc && refreshFunc();
        })
        .catch((error) => {
          console.log(error);
        });
    }
  };

  changeClaimNote = (e) => {
    this.setState({
      claimNoteBodyError: undefined,
      claimNoteBody: e.target.value,
      claimNoteBodyChanged: true,
    });
  };

  yesClaim = () => {
    const { issue_id, claimNoteBody, currentUserClaimed, currentUserClaimedContent} = this.state;
    const { refreshFunc, current_user} = this.props;
    if(claimNoteBody){
      // 新增声明
      if(!currentUserClaimed){
        axios.post(`/issues/${issue_id}/claims.json`, {
          claim_note: claimNoteBody,
        })
        .then((result) => {
          const map = result.data.claimers.filter(item =>{return item.user_login === current_user.login});
          this.setState({
            claimerData: result.data.claimers,
            currentUserClaimed: result.data.currentUserclaimed,
            claimNotePop: false,
            currentUserClaimedContent: map[0],
            claimNoteBody: map[0] && map[0].note_body
          });
          refreshFunc && refreshFunc();
        })
        .catch((error) => {
          console.log(error);
        });
      }else{
        // 更新声明
        axios.put(`/issues/${issue_id}/claims.json`, {
          claim_note: claimNoteBody,
          claim_id: currentUserClaimedContent.claim_id,
        })
        .then((result) => {
          this.setState({
            claimerData: result.data.claimers,
            currentUserClaimed: result.data.currentUserclaimed,
            claimNotePop: false
          });
          refreshFunc && refreshFunc();
        })
        .catch((error) => {
          console.log(error);
        });
      }
    }else{
      this.setState({claimNoteBodyError: '请输入您的声明留言'});
    }
  };

  addClaim = () => {
    if (this.props.checkIfLogin() === false) {
      this.props.showLoginDialog();
      return;
    } else {
      this.setState({
        claimNotePop: true,
      });
    }
  };

  cancelClaim = () => {
    const {currentUserClaimedContent} = this.state;
    this.setState({
      claimNotePop: false,
      claimNoteBodyError: undefined,
      claimNoteBody: currentUserClaimedContent ? currentUserClaimedContent.note_body : ''
    });
  };

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

  setVisibleFunc = (flag, index) => {
    const { claimerData } = this.state;
    var lx = claimerData.concat();
    lx.map((i) => (i.visible = false));
    if (flag) {
      lx[index].visible = flag;
    }
    lx.splice();
    this.setState({
      claimerData: lx,
    });
  };

  render() {
    const { claimerData, currentUserClaimed, claimNoteBody, claimNoteBodyError } = this.state;

    const renderClaim = () => {
      return (
        <div className="claimNote_input" style={{ width: "400" }}>
          <div className="mb10"> 声明留言：</div>
          <TextArea
            rows={4}
            type="text"
            placeholder="例如可以留言你的解决思路......"
            onChange={this.changeClaimNote}
            value={claimNoteBody}
            className={claimNoteBodyError ? 'error' : ''}
          />
          <div style={{color: 'red',height:"20px",lineHeight:"20px"}}>{claimNoteBodyError}</div>
          <div style={{ display: "flex", justifyContent: "center" }}>
            <Button style={{width:"67px" }} onClick={() => this.cancelClaim()}>取 消</Button>
            <Button
              onClick={() => this.yesClaim()}
              style={{ marginLeft: "20px",width:"67px" }}
              type={"primary"}
            >
              确 认
            </Button>
          </div>
        </div>
      );
    };

    const renderUser = (item, key) => {
      const { current_user } = this.props;
      return (
        <div>
          <FlexAJ className="menuMaininfos">
            <AlignCenter>
              <Link
                to={`/${item && item.user_login}`}
                className="show-user-link"
              >
                <img
                  className="radius"
                  src={getImageUrl(`/${item && item.user_picture}`)}
                  alt=""
                  width="46"
                  height="46"
                />
              </Link>
              <Link
                to={`/${item && item.user_login}`}
                className="show-user-link color-black ml10"
              >
                <div>
                  <div className="font-16" style={{fontWeight:500,color:"#1e1d1d"}}>{current_user.login === item.user_login ? "你": item.user_name} </div>
                  <span className="color-grey-8 font-12"> 声明于 {item.created_at}</span>
                </div>
              </Link>
            </AlignCenter>
          </FlexAJ>
          <div className="claimNote">
            {current_user.login == item.user_login ? (
              <div>
                <div className="mb5">你的留言：</div>
                <span>{item.note_body}</span>
                <br />
                <div
                  style={{
                    display: "flex",
                    justifyContent: "center",
                    paddingBottom: "10px",
                    paddingTop: "10px",
                    width:"83px"
                  }}
                >
                  <Button
                    onClick={() => this.delClaim()}
                    type={"primary"}
                  >
                    取消声明
                  </Button>
                </div>
              </div>
            ) : (
              <div>
                {item.note_body.length == 0 ? (
                  <span>未留言</span>
                ) : (
                  <div>
                    <div className="mb5">声明留言：</div>
                    <span>{item.note_body}</span>
                  </div>
                )}
              </div>
            )}
          </div>
        </div>
      );
    };

    return (
      <div>
        <Popover
          visible={this.state.claimNotePop}
          content={renderClaim()}
          trigger="click"
          placement="bottom"
          overlayClassName="menuPanels maxWidth"
        >
          {currentUserClaimed === 1 ? <a
            className="topWrapper_btn"
            onClick={() => {this.setState({claimNotePop: true});}}
            style={{ display: "inline-block" }}
          >
            更改声明
          </a> : <Button onClick={() => this.addClaim()} type="primary">
            <i className="iconfont icon-shengming font-14 mr5 color-white"></i>
            声明
          </Button>}
        </Popover>

        {claimerData && claimerData.length > 0 ? (
          <div>
            <div className="mt15">
              <span>声明要关注/解决此疑修的用户</span>
              <span className="infoCount">{claimerData.length}</span>
            </div>
            <div
              className="claimattrPerson"
              onMouseLeave={() => this.setVisibleFunc(false)}
            >
              {claimerData.map((item, key) => {
                return (
                  <Popover
                    content={renderUser(item, key)}
                    visible={item.visible}
                    placemen
                    t="top"
                    overlayClassName="menuPanels"
                    width={400}
                  >
                    <Link key={key} to={`/${item.user_login}`}>
                      <img
                        src={getImageUrl(`/${item.user_picture}`)}
                        alt=""
                        onMouseOver={() => this.setVisibleFunc(true, key)}
                      />
                    </Link>
                  </Popover>
                );
              })}
            </div>
          </div>
        ) : (
          <div className="mt15">
            <span>声明要关注/解决此疑修的用户</span>
            <span className="infoCount">0</span>
          </div>
        )}
      </div>
    );
  }
}

export default claims;
