import React, { useEffect, useState, useRef } from "react";
import { withRouter } from "react-router-dom";
import { Tree, Input, Dropdown, Menu, Button, Modal, message, AutoComplete, Tooltip } from "antd";
import AddOrEditPostGroupModal from "../modal/AddOrEditPostGroupModal";
import User from '@/common/js/user'
import StoreService from "@/domains/store-domain/storeService";
import { DepType } from '@/domains/store-domain/constants';
import Bus from '@/core/bus';
import WWOpenDataCom from '@/components/WWOpenDataCom';
import "./LeftStructureTree.less";

const { Search } = Input;
const { DirectoryTree } = Tree;
const { Option } = AutoComplete;
function LeftStructureTree(props) {
  const { treeType } = props;
  const [treeData, setTreeData] = useState([]);
  const [addOrEditPostGroupShow, setAddOrEditPostGroupShow] = useState(false);
  const [postGroupModalLevel, setPostGroupModalLevel] = useState("");
  const [operatePostGroupModalType, setOperatePostGroupModalType] = useState("");
  const [postGroupModalTitle, setPostGroupModalTitle] = useState("");
  const [postGroupModalLable, setPostGroupModalLable] = useState("");
  const [postGroupName, setPostGroupName] = useState("");
  const [currentGroupData, setCurrentGroupData] = useState({});
  const [completeOptions, setCompleteOption] = useState([]);
  const [selectedKeys, setSelectedKeys] = useState([]); // 设置选中的部门key值
  const [queryName, setQueryName] = useState(''); // 搜索框内的值
  const [selctQueryName, setSelctQueryName] = useState(''); // 搜索出结果后最终选择的名字
  const [postGroupTreeData, setPostGroupTreeData] = useState([]); // 为了判定创建和编辑时的数据会不会重明
  const [open, setOpen] = useState(false);
  const timer = useRef(null)
  const queryNameRef = useRef(null)

  useEffect(() => {
    queryNameRef.current = queryName
  }, [
    queryName
  ])

  useEffect(() => {
    setQueryName('');   //切换tab时搜索置空
    setCompleteOption([]);
    setOpen(false); //切换tab时搜索的下拉框置为空
    getTreeData().then((res) => {
      const _defaultSelectedKeys = [];
      if (res.length > 0) {
        _defaultSelectedKeys.push(res[0].id);
        setSelectedKeys(_defaultSelectedKeys);
        props.onChangeSelectDep(res[0])
        props.searchUserList(res[0], treeType, 1);
      } else {
        props.searchUserList({ id: null }, treeType, 1);
      }
    });
  }, [props.treeType]);

  useEffect(() => {
    Bus.bind("addCustomer", (record) => { addCustomer(record.treeType, record.query) })
  }, []);
  useEffect(() => {
    Bus.bind("changeTreeData", (record) => { getTreeData(record.treeType) })
  }, []);
  const renderTitle = (title) => (
    <span className="catalog-title">
      {title}
    </span>
  );
  const renderItem = (record, type) => ({
    value: record.userName || record.name,
    label: (
      <div
        className="search-result-item"
        style={{
          display: 'flex',
          justifyContent: 'space-between',
        }}
        depId={record.id}
        type={type}

      >
        {type === 'user' ?
          <div className="search-result-item__left">
            <span className="icon iconfont title-icon">&#xe603;</span>
            <WWOpenDataCom type="userName" openid={record.userName} />
          </div>
          :
          <div className="search-result-item__left">
            {props.treeType === '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>
    ),
  });

  const 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 handleDepName(depArray) {
    const depArrayDom = depArray.map((item, index) => {
      return <span><WWOpenDataCom type="departmentName" openid={item} />；</span>
    });
    return depArrayDom;
  };
  function handlePlaceHolder() {
    let placeholder = '';
    switch (props.treeType) {
      case 'departMentTab':
        placeholder = '搜索学员姓名、部门';
        break;
      case 'postGrouptab':
        placeholder = '搜索学员姓名/岗位/岗位组';
        break;
      case 'customGroupTab':
        placeholder = '搜索学员姓名/自定义分组集合/自定义分组';
        break;
      default:
        break;
    }
    return placeholder
  }
  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, treeType, 1);
  }

  // 获取关键词的搜索结果
  function getCompleteOptionData(value) {
    // setQueryName(value);
    setCompleteOption([]);
    if (!value) {
      return
    }
    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);
    });
  }


  async function addCustomer(treeType, query) {
    await getTreeData(treeType);
    props.searchUserList(query, treeType, 1);
  }
  function getTreeData(treeType) {
    return new Promise((resolve, reject) => {
      const params = {
        departmentTypeEnum: DepType[treeType] || DepType[props.treeType],
        enterpriseId: User.getEnterpriseId(),
        source: 0,//0代表来自企培
        storeId: User.getStoreId(),
        userId: User.getUserId(),
        whetherCount: true
      }
      StoreService.queryDepartmentTree(params).then((res) => {
        const { result = [] } = res
        let { departmentVOList = [] } = result;
        let _treeData = handleData(result);
        setTreeData(_treeData);
        resolve(result);
      });

    })

  }
  function handleData(dataArray) {
    const _dataArray = dataArray.map((item, index) => {
      item.title = "";
      item.key = item.id;
      if (item.sonDepartmentVOList) {
        item.children = item.sonDepartmentVOList;
        handleData(item.sonDepartmentVOList)
      }
      return item
    })
    return _dataArray;
  }
  const leftBoxWidth =
    (document.getElementById("left-box") &&
      document.getElementById("left-box").style.width) ||
    "304px";

  const moreOpenGroupOperate = (record) => (
    <Menu>
      <Menu.Item key="edit">
        <span onClick={() => { props.treeType === 'postGrouptab' ? editPostGroup(record) : editCustomGroup(record) }}>编辑</span>
      </Menu.Item>
      {record.depLevel === 0 &&
        <Menu.Item key="add" >
          <span onClick={() => { props.treeType === 'postGrouptab' ? addPostGroup(1, record) : addCustomGroup(1, record) }}>
            {props.treeType === 'postGrouptab' &&
              <span>新建岗位</span>
            }
            {props.treeType === 'customGroupTab' &&
              <span>新建分组</span>
            }
          </span>
        </Menu.Item>
      }
      {/* { (record.departmentCount === 0 || !record.departmentCount) && */}
      <Menu.Item key="del">
        <span onClick={() => { props.treeType === 'postGrouptab' ? delPostGroup(record) : delCustomGroup(record) }}>删除</span>
      </Menu.Item>
      {/* } */}
    </Menu>
  );


  function closeAddOrEditPostGroupModal() {
    setAddOrEditPostGroupShow(false);
  }

  //添加岗位组/岗位
  function addPostGroup(level, record) {
    if (level === 0) {
      if (treeData.length > 9) {
        message.error("岗位组数量已达10个上限");
        return;
      }
    }
    if (level === 1) {
      if (record.sonDepartmentVOList) {
        if (record.sonDepartmentVOList.length > 19) {
          message.error("岗位数量已达20个上限");
          return;
        }
      }
    }

    setCurrentGroupData({});
    setAddOrEditPostGroupShow(true);
    setOperatePostGroupModalType("add");
    setPostGroupModalLevel(level);
    setCurrentGroupData(record);
    console.log('treeData', record);
    if (level === 0) {
      setPostGroupModalTitle('添加岗位组');
      setPostGroupModalLable('岗位组');
      setPostGroupTreeData(treeData);
    } else {
      setPostGroupModalTitle('添加岗位'); // sub代表岗位
      setPostGroupModalLable('岗位');
      setPostGroupTreeData(record.sonDepartmentVOList || []);
    }
  }
  //编辑岗位组/岗位
  function editPostGroup(record) {
    setAddOrEditPostGroupShow(true);
    setOperatePostGroupModalType("edit");
    //level为0的时候编辑的是岗位组 大于0的时候
    setPostGroupModalLevel(record.depLevel);
    setCurrentGroupData(record);
    console.log('treeData', record);
    if (record.depLevel === 0) {
      setPostGroupModalTitle('编辑岗位组');
      setPostGroupModalLable('岗位组');
      setPostGroupTreeData(treeData);
    } else {
      setPostGroupModalTitle('编辑岗位');
      setPostGroupModalLable('岗位');
      setPostGroupTreeData(getParentChildernData(record.parentId));
    }
  }

  // 获取父节点下的所有的子级数据
  function getParentChildernData(parentId) {
    let _parentChildernData = []
    treeData.map((item, index) => {
      if (parentId === item.id) {
        _parentChildernData = item.sonDepartmentVOList
      }
    })
    return _parentChildernData
  }
  function delPostGroup(record) {
    let title = '确认删除该岗位组吗？';
    let content = '删除后，该岗位组下的岗位及也将全部删除。';
    if (record.departmentCount && record.departmentCount > 0) {
      title = '删除失败';
      if (record.depLevel > 0) {
        content = `${record.name}存在学员，不能删除该岗位`;
      } else {
        content = `${record.name}存在学员，不能删除该岗位组`;
      }
      Modal.warning({
        title,
        content,
        icon: <span className='icon iconfont default-warning-icon'>&#xe80d;</span>,
        okText: "我知道了"
      })
      return
    }
    if (record.level > 0) {
      title = '确认删除该岗位吗？';
      content = '删除后，不可恢复';
    }
    Modal.confirm({
      title,
      content,
      icon: <span className='icon iconfont default-confirm-icon'>&#xe6f4;</span>,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        delGroup(record);
      },
    });
  }
  function delGroup(record) {
    let parmas = {
      departmentId: record.id,
      enterpriseId: User.getEnterpriseId(),
      source: 0,
      storeId: User.getStoreId(),
      userId: User.getUserId()
    }
    StoreService.delDepartment(parmas).then((res) => {
      message.success(`删除成功`)
      getTreeData();
    });
  }



  //添加自定义分组集合/分组
  function addCustomGroup(level, record) {
    if (level === 0) {
      if (treeData.length > 9) {
        message.error("自定义分组集合数量已达10个上限");
        return;
      }
    }
    if (level === 1) {
      if (record.sonDepartmentVOList) {
        if (record.sonDepartmentVOList.length > 19) {
          message.error("自定义分组数量已达20个上限");
          return;
        }
      }
    }
    setCurrentGroupData({});
    setAddOrEditPostGroupShow(true);
    setOperatePostGroupModalType("add");
    setPostGroupModalLevel(level);
    setCurrentGroupData(record)
    if (level === 0) {
      setPostGroupModalTitle('添加分组集合');
      setPostGroupModalLable('分组集合');
      setPostGroupTreeData(treeData);
    } else {
      setPostGroupModalTitle('添加分组'); // sub代表岗位
      setPostGroupModalLable('分组');
      setPostGroupTreeData(record.sonDepartmentVOList || []);
    }
  }
  //编辑自定义分组集合/分组
  function editCustomGroup(record) {
    setAddOrEditPostGroupShow(true);
    setOperatePostGroupModalType("edit");
    setPostGroupModalLevel(record.level);
    setCurrentGroupData(record)
    //level为0的时候编辑的是岗位组 大于0的时候
    if (record.depLevel === 0) {
      setPostGroupModalTitle('编辑分组集合');
      setPostGroupModalLable('分组集合');
      setPostGroupTreeData(treeData);
    } else {
      setPostGroupModalTitle('编辑分组');
      setPostGroupModalLable('分组');
      setPostGroupTreeData(getParentChildernData(record.parentId));
    }
  }
  function delCustomGroup(record) {
    let title = '确认删除该分组集合吗？';
    let content = '删除后，该分组集合下的岗位及也将全部删除。';
    if (record.departmentCount && record.departmentCount > 0) {
      title = '删除失败';
      if (record.level > 0) {
        content = `${record.name}存在学员，不能删除该分组`;
      } else {
        content = `${record.name}存在学员，不能删除该分组集合`;
      }
      Modal.warning({
        title,
        content,
        icon: <span className='icon iconfont default-warning-icon'>&#xe80d;</span>,
        okText: "我知道了"
      })
      return
    }
    if (record.level > 0) {
      title = '确认删除该分组吗？';
      content = '删除后，不可恢复';
    }
    Modal.confirm({
      title,
      content,
      icon: <span className='icon iconfont default-confirm-icon'>&#xe6f4;</span>,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        delGroup(record)
      },
    });
  }


  function confirmAddOrEditPostGroup() {
    closeAddOrEditPostGroupModal();
    getTreeData()
  }

  function selectUserList(record, e) {
    const _selectKeys = [];
    if(e.selectedNodes && e.selectedNodes.length>0){
      _selectKeys.push(e.selectedNodes[0].id)
    }
    setSelectedKeys(_selectKeys);
    props.onChangeSelectDep(e.selectedNodes[0]);
    props.searchUserList(e.selectedNodes[0], treeType, 1);
  }


  function changeName(value) {
    setQueryName(value); setOpen(true);
    clearTimeout(timer.current)
    timer.current = setTimeout(() => {
      getCompleteOptionData(queryNameRef.current)
    }, 500)

  }
  return (
    <div className="left-structure-tree">
      <div className="organization">
        <div className="search-con">
          {/* <Complete/> */}
          <AutoComplete
            dropdownClassName="certain-category-search-dropdown"
            dropdownMatchSelectWidth={250}
            allowClear
            onChange={changeName}
            // onSearch={(value)=>{getCompleteOptionData(value)}}
            notFoundContent={notFoundContentNode()}
            value={queryName}
            open={open}
            onFocus={() => { setOpen(true) }}
            onBlur={() => { setOpen(false) }}
            style={{
              width: 250,
            }}
            options={completeOptions}
            onSelect={confirmSearchSelect}
            placeholder={handlePlaceHolder()}
          >
            <Search
              style={{ width: 250 }}
              enterButton={<span className='icon iconfont'>&#xe832;</span>}
            />
          </AutoComplete>
        </div>
        {(props.treeType === 'postGrouptab' || props.treeType === 'customGroupTab') && (
          <div className="operate">
            {props.treeType === 'postGrouptab' &&
              <Button
                className="add-btn"
                onClick={() => {
                  addPostGroup(0)
                }}
              >
                添加岗位组
              </Button>
            }
            {props.treeType === 'customGroupTab' &&
              <Button
                className="add-btn"
                onClick={() => {
                  addCustomGroup(0)
                }}
              >
                添加自定义分组
              </Button>
            }
          </div>
        )}
        <div className="tree-con">
          {!selctQueryName ?
            <DirectoryTree
              defaultExpandAll
              showIcon={false}
              treeData={treeData}
              selectedKeys={selectedKeys}
              onSelect={selectUserList}
              titleRender={(nodeData) => {
                return (
                  <div
                    className="node-title-div"
                    onMouseOver={(e) => {
                      if ((props.treeType === 'postGrouptab' || props.treeType === 'customGroupTab')) {
                        if (nodeData.key === "null") return;
                        let moreDiv = e.currentTarget.getElementsByClassName(
                          "item-more"
                        )[0];
                        let countDiv = e.currentTarget.getElementsByClassName(
                          "item-count"
                        )[0];
                        if (moreDiv) {
                          moreDiv.style.visibility = "visible";
                        }
                        if (countDiv) {
                          countDiv.style.visibility = "hidden";
                        }
                      }
                    }}
                    onMouseOut={(e) => {
                      if ((props.treeType === 'postGrouptab' || props.treeType === 'customGroupTab')) {
                        if (nodeData.key === "null") return;
                        let moreDiv = e.currentTarget.getElementsByClassName(
                          "item-more"
                        )[0];
                        let countDiv = e.currentTarget.getElementsByClassName(
                          "item-count"
                        )[0];
                        if (moreDiv) {
                          moreDiv.style.visibility = "hidden";
                        }
                        if (countDiv) {
                          countDiv.style.visibility = "visible";
                        }
                      }
                    }}
                  >
                    <div className="item-icon">
                      <span className="icon iconfont title-icon">&#xe604;</span>
                    </div>
                    <div
                      className="item-title"
                      style={{
                        width:
                          leftBoxWidth <= "240px"
                            ? "35%"
                            : leftBoxWidth <= "304px"
                              ? "60%"
                              : "78%",
                      }}
                    >
                      {props.treeType === 'departMentTab' ?
                        <span><WWOpenDataCom type="departmentName" openid={nodeData.name} /></span>
                        :
                        <span>{nodeData.name}</span>
                      }
                    </div>
                    <div className="item-count">({nodeData.departmentCount || 0})</div>
                    {(props.treeType === 'postGrouptab' || props.treeType === 'customGroupTab') && (
                      <Dropdown overlay={moreOpenGroupOperate(nodeData)}>
                        <div className="item-more icon iconfont">&#xe927;</div>
                      </Dropdown>
                    )}
                  </div>
                );
              }}
            />
            :
            <div>
              {/* { (props.treeType==='departMentTab') &&  */}
              <div>
                {selctQueryName.type === 'userName' ?
                  <WWOpenDataCom type="userName" openid={selctQueryName.openid} />
                  :
                  <WWOpenDataCom type="departmentName" openid={selctQueryName.openid} />
                }
              </div>

              {/* } */}
              {/* { (props.treeType==='postGrouptab' || props.treeType=== 'customGroupTab') && 
                <div>
                  { option.name?
                   <span>{option.name}</span>
                   :
                   <span>{option.userName}</span>
                  }
                  
                </div>
              } */}
            </div>
          }


        </div>
      </div>
      {addOrEditPostGroupShow && (
        <AddOrEditPostGroupModal
          onClose={() => {
            closeAddOrEditPostGroupModal();
          }}
          onConfirm={() => {
            confirmAddOrEditPostGroup();
          }}
          title={postGroupModalTitle}
          postGroupModalLevel={postGroupModalLevel}
          modalOperateType={operatePostGroupModalType}
          postGroupName={postGroupName}
          postGroupTreeData={postGroupTreeData}
          label={postGroupModalLable}
          currentTab={props.treeType}
          currentGroupData={currentGroupData}
        />
      )}
    </div>
  );
}

export default withRouter(LeftStructureTree);
