/*
 * @Author: yuananting
 * @Date: 2021-08-05 17:09:36
 * @LastEditors: yuananting
 * @LastEditTime: 2021-08-12 19:37:35
 * @Description: 新建培训任务-选择指派对象
 * @Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 * @@Copyrigh: © 2020 杭州杰竞科技有限公司 版权所有
 */
import React, { useState, useEffect } from 'react';
import { Modal, Tree, Tooltip, AutoComplete, Tabs } 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;

function ChooseAssignorModal(props) {
  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 [searchKey, setSearchKey] = useState('');
  const [open, setOpen] = useState(false);

  const AssignTypeEnum = {
    departMentTab: 'SECTION',
    postGrouptab: 'POST',
    customGroupTab: 'CUSTOM',
  };
  useEffect(() => {
    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 = [0, 1].includes(item.depLevel) ? item.id : item.storeCustomerId;
      item.key = item.checkedId;
      item.children = [];
      if (activeKey !== 'departMentTab' && item.depLevel === 0) {
        item.disableCheckbox = true;
      }
      item.assignType = [0, 1].includes(item.depLevel) ? AssignTypeEnum[activeKey] : 'CUSTOMER';
      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((innerItem) => innerItem.checkedId !== item.checkedId);
    const _checkedAssignorKeys = _checkedAssignorList.map((item) => item.checkedId);
    setCheckedAssignorKeys(_checkedAssignorKeys);
    setCheckedAssignorList(_checkedAssignorList);
  }

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

  function renderTitle(title) {
    return <span>{title}</span>;
  }

  function renderItem(record, type) {
    return {
      value: record.userName || record.name,
      label: (
        <div
          style={{
            display: 'flex',
            justifyContent: 'space-between',
          }}
          depId={record.id}
          type={type}>
          {type === 'user' ? (
            <div>
              <WWOpenDataCom type='userName' openid={record.userName} />
            </div>
          ) : (
            <div>
              <WWOpenDataCom type='departmentName' openid={record.name} />
            </div>
          )}
          {type === 'user' &&
            record.postDepNamesList.map((item, index) => {
              return (
                <span>
                  <WWOpenDataCom type='departmentName' openid={item} />
                </span>
              );
            })}
          {type === 'post' && (
            <span type='post' openid={record.parentName}>
              {record.parentName}
            </span>
          )}
        </div>
      ),
    };
  }

  function getCompleteOptionData(value) {
    setCompleteOption([]);
    const params = {
      depType: DepType[props.treeType],
      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 (props.treeType) {
          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 (props.treeType) {
          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(departmentGroupObj).length !== 0) {
        _completeOptions.push(departmentGroupObj);
      }
      if (Object.keys(postobj).length !== 0) {
        _completeOptions.push(postobj);
      }
      setCompleteOption(_completeOptions);
    });
  }

  function handlePlaceHolder() {
    let placeholder = '';
    switch (props.treeType) {
      case 'departMentTab':
        placeholder = '搜索学员姓名、部门';
        break;
      case 'postGrouptab':
        placeholder = '搜索学员姓名/岗位/岗位组';
        break;
      case 'customGroupTab':
        placeholder = '搜索学员姓名/自定义分组集合/自定义分组';
        break;
      default:
        break;
    }
    return placeholder;
  }

  return (
    <Modal
      className='choose-assignor-modal'
      title='添加指派学员'
      visible={true}
      onCancel={props.onClose}
      onOk={() => {
        props.onConfirm(checkedAssignorList);
        props.onClose();
      }}
      width={680}
      maskClosable={false}>
      <div className='assignor-container'>
        <div className='left-list'>
          {/* <AutoComplete
            dropdownClassName='certain-category-search-dropdown'
            dropdownMatchSelectWidth={272}
            allowClear
            onChange={(value) => setSearchKey(value)}
            onSearch={(value) => {
              getCompleteOptionData(value);
            }}
            // notFoundContent={notFoundContentNode()}
            value={searchKey}
            open={open}
            onFocus={() => {
              setOpen(true);
            }}
            onBlur={() => {
              setOpen(false);
            }}
            style={{
              width: 272,
            }}
            options={completeOptions}
            // onSelect={confirmSearchSelect}
            placeholder={handlePlaceHolder()}></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'>
                      {[0, 1].includes(nodeData.depLevel) ? (
                        <div>
                          <span className='icon iconfont title-icon'>&#xe604;</span>
                          <span className='title-name'>
                            <WWOpenDataCom type='departmentName' openid={nodeData.name} />
                          </span>
                        </div>
                      ) : (
                        <div>
                          <span className='icon iconfont title-icon'>&#xe603;</span>
                          <span className='title-name'>
                            <WWOpenDataCom type='userName' openid={nodeData.userName} />
                          </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'>
                    {[0, 1].indexOf(item.depLevel) === -1 ? (
                      <div>
                        <span className='icon iconfont title-icon'>&#xe603;</span>
                        <Tooltip title={<WWOpenDataCom type='userName' openid={item.userName} />}>
                          <span className='title-name'>
                            <WWOpenDataCom type='userName' openid={item.userName} />
                          </span>
                        </Tooltip>
                      </div>
                    ) : (
                      <div>
                        <span className='icon iconfont title-icon'>&#xe604;</span>
                        <Tooltip title={<WWOpenDataCom type='departmentName' openid={item.name} />}>
                          <span className='title-name'>
                            <WWOpenDataCom type='departmentName' openid={item.name} />
                          </span>
                        </Tooltip>
                      </div>
                    )}
                  </span>
                  <span className='icon iconfont clear-icon' onClick={() => removeCheckedAssignor(item)}>
                    &#xe717;
                  </span>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </Modal>
  );
}

export default ChooseAssignorModal;
