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 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";
import showActionSheet from "@/components/basic/ActionSheet";


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 [enterTimestmap] = useState(new Date().getTime())
    const [desc, setDesc] = useState('')
    const { t } = useTranslation()
    const [imgUrl, setImgUrl] = useState('')
    const [showPicker, setShowPicker] = 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 [isYesterday, setIsYesterday] = useState(false)
    const [labels, setLabels] = useState<any>([])
    const [bottom, setBottom] = useState(-120)

    const [titleFocus, setTitleFocus] = useState(false)
    const [posting, setPosting] = useState(false)


    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()

        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 {
            Taro.enableAlertBeforeUnload({
                message: t('health.back_no_save'),
                success(res) {

                },
                fail(res) {

                },
                complete(res) {

                },
            })
        }
    }, [])

    useLoad(() => {

    })

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

        })
    })

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

    function save() {
        if (router.params.edit) {
            edit()
            return
        }

        var date = new Date(selDate + ' ' + time + ':' + dayjs(enterTimestmap).format('ss'))
        date.setMilliseconds(new Date(enterTimestmap).getMilliseconds())

        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()
        }
        if (posting) return
        setPosting(true)
        createMoment(params).then(res => {
            setTimeout(() => {
                setPosting(false)
            }, 1000)

            if (process.env.TARO_ENV == 'weapp') {
                // Taro.navigateBack();
                Taro.redirectTo({
                    url: '/_health/pages/post_result?data=' + JSON.stringify(res)
                })
            }

            Taro.disableAlertBeforeUnload({

            })

            global.refreshWindow()
            global.refreshHistory()

            if (global.postMomentSuccess) {
                global.postMomentSuccess()
            }
        }).catch(e => {
            debugger
            setPosting(false)
        })
    }

    function edit() {
        var date = new Date(selDate + ' ' + time + ':' + dayjs(enterTimestmap).format('ss'))

        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 (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()
        }

        if (posting) return
        setPosting(true)
        updateMoment(params, router.params.id).then(res => {
            setPosting(false)
            if (process.env.TARO_ENV == 'weapp') {
                Taro.navigateBack();
            }

            global.refreshWindow()
            global.refreshHistory()
            global.refreshMoment()
        }).catch(e => {
            setPosting(false)
        })
    }

    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

        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 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日 ')
        }
    }

    function showTags() {
        if (router.params.edit || !router.params.is_temp) return false

        return true
    }

    function tapPic(){
        showActionSheet({
            title:'',
            itemList:[t('health.choose_photo'),t('health.camera'),t('health.delete')],
            success: function (res) {
                switch(res){
                    case 0:
                        addImage(false)
                        break;
                    case 1:
                        addImage(true)
                        break;
                    case 2:
                        setImgUrl('')
                        break;
                }
            }
        })
    }


    return <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="h26" style={{ color: MainColorType.link, marginTop: rpxToPx(8) }}>{t('health.edit_time')}</View>

            </View>

            <Input className="meal_name" value={title}
                placeholder={health.mode == 'EAT' ? t('health.meal_label') : t('health.activity_title')}
                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)
                }}

            />

            <View style={{ position: 'relative' }}>
                <View className="border_footer_line" style={{ left: rpxToPx(96) }} />
            </View>

            {
                showTags() && <View className="tag_list">
                    <ScrollView style={{ width: rpxToPx(750), flexDirection: 'row', display: 'flex', height: rpxToPx(108) }} scrollX enableFlex showScrollbar={false}>
                        <View style={{ width: rpxToPx(96), flexShrink: 0 }} />
                        {
                            labels.map((item, index) => {
                                return <View className="add_page_tag_btn"
                                style={{
                                    backgroundColor:item.title==title?getThemeColor(health.mode):'#B2B2B21A',
                                    color:item.title==title?'#fff':'#000'
                                }}
                                key={index} onClick={() => {
                                    setTitle(item.title)
                                }}>{item.title}</View>
                            })
                        }
                        <View style={{ width: rpxToPx(40), flexShrink: 0 }} />
                    </ScrollView>
                </View>
            }

            <View style={{ height: rpxToPx(40), flexShrink: 0 }} />


            <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={() => tapPic()}><Image src={imgUrl} mode="aspectFill" className="cover" /></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_moment')}
            onClick={save}
        /></View>

        {
            showPicker && timeContent()
        }
        {
            showTimePicker && <PostMomentTime
                title={ t('health.log_time_title')}
                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>
}