/*
 * @Author: wanghaofeng
 * @date: 2020/11/14 17:42
 * @Description：权限管理-选择成员弹窗
 */

import React from 'react';
import { Modal, Input, message, Tooltip } from 'antd';
import { XMTable } from '@/components';
import college from '@/common/lottie/college.json';
import Service from '@/common/js/service';
import User from '@/common/js/user'
import SetEmployeeModal from "./SetEmployeeModal";
import search from '../../lottie/search/data.json';
import MemberTree from '../components/MemberTree'
import './ChooseMembersModal.less';
import _ from 'underscore';

const { Search } = Input;

class NewChooseMembersModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selectUserList:[],
      selectObject: {},
      visible:this.props.visible,
      openSetModal: false,
    }
  }

  componentDidMount() {
    
  }

  handleClose = ()=>{
    this.props.close()
  }
  
   // 信息列表——右边
  selectedColumnsRight = () => {
    const selectColumns = [
      {
        title: '学员名',
        key: 'nameRight',
        dataIndex: 'userName',
        width: '70%',
        render: (value, record) => {
          const { userName = '', avatar } = record;
          return (
            <div className='avatar'>
              <span className="icon iconfont avatar-icon">&#xe84a;</span>
              <Tooltip title={userName}>
                <span className='userImg'>{userName}</span>
              </Tooltip>
            </div> 
          )
        }
      },{
        title : '操作',
        key : 'edit',
        dataIndex : 'edit',
        width : '30%',
        align : 'right',
        render: (value, record) => {
          return (
            <div className='edit' onClick={() => this.clearOneUser(record)}>
              <span className="icon iconfont edit-icon">&#xe717;</span>
            </div>
          )
        }
      },
    ]
    return selectColumns;
  }

  treeSelect = (record)=>{
    this.setState({
      selectUserList:record
    })
  }

  clearOneUser = (record) =>{
    const {selectUserList} = this.state;
    const _selectUserList = selectUserList.map((item,index)=>{
      if(item.userId !== record.userId){
        return item
      }  
    })
    this.setState({
      selectUserList:_selectUserList
    })
  }
   // 清空所有成员
   clearAllUser = () => {
    this.setState({
      selectUserList : [],
    })
  }
  addCustomer = () => {
    const { selectUserList } = this.state;
    let enterpriseVisibleUserIdList = [];            // 保存新加进去的成员
    selectUserList.map((item) => {
      enterpriseVisibleUserIdList.push(item.enterpriseVisibleUserId)
      return enterpriseVisibleUserIdList
    })
    const _params = {
      storeId: User.getStoreId(),
      enterpriseVisibleUserIdList,
    }   
    Service.Hades('public/hades/addBatchEnterpriseStoreCustomer', _params).then((res) => {
      this.props.onConfirm(); 
    })
  }
   // 批量添加成员(点击确定)
  addUser = (selectUserList) => {
    let enterpriseUserList = [];            // 保存新加进去的成员
    selectUserList.map((item) => {
      enterpriseUserList.push({
        roleCode: item.roleCode,
        enterpriseVisibleUserId: item.enterpriseVisibleUserId
      })
      return enterpriseUserList
    })
    const _params = {
      storeId: User.getStoreId(),
      enterpriseUserList,
    }   
    Service.Hades('public/hades/addBatchEnterpriseStoreUser', _params).then((res) => {
      if (res.code === '200') {
        this.props.onConfirm();
        this.setState({
          openSetModal: false,
        })   
      }
    })
  }

  render() {
    const {type,openSetModal,visible} = this.props;
    const {selectUserList,selectObject} = this.state;
    const title = type === 'USER' ? '添加员工' : '添加学员';
    return (    
      <div>
        {/* 添加学员页面 */}
        <Modal
          className="choose-member-modal"
          visible={visible}
          onCancel={() => this.handleClose()}
          onOk={() => {
            if (User.getVersion() && User.getVersion().whetherReachUserNum) {
              message.error("添加失败，企业使用人数超出限制")
              return
            }
            if (_.isEmpty(selectUserList)) {
              message.warning(type === 'USER' ? '请选择员工' : '请选择学员')
              return null;
            }
            type === 'USER' ? this.setState({ openSetModal: true},()=>{this.handleClose()}) : this.addCustomer();
          }}
          okText={type === 'USER' ? '下一步' : '确定'}
          title={title}
          width={680}
          maskClosable={false}
          closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
        >
          <div className='member-container'>
            <div className='container-left'>
              <div className='container-left-body'>
                <Search 
                  placeholder='搜索成员'
                  className='search search-input'
                  enterButton={<span className="icon iconfont">&#xe832;</span>}
                />
                <div className='container-left-body-table'>
                   <MemberTree onSelect={(record)=>{this.treeSelect(record)}}/>
                </div>
              </div>
            </div>
            {/* 已选择的成员列表 */}
            <div className='container-right'>
              <span className='span-left'>已选择{type === 'USER' ? '员工' : '学员'}</span>
              <div className='span-right' onClick={() => this.clearAllUser()}>
                <span className={ (selectUserList.length > 0) ? 'span-right-l' : null }>清空</span>
              </div>
              <div className='container-right-body'>
                <XMTable 
                  renderEmpty={{
                    image: college,
                    description: '暂无数据'
                  }}
                  rowKey={(record) => record.enterpriseVisibleUserId}
                  dataSource={selectUserList}
                  columns={this.selectedColumnsRight()}
                  showHeader={false}
                  scroll={{ y: 375 }}
                  pagination={false}
                  size={'small'}
                />
              </div>
            </div>
          </div>   
        </Modal>
        {openSetModal &&
          <SetEmployeeModal
            list={selectUserList}
            selectObject={selectObject}
            onChange={(key, value) => {
              selectObject[key] = value;
              this.setState({ selectObject });
            }}
            onClose={() => {
              this.setState({ openSetModal: true},()=>{this.handleClose()})
              this.setState({ openSetModal: false, visible: true })  
            }}
            onCancel={() => {
              this.handleClose();
              this.setState({ openSetModal: false });
            }}
            onOk={(list) => {
              this.addUser(list);
            }}
          />
        }
      </div>
    )
  }
}

export default NewChooseMembersModal;