import { Tree } from 'antd';
import React, { useState, useEffect, useRef } from 'react';
import goUp from "@images/goUp.png";
import apiObj from '@api/index';
/****
 * 公用
 * 当前登录用户权限下的组织结构树
 * 自带获取数据源功能
 *入参：checkEv选中事件，checkeds已选中项
 * *****/
const { post, api } = apiObj;
function MyDeptStruct(props) {
    useEffect(() => {
        getHospitalTree();
    }, []);
    const { checkEv, checkeds } = props;
    const [treeData, setTreeData] = useState(null);
    const [hasScrolled, setHasScrolled] = useState(false);
    const box = useRef();

    //获取当前用户组织
    function getHospitalTree() {
        post(api.getHospitalTree).then((res) => {
            if (res.data.code === 200) {
                const data = res.data.data
                let arr = structureTreeData(data)
                setTreeData(arr)
            }
        })
    }
    //数据转换为树形结构所需字段
    function structureTreeData(arr) {
        arr.forEach(item => {
            item.key = item.hospitalId + '-' + item.hospitalName;
            item.title = item.hospitalName;
            if (!item.children && item.depts) {     //有科室时已选中区域要显示上级医院名称+科室名称，传参需传医院id及科室id
                item.depts.forEach(it => {
                    it.key = item.hospitalId + '-'+item.hospitalName + '-' + it.deptId + '-' + it.deptName;
                });
                item.children = JSON.parse(JSON.stringify(item.depts).replace(/deptName/g, 'title').replace(/deptId/g, 'key'))
                return
            }
            if (item.children) {
                structureTreeData(item.children)
            }
        })
        return arr
    }
    //菜单选中事件
    function onCheck(checkedKeys,e) {
        checkEv(checkedKeys,e)
    }
    function handleScroll(e) {
        if (e.target.scrollTop > 500) {
            setHasScrolled(true)
        } else {
            setHasScrolled(false)
        }
    }
    function goTop() {
        box.current.scrollTop = 0
    }
    function onSelect() { }
    //const defaultCheckedKeys = checkeds && checkeds.softwareMenuIds ? checkeds.softwareMenuIds.slice() : []
    if(!treeData){
        return null;
    }
    return (
        <div className='treeContent' >
            <p className='title'>组织结构</p>
            <div className='tree' onScrollCapture={handleScroll} ref={box}>
                <Tree
                    checkable
                    checkedKeys={checkeds}
                    onCheck={onCheck}
                    onSelect={onSelect}
                    treeData={treeData}

                />
            </div>

            {
                hasScrolled ?
                    <div className='goTop' onClick={goTop} >
                        <img src={goUp} />
                    </div>
                    : null
            }

        </div>

    )
}

export default MyDeptStruct;