/*
 * @Author: yuananting
 * @Date: 2021-08-12 16:27:38
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-17 19:10:02
 * @Description: 新建培训任务-选择协同人员
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */

import React, { useState, useEffect } from 'react';
import { Modal, Input, Tooltip, List, Checkbox } from 'antd';
import StoreService from '@/domains/store-domain/storeService';
import './ChooseCollaboratorModal.less';
import WWOpenDataCom from '@/components/WWOpenDataCom';
import LottieIcon from '@/components/LottieIcon';

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.id;
        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 = item.checkedId === props.createId;
      return item;
    });
    const createrItem = checkedCollaboratorList.filter((item) => item.checkedId === props.createId);
    setEmployeeList(_employeeList);
    setCheckedCollaboratorList(createrItem);
    setCheckedCollaboratorKeys([props.createId]);
    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 = item.checkedId === props.createId;
        return item;
      });
      const removeIds = _employeeList.filter((item) => !item.checked).map((childItem) => childItem.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'>
            <Choose>
              <When condition={employeeList.length > 0}>
                <List
                  header={
                    <Checkbox checked={allChecked} onChange={handleCheckedAll}>
                      全部
                    </Checkbox>
                  }
                  dataSource={employeeList}
                  renderItem={(item, index) => (
                    <List.Item>
                      <Checkbox
                        checked={item.checked}
                        value={item}
                        key={item.checkedId}
                        disabled={item.checkedId === props.createId}
                        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>
                  )}
                />
              </When>
              <Otherwise>
                <LottieIcon title='搜索无结果' type='search' size={150} />
              </Otherwise>
            </Choose>
          </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 ${item.checkedId === props.createId && 'disabled'}`}
                    onClick={() => removeCheckedCollaborator(item)}>
                    &#xe717;
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </Modal>
  );
}

export default ChooseCollaboratorModal;
