import React, {useState, useEffect} from 'react';
import Document from 'react-document-title'
import AddressList from '../../components/AddressList';
import axiosRequest from '../../utils/request';
import Skeleton from '../../components/Skeleton'
import './index.less'
import Empty from '../Empty'


const AddressBook = (props) => {
    const [start, setStart] = useState(true);
    const [loading, setLoading] = useState(false);
    const [data, setData] = useState([]);
    // const [type, setType] = useState('basic')

    // const {id} = props.match.params;

    // console.log(id, ss);

    const getData = () => {
        setLoading(true);
        axiosRequest({
            method: 'post',
            url: '/idtAppServiceV6/oApp/getDeptTree',
        }).then(res => {
            setStart(false);
            setLoading(false);
            setData(res)
        });
    };
    useEffect(() => {
        getData()
    }, []);

    // const [userLoading, setUserLoading] = useState(false)
    const treeClick = (DEPTID) => {
        const newData = [...data];
        const index = newData.findIndex(item => item.DEPTID === DEPTID);
        const checked = newData[index].checked ? newData[index] : false;
        newData[index] = {...newData[index], loading: true, children: [], checked: !checked};
        setData(newData);
        !checked && getUser(DEPTID)
    };
    const getUser = (DEPTID) => {
        axiosRequest({
            method: 'post',
            url: `/idtAppServiceV6/oApp/getSearchAddressBook?deptId=${DEPTID}`,
        }).then(res => {
            const child = res.userList && res.userList.length > 0 ? res.userList : [];
            const newData = [...data];
            const index = newData.findIndex(item => item.DEPTID === DEPTID);
            newData[index] = {...newData[index], loading: false, children: child, checked: true};
            setData(newData)
            // setData()
        });
    };
    return (
        <Document title="通讯录">
            <div>
                <div className='adMainBox'>
                    {loading ? <Skeleton/> : (!start && ( data.length > 0 ? (
                        <AddressList data={data} onCLick={treeClick}/>
                    ): <Empty/>))}

                </div>
            </div>

        </Document>
    );
};

export default AddressBook;

