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

import React from 'react';
import { Modal, Input, Table } from 'antd';
import Service from '@/common/js/service';
// import _ from 'underscore';
import './ChooseMembersModal.less';
import User from '@/common/js/user'

const { Search } = Input;

class ChooseMembersModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      allUserList : [],                               // 所有成员列表
      selectUserList: [],                             // 已选则成员
      temporaryList: [],                              // 临时用户成员列表（搜索时使用）
      instId : window.currentUserInstInfo.instId,     // 机构Id
      searchKey : null,                                 // 搜索内容  
      selectedRowKeys : [],                            // 勾选的成员  
      userAuthority : ['可编辑', '可查看/下载', '仅可查看'] ,
    }
  }

  componentDidMount() {
    this.getFileUserAuthority();
  }

  // 获取对应文件相关成员
  getFileUserAuthority = (searchKey='') => {
    const { dataInfo = {} } = this.props;
    const { folderType, id } = dataInfo;
    const _params = {
      folderTypeEnum : folderType,
      id,
      storeId:User.getStoreId()
    }
    Service.Hades('public/hadesStore/getFileUser', _params).then((res) => {
      if (res.result) {
        let _allUserList = [];
        _allUserList = res.result;
        // 判断是否进行了搜索
        if (searchKey === '') {
          this.setState({
            allUserList : _allUserList
          })
        } else {
          let searchPersonList = [];
          _allUserList.map(item => {
            if (item.adminName.indexOf(searchKey) > -1) {
              searchPersonList.push(item);
            }
            return searchPersonList
          })
          this.setState({
            allUserList: searchPersonList
          })
        }
      }
    })
  }

  // 勾选成员
  onChangeRow = (_selectedRowKeys, selectedRows) => {
    let { temporaryList, allUserList } = this.state;
    let _temporaryIdList = [], _temporaryList = [];

    // 解决搜索款2次搜索的问题
    if (temporaryList.length === 0) {
      _temporaryList = selectedRows;
    } else {
      temporaryList = temporaryList.concat(selectedRows);
      // 之前搜索并勾选的选项以及当前页被勾选的选项
      temporaryList = temporaryList.filter(item => (!allUserList.includes(item) || selectedRows.includes(item)) && _selectedRowKeys.includes(item.userId));
      
      temporaryList.map(item => {
        if (!_temporaryIdList.includes(item.userId)) {
          _temporaryIdList.push(item.userId);
          _temporaryList.push(item);
        }
        return (_temporaryIdList, _temporaryList)
      });
    }

    this.setState({
      temporaryList : _temporaryList,
      selectUserList : _temporaryList,
      selectedRowKeys : _selectedRowKeys
    })
  }

  // 勾选禁用
  getCheckboxProps = (record) => {
    if (record.whetherExist) {
      return ({
        disabled : true,
        checked: true
      })
    }
  }

  // 清空所有成员
  clearAllUser = () => {
    this.setState({
      selectedRowKeys : [],
      selectUserList : [],
      temporaryList : []
    })
  }

  // 清除单个成员(点击“x”)
  clearOneUser = (user) => {
    let { selectUserList, selectedRowKeys } = this.state
    // 清除成员不是之前选的
    selectedRowKeys = selectedRowKeys.filter(item => item !== user.userId);
    selectUserList = selectUserList.filter(item => item.userId !== user.userId);
    this.setState({
      selectedRowKeys,
      selectUserList
    })
    
  }

  // 点击全选
  onSelectAll = (selected, selectedRows, changeRows) => {
    let { temporaryList, allUserList } = this.state;
    let newSelectUserList = [], allUserId = [];
    allUserList.map(item => allUserId.push(item.userId));
    temporaryList = temporaryList.filter(item => !allUserId.includes(item.userId));
    
    if (selectedRows.length === 0) {
      // 取消勾选，保留之前已经选择的成员
      newSelectUserList = temporaryList;
    } else {
      newSelectUserList = temporaryList.concat(allUserList);
      newSelectUserList = newSelectUserList.filter(item => !item.whetherExist);
    }

    this.setState({
      selectUserList : newSelectUserList,
      temporaryList: newSelectUserList
    })
  }

  // 批量添加成员(点击确定)
  addMember = () => {
    const { selectUserList, instId } = this.state;
    const { dataInfo, disk } = this.props;
    const { id, createId } = dataInfo;
    let rightsList = [];            // 保存新加进去的成员
    selectUserList.map((item) => {
      rightsList.push({
        rights: "LOOK_DOWNLOAD",
        userId: item.userId
      })
      return rightsList
    })
    const _params = {
      instId,
      id,
      disk,
      createId,
      rightsList,
    }   
    Service.Hades('public/hadesStore/addFileUserAuthorityList', _params).then((res) => {
      if (res.code === '200') {
        this.handleClose(); 
        this.setState({
          temporaryList: []
        })   
      }
    })
  }

  // 搜索成员
  handleSearch = () => { 
    const { searchKey } = this.state;
    this.getFileUserAuthority(searchKey);
  }

  // 搜索框值更改
  handleChangeSearchKey = (e) => {
    const { value } = e.target;
    this.setState({ 
      searchKey : value 
    });
  }

  // 关闭弹窗
  handleClose = () => {  
    this.props.handleChooseModal();
  }

  // 信息列表-—左边
  selectedColumnsLeft = () => {
    const selectColumns = [
      {
        title: '全选',             // 实际为头像，但在表格上这行要求显示为全选
        key: 'avatar',
        dataIndex: 'avatar',
        width: '40%',
        render: (value, record) => {
          const { adminName } = record;

          return (
            <div className='avatar'>
              {
                value ?
                [<img className='avatar-img' src={ value } key='avatar' alt=""/>]
                : [<img className='avatar-img' src='https://image.xiaomaiketang.com/xm/dEyxDRKwFw.png' key='avatar' alt=""/>]
              }
              <span className='userImg'>
                { adminName }
              </span>
            </div>  
          )
        }
      }
    ]
    return selectColumns
  }

  // 信息列表——右边
  selectedColumnsRight = () => {
    const selectColumns = [
      {
        title: '用户名',
        key: 'adminNameRight',
        dataIndex: 'adminName',
        width: '70%',
        render: (value, record) => {
          const { adminName = '', avatar } = record;
          return (
            <div className='avatar'>
              <img className='avatar-img' src={ avatar || 'https://image.xiaomaiketang.com/xm/dEyxDRKwFw.png' } key='avatar' alt=""/>
            <span className='userImg'>
              { adminName }
            </span>
          </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;
  }

  render() {
    const { isOpen } = this.props;
    const { selectUserList, allUserList, searchKey, selectedRowKeys } = this.state;
    const title = '添加成员';
    
    return (    
      <div>
        {/* 添加学员页面 */}
        <Modal
          visible={isOpen}
          onCancel={this.handleClose}
          onOk={this.addMember}
          title={title}
          width={680}
          maskClosable={false}
          closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
        >
          <div className='choose-container'>
            {/* 拥有文件夹权限的成员列表 */}
            <div className='container-left'>
              <div className='container-left-header'>选择</div>
              <div className='container-left-body'>
                <Search 
                  placeholder='请输入姓名'
                  value={searchKey}
                  onSearch={this.handleSearch}
                  onChange={this.handleChangeSearchKey}
                  className='search search-input'
               
                  enterButton={<span className="icon iconfont">&#xe832;</span>}
                />
                <div className='container-left-body-table'>
                  <Table 
                    rowKey={(record) => record.userId}
                    dataSource={allUserList}
                    columns={this.selectedColumnsLeft()}               
                    pagination={false}
                    scroll={{ y: 290}}
                    // bordered={true}
                    size={'small'}
                    rowSelection={{
                      columnWidth : 24,
                      selectedRowKeys,
                      onChange : this.onChangeRow,
                      getCheckboxProps : this.getCheckboxProps,
                      onSelectAll : (selected, selectedRows, changeRows) => {
                        this.onSelectAll(selected, selectedRows, changeRows)
                      }
                    }}
                  />
                </div>
              </div>
            </div>
            {/* 已选择的成员列表 */}
            <div className='container-right'>
              <span className='span-left'> 
                已选：
                <span className={ (selectUserList.length > 0) ? 'span-left-l' : null }>
                  {selectUserList.length} 
                </span> 
              </span>
              <div className='span-right' onClick={() => this.clearAllUser()}>
                <span className={ (selectUserList.length > 0) ? 'span-right-l' : null }>清空</span>
              </div>
              <div className='container-right-body'>
                <Table 
                  rowKey={(record) => record.userId}
                  dataSource={selectUserList}
                  columns={this.selectedColumnsRight()}
                  showHeader={false}
                  scroll={{ y: 375 }}
                  pagination={false}
                  size={'small'}
                />
              </div>
            </div>
          </div>   
        </Modal>
      </div>
    )
  }
}

export default ChooseMembersModal;