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

import React, { useState, useEffect } from 'react';
import { Modal, Input, Tooltip, List, Checkbox } 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 StoreService from '@/domains/store-domain/storeService';
import search from '@/common/lottie/search';
import './ChooseCollaboratorModal.less';
import WWOpenDataCom from '@/components/WWOpenDataCom';

import _ from 'underscore';

const { Search } = Input;

function ChooseCollaboratorModal(props) {
  const [searchKey, setSearchKey] = useState(''); // 搜索内容
  const [employeeList, setEmployeeList] = useState([]); // 员工列表
  const [seletedCollaboratorList, setSeletedCollaboratorList] = useState(props.currentCollaboratorList || []); // 勾选的协同人员
  const [allChecked, setAllChecked] = useState(false);

  useEffect(() => {
    getEmployeeList();
  }, [searchKey]);

  function getEmployeeList() {
    const params = {
      current: 1,
      size: 999,
      nickName: searchKey,
      phone: '',
      roleCodes: [],
    };
    StoreService.getEmployeeList(params).then((res) => {
      const { records } = res.result;
      records.map((item) => {
        item.checked = false;
        seletedCollaboratorList.map((childItem) => {
          if (item.id === childItem.id) {
            item.checked = true;
          }
          return childItem;
        });
        return item;
      });
      if (props.currentCollaboratorList.length === records.length) {
        setAllChecked(true);
      }
      setEmployeeList(records);
    });
  }

  function renderDepItem(record) {
    if (!record.depNameList) {
      return <span>-</span>;
    }
    return record.depNameList.map((item, index) => {
      return (
        <span>
          <WWOpenDataCom type='departmentName' openid={item} />
          {index < record.depNameList.length - 1 ? '、' : ''}
        </span>
      );
    });
  }

  function handleSeletedCollaborator(e) {
    const { value, checked } = e.target;
    let _seletedCollaboratorList = [...seletedCollaboratorList];
    let _employeeList = [];
    if (checked) {
      _employeeList = employeeList.map((item) => {
        if (item.id === value.id) {
          item.checked = true;
        }
        return item;
      });
      _seletedCollaboratorList.push({ ...value, checked: true });
    } else {
      _employeeList = employeeList.map((item) => {
        if (item.id === value.id) {
          item.checked = false;
        }
        return item;
      });
      _seletedCollaboratorList = seletedCollaboratorList.filter((item) => item.id !== value.id);
    }

    setEmployeeList(_employeeList);
    setSeletedCollaboratorList(_seletedCollaboratorList);
  }

  function removeSelectedCollaborator(record) {
    const _employeeList = employeeList.map((item) => {
      if (item.id === record.id) {
        item.checked = false;
      }
      return item;
    });

    const _seletedCollaboratorList = seletedCollaboratorList.filter((item) => item.id !== record.id);

    setEmployeeList(_employeeList);
    setSeletedCollaboratorList(_seletedCollaboratorList);
  }

  function clearSelectedCollaborator() {
    const _employeeList = employeeList.map((item) => {
      item.checked = false;
      return item;
    });
    setEmployeeList(_employeeList);
    setSeletedCollaboratorList([]);
    setAllChecked(false);
    props.onConfirm([]);
  }

  function handleSeletedAll(e) {
    let _employeeList = [];
    let _seletedCollaboratorList = [];
    if (e.target.checked) {
      _employeeList = employeeList.map((item) => {
        item.checked = true;
        return item;
      });
      _seletedCollaboratorList = seletedCollaboratorList.concat([..._employeeList]);
    } else {
      _employeeList = employeeList.map((item) => {
        item.checked = false;
        return item;
      });
      const removeIds = _employeeList.map((item) => item.id);
      _seletedCollaboratorList = seletedCollaboratorList.filter((item) => {
        return removeIds.indexOf(item.id) < 0;
      });
    }

    setEmployeeList(_employeeList);
    setSeletedCollaboratorList(_seletedCollaboratorList);
    setAllChecked(e.target.checked);
  }

  return (
    <Modal
      className='choose-collaborator-modal'
      title='选择协同者'
      visible={true}
      onCancel={props.onClose}
      onOk={() => {
        props.onConfirm(seletedCollaboratorList);
        props.onClose();
      }}
      width={680}
      maskClosable={false}>
      <div className='collaborator-container'>
        <div className='left-list'>
          <Search
            placeholder='搜索员工'
            value={searchKey}
            onChange={(e) => setSearchKey(e.target.value.trim())}
            onSearch={getEmployeeList}
            className='search search-input'
            enterButton={<span className='icon iconfont'>&#xe832;</span>}
          />
          <div className='data-body'>
            <List
              header={
                <Checkbox checked={allChecked} onChange={handleSeletedAll}>
                  全部
                </Checkbox>
              }
              dataSource={employeeList}
              renderItem={(item, index) => (
                <List.Item>
                  <Checkbox checked={item.checked} value={item} key={item.id} onChange={handleSeletedCollaborator}>
                    <div className='employee-item'>
                      <span className='user-name'>
                        <span className='icon iconfont avatar-icon'>&#xe84a;</span>
                        <Tooltip title={<WWOpenDataCom type='userName' openid={item.nickName} />}>
                          <span className='user-name'>
                            <WWOpenDataCom type='userName' openid={item.nickName} />
                          </span>
                        </Tooltip>
                      </span>
                      <span className='dep-info'>{renderDepItem(item)}</span>
                    </div>
                  </Checkbox>
                </List.Item>
              )}
            />
          </div>
        </div>
        <div className='right-list'>
          <div className='header-line'>
            <span className='tip-text'>已选择</span>
            <span className='clear-btn' onClick={clearSelectedCollaborator}>
              清空
            </span>
          </div>
          <div className='data-body'>
            {seletedCollaboratorList.map((item, index) => {
              return (
                <div className='selected-item'>
                  <span className='item-name'>
                    <span className='icon iconfont avatar-icon'>&#xe84a;</span>
                    <Tooltip title={<WWOpenDataCom type='userName' openid={item.nickName} />}>
                      <span className='name-text'>
                        <WWOpenDataCom type='userName' openid={item.nickName} />
                      </span>
                    </Tooltip>
                  </span>
                  <span className='icon iconfont clear-icon' onClick={() => removeSelectedCollaborator(item)}>
                    &#xe717;
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </Modal>
  );
}

export default ChooseCollaboratorModal;
