import './ContentItem.scss'
import notFollow from '../../static/notFollow.png'
import followed from '../../static/followed.png'
import {useContext, useEffect, useState} from "react";
import {Root} from "../../dataCenter/Root";

function ContentItem(props) {
    const {dataCenter, fetchData} = useContext(Root)
    const {toolbox_icon, toolbox_name, toolbox_desc, toolbox_url, toolbox_id} = props.value
    const [isFollow, setIsFollow] = useState(false)
    const [itemIcon, setItemIcon] = useState(toolbox_icon)

    const jumpUrl = url => window.location.href = url

    const follow = () => {
        const _follow = dataCenter.userInfo.follow.slice()
        if (!isFollow) {
            _follow.push(toolbox_id)
        } else {
            const index = _follow.indexOf(toolbox_id)
            _follow.splice(index, 1)
        }
        console.log( {follow: JSON.stringify(_follow), uid: dataCenter.userInfo.uid})
        fetchData('/users/follow', {follow: JSON.stringify(_follow), uid: dataCenter.userInfo.uid})
            .then(() => fetchData('/users/getUser', {uid: 100001}, 'userInfo'))
    }

    useEffect(() => {
        if (dataCenter.userInfo?.follow.includes(toolbox_id)) {
            setIsFollow(true)
        } else {
            setIsFollow(false)
        }
    }, [dataCenter.toolBox, dataCenter.userInfo])

    return (
        <div className="content-item">
            <div className="item-icon" onClick={() => jumpUrl(toolbox_url)}>
                {
                    !itemIcon && <div className="defaultIcon">{toolbox_name[0]}</div>
                }
                {
                    itemIcon && <img src={itemIcon} alt='' onError={e => setItemIcon(null)}/>
                }

            </div>
            <div className="item-name" onClick={() => jumpUrl(toolbox_url)}>{toolbox_name}</div>
            <div className="item-desc">{toolbox_desc}</div>
            <a className='item-url' href={toolbox_url}>{toolbox_url}</a>
            <div className="follow">
                <img className='icon-follow' src={isFollow ? followed : notFollow} alt="" onClick={() => follow()}/>
                收藏
            </div>
        </div>
    )
}

export default ContentItem
