import { View, Image, Text } from '@tarojs/components'
import './FoodConsole.scss'
import { rpxToPx } from '@/utils/tools'
import Taro from '@tarojs/taro'
import Slider from '@/components/input/Slider'
import { useEffect, useState } from 'react'
import { baseUrl } from '@/services/http/api'
import { createFoodJournal } from '@/services/foodJournal'
import { useSelector } from 'react-redux'
import { jumpPage } from '../trackTimeDuration/hooks/Common'
let useNavigation;
if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
}

export default function Component(props: { addItem: Function }) {
    const user = useSelector((state: any) => state.user);
    const [imgUrl, setImgUrl] = useState('')
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    useEffect(() => {
        var str = Taro.getStorageSync('pic')
        if (str && str.length > 0) {
            setImgUrl(str)
        }
    }, [])

    function choose(isAlbum = true) {
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
            return;
        }
        clearFile()
        Taro.chooseImage({
            count: 1,
            sizeType: ['compressed'],
            sourceType: [isAlbum ? 'album' : 'camera'],
            success: function (res) {
                console.log(res)
                var tempFilePaths = res.tempFilePaths
                Taro.getFileSystemManager().saveFile({
                    tempFilePath: tempFilePaths[0],
                    success: function (res) {
                        var savedFilePath = res.savedFilePath
                        Taro.setStorageSync('pic', savedFilePath)
                        console.log(savedFilePath)
                        setImgUrl(savedFilePath as any)

                        uploadFile(savedFilePath)
                    }
                })
            }
        })
    }


    function clearFile() {
        Taro.getFileSystemManager().getSavedFileList({
            success: function (res) {
                if (res.fileList.length > 0) {
                    Taro.removeSavedFile({
                        filePath: res.fileList[0].filePath,
                        complete: function (res) {
                            console.log(res)
                            console.log('remove success')
                        }
                    })
                }
            }
        })
    }

    function getCache(key: string) {
        var value = Taro.getStorageSync(key)
        if (value) {
            return JSON.parse(value)
        }
        return null;
    }

    function saveCache(key: string) {
        var strList = Taro.getStorageSync('food_operate')
        var list: any = []
        if (strList) {
            list = JSON.parse(strList)
        }
        list.add({
            key,
            timestamp: new Date().getTime()
        })
        Taro.setStorageSync('food_operate', JSON.stringify(list)
        )
    }

    function uploadFile(path) {
        Taro.showLoading({
            title: '加载中'
        })
        var dot = path.lastIndexOf('.')
        var fileExt = dot > 0 ? path.substring(dot) : ''
        // console.log(avatarUrl)
        Taro.request({
            method: 'GET',
            url: `${baseUrl}/api/thirdparty/aliyun/oss-form-upload`,
            header: {
                'Authorization': 'bearer ' + global.token
            },
            data: {
                type: 'FOOD_JOURNAL',
                file_ext: fileExt
            },
            success: (rsp) => {
                console.log(rsp)
                Taro.uploadFile({
                    url: rsp.data.upload_url,
                    filePath: path,
                    name: 'file',
                    formData: rsp.data.fields,
                    success: rlt => {
                        console.log(rlt)
                        createData(rsp.data.view_url)

                        // uploadAvatar(rsp.data.view_url)
                        // _this.changeAvatar(rsp.data.view_url);
                    },
                    fail: rlt => {
                        Taro.hideLoading()
                        Taro.showModal({
                            content: rlt.errMsg
                        })
                    }
                })
            }
        })
    }

    function createData(url) {
        var date = new Date();
        var time = date.getTime()
        var strDate = (date.getFullYear() + '') + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());

        createFoodJournal({
            cover: url,
            start: {
                timestamp: time,
                date: strDate
            }

        }).then(res => {
            console.log(res)
            props.addItem(res)
            clearFile()
            setImgUrl('')
            Taro.removeStorageSync('pic')
            Taro.hideLoading()
        }).catch(e => {
            Taro.hideLoading()
        })
    }

    return <View >
        <View style={{ display: 'flex', width: rpxToPx(750), alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }}>
            <View style={{ display: 'flex', flexDirection: 'column' }}>
                <Slider />
                {/* <View className='box11' onClick={()=>choose(true)}>{
                    imgUrl && <Image style={{ width: '100%', height: '100%' }} src={imgUrl} mode="aspectFill" />
                }
                </View> */}
                <View className='camera_bg' onClick={() => choose(false)}>
                    <Image src={require('@assets/images/camera2.png')} className='camera_icon' />
                    <Text className='camera_text'>拍摄食物</Text>
                    <Text className='album_text'>从相册选择</Text>
                    <View className='album_bottom' onClick={(e) => { choose(true); e.stopPropagation() }} />
                </View>
                <Slider />
            </View>
            <View className='demo1' />
            {/* <Text style={{ color: '#fff',marginBottom:20 }} onClick={()=>choose(false)}>拍照</Text>
            <Text style={{ color: '#fff' }} onClick={uploadFile}>上传</Text> */}

        </View>
    </View>
}