import { View, Image, Text, Switch } from '@tarojs/components'
import './FoodConsole.scss'
import { rpxToPx, vibrate } 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'
import { IconShare } from '@/components/basic/Icons'
import { useTranslation } from 'react-i18next'
import { ColorType } from '@/context/themes/color'
import { clearFoodCache, getFoodCache, saveFoodCache } from './hooks/ExtraData'
import { async } from 'q'
import { checkAuthorized } from '@/utils/check_authorized'
let useNavigation;
if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
}

export default function Component(props: { addItem: Function, firstItem: any }) {
    const user = useSelector((state: any) => state.user);
    const [modeOn, setModeOn] = useState(false)
    const [firstData, setFirstData] = useState(props.firstItem)
    const [lastUnFinished, setLastUnFinished] = useState(false)
    const common = useSelector((state: any) => state.common);
    const { t } = useTranslation()
    const [imgUrl, setImgUrl] = useState('')
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    // useEffect(() => {
    //     setFirstData(props.firstItem)
    // }, [props.firstItem, props.firstItem.feel.post_meal])

    useEffect(() => {
        if (props.firstItem) {
            setFirstData(props.firstItem)
        }
    }, [props.firstItem])

    useEffect(() => {
        if (firstData &&
            firstData.mindful_mode == 'AWARE' &&
            (firstData.status != 'PART_COMPLETED' && firstData.status != 'COMPLETED')
        ) {
            setLastUnFinished(true)
            setModeOn(true)
        }
        else {
            setLastUnFinished(false)
            var isOn = Taro.getStorageSync('food_switch')
            setModeOn(isOn)
        }
        // if (firstData &&
        //     firstData.mindful_mode == 'AWARE' &&
        //     firstData.status != 'PART_COMPLETED' &&
        //     (!firstData.feel.post_meal || !firstData.feel.pre_meal)) {
        //     setLastUnFinished(true)
        //     setModeOn(true)
        // }
        // else {
        //     setLastUnFinished(false)
        //     var isOn = Taro.getStorageSync('food_switch')
        //     setModeOn(isOn)
        // }
    }, [firstData])

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

    async function choose(isAlbum = true) {
        if (!user.isLogin) {
            jumpPage('/pages/account/ChooseAuth', 'ChooseAuth', navigation)
            return;
        }

        var params = {
            event: 'add_a_picture',
            value: isAlbum ? 'choose_from_album' : 'use_camera',
        }

        saveFoodCache('create', params)

        if (process.env.TARO_ENV == 'rn') {
            Taro.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: [isAlbum ? 'album' : 'camera'],
                success: function (res) {
                    chooseSuccess(res, isAlbum)
                    checkAuthorized()
                },
                fail: function (res) {
                    chooseFailed(res, isAlbum)
                    checkAuthorized()
                }
            })

        }
        else {
            Taro.chooseMedia({
                count: 1,
                sizeType: ['compressed'],
                mediaType: ['image'],
                sourceType: [isAlbum ? 'album' : 'camera'],
                success: function (res) {
                    chooseSuccess(res, isAlbum)
                    checkAuthorized()
                },
                fail: function (res) {
                    chooseFailed(res, isAlbum)
                    checkAuthorized()
                }
            })
        }
    }

    async function chooseSuccess(res, isAlbum) {
        var params = {
            event: 'add_a_picture',
            value: isAlbum ? 'choose_from_album_confirm' : 'use_camera_confirm',
        }

        saveFoodCache('create', params)

        var savedFilePath = process.env.TARO_ENV=='rn'?res.tempFiles[0].path:res.tempFiles[0].tempFilePath

        // var savedFilePath = res.savedFilePath
        await Taro.setStorage({key:'pic', data:savedFilePath})
        setImgUrl(savedFilePath as any)

        uploadFile(savedFilePath, isAlbum ? 'album' : 'camera')


    }
    function chooseFailed(res, isAlbum) {
        var params = {
            event: 'add_a_picture',
            value: isAlbum ? 'choose_from_album_cancel' : 'use_camera_cancel',
        }

        saveFoodCache('create', params)
    }


    function uploadFile(path, source) {
        Taro.showLoading({
            title: '加载中'
        })
        var dot = path.lastIndexOf('.')
        var fileExt = dot > 0 ? path.substring(dot) : ''
        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) => {
                if (rsp.statusCode != 200) {
                    Taro.showToast({
                        title: '操作失败，请检查网络',
                        icon: 'none'
                    })
                    return
                }
                Taro.uploadFile({
                    url: rsp.data.upload_url,
                    filePath: path,
                    name: 'file',
                    formData: rsp.data.fields,
                    success: rlt => {
                        createData(rsp.data.view_url, source)

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

    async function createData(url, source) {
        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());
        var event = await getFoodCache('create')
        debugger
        createFoodJournal({
            media: [{
                url,
                type: url.indexOf('mp4') != -1 ? 'video' : 'image',
                source: source
            }],
            start: {
                timestamp: time,
                date: strDate
            },
            mindful_mode: modeOn ? 'AWARE' : 'NORMAL',
            extra: {
                event: event
            }

        }).then(res => {
            props.addItem(res)
            setImgUrl('')
            Taro.removeStorage({key:'pic'})
            Taro.hideLoading()
            setFirstData(res)
            clearFoodCache('create')
        }).catch(e => {
            Taro.hideLoading()
        })
    }

    async function modeChange(e) {

        setModeOn(e.detail.value)
        await Taro.setStorage({key:'food_switch', data:e.detail.value})

        var params = {
            event: 'switch_toggle',
            value: e.detail.value ? 'on' : 'off',
        }


        saveFoodCache('create', params)
    }

    function more() {
        const resource = common.resources.filter((item: any) => {
            return item.code == 'about_mindful_eating'
        })

        jumpPage('/pages/common/H5?title=' + '' + '&url=' + resource[0].url)
    }

    function getLineBottom() {
        if (user.isLogin) {
            return props.firstItem ? -rpxToPx(60) : 0
        }
        else {
            return props.firstItem ? 0 : rpxToPx(60)
        }
    }

    function clickSwitch() {
        if (lastUnFinished) {
            vibrate('heavy')
            Taro.showModal({
                title: t('feature.common.prompt'),
                content: t('feature.food.disable_switch_modal_title'),
                confirmText: t('feature.food.disable_switch_modal_btn'),
                showCancel: false
            })
        }
    }

    return <View style={{ marginBottom: rpxToPx(60) }}>
        <View className='food_console_box'>
            <View style={{ display: 'flex', flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                <Text className='food_console_title'>感知模式</Text>
                <Switch className='myswitch'
                    onClick={clickSwitch}
                    disabled={lastUnFinished} checked={modeOn}
                    color={props.firstItem && props.firstItem.status == 'WAIT_FOR_POSTMEAL' ? ColorType.food : ColorType.fast}
                    style={{ marginRight: rpxToPx(40), opacity: lastUnFinished ? 0.4 : 1 }}
                    onChange={modeChange} />
            </View>
            {
                modeOn && <View className='food_console_desc'>
                    <View className='food_console_desc_point'
                        style={{
                            backgroundColor: props.firstItem && props.firstItem.status == 'WAIT_FOR_POSTMEAL' ? ColorType.food : ColorType.fast,
                            marginTop: props.firstItem && props.firstItem.status == 'WAIT_FOR_POSTMEAL' ? rpxToPx(46 + 18) : rpxToPx(18)
                        }} />
                    <Text style={{ color: '#ffffff66' }}>{t('feature.food.sence_desc')}</Text>
                </View>
            }
            {
                !modeOn && <View className='food_console_desc_off'>
                    <Text style={{ color: '#ffffff66' }}>{t('feature.food.sence_desc_off')}</Text>
                </View>
            }
        </View>
        {
            !lastUnFinished && <View style={{ display: 'flex', position: 'relative', width: rpxToPx(750), alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }}>
                <View style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                    <View className='camera_bg' onClick={() => choose(false)}>
                        <Image src={require('@assets/images/camera2.png')} className='camera_icon' />
                        <Text className='camera_text'>{t('feature.food.camera')}</Text>
                        <Text className='album_text'>{t('feature.food.album')}</Text>
                        <View className='album_bottom' onClick={(e) => {
                            choose(true);
                            if (process.env.TARO_ENV == 'weapp') {
                                e.stopPropagation()
                            }
                        }} />
                    </View>
                    {
                        modeOn && <View style={{ height: rpxToPx(60) }} />
                    }
                    {modeOn && <Slider edit={true} />}
                </View>
                <View className='center_line2' style={{ bottom: getLineBottom() }} />
            </View>
        }

    </View>
}