/*
 * @Author: yuananting
 * @Date: 2021-08-05 17:09:36
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-18 16:23:22
 * @Description: 新建培训任务-选择指派学员
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useState, useEffect, useRef } from 'react';
import { Modal, Tree, Tooltip, 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 _ from 'underscore';
import './ChooseAssignorModal.less';
import $ from 'jquery';
import LottieIcon from '@/components/LottieIcon';

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

function ChooseAssignorModal(props) {
  const AssignTypeEnum = {
    departMentTab: 'SECTION',
    postGrouptab: 'POST',
    customGroupTab: 'CUSTOM',
  };

  const DeptTypeEnum = {
    departMentTab: ['部门'],
    postGrouptab: ['岗位', '岗位组'],
    customGroupTab: ['分组', '分组集合'],
  };
  const [dropDownVisible, setDropDownVisible] = useState(false);
  const [structureData, setStructureData] = useState([]);
  const [activeKey, setActiveKey] = useState('departMentTab');
  const [checkedAssignorList, setCheckedAssignorList] = useState(props.currentAssignorList || []); // 勾选的指派学员
  const [checkedAssignorKeys, setCheckedAssignorKeys] = useState(handleCheckedKeys(props.currentAssignorList, props.currentAssignorList, []));
  const [queryName, setQueryName] = useState(''); // 搜索框内的值
  const [departmentUserVOList, setDepartmentUserVOList] = useState([]);
  const [departmentVOList, setDepartmentVOList] = useState([]);
  const [subLevelDepartmentVOList, setSubLevelDepartmentVOList] = useState([]);

  const queryNameRef = useRef(null);
  const timer = useRef(null);

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

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

  useEffect(() => {
    documentClick();
  }, []);

  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 = handleCheckedKeys(structureData, checkedAssignorList, []);
      setStructureData(structureData);
      setCheckedAssignorKeys(checkedKeys);
    });
  }

  function handleCheckedKeys(dataArray, checkedAssignorList, checkedKeys) {
    dataArray.map((item, index) => {
      if (checkedAssignorList.find((checkedItem) => checkedItem.checkedId === item.checkedId)) {
        checkedKeys.push(item.id);
      }
      if (item.children?.length > 0) {
        handleCheckedKeys(item.children, checkedAssignorList, checkedKeys);
      }
    });
    return 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.id;
      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 = handleCheckedKeys(structureData, _checkedAssignorList, []);
    setCheckedAssignorList(_checkedAssignorList);
    setCheckedAssignorKeys(_checkedAssignorKeys);
  }

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

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

  function getCompleteOptionData(value) {
    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 { result = {} } = res;
      const { departmentUserVOList = [], departmentVOList = [], subLevelDepartmentVOList = [] } = result;
      const _departmentUserVOList = departmentUserVOList.map((item) => {
        item.checkedName = item.userName;
        item.checkedId = item.storeCustomerId;
        item.checked = checkedAssignorList.find((checkedItem) => checkedItem.checkedId === item.checkedId);
        item.checkedType = 'CUSTOMER';
        return item;
      });
      const _departmentVOList = departmentVOList.map((item) => {
        item.disabled = activeKey !== 'departMentTab';
        item.checkedName = item.name;
        item.checkedId = item.id;
        item.checked = checkedAssignorList.find((checkedItem) => checkedItem.checkedId === item.checkedId);
        item.checkedType = AssignTypeEnum[activeKey];
        return item;
      });

      const _subLevelDepartmentVOList = subLevelDepartmentVOList.map((item) => {
        item.checkedName = item.name;
        item.checkedId = item.id;
        item.checked = checkedAssignorList.find((checkedItem) => checkedItem.checkedId === item.checkedId);
        item.checkedType = AssignTypeEnum[activeKey];
        return item;
      });
      setDepartmentUserVOList(_departmentUserVOList);
      setDepartmentVOList(_departmentVOList);
      setSubLevelDepartmentVOList(_subLevelDepartmentVOList);
    });
  }

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

  function handleCheckedSearchAssignor(e, type) {
    const { value, checked } = e.target;
    let _departmentUserVOList = [...departmentUserVOList];
    let _departmentVOList = [...departmentVOList];
    let _subLevelDepartmentVOList = [...subLevelDepartmentVOList];
    let _checkedAssignorList = [...checkedAssignorList];
    if (type === 'CUSTOMER') {
      if (checked) {
        _departmentUserVOList = departmentUserVOList.map((item) => {
          if (item.checkedId === value.checkedId) {
            item.checked = true;
          }
          return item;
        });
        _checkedAssignorList.push({ ...value, checked: true });
      } else {
        _departmentUserVOList = departmentUserVOList.map((item) => {
          if (item.checkedId === value.checkedId) {
            item.checked = false;
          }
          return item;
        });
        _checkedAssignorList = _checkedAssignorList.filter((item) => item.checkedId !== value.checkedId);
      }
      setDepartmentUserVOList(_departmentUserVOList);
    }

    if (type === 'DEPART') {
      if (checked) {
        _departmentVOList = departmentVOList.map((item) => {
          if (item.checkedId === value.checkedId) {
            item.checked = true;
          }
          return item;
        });
        _checkedAssignorList.push({ ...value, checked: true });
      } else {
        _departmentVOList = departmentVOList.map((item) => {
          if (item.checkedId === value.checkedId) {
            item.checked = false;
          }
          return item;
        });
        _checkedAssignorList = _checkedAssignorList.filter((item) => item.checkedId !== value.checkedId);
      }
      setDepartmentVOList(_departmentVOList);
    }

    if (type === 'GROUP') {
      if (checked) {
        _subLevelDepartmentVOList = subLevelDepartmentVOList.map((item) => {
          if (item.checkedId === value.checkedId) {
            item.checked = true;
          }
          return item;
        });
        _checkedAssignorList.push({ ...value, checked: true });
      } else {
        _subLevelDepartmentVOList = subLevelDepartmentVOList.map((item) => {
          if (item.checkedId === value.checkedId) {
            item.checked = false;
          }
          return item;
        });
        _checkedAssignorList = subLevelDepartmentVOList.filter((item) => item.checkedId !== value.checkedId);
      }
      setSubLevelDepartmentVOList(_subLevelDepartmentVOList);
    }

    const _checkedAssignorKeys = handleCheckedKeys(structureData, _checkedAssignorList, []);
    setCheckedAssignorKeys(_checkedAssignorKeys);
    setCheckedAssignorList(_checkedAssignorList);
  }

  // 弱提示渲染
  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;
  }

  function renderOptions() {
    return (
      <div className='left-search-dropdown' id='left-search-dropdown'>
        {departmentUserVOList.length > 0 && (
          <div>
            <div>学员</div>
            {departmentUserVOList.map((record) => {
              return (
                <Checkbox checked={record.checked} value={record} key={record.checkedId} onChange={(e) => handleCheckedSearchAssignor(e, 'CUSTOMER')}>
                  <div className='search-result-item' depId={record.checkedId} type={type}>
                    <div className='search-result-item__left'>
                      <WWOpenDataCom type='userName' openid={record.userName} />
                    </div>
                    <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>
                  </div>
                </Checkbox>
              );
            })}
          </div>
        )}
        {subLevelDepartmentVOList.length > 0 && (
          <div>
            <div>{DeptTypeEnum[activeKey][0]}</div>
            {subLevelDepartmentVOList.map((record) => {
              return (
                <Checkbox checked={record.checked} value={record} key={record.checkedId} onChange={(e) => handleCheckedSearchAssignor(e, 'GROUP')}>
                  <div className='search-result-item' depId={record.checkedId} type={type}>
                    <div className='search-result-item__left'>{<WWOpenDataCom type='departmentName' openid={record.name} />}</div>
                  </div>
                </Checkbox>
              );
            })}
          </div>
        )}
        {departmentVOList.length > 0 && (
          <div>
            <div>{activeKey === 'departMentTab' ? DeptTypeEnum[activeKey][0] : DeptTypeEnum[activeKey][1]}</div>
            {departmentVOList.map((record) => {
              return (
                <Checkbox
                  disabled={record.disabled}
                  checked={record.checked}
                  value={record}
                  key={record.checkedId}
                  onChange={(e) => handleCheckedSearchAssignor(e, 'DEPART')}>
                  <div className='search-result-item' depId={record.checkedId} type={type}>
                    <div className='search-result-item__left'>
                      {activeKey === 'departMentTab' ? <WWOpenDataCom type='departmentName' openid={record.name} /> : <span>{record.name}</span>}
                    </div>
                    <div className='search-result-item__right'>{activeKey === 'postGrouptab' && <span>{record.parentName}</span>}</div>
                  </div>
                </Checkbox>
              );
            })}
          </div>
        )}

        {departmentUserVOList.length === 0 && departmentVOList.length === 0 && subLevelDepartmentVOList.length === 0 && renderEmptyContent()}
      </div>
    );
  }

  function documentClick() {
    document.onclick = function (e) {
      let _con = $('#left-search-dropdown');
      if (!_con.is(e.target) && _con.has(e.target).length === 0) {
        setDropDownVisible(false);
      }
    };
  }

  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'>
          <Search
            style={{ width: 272 }}
            placeholder={handlePlaceHolder()}
            value={queryName}
            enterButton={<span className='icon iconfont'>&#xe832;</span>}
            onChange={(e) => {
              setQueryName(e.target.value);
              setDropDownVisible(!!e.target.value);
            }}
          />
          {dropDownVisible && renderOptions()}
          <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'>
              <Choose>
                <When condition={structureData.length > 0}>
                  <DirectoryTree
                    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>
                      );
                    }}
                  />
                </When>
                <Otherwise>
                  <LottieIcon title='搜索无结果' type='search' size={150} />
                </Otherwise>
              </Choose>
            </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'>
            <Choose>
              <When condition={checkedAssignorList.length > 0}>
                {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>
                  );
                })}
              </When>
              <Otherwise>
                <LottieIcon title='暂无数据' type='college' size={150} />
              </Otherwise>
            </Choose>
          </div>
        </div>
      </div>
    </Modal>
  );
}

export default ChooseAssignorModal;
