import { View, Text, Textarea, Image, Input, ScrollView } from "@tarojs/components";
import Taro, { useLoad, useRouter, useUnload } from "@tarojs/taro";
import { useTranslation } from "react-i18next";
import './add_moment.scss'
import { useEffect, useState } from "react";
import { saveFoodCache } from "@/features/food/hooks/ExtraData";
import { baseUrl } from "@/services/http/api";
import { checkAuthorized } from "@/utils/check_authorized";
import { eatMeals } from "@/services/trackSomething";
import Modal from "@/components/layout/Modal.weapp";
import dayjs from "dayjs";
import TimePicker from "@/features/common/TimePicker";
import { MainColorType } from "@/context/themes/color";
import { createMoment, getLabelsEvent, updateMoment } from "@/services/health";
import { useDispatch, useSelector } from "react-redux";
import { getThemeColor } from "@/features/health/hooks/health_hooks";
import { setShowActionTip } from "@/store/health";
import DurationPicker from "../components/duration_picker";
import NewModal from "../base/new_modal";
import PostMomentTime from "../components/post_moment_time";
import AddLabel from "../components/add_label";
import showAlert from "@/components/basic/Alert";
import NewButton, { NewButtonType } from "../base/new_button";
import { rpxToPx } from "@/utils/tools";
import StatusIndicator, { StatusType } from "../base/status_indicator";
import { IconCheck } from "@/components/basic/Icons";


let useRoute;
let useNavigation;
let scenario = '';
if (process.env.TARO_ENV == 'rn') {
    useRoute = require("@react-navigation/native").useRoute
    useNavigation = require("@react-navigation/native").useNavigation
}

