/*
 * @Author: yuananting
 * @Date: 2021-08-05 17:09:36
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-16 14:47:51
 * @Description: 新建培训任务-选择指派对象
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useState, useEffect, useRef } from 'react';
import { Modal, Tree, Tooltip, AutoComplete, Tabs, Input, Checkbox } from 'antd';
import User from '@/common/js/user';
import { DepType } from '@/domains/store-domain/constants';
import StoreService from '@/domains/store-domain/storeService';
import WWOpenDataCom from '@/components/WWOpenDataCom';
import './ChooseAssignorModal.less';

const { TabPane } = Tabs;
const { DirectoryTree } = Tree;
const { Search } = Input;

function ChooseAssignorModal(props) {
  const AssignTypeEnum = {
    departMentTab: 'SECTION',
    postGrouptab: 'POST',
    customGroupTab: 'CUSTOM',
  };
  const [structureData, setStructureData] = useState([]);
  const [activeKey, setActiveKey] = useState('departMentTab');
  const [checkedAssignorList, setCheckedAssignorList] = useState(props.currentAssignorList || []); // 勾选的指派对象
  const [checkedAssignorKeys, setCheckedAssignorKeys] = useState(props.currentAssignorList.map((item) => item.checkedId) || []);
  const [completeOptions, setCompleteOption] = useState([]);
  const [open, setOpen] = useState(false);
  const [queryName, setQueryName] = useState(''); // 搜索框内的值
  const queryNameRef = useRef(null);
  const timer = useRef(null);

  useEffect(() => {
    queryNameRef.current = queryName;
    setOpen(!!queryName);
    clearTimeout(timer.current);
    timer.current = setTimeout(() => {
      if (!!queryName) return getCompleteOptionData(queryNameRef.current);
      setCompleteOption([]);
    }, 500);
  }, [queryName]);

  useEffect(() => {
    setQueryName(''); // 切换tab时搜索置空
    setCompleteOption([]);
    setStructureData([]);
    getStructureData();
  }, [activeKey]);

  function getStructureData() {
    const params = {
      depType: DepType[activeKey],
      enterpriseId: User.getEnterpriseId(),
      source: 0, // 0代表来自企培
      storeId: User.getStoreId(),
      userId: User.getUserId(),
      whetherCount: false,
      distinct: false,
      queryType: 'CUSTOMER',
    };
    StoreService.getDepartmentUserNotPage(params).then((res) => {
      const { result = [] } = res;

      const structureData = handleStructureData(result.departmentVOList);
      const checkedKeys = checkedAssignorList.map((item) => item.checkedId);

      setStructureData(structureData);
      setCheckedAssignorKeys(checkedKeys);
    });
  }

  function handleStructureData(dataArray) {
    const _dataArray = dataArray.map((item, index) => {
      item.title = '';
      item.checkedId = item.storeCustomerId || item.id;
      item.checkedType = item.storeCustomerId ? 'CUSTOMER' : AssignTypeEnum[activeKey];
      item.checkedName = item.storeCustomerId ? item.userName : item.name;
      item.key = item.checkedId;
      item.children = [];
      if (activeKey !== 'departMentTab' && item.depLevel === 0) {
        item.disableCheckbox = true;
      }
      if (item.departmentUserVOList) {
        item.children = item.departmentUserVOList;
      }
      if (item.sonDepartmentVOList) {
        item.children = [...item.children, ...item.sonDepartmentVOList];
      }
      if (item.children.length > 0) {
        handleStructureData(item.children);
      } else {
        delete item.children;
      }
      return item;
    });

    return _dataArray;
  }

  function onCheckAssignor(key, e) {
    const { node, checked } = e;

    let _checkedAssignorList = [...checkedAssignorList];

    if (checked) {
      _checkedAssignorList.push(node);
    } else {
      _checkedAssignorList = _checkedAssignorList.filter((item) => {
        return item.checkedId !== node.checkedId;
      });
    }

    const _checkedAssignorKeys = _checkedAssignorList.map((item) => item.checkedId);
    setCheckedAssignorKeys(_checkedAssignorKeys);
    setCheckedAssignorList(_checkedAssignorList);
  }

  function removeCheckedAssignor(item) {
    const _checkedAssignorList = checkedAssignorList.filter((childItem) => childItem.checkedId !== item.checkedId);
    const _checkedAssignorKeys = _checkedAssignorList.map((item) => item.checkedId);
    setCheckedAssignorKeys(_checkedAssignorKeys);
    setCheckedAssignorList(_checkedAssignorList);
  }

  function clearCheckedAssignor() {
    setCheckedAssignorKeys([]);
    setCheckedAssignorList([]);
  }

  function renderTitle(title) {
    return <span className='catalog-title'>{title}</span>;
  }

  function renderItem(record, type) {
    return {
      value: record.userName || record.name,
      label: (
        <Checkbox>
          <div
            className='search-result-item'
            style={{
              display: 'flex',
              justifyContent: 'space-between',
            }}
            depId={record.id}
            type={type}>
            {type === 'user' ? (
              <div className='search-result-item__left'>
                <WWOpenDataCom type='userName' openid={record.userName} />
              </div>
            ) : (
              <div className='search-result-item__left'>
                {activeKey === 'departMentTab' ? <WWOpenDataCom type='departmentName' openid={record.name} /> : <span>{record.name}</span>}
              </div>
            )}
            {type === 'user' && (
              <div className='search-result-item__right'>
                <Tooltip title={<div>{handleDepName(record.depNamesList)}</div>} placement='top' arrowPointAtCenter>
                  {record.depNamesList.map((item, index) => {
                    return (
                      <span>
                        <WWOpenDataCom type='departmentName' openid={item} />
                        {index < record.depNamesList.length - 1 ? ';' : ''}
                      </span>
                    );
                  })}
                </Tooltip>
              </div>
            )}
            {type === 'post' && (
              <span type='post' openid={record.parentName}>
                {record.parentName}
              </span>
            )}
          </div>
        </Checkbox>
      ),
    };
  }

  function getCompleteOptionData(value) {
    setCompleteOption([]);
    const params = {
      depType: DepType[activeKey],
      queryName: value,
      enterpriseId: User.getEnterpriseId(),
      source: 0, //0代表来自企培
      storeId: User.getStoreId(),
      userId: User.getUserId(),
      whetherCount: false,
      distinct: false,
      queryType: 'CUSTOMER',
    };
    StoreService.getDepartmentUser(params).then((res) => {
      const _completeOptions = [];
      const userObj = {};
      const departmentGroupObj = {};
      const postobj = {};
      const { result = {} } = res;
      const { departmentUserVOList = [], departmentVOList = [], subLevelDepartmentVOList = [] } = result;
      if (departmentUserVOList.length > 0) {
        userObj.label = renderTitle('学员');
        userObj.options = departmentUserVOList.map((item, index) => {
          return renderItem(item, 'user');
        });
      }
      if (departmentVOList.length > 0) {
        switch (activeKey) {
          case 'departMentTab':
            departmentGroupObj.label = renderTitle('部门');
            break;
          case 'postGrouptab':
            departmentGroupObj.label = renderTitle('岗位组');
            break;
          case 'customGroupTab':
            departmentGroupObj.label = renderTitle('分组集合');
            break;
          default:
            break;
        }
        departmentGroupObj.options = departmentVOList.map((item, index) => {
          return renderItem(item, 'group');
        });
      }
      if (subLevelDepartmentVOList.length > 0) {
        switch (activeKey) {
          case 'postGrouptab':
            postobj.label = renderTitle('岗位');
            break;
          case 'customGroupTab':
            postobj.label = renderTitle('分组');
            break;
          default:
            break;
        }
        postobj.options = subLevelDepartmentVOList.map((item, index) => {
          return renderItem(item, 'post');
        });
      }
      if (Object.keys(userObj).length !== 0) {
        _completeOptions.push(userObj);
      }
      if (Object.keys(postobj).length !== 0) {
        _completeOptions.push(postobj);
      }
      if (Object.keys(departmentGroupObj).length !== 0) {
        _completeOptions.push(departmentGroupObj);
      }

      setCompleteOption(_completeOptions);
    });
  }

  // 搜索空状态渲染;
  function notFoundContentNode() {
    return (
      <div className='empty-con'>
        <img src='https://image.xiaomaiketang.com/xm/wRDrb2pJFb.png' className='empty-img' />
        <div className='empty-text'>暂无数据</div>
      </div>
    );
  }

  function confirmSearchSelect(value, option) {
    const param = {};
    setOpen(false);
    setQueryName(value);
    if (option.label.props.type === 'user') {
      param.queryName = value;
    } else {
      param.id = option.label.props.depId;
    }
    props.searchUserList(param, activeKey, 1);
  }

  // 弱提示渲染
  function handlePlaceHolder() {
    let placeholder = '';
    switch (activeKey) {
      case 'departMentTab':
        placeholder = '搜索学员、部门';
        break;
      case 'postGrouptab':
        placeholder = '搜索学员、岗位、岗位组';
        break;
      case 'customGroupTab':
        placeholder = '搜索学员、分组、分组集合';
        break;
      default:
        break;
    }
    return placeholder;
  }

  function handleDepName(depArray) {
    const depArrayDom = depArray.map((item, index) => {
      return (
        <span>
          <WWOpenDataCom type='departmentName' openid={item} />；
        </span>
      );
    });
    return depArrayDom;
  }

  return (
    <Modal
      className='choose-assignor-modal'
      title='添加指派学员'
      visible={true}
      onCancel={props.onClose}
      onOk={() => {
        props.onConfirm(checkedAssignorList);
      }}
      width={680}
      maskClosable={false}>
      <div className='assignor-container'>
        <div className='left-list'>
          <AutoComplete
            dropdownClassName='left-search-dropdown'
            dropdownMatchSelectWidth={272}
            allowClear
            onChange={(value) => setQueryName(value)}
            notFoundContent={notFoundContentNode()}
            value={queryName}
            open={open}
            onFocus={() => {
              setOpen(true);
            }}
            onBlur={() => {
              setOpen(false);
            }}
            style={{
              width: 272,
            }}
            options={completeOptions}
            // onSelect={confirmSearchSelect}
            placeholder={handlePlaceHolder()}>
            <Search style={{ width: 272 }} enterButton={<span className='icon iconfont'>&#xe832;</span>} />
          </AutoComplete>
          <div className='data-body'>
            <Tabs size={'small'} onChange={(key) => setActiveKey(key)}>
              <TabPane key='departMentTab' tab='部门'></TabPane>
              <TabPane key='postGrouptab' tab='岗位组'></TabPane>
              <TabPane key='customGroupTab' tab='自定义分组'></TabPane>
            </Tabs>
            <div className='tree-con'>
              <DirectoryTree
                defaultExpandAll
                checkable
                checkStrictly
                showIcon={false}
                treeData={structureData}
                checkedKeys={checkedAssignorKeys}
                onCheck={(key, e) => onCheckAssignor(key, e)}
                titleRender={(nodeData) => {
                  return (
                    <div className='node-title-div'>
                      {nodeData.checkedType === 'CUSTOMER' ? (
                        <div>
                          <span className='icon iconfont title-icon'>&#xe603;</span>
                          <span className='title-name'>
                            <WWOpenDataCom type='userName' openid={nodeData.checkedName} />
                          </span>
                        </div>
                      ) : (
                        <div>
                          <span className='icon iconfont title-icon'>&#xe604;</span>
                          <span className='title-name'>
                            <WWOpenDataCom type='departmentName' openid={nodeData.checkedName} />
                          </span>
                        </div>
                      )}
                    </div>
                  );
                }}
              />
            </div>
          </div>
        </div>
        <div className='right-list'>
          <div className='header-line'>
            <span className='tip-text'>已选择</span>
            <span className='clear-btn' onClick={clearCheckedAssignor}>
              清空
            </span>
          </div>
          <div className='data-body'>
            {checkedAssignorList.map((item, index) => {
              return (
                <div className='selected-item'>
                  <span className='item-title'>
                    {item.checkedType === 'CUSTOMER' ? (
                      <div>
                        <span className='icon iconfont title-icon'>&#xe603;</span>
                        <Tooltip title={<WWOpenDataCom type='userName' openid={item.checkedName} />}>
                          <span className='title-name'>
                            <WWOpenDataCom type='userName' openid={item.checkedName} />
                          </span>
                        </Tooltip>
                      </div>
                    ) : (
                      <div>
                        <span className='icon iconfont title-icon'>&#xe604;</span>
                        <Tooltip title={<WWOpenDataCom type='departmentName' openid={item.checkedName} />}>
                          <span className='title-name'>
                            <WWOpenDataCom type='departmentName' openid={item.checkedName} />
                          </span>
                        </Tooltip>
                      </div>
                    )}
                  </span>
                  <span className='icon iconfont clear-icon' onClick={() => removeCheckedAssignor(item)}>
                    &#xe717;
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </Modal>
  );
}

export default ChooseAssignorModal;
