import React, { useEffect, useState } from "react";
import { withRouter } from "react-router-dom";
import { Tree, Input, Dropdown, Menu,Button,Modal,message,AutoComplete} 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 [postGroupTreeData,setPostGroupTreeData] = useState([]); // 为了判定创建和编辑时的数据会不会重明

  const [open,setOpen]=useState(false);
  const renderTitle = (title) => (
    <span>
      {title}
    </span>
  );
  const renderItem = (record,type) => ({
    value: record.userName || record.name,
    label: (
      <div
        style={{
          display: 'flex',
          justifyContent: 'space-between',
        }}
      >
        {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>{record.parentName}</span>
        }
      </div>
    ),
  });

  const notFoundContentNode = ()=>{
    return <span>暂无数据</span>
  }
  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){
    console.log('option',option);
    setOpen(false);
    setQueryName(value);
    props.searchUserList({queryName:value},treeType,1);
  }

  // 获取关键词的搜索结果
  function getCompleteOptionData(value){
    // setQueryName(value);
    console.log("treeType",props.treeType);
    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);
    });
  }

  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);
      }
    });
  },[props.treeType]);

  useEffect(()=>{
    Bus.bind("addCustomer",(record)=>{addCustomer(record.treeType,record.query)})
  },[]);
  useEffect(()=>{
    Bus.bind("changeTreeData",(record)=>{getTreeData(record.treeType)})
  },[]);
  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.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.lenght > 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.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 = [];
    _selectKeys.push(e.selectedNodes[0].id)
    setSelectedKeys(_selectKeys);
    props.onChangeSelectDep(e.selectedNodes[0]);
    props.searchUserList(e.selectedNodes[0],treeType,1);
  }

  return (
    <div className="left-structure-tree">
      <div className="organization">
          <div className="search-con">
            {/* <Complete/> */}
            <AutoComplete
              dropdownClassName="certain-category-search-dropdown"
              dropdownMatchSelectWidth={250}
              allowClear
              onChange={(value)=>setQueryName(value)}
              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()}
            >
            </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">
        <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>
      </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);