export default function AddMoment() {
    const [desc, setDesc] = useState('')
    const { t } = useTranslation()
    const [imgUrl, setImgUrl] = useState('')
    const [showPicker, setShowPicker] = useState(false)
    const [durationPicker, setDurationPicker] = useState(false)
    const [durationT, setDurationT] = useState(0)
    const dispatch = useDispatch()
    const health = useSelector((state: any) => state.health);
    const [timestamp, setTimestamp] = useState(new Date().getTime())
    const [showTimePicker, setShowTimePicker] = useState(false)
    const [showTitlePicker, setShowTitlePicker] = useState(false)
    const [isYesterday, setIsYesterday] = useState(false)
    const [labels, setLabels] = useState<any>([])
    const [bottom, setBottom] = useState(-120)



    let router
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

    if (process.env.TARO_ENV == 'rn') {
        router = useRoute()
    }
    else {
        router = useRouter()
    }

    const [time, setTime] = useState(dayjs().format('HH:mm'))
    const [selDate, setSelDate] = useState(dayjs().format('YYYY-MM-DD'))
    const [title, setTitle] = useState(router.params.title)

    const { event_id, is_temp, schedule_id } = router.params

    const moment = router.params.moment ? JSON.parse(router.params.moment) : null

    useEffect(() => {
        global.set_time = new Date().getTime()

        // Taro.onKeyboardHeightChange(res => {
        //     setBottom(res.height > 0 ? res.height : -120)
        // })


        getLabelsEvent({ window: health.mode, use: is_temp ? 'ONE_RECORD' : '' }).then(res => {
            setLabels((res as any).labels)
            if (is_temp && title == '') {
                // setShowTitlePicker(true)
            }
        })


        if (router.params.edit) {
            var detail = JSON.parse(router.params.detail)
            setTitle(detail.title)
            var moment = detail.moments[0]
            setDesc(moment.description)
            var timeObj = moment.time
            setTime(dayjs(timeObj.timestamp).format('HH:mm'))
            setSelDate(dayjs(timeObj.timestamp).format('YYYY-MM-DD'))
            if (moment.media.length > 0) {
                setImgUrl(moment.media[0].url)
            }
        }
        else {
            debugger
            Taro.enableAlertBeforeUnload({
                message: 'hhh',
                success(res) {

                },
                fail(res) {

                },
                complete(res) {

                },
            })
        }
    }, [])

    useLoad(() => {

    })

    useUnload(() => {
        Taro.disableAlertBeforeUnload({

        })
    })



    function duration() {
        const seconds = durationT / 1000
        var hours = Math.floor(seconds / 3600)
        var minutes = Math.floor((seconds % 3600) / 60)
        // const { hours, minutes } = getIntervalHoursAndMinutes(meal.schedule_end_time, meal.schedule_start_time)
        var time = ''
        if (hours > 0) {
            time = hours + '小时'
        }
        if (minutes > 0) {
            time += minutes + '分钟'
        }
        return time
    }

    function tapTime() {
        setShowPicker(true)
    }

    function tapDuration() {
        setDurationPicker(true)
    }

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

    function save() {
        // if (desc.length == 0 && imgUrl.length == 0) {
        //     Taro.showToast({
        //         icon: 'none',
        //         title: '请输入描述或添加图片'
        //     })
        //     return
        // }
        if (router.params.edit) {
            edit()
            return
        }
        // var date = new Date(timestamp)
        // var hour = parseInt(time.split(':')[0] + '')
        // var minute = parseInt(time.split(':')[1] + '')
        // date.setHours(hour)
        // date.setMinutes(minute)
        // var timestamp1 = date.getTime()
        // if (isYesterday) {
        //     timestamp1 -= 24 * 3600 * 1000
        // }
        // debugger

        var date = new Date(selDate + ' ' + time + ':00')

        var params: any = {
            schedule_id: schedule_id,
            title: title,
            description: desc,
            start: {
                date: dayjs(date.getTime()).format('YYYYMMDD'),
                timestamp: date.getTime()
            }
        }


        if (imgUrl.length > 0) {
            params.media = [{
                url: imgUrl,
                type: imgUrl.indexOf('mp4') != -1 ? 'video' : 'image',
                source: 'album'
            }]
        }
        if (event_id && event_id != 'undefined') {
            params.event_id = event_id
        }

        if (is_temp) {
            params.event = health.mode == 'EAT' ? 'EAT_CUSTOM' : 'ACTIVE_CUSTOM'
        }
        // if (moment.target && moment.target.duration) {
        //     params.duration = durationT//moment.target.duration
        // }

        if (durationT) {
            params.duration = durationT * 60 * 1000
        }


        params.extra = {
            set_time: global.set_time ? global.set_time : new Date().getTime(),
            confirm_time: new Date().getTime()
        }
        createMoment(params).then(res => {
            if (process.env.TARO_ENV == 'weapp') {
                // Taro.navigateBack();
                Taro.redirectTo({
                    url: '/_health/pages/post_result?data=' + JSON.stringify(res)
                })
            }

            if (health.mode == 'EAT') {
                dispatch(setShowActionTip({
                    isShow: true,
                    isCompleted: false
                }))
            }

            Taro.disableAlertBeforeUnload({

            })

            global.refreshWindow()
            global.refreshHistory()
        })
    }

    function edit() {
        var date = new Date(selDate + ' ' + time + ':00')

        var params: any = {
            schedule_id: schedule_id,
            title: title,
            description: desc,
            start: {
                date: dayjs(date.getTime()).format('YYYYMMDD'),
                timestamp: date.getTime()
            }
        }


        if (imgUrl.length > 0) {
            params.media = [{
                url: imgUrl,
                type: imgUrl.indexOf('mp4') != -1 ? 'video' : 'image',
                source: 'album'
            }]
        }
        if (event_id && event_id != 'undefined') {
            params.event_id = event_id
        }

        if (is_temp) {
            params.event = health.mode == 'EAT' ? 'EAT_CUSTOM' : 'ACTIVE_CUSTOM'
        }
        // if (moment.target && moment.target.duration) {
        //     params.duration = durationT//moment.target.duration
        // }

        if (durationT) {
            params.duration = durationT * 60 * 1000
        }

        Taro.disableAlertBeforeUnload({

        })


        params.extra = {
            set_time: global.set_time ? global.set_time : new Date().getTime(),
            confirm_time: new Date().getTime()
        }
        updateMoment(params, router.params.id).then(res => {
            if (process.env.TARO_ENV == 'weapp') {
                Taro.navigateBack();
                // Taro.redirectTo({
                //     url: '/_health/pages/post_result?data=' + JSON.stringify(res)
                // })
            }

            global.refreshWindow()
            global.refreshHistory()
            global.refreshMoment()
        })
    }

    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 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 => {
                        setImgUrl(rsp.data.view_url)
                        Taro.hideLoading()
                        // 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
                        })
                    }
                })
            }
        })
    }

    function timeContent() {
        return <Modal
            testInfo={null}
            dismiss={() => {
                setShowPicker(false)
            }}
            confirm={() => { }}>
            {
                pickerContent()
            }
        </Modal>
    }

    function pickerContent() {
        return <TimePicker time={time}
            color={MainColorType.eat}
            title={title}
            confirm={(e) => {
                confirmPickerTime(e)
            }}
            cancel={() => {
                setShowPicker(false)
            }} />
    }

    function confirmPickerTime(e) {
        const list = e.split(':')
        const date = new Date()
        date.setHours(list[0])
        date.setMinutes(list[1])

        console.log(date)
        setTimestamp(date.getTime())
        setShowPicker(false)
    }

    function durationContent() {
        return <View></View>
    }

    function getDate() {
        var sel = dayjs(selDate)
        var now = dayjs().format('YYYY-MM-DD')
        const yesterday = dayjs().subtract(1, 'day');
        if (sel.format('YYYY-MM-DD') == now) {
            return ''
        }
        if (yesterday.format('YYYY-MM-DD') == sel.format('YYYY-MM-DD')) {
            return global.language == 'en' ? 'Yesterday ' : '昨天 '
        }
        else {
            return global.language == 'en' ? sel.format('MMM D ') : sel.format('MMMD日 ')
        }

    }


    return <View>
        {/* {
            health.mode != 'FAST' && health.mode != 'SLEEP' &&
            <View className="addmoment_header">
                <Text className="header_time" onClick={tapTime} style={{ color: getThemeColor(health.mode) }}>{dayjs().format('HH:mm')}</Text>
                {
                    (health.mode == 'EAT' || health.mode == 'ACTIVE') && <View className="header_line" />
                }
                {
                    (health.mode == 'EAT' || health.mode == 'ACTIVE') && <Text className="header_time" style={{ color: getThemeColor(health.mode) }} onClick={tapDuration}>{duration()}</Text>
                }
            </View>
        } */}

        <View style={{
            display: 'flex',
            backgroundColor: '#fff',
            // padding: rpxToPx(40),
            flexDirection: 'column',
            height: rpxToPx(642),
            width: rpxToPx(750),
            boxSizing: 'border-box'

        }}>
            <View className="addmoment_header" onClick={() => {
                setShowTimePicker(true)
            }}>
                <StatusIndicator type={StatusType.big}
                    color={getThemeColor(health.mode)}
                    fontSize={rpxToPx(30)}
                    fontColor={getThemeColor(health.mode)}
                    text={getDate() + time}>
                    <IconCheck color="#fff" width={rpxToPx(24)} height={24} />
                </StatusIndicator>
                <View className="h22" style={{ color: MainColorType.link, marginTop: rpxToPx(8) }}>编辑打卡</View>

            </View>

            <Input className="meal_name" value={title}
                placeholder={health.mode == 'EAT' ? 'Meal Name' : 'Active Name'}
                style={{ caretColor: getThemeColor(health.mode) }}
                // cursorColor='#ff0000'
                // onFocus={() => {
                //     setTitleFocus(true)
                // }}
                // onBlur={() => {
                //     setTitleFocus(false)
                // }}
                onInput={(e: any) => {
                    setTitle(e.target.value)
                }}
                onKeyboardHeightChange={(e) => {
                    setBottom(e.detail.height > 0 ? e.detail.height : -120)
                }}

            />

            <Textarea placeholder="简单描述（选填）" className="textarea g01"
                placeholder-style="color:#B2B2B2"
                value={desc}
                onInput={e => {
                    setDesc(e.detail.value)
                }} />

            <View className="form">
                {
                    imgUrl.length > 0 && <View className="cover" ><NewButton type={NewButtonType.img} onClick={() => addImage(false)}><Image src={imgUrl} mode="aspectFill" className="cover" onClick={addImage} /></NewButton></View>
                }
                {
                    imgUrl.length == 0 && <View style={{ display: 'flex', flexDirection: 'row' }}>
                        <View className="cover" ><NewButton type={NewButtonType.img} onClick={() => addImage(false)}><View className="cover" >
                            <Image src={require('@assets/_health/album.png')} style={{ width: 40, height: 40 }} />
                        </View></NewButton></View>
                        <View className="cover" style={{ marginLeft: rpxToPx(40) }}><NewButton type={NewButtonType.img} onClick={() => addImage(true)}><View className="cover" >
                            <Image src={require('@assets/_health/camera.png')} style={{ width: 40, height: 40 }} />
                        </View></NewButton></View>
                    </View>
                }

            </View>
        </View>


        <View style={{ flex: 1 }} />

        <View className="main_footer"><NewButton
            type={NewButtonType.fill}
            color={getThemeColor(health.mode)}
            width={rpxToPx(646)}
            height={rpxToPx(96)}
            title={t('health.log')}
            onClick={save}
        /></View>


        {/* <View className="save" style={{ backgroundColor: getThemeColor(health.mode) }} onClick={save}>Save</View> */}
        {
            showPicker && timeContent()
        }
        {
            showTimePicker && <PostMomentTime
                time={time}
                date={selDate}
                isTemp={is_temp}
                moment={moment}
                onChange={(e) => {
                    const { date, duration, time, isYesterday } = e;
                    setTime(time)
                    setSelDate(date)
                    setIsYesterday(isYesterday)
                    setDurationT(duration)
                    setShowTimePicker(false)
                }} dismiss={() => {
                    setShowTimePicker(false)
                }} />
        }
        {
            <View className="tag_list" style={{ bottom: bottom }}>
                <ScrollView style={{ width: rpxToPx(750), flexDirection: 'row', display: 'flex', height: rpxToPx(108) }} scrollX enableFlex showScrollbar={false}>
                    <View style={{ width: rpxToPx(40), flexShrink: 0 }} />
                    {
                        labels.map((item, index) => {
                            return <View className="add_page_tag_btn" key={index} onClick={() => {
                                setTitle(item.title)
                            }}>{item.title}</View>
                        })
                    }
                    <View style={{ width: rpxToPx(40), flexShrink: 0 }} />
                </ScrollView>
            </View>
        }

    </View>
}