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

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

const { Search } = Input;

class ChooseMembersModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isOpen: props.isOpen,
      allUserList : [],                               // 所有成员列表
      selectUserList: [],                             // 已选则成员
      temporaryList: [],                              // 临时学员成员列表（搜索时使用）
      instId : window.currentUserInstInfo.instId,     // 机构Id
      searchKey : null,                                 // 搜索内容  
      selectedRowKeys : [],                            // 勾选的成员  
      query: {
        current: 1,
        size: 300,
        enterpriseId: User.getEnterpriseId(),
        storeId: User.getStoreId(),
        visibleTypeEnum: props.type,
      },
      openSetModal: false,
      selectObject: {},
    }
  }

  componentDidMount() {
    this.getUserAuthority();
  }

  // 获取对应文件相关成员
  getUserAuthority = (searchKey='') => {
    const { query } = this.state;
    query.name = searchKey;
    Service.Hades('public/hades/getEnterpriseVisibleUserPage', query).then((res) => {
      if (res.result) {
        this.setState({
          allUserList: res.result.records,
        })
      }
    })
  }

  // 勾选成员
  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.enterpriseVisibleUserId));
      
      temporaryList.map(item => {
        if (!_temporaryIdList.includes(item.enterpriseVisibleUserId)) {
          _temporaryIdList.push(item.enterpriseVisibleUserId);
          _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.enterpriseVisibleUserId);
    selectUserList = selectUserList.filter(item => item.enterpriseVisibleUserId !== user.enterpriseVisibleUserId);
    this.setState({
      selectedRowKeys,
      selectUserList
    })
    
  }

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

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

  // 批量添加成员(点击确定)
  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.handleClose(true); 
        this.setState({
          temporaryList: [],
          openSetModal: false,
        })   
      }
    })
  }

  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) => {
      if (res.code === '200') {
      this.handleClose(true); 
      this.setState({
          temporaryList: []
        })   
      }
    })
  }

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

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

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

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

          return (
            <div className='avatar'>
              <span className="icon iconfont avatar-icon">&#xe84a;</span>
              <Tooltip title={name}>
                <span className='userImg'>{name}</span>
              </Tooltip>
            </div>  
          )
        }
      }
    ]
    return selectColumns
  }

  // 信息列表——右边
  selectedColumnsRight = () => {
    const selectColumns = [
      {
        title: '学员名',
        key: 'nameRight',
        dataIndex: 'name',
        width: '70%',
        render: (value, record) => {
          const { name = '', avatar } = record;
          return (
            <div className='avatar'>
              <span className="icon iconfont avatar-icon">&#xe84a;</span>
              <Tooltip title={name}>
                <span className='userImg'>{name}</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;
  }

  render() {
    const { type } = this.props;
    const {
      selectUserList,
      allUserList, 
      searchKey, 
      selectedRowKeys, 
      openSetModal, 
      isOpen,
      selectObject,
    } = this.state;
    const title = type === 'USER' ? '添加员工' : '添加学员';
    return (    
      <div>
        {/* 添加学员页面 */}
        <Modal
          className="choose-member-modal"
          visible={isOpen}
          onCancel={() => this.handleClose()}
          onOk={() => {
            if (_.isEmpty(selectUserList)) {
              message.warning(type === 'USER' ? '请选择员工' : '请选择学员')
              return null;
            }
            type === 'USER' ? this.setState({ openSetModal: true, isOpen: false }) : this.addCustomer();
          }}
          okText={type === 'USER' ? '下一步' : '确定'}
          title={title}
          width={680}
          maskClosable={false}
          okButtonProps={!_.isEmpty(selectUserList) ? {} : {
            disabled: true
          }}
          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='搜索成员'
                  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'>
                  <XMTable 
                    rowKey={(record) => record.enterpriseVisibleUserId}
                    dataSource={allUserList}
                    columns={this.selectedColumnsLeft()}               
                    pagination={false}
                    scroll={{ y: 290}}
                    renderEmpty={{
                      image: searchKey ? search : '',
                      description: <div>
                        <div style={{ color: '#333' }}>暂无数据</div>
                        <div style={{ color: '#666', padding: '0 32px', fontSize: '12px' }}>需要先将员工添加到企微可见范围后，员工才会出现在这里</div>
                      </div>
                    }}
                    size={'small'}
                    rowSelection={{
                      columnWidth : 63,
                      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'>已选择{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'>
                <Table 
                  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: false, isOpen: true })  
            }}
            onCancel={() => {
              this.handleClose();
              this.setState({ openSetModal: false });
            }}
            onOk={(list) => {
              this.addUser(list);
            }}
          />
        }
      </div>
    )
  }
}

export default ChooseMembersModal;