import { View } from '@tarojs/components'
import './FoodTimeline.scss'
import FoodTimelineItem from './FoodTimelineItem'
import { useEffect, useState } from 'react'
import { delFoodJournal } from '@/services/foodJournal'
import Taro from '@tarojs/taro'

export default function Component(props: { array: any, refresh: Function, forceRefresh: Function }) {
    const [list, setList] = useState(props.array)

    useEffect(() => {
        setList(props.array)
    }, [props.array, props.array.length])

    function del(index) {
        delFoodJournal(list[index].id).then(res => {
            var temps = list.splice(index, 1)
            setList(temps)
            props.refresh()
        }).catch(e => {

        })
    }

    // function preview(index){
    //     var urls:any = []
    //     list.map(item=>{
    //         urls.push(item.cover)
    //     })
    //     Taro.previewImage({
    //         current: list[index].cover,
    //         urls: urls
    //     })
    // }

    function preview(index) {
        var urls: any = []
        list.map(item => {
            urls.push({
                url: item.media[0].url,
                type: item.media[0].url.indexOf('mp4') != -1 ? 'video' : 'image'
            })
        })
        Taro.previewMedia({
            current: index,
            sources: urls
        })
    }

    function updateItem(index, data) {
        list[index] = data
        setList(list)
    }

    return <View style={{ flexDirection: 'column', display: 'flex' }}>
        {
            list.map((item, index) => {
                return <FoodTimelineItem data={item} index={index} key={index}
                    delete={() => del(index)}
                    preview={() => preview(index)}
                    update={(data) => updateItem(index, data)}
                    forceRefresh={() => props.forceRefresh()}
                    refresh={() => {props.refresh();console.log('oppppp');debugger}}
                />
            })
        }
    </View>
}