import React, { Component } from "react";
import axios from "axios";
import { AlignCenter , FlexAJ  } from '../Component/layout';
import { Popover, List, Button, Dropdown, 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
     };
   
   };

   getClaimers = ()=>{
      const {issue_id} = this.state;
     axios.get(`/issues/${issue_id}/claims.json`)
       .then((result) => {
         if(result){
          this.setState({
              claimerdata: result.data.claimers,
              currentUserClaimed: result.data.currentUserclaimed,
            });
         }  
       }).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:'',
            });
            const { refreshFunc } = this.props;
            refreshFunc && refreshFunc();
        })
          .catch(error => {
            console.log(error);
          });
        }
   };
   
   changeClaimNote = (e)=>{
    this.setState({
      claimNoteBody: e.target.value,
      claimNoteBodyChanged: true,
    });
   };

   yesClaim = ()=>{
      const {issue_id,claimNoteBody} = this.state;
      const { refreshFunc } = this.props;

      axios.post(`/issues/${issue_id}/claims.json`, {
        claim_note: claimNoteBody
      })
      .then(result => {
        this.setState({
            claimerdata: result.data.claimers,
            currentUserClaimed: result.data.currentUserclaimed,
            claimNotePop:false,
          });
          refreshFunc && refreshFunc();
      })
        .catch(error => {
          console.log(error);
        });
   };

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

   };

   updateClaim = (claimId,key)=>{
      const {issue_id,claimNoteBody,claimNoteBodyChanged} = this.state;
      const { refreshFunc } = this.props;
      if(claimNoteBodyChanged){
        axios.put(`/issues/${issue_id}/claims.json`, {
          claim_note: claimNoteBody,
          claim_id: claimId
        })
        .then(result => {
          this.setState({
              claimerdata: result.data.claimers,
              currentUserClaimed: result.data.currentUserclaimed,
            });
            refreshFunc && refreshFunc();
        })
          .catch(error => {
            console.log(error);
          });
        }
      this.setVisibleFunc(false,key)
    };



   cancleClaim = ()=>{
    this.setState({
      claimNotePop: false,
    })
   };

   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,
       issue_id
     } = this.state;
     
     const rednerlist = (item)=>{
       return (
         <div>
            <Link to={`/${item && item.user_login}`} className="show-user-link">
              <img
                className="radius"
                src={getImageUrl(`/${item && item.user_picture}`)}
                alt=""
                width="30"
                height="30"/>
            </Link>
            <Link to={`/${item && item.user_login}`}
              className="show-user-link color-black ml10 fwb">
              {item && item.user_name}
            </Link>
            <span className="color-grey-8"> 声明于 {item.created_at}</span>
            </div>
         );
     };
     
     const renderClaim = ()=>{
        return(
          <div className="claimNote_input">
              <span> 声明留言：</span> <br/>
              <TextArea rows={4} type="text" placeholder="例如可以留言你的解决思路......"  onChange={this.changeClaimNote}/><br/><br/>
              <div  style={{display:"flex",justifyContent:'center'}}>
                <Button onClick={()=>this.cancleClaim()}   >取 消</Button>
                <Button onClick={()=>this.yesClaim()}  style={{marginLeft:"20px"}} 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="30"
                    height="30"/>
                </Link>
                <Link to={`/${item && item.user_login}`}
                  className="show-user-link color-black ml10 fwb">
                    <div >
                     {current_user.login == item.user_login?(<div>你</div>
                     ):(
                       <div>{item && item.user_name}</div>
                     )} 
                    </div>
                </Link>
                <div style={{marginLeft:"10px"}}> <span className="color-grey-8"> 声明于 {item.created_at}</span></div>
              </AlignCenter>
            </FlexAJ>
            <div className="claimNote">
              {current_user.login==item.user_login?(
                <div><span>你的留言：</span><br/>
                <TextArea  onChange={this.changeClaimNote} type="text" defaultValue={item.note_body} /><br/>
                <div  style={{display:"flex",justifyContent:'center',paddingBottom:"10px",paddingTop:"10px"}}>
                      <Button onClick={()=>this.updateClaim(item.claim_id,key)}   type={'primary'} >更新声明留言</Button>
                </div>
                </div>
              ):
              (
                <div>
                {item.note_body.length==0?(
                  <span>未留言</span>
                ):(
                  <div><span>声明留言：</span><br/>
                  <span>{item.note_body}</span></div>
                )}
                </div>
              )}
            </div>

           </div>
        )
     };

     return (
       <div> 
         {currentUserClaimed===1?(
           <div><Button onClick={()=>this.delClaim()} >取消声明</Button>
           </div>
         ):(
           <Popover  visible={this.state.claimNotePop}  content={renderClaim()} trigger='click' placement="bottom" overlayClassName="menuPanels">
           <Button onClick={()=> this.addClaim()} type="primary"><i className="iconfont icon-shengming font-14 mr5 color-white"></i>声明</Button>
           </Popover>
         )}

         <div className="ant-divider ant-divider-horizontal"> </div>

         
         {    
           claimerdata&&claimerdata.length>0?(
             <div>
              <div className="mt15">
                <span>声明要关注/解决此疑修的用户</span>
                <span className="infoCount">{claimerdata.length}</span>
              </div>
              <div className="attrPerson" onMouseLeave={()=>this.setVisibleFunc(false)}>
                {claimerdata.map((item,key)=>{
                  return(
                   <Popover content={renderUser(item,key)}  visible={item.visible} placement="top" overlayClassName="menuPanels">
                      <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;