/*
 * @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 './ChooseMembersModal.less';
import _ from 'underscore';
import WechatApi from '@/common/js/wechatApi';
import WWOpenDataCom from '@/components/WWOpenDataCom';

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();
    this.initWechatConfig();
  }

  initWechatConfig = async () => {
    WechatApi.initConfig({ isAgentConfig: true, url: window.location.href.split('#')[0] }).then(()=>{
      console.info('window.WWOpenData', window.WWOpenData);
  //     if (WWOpenData.checkSession) {
  //       WWOpenData.checkSession({
  //           success() {
  //               console.info('open-data 登录态校验成功')
  //           },
  //           fail() {
  //               console.error('open-data 登录态过期')
  //           },
  //       })
  //   }

  //   if (WWOpenData.on) {
  //     /**
  //      * ww-open-data 元素数据发生变更时触发
  //      */
  //     WWOpenData.on('update', event => {
  //         const openid = event.detail.element.getAttribute('openid')
  //         console.info('渲染数据发生变更', openid, event.detail.hasData)
  //     })
  //     /**
  //      * ww-open-data 获取数据失败时触发
  //      */
  //     WWOpenData.on('error', () => {
  //         console.error('获取数据失败')
  //     })
  // }

  // WWOpenData.bindAll(document.querySelectorAll('ww-open-data'))

    })
    .catch(error=>{
      console.log("error-----",error);
    })
  }
    

  // 获取对应文件相关成员
  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>
                {/* <WWOpenDataCom type="userName" openid={name}/> */}
              </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 (User.getVersion() && User.getVersion().whetherReachUserNum) {
              message.error("添加失败，企业使用人数超出限制")
              return
            }
            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 : college,
                      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'>
              <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: false, isOpen: true })  
            }}
            onCancel={() => {
              this.handleClose();
              this.setState({ openSetModal: false });
            }}
            onOk={(list) => {
              this.addUser(list);
            }}
          />
        }
      </div>
    )
  }
}

export default ChooseMembersModal;