import React, { Component } from 'react';
import { getImageUrl} from 'educoder';
import PreCreate from './PreCreate';
import './manage.css'
import '../exchange.css'
import {Link} from 'react-router-dom'
import axios from 'axios';
import update from 'immutability-helper'

import AddModeratorModal from './AddModeratorModal'



class PrePlateManage extends Component {
  constructor(props){
    super(props);
    this.state={
      visible:false,
      children_tags:undefined,
      subId:undefined,
      subName:undefined,
      // 新增版主有关
      addVisible:undefined,
      operationPlateId:undefined
    }
  }
  componentDidMount=()=>{
    this.getSubModerator();
  }
  // 获取所有二级板块
  getSubModerator=()=>{
    const { plateId } = this.props.match.params;
    const url = `/forum_sections/${plateId}/managements`;
    axios.get(url).then((result)=>{
      if(result){
        this.setState({
          children_tags:result.data.forum_tag && result.data.forum_tag.children_tags
        })
      }
    }).catch((error)=>{

    })
  }
  // 新建板块和重命名板块后的刷新方法
  reSetInfo=()=>{
    this.setState({
      visible:false,
      subId:undefined,
      subName:undefined
    })
    this.getSubModerator();
    const { plateId } = this.props.match.params;
    const { getPlateInfo } = this.props;
    getPlateInfo(plateId);
  }

  // 展开
  expandEvent=(index,flag)=>{
    this.setState(
      (prevState) => ({ 
        children_tags : update(prevState.children_tags, {[index]: { expand: {$set: flag} }}),
      })
    )
  }

  // 显示删除版主的按钮
  deleteManageEvent=(index,flag)=>{
    console.log(index)
    this.setState(
      (prevState) => ({ 
        children_tags : update(prevState.children_tags, {[index]: { isDeleting: {$set: flag} }}),
      })
    )
  }

  // 新建二级板块
  createSubPlateEvent=()=>{
    this.setState({
      visible:true,
      subId:undefined,
      subName:undefined
    })
  }
  // 二级板块重命名
  RenamneSubPlateEvent=(id,name)=>{
    this.setState({
      visible:true,
      subId:id,
      subName:name
    })
  }

  // 删除二级板块
  DeleteSubPlateEvent=(id)=>{
    this.props.confirm({
      content: '确认删除二级板块?',
      onOk: () => {
        const { plateId } = this.props.match.params;
        const url=`/forum_sections/destroy_forum.json`
        axios.post(url,{
          children_section_id:id,
          id: plateId
        }).then(result=>{
          if(result){
            this.props.showNotification(result.data.message);
            this.getSubModerator();
            const { getPlateInfo } = this.props;
            getPlateInfo(plateId);
          }
        }).catch((error)=>{
    
        })
      },
      onCancel() {
        console.log('Cancel');
      }
    })
    
  }

  // 关闭新建弹框
  colseModalEvent=()=>{
    this.setState({
      visible:false
    })
  }

  // 删除版主
  deletePlateEvent=(id,name,index,key)=>{
    console.log(index,'dddd',key);
    this.props.confirm({
      content: `是否确认解除“${name}”的二级版主权限？`,
      onOk: () => {
        const { plateId } = this.props.match.params;
        const url=`/forum_sections/${plateId}/destroy_moderator/${id}`
        axios.post(url).then(result=>{
          if(result){
            this.props.showNotification(result.data.message);
            const { children_tags } = this.state;
            // 去掉当前选中的版主
            let tempObj = children_tags[index].forum_moderators;
            tempObj = tempObj.filter((_, i) => i !== key)  ;
            children_tags[index].forum_moderators = tempObj;
            this.setState({ children_tags })
          }
        }).catch((error)=>{
    
        })
      },
      onCancel() {
        console.log('Cancel');
      }
    })
  }

  // 新增版主弹框
  showAddBox=(flag,plateId)=>{
    this.setState({
      addVisible:true,
      operationPlateId:plateId
    })
  }
  hideAddBox=()=>{
    this.setState({
      addVisible:false,
      operationPlateId:undefined
    })
  }


  render(){
    const { visible  ,children_tags , subId , subName , addVisible , operationPlateId } = this.state;
    // console.log("child",children_tags);
    const forumTagList = ()=>{
      if(children_tags && children_tags.length>0){
        return(
          <div className="subPlateList">
            {
              children_tags.map((item,key)=>{
                return(
                  <div>
                    <div className={item.expand ? "subPlateItem active":"subPlateItem"}>
                      <p className="subPlateItem_head">
                        <span>{item.title}</span>
                        <span>
                          <span className="c_point mr10 color-green font-12" onClick={()=>this.RenamneSubPlateEvent(item.id,item.title)}>重命名</span>
                          <span className="c_point color-grey-9 sendPoint pl10" onClick={()=>this.DeleteSubPlateEvent(item.id)}>删除板块</span>
                        </span>
                      </p>
                      <p className="mt10 mb10 color-grey3">二级版主</p>
                      <div className="plateManager">
                        { renderSubList(item.forum_moderators,key,item.isDeleting) }
                        <span className="fr">
                          {/* 展开 */}
                          {
                            item.forum_moderators && item.forum_moderators.length > 5 && !item.expand &&
                            <span className="c_point mr30" onClick={()=>this.expandEvent(key,true)}><i className="iconfont icon-gengduo1 font-36 color-grey-9"></i></span>
                          }
                          {/* 收起 */}
                          {
                            item.forum_moderators && item.forum_moderators.length > 5 && item.expand &&
                            <span className="c_point mr30" onClick={()=>this.expandEvent(key,false)}><i className="iconfont icon-shangjiantou-tianchong font-36 color-grey-9"></i></span>
                          }
                          {/* 新增版主 */}
                          <span className="c_point mr30" onClick={()=>this.showAddBox(true,item.id)}><i className="iconfont icon-roundaddfill color-green font-36"></i></span>
                          {/* 删除版主 */}
                          {
                            item.forum_moderators && item.forum_moderators.length > 0 && !item.isDeleting &&
                            <span className="c_point mr30" onClick={()=>this.deleteManageEvent(key,true)}><i className="iconfont icon-default color-grey-9 font-36"></i></span>
                          }
                          {
                            item.isDeleting && <span className="c_point mr30 completeIcon" onClick={()=>this.deleteManageEvent(key,false)}>完成</span>
                          }
                          
                        </span>
                      </div>
                    </div>
                  </div>
                )
              })
            }
          </div>
        )
      }
    }

    const renderSubList = (item,index,deletingFlag) =>{
      if(item){
        return(
          <ul>
            {
              item.map((i,key)=>{
                return(
                  <React.Fragment>
                    {
                      !i.isDelete && 
                      <li>
                        <a href={`/users/${i.login}`}><img alt="" src={getImageUrl(`images/${i.image_url}`)} width="39" height="39" className="radius mb3"/></a>
                        {
                          deletingFlag && 
                          <i className="iconfont icon-htmal5icon19 deletePlateIcon" onClick={()=>this.deletePlateEvent(`${i.moderator_id}`,`${i.username}`,index,key)}></i>
                        }
                        <a href={`/users/${i.login}`}><span className="task-hide" style={{width:"39px",display:"block"}}>{i.username}</span></a>
                      </li>
                    }
                  </React.Fragment>
                  
                )
              })
            }
          </ul>
        )
      }
    }
    return(
      <div>
        <div className="padding20-30 edu-back-white font-22 mb20 clearfix">
          <PreCreate 
            {...this.props} 
            {...this.state}
            visible={visible}
            title="新建"
            refresh={this.reSetInfo}
            close={this.colseModalEvent}
            subId={subId}
            subName={subName}
          />

          <AddModeratorModal 
            {...this.props} 
            {...this.state}
            visible = {addVisible}
            operationPlateId={operationPlateId}
            hideAddBox={this.hideAddBox}
            getSubModerator={this.getSubModerator}
          />
          <span className="fl color-grey3 font-16">二级板块管理</span>
          <a onClick={this.createSubPlateEvent} className="fr middle-default-btn small-green-btn">新建板块</a>
        </div>
        {forumTagList()}
      </div>
    )
  }
}

export default PrePlateManage;