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

import React from 'react';
import { Modal, Table, Dropdown, Menu, Tooltip, message } from 'antd';
import Service from '@/common/js/service';
import ChooseMembersModal from './ChooseMembersModal';
import _ from 'underscore';
import './ManagingMembersModal.less';
import User from '@/common/js/user'
class ManagingMembersModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dataSource : [],                              // 数据源
      addManagingMember: false,                     // 是否点击了添加成员
      storeId :User.getStoreId() ,   // 学院Id
      iconRotateList: [],
      userAuthority : ['可编辑', '可下载', '可查看', '', '创建者', '学院管理员'] ,  // 空 代表删除
    } 
  }
  componentDidMount() {
    this.setState({
      showLoading: true
    })
    this.getFileUserAuthority();
  }
  // 获取成员列表
  getFileUserAuthority = () => {
    const { storeId } = this.state;
    const { dataInfo } = this.props;
    const { id } = dataInfo;
    const _params = {
      storeId,
      id
    }

    Service.Hades('public/hadesStore/getFileUserAuthority', _params).then((res) => {
      if(res.result) {
        // 数据排序，文件创建者在最前,并修改文案为所有者
        let _selectUserList = [], _dataSource = [], flag = [], _iconRotateList = [];
        // 列表排序，文件夹创建者和机构学院管理员默认排在最前
        res.result.map((item, index) => {             
          if (item.fileUserEnum === "CREATE" || item.fileUserEnum === 'SUPER_ADMIN') {
            _dataSource.push(item);
            flag.push(index);
          } else {
            _iconRotateList.push({ userId: item.userId, iconRotate: false});
          }
          return _dataSource;
        })  
        _dataSource = _.uniq(_dataSource.concat(res.result));
        this.setState({
          dataSource :  _dataSource,                       // 所有成员
          selectUserList : _selectUserList,                // 已拥有该文件权限的成员
          iconRotateList: _iconRotateList                 
        })
      } 
    })
  }

  // 修改成员权限
  updateFileUserAuthority = (params, newRights = 1) => {
    const rightList =  ['EDIT', 'LOOK_DOWNLOAD', 'LOOK'];
    let { iconRotateList } = this.state;
    let _params = params;
    _params.rights = rightList[newRights]; 
    
    // 展开图标
    if (_params.currentRight === rightList[newRights]) {
      iconRotateList.map(item => {
        if (item.userId === _params.userId) {
          item.iconRotate = false;
        }
        return iconRotateList;
      })
      this.setState({ iconRotateList });
      return;      
    }
    delete _params.currentRight;

    // 此接口只返回成功与失败,没有其他数据
    Service.Hades('public/hadesStore/updateFileUserAuthority', _params).then((res) => {
      this.getFileUserAuthority()
      message.success(res.message);
    })
  }

  // 移除成员二次确认弹窗
  removeUser = (params, _rights = 1) => {
    const rightList =  ['EDIT', 'LOOK_DOWNLOAD', ''];
    let _params = params;
    _params.rights = rightList[_rights];
    
    Modal.confirm({
      title: '移除',
      content: '确定要移除该成员',
      icon: <span className="icon iconfont default-confirm-icon">&#xe6f4;</span>,
      onOk: () => {
        Service.Hades('public/hadesStore/updateFileUserAuthority', _params).then((res) => {
          if (res.code === '200') {
            message.success('删除成功');
            this.getFileUserAuthority();
          }
        })
      }
    });
  }

  // 关闭权限管理弹窗
  handleClose = () => {
    this.props.onClose();
  }

  // 旋转下拉图标
  changeIconRotate = (record) => {
    let { iconRotateList } = this.state;
    iconRotateList.map(item => {
      if (item.userId === record.userId) {
        item.iconRotate = !item.iconRotate;
      }
      return iconRotateList
    }) 
    this.setState({
      iconRotateList
    })
  }

  // 点击添加成员按钮
  handleChooseModal = () => {
    this.setState({
      isOpen : !this.state.isOpen,
      addManagingMember : !this.state.addManagingMember
    },() => {
      this.getFileUserAuthority();
    })
  }

  // 管理成员下拉框 
  renderMenu = (record) => {
    let { dataSource } = this.state;
    const { dataInfo } = this.props;
    const { folderType, id } = dataInfo;
    const updateId = dataSource.filter(item => item.fileUserEnum === "CREATE")[0].userId;
    const params = {
      storeId : this.state.storeId,                           // 机构Id
      id : id,                                              // 文件ID
      userId : record.userId,                               // 被修改权限用户ID
      updateId,                                             // 文件夹创建者ID
      currentRight: record.rights                           // 当前权限
    };
    const { userAuthority } = this.state;
    const menu = (
      <Menu>  
        <Menu.Item key="EDIT">
          <div onClick={() => this.updateFileUserAuthority(params, 0)} >
            {userAuthority[0]}
            <br />
            {
              (folderType === 'FILE') ?
              [<span className='menu-bottom' key='EDIT'>上传/下载/删除/复制/<br />移动/重命名</span>] :
              [<span className='menu-bottom' key='EDIT'>创建/上传/下载/删除/<br />复制/移动/重命名</span> ]
            }
          </div>
        </Menu.Item>
        <Menu.Item key="DOWNLOADING">
          <div onClick={() => this.updateFileUserAuthority(params, 1)}>
            {userAuthority[1]}
            <br />
            <span className='menu-bottom'>下载、复制</span>
          </div>
        </Menu.Item>
        <Menu.Item key="LOOK" >
          <div onClick={() => this.updateFileUserAuthority(params, 2)}>{userAuthority[2]}</div>
          <span className='menu-bottom'>查看</span>
        </Menu.Item>
        <Menu.Divider key='LINE'/>
        <Menu.Item key="REMOVE" >
          <div className='remove' onClick={() => this.removeUser(params, userAuthority[3])}>移除</div>
        </Menu.Item>
      </Menu>     
    )
    
    return menu;
  }

  // 表格信息列表格式
  selectedColumns = () => {
    const selectColumns = [
      {
        title : '头像',
        key : 'avatar',
        dataIndex : 'avatar',
        width : '8%',
        align : 'right',
        render : (value, 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=""/>]
              }
            </div>
          )
        }
      },{
        title : '用户名',
        key : 'adminName',
        dataIndex : 'adminName',
        width : '40%',
        align : 'left',
        render : (value, record) => {  
          return (
            <span className='adminName'>
              { value }
            </span>
          )
        }
      },{
        title : '权限',
        key : 'rights',
        dataIndex : 'rights',
        width : '50%',
        align :'right',
        render : (value, record) => {
          const imgSrcList = ['https://image.xiaomaiketang.com/xm/Th5cKisf6f.png', 'https://image.xiaomaiketang.com/xm/nzAcc6ryTp.png'];
          let num = 0, imgSrc = imgSrcList[0];
          const { iconRotateList } = this.state;

          iconRotateList.map(item => {
            if (item.userId === record.userId) {
              imgSrc = !item.iconRotate ? imgSrcList[0] : imgSrcList[1];
            }
            return imgSrc;
          })
          // 判断不同权限的人所能看到的
          if (record.fileUserEnum === "CREATE") {               // 创建者
            num = 4;
          } else if (record.fileUserEnum === 'SUPER_ADMIN') {       // 学院管理员
            num = 5;
          } else {
            if (record.rights === "LOOK_DOWNLOAD") {
              num = 1;
            } else if (record.rights === "EDIT") {
              num = 0;
            }else if(record.rights=="LOOK"){
              num = 2;
            }
          }
          return (
            <div className='rights'>
              {
                (num === 4 || num === 5) && <span>{this.state.userAuthority[num]}</span>
              }
              <Dropdown 
                overlay={this.renderMenu(record)} 
                trigger={['click']}
                onVisibleChange={() => this.changeIconRotate(record)}
              >
                <span>
                  {
                    num < 4 && 
                    [
                      <span key={num}>{this.state.userAuthority[num]}</span>,
                      <img className='img-type' src={imgSrc} key={imgSrc} alt=""/>
                    ]
                  }
                </span>
              </Dropdown>
            </div>
          )
        }
      }
    ]
    return selectColumns;
  }

  renderTitle = () => {
    return <div className="tip-title" style={{width:200}}>不在名单内的员工不可查看此文件/文件夹</div>
  }

  render() {
    const { isOpen, disk } = this.props;
    const { addManagingMember, dataSource } = this.state;
    const title = '权限管理';
    return (     
      <div>
        {
          // 管理学员页面
          !addManagingMember &&
          <Modal
            footer={null}
            visible={isOpen}
            onCancel={this.handleClose}
            title={title} 
            width={680}
            maskClosable={false}
            closeIcon={<span className="icon iconfont modal-close-icon">&#xe6ef;</span>}
          >
            <div className='managing-header'>
              <div className='managing-left'>
                已有成员
                <Tooltip title={this.renderTitle()} arrowPointAtCenter>                
                  <img src="https://image.xiaomaiketang.com/xm/JbGfBpiPjt.png"  className='tool-tip-left' alt=""/>
                </Tooltip>     
              </div>
              <div className='managing-right' onClick={ () => this.handleChooseModal() }>
                <span className="icon iconfont tool-tip-right">
                  &#xe61f;
                </span>
                添加成员
              </div> 
            </div>   
            <div className='managing-body'>
              <Table 
                // bordered={true}
                columns={this.selectedColumns()}
                dataSource={dataSource}
                rowKey={(record, index) => record.userId}
                showHeader={false}
                size={'middle'}
                scroll={{ y : 300 }}
                pagination={false}
              />
            </div>   
          </Modal> 
        }
        {
          // 选择成员页面
          addManagingMember &&
          <ChooseMembersModal 
            isOpen={addManagingMember}
            handleChooseModal={this.handleChooseModal}
            dataInfo={this.props.dataInfo}
            disk={disk}
          />
        }
      </div>
    )
  }
}

export default ManagingMembersModal;