/*
 * @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 [checkedCollaboratorList, setCheckedCollaboratorList] = useState(props.currentCollaboratorList || []); // 勾选的协同人员
  const [checkedCollaboratorKeys, setCheckedCollaboratorKeys] = useState(props.currentCollaboratorList.map((item) => item.checkedId) || []);
  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.checkedName = item.nickName;
        item.checkedId = item.userId;
        item.checked = checkedCollaboratorKeys.includes(item.checkedId);
        return item;
      });
      const checkedEmployeeList = records.filter((item) => item.checked);
      const _checkedAll = records.length === checkedEmployeeList.length;
      setEmployeeList(records);
      setAllChecked(_checkedAll);
    });
  }

  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 handleCheckedCollaborator(e) {
    const { value, checked } = e.target;
    let _checkedCollaboratorList = [...checkedCollaboratorList];
    let _employeeList = [];
    if (checked) {
      _employeeList = employeeList.map((item) => {
        if (item.checkedId === value.checkedId) {
          item.checked = true;
        }
        return item;
      });
      _checkedCollaboratorList.push({ ...value, checked: true });
    } else {
      _employeeList = employeeList.map((item) => {
        if (item.checkedId === value.checkedId) {
          item.checked = false;
        }
        return item;
      });
      _checkedCollaboratorList = checkedCollaboratorList.filter((item) => item.checkedId !== value.checkedId);
    }
    const _checkedCollaboratorKeys = _checkedCollaboratorList.map((item) => item.checkedId);
    const checkedEmployeeList = _employeeList.filter((item) => item.checked);
    const _checkedAll = employeeList.length === checkedEmployeeList.length;
    setEmployeeList(_employeeList);
    setCheckedCollaboratorList(_checkedCollaboratorList);
    setCheckedCollaboratorKeys(_checkedCollaboratorKeys);
    setAllChecked(_checkedAll);
  }

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

    const _checkedCollaboratorList = checkedCollaboratorList.filter((item) => item.checkedId !== record.checkedId);
    const _checkedCollaboratorKeys = _checkedCollaboratorList.map((item) => item.checkedId);
    const checkedEmployeeList = _employeeList.filter((item) => item.checked);
    const _checkedAll = employeeList.length === checkedEmployeeList.length;
    setAllChecked(_checkedAll);
    setCheckedCollaboratorList(_checkedCollaboratorList);
    setCheckedCollaboratorKeys(_checkedCollaboratorKeys);
    setEmployeeList(_employeeList);
  }

  function clearCheckedCollaborator() {
    const _employeeList = employeeList.map((item) => {
      item.checked = false;
      return item;
    });
    setEmployeeList(_employeeList);
    setCheckedCollaboratorList([]);
    setCheckedCollaboratorKeys([]);
    setAllChecked(false);
  }

  function handleCheckedAll(e) {
    let _employeeList = [];
    let _checkedCollaboratorList = [];
    if (e.target.checked) {
      _employeeList = employeeList.map((item) => {
        item.checked = true;
        return item;
      });
      const filterList = employeeList.filter((item) => {
        return !checkedCollaboratorKeys.includes(item.checkedId);
      });
      _checkedCollaboratorList = checkedCollaboratorList.concat([...filterList]);
    } else {
      _employeeList = employeeList.map((item) => {
        item.checked = false;
        return item;
      });
      const removeIds = _employeeList.map((item) => item.checkedId);
      _checkedCollaboratorList = checkedCollaboratorList.filter((item) => {
        return !removeIds.includes(item.checkedId);
      });
    }

    const _checkedCollaboratorKeys = _checkedCollaboratorList.map((item) => item.checkedId);

    setEmployeeList(_employeeList);
    setCheckedCollaboratorList(_checkedCollaboratorList);
    setCheckedCollaboratorKeys(_checkedCollaboratorKeys);
    setAllChecked(e.target.checked);
  }

  return (
    <Modal
      className='choose-collaborator-modal'
      title='选择协同者'
      visible={true}
      onCancel={props.onClose}
      onOk={() => {
        props.onConfirm(checkedCollaboratorList);
        props.onClose();
      }}
      width={680}
      maskClosable={false}>
      <div className='collaborator-container'>
        <div className='left-list'>
          <Search
            placeholder='搜索员工'
            value={searchKey}
            style={{ paddingRight: 16 }}
            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={handleCheckedAll}>
                  全部
                </Checkbox>
              }
              dataSource={employeeList}
              renderItem={(item, index) => (
                <List.Item>
                  <Checkbox checked={item.checked} value={item} key={item.checkedId} onChange={handleCheckedCollaborator}>
                    <div className='employee-item'>
                      <span className='item-title'>
                        <span className='icon iconfont title-icon'>&#xe84a;</span>
                        <Tooltip title={<WWOpenDataCom type='userName' openid={item.checkedName} />}>
                          <span className='title-name'>
                            <WWOpenDataCom type='userName' openid={item.checkedName} />
                          </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={clearCheckedCollaborator}>
              清空
            </span>
          </div>
          <div className='data-body'>
            {checkedCollaboratorList.map((item, index) => {
              return (
                <div className='selected-item'>
                  <span className='item-title'>
                    <span className='icon iconfont title-icon'>&#xe84a;</span>
                    <Tooltip title={<WWOpenDataCom type='userName' openid={item.checkedName} />}>
                      <span className='title-name'>
                        <WWOpenDataCom type='userName' openid={item.checkedName} />
                      </span>
                    </Tooltip>
                  </span>
                  <span className='icon iconfont clear-icon' onClick={() => removeCheckedCollaborator(item)}>
                    &#xe717;
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </Modal>
  );
}

export default ChooseCollaboratorModal;
