import { View, Image, Text, Input, Textarea } from "@tarojs/components";
import { useSelector } from "react-redux";
import './timeline_detail.scss'
import '@features/health/History.scss'
import { useEffect, useState } from "react";
import Taro, { useRouter } from "@tarojs/taro";
import dayjs from "dayjs";
import { getThemeColor } from "@/features/health/hooks/health_hooks";
import { baseUrl } from "@/services/http/api";
import { checkAuthorized } from "@/utils/check_authorized";
import { createMoment, getEvents } from "@/services/health";
import NewButton, { NewButtonType } from "../base/new_button";
import { IconClose } from "@/components/basic/Icons";
import { rpxToPx } from "@/utils/tools";
import { MainColorType } from "@/context/themes/color";
import NewModal from "../base/new_modal";
import Card from "../components/card";
import ChooseDateTime from "../components/choose_date_time";
import TimeTitleDesc from "../components/time_title_desc";
import CoverList from "../components/cover_list";
import ListFooter from "../components/list_footer";

let timestamp = 0;
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 TimelineDetail() {
    const health = useSelector((state: any) => state.health);
    const user = useSelector((state: any) => state.user);
    const [list, setList] = useState<any>([])
    const [detail, setDetail] = useState<any>(null)
    const [desc, setDesc] = useState('')
    const [imgUrl, setImgUrl] = useState('')
    const [btnDisable, setBtnDisable] = useState(true)
    const [showPop, setShowPop] = useState(false)
    const [publish, setPublish] = useState<any>(null)
    const [bottom, setBottom] = useState(20)
    const [loaded, setLoaded] = useState(false)
    const [showTimePicker, setShowTimePicker] = useState(false)
    const [time, setTime] = useState(dayjs().format('HH:mm'))
    const [selTime, setSelTime] = useState(dayjs().format('HH:mm'))
    const [selDate, setSelDate] = useState(dayjs().format('YYYY-MM-DD'))
    let router
    let navigation;
    if (useNavigation) {
        navigation = useNavigation()
    }

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

    const { schedule_id, event_id } = router.params

    useEffect(() => {
        Taro.setNavigationBarColor({
            backgroundColor: showPop ? '#191919' : '#ffffff',
            frontColor: '#000000'
        })
    }, [showPop])

    useEffect(() => {
        Taro.onKeyboardHeightChange(res => {
            setBottom(res.height > 0 ? res.height : 20)
        })

        getDatas()
    }, [])

    useEffect(() => {
        if (desc.length > 0 || imgUrl.length > 0) {
            setBtnDisable(false)
        }
        else {
            setBtnDisable(true)
        }
    }, [desc, imgUrl])

    function getDatas() {
        getEvents(event_id).then(res => {
            setLoaded(true)
            setDetail(res)
            setList((res as any).moments)
            setPublish((res as any).publish)
        })
    }

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

    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 tapPost() {
        if (desc.length == 0 && imgUrl.length == 0) {
            Taro.showToast({
                icon: 'none',
                title: '请输入描述或添加图片'
            })
            return
        }
        var dt = new Date(selDate + ' ' + time + ':00')
        var params: any = {
            schedule_id: schedule_id,
            description: desc,
            start: {
                date: dayjs(dt.getTime()).format('YYYYMMDD'),
                timestamp: dt.getTime()
            },

            // real_end_time: meal.target_end_time,
        }


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

        params.event_id = event_id
        createMoment(params).then(res => {
            getDatas()
            setImgUrl('')
            setDesc('')
            global.refreshWindow()
            global.refreshHistory()
            setShowPop(false)
        })

    }

    function mediaCount() {
        let count = 0;
        list && list.map(moment => {
            moment.media.map((obj) => {
                count++
            })
        })
        return count;
    }

    function imgList() {
        var array: any = []
        list && list.map(moment => {
            moment.media.map((obj) => {
                array.push(obj.url)
            })
        })
        return array;
    }

    if (!loaded) return <View />

    return <View style={{ display: 'flex', flex: 1 }}>
        <View className="detail_header">
            <Image className="detail_header_header"
                src={user.avatar}
                mode="aspectFill"
            />
            <View className="detail_header_content">
                <Text className="detail_nickname">{user.nickname}</Text>
                {
                    (detail.scenario != 'MEAL' && detail.scenario != 'ACTIVITY') &&
                    <TimeTitleDesc
                        time={dayjs(detail.time.timestamp).format('HH:mm')}
                        title={detail.title}
                    />
                }
                {
                    detail.scenario == 'ACTIVITY' && !list &&
                    <TimeTitleDesc
                        time={dayjs(detail.time.timestamp).format('HH:mm')}
                        title={detail.title}
                    />
                }
                {
                    list && list.map((item, index) => {
                        return <View key={index} style={{ flexDirection: 'column', display: 'flex' }}>
                            <TimeTitleDesc
                                time={dayjs(item.time.timestamp).format('HH:mm')}
                                title={item.title}
                                desc={item.description}
                            />
                        </View>
                    })
                }
                {/* {
                    <View className="media" style={{ marginRight: mediaCount() == 4 ? 80 : 0, marginTop: rpxToPx(24) }}>
                        {
                            list && list.map(moment => {
                                return moment.media.map((obj, j) => {
                                    return <Image className="media_item" mode="aspectFill" onClick={() => { }} src={obj.url} key={j * 10} />
                                })
                            })

                        }

                    </View>
                } */}
                <View style={{ marginTop: rpxToPx(24) }}>
                    <CoverList imgs={imgList()} count={mediaCount()} />
                </View>
                {
                    publish && <View style={{display:'flex',flexDirection:'row',height:rpxToPx(60),alignItems:'center'}}>
                        <Text className="h24 g02">发布于{dayjs(publish.timestamp).format('MM-DD HH:mm')}</Text>
                    </View>
                }
            </View>
        </View>
        <ListFooter />
        {
            health.mode != 'ACTIVE' && health.mode != 'EAT' && <View className="add_note"><NewButton type={NewButtonType.link} title="写个笔记" onClick={() => {
                timestamp = new Date().getTime()
                setShowPop(true)

            }} /></View>
        }


        {
            showPop && <View className="publish_bg">
                <NewButton type={NewButtonType.img}
                    btnStyle={{
                        position: 'absolute', left: rpxToPx(52),
                        top: 0,
                        color: '#fff',
                        width: 32,
                        height: 32
                    }}
                    onClick={() => {
                        setShowPop(false)
                    }}>
                    <IconClose color="#fff" width={20} height={20} />
                </NewButton>
                <View onClick={() => setShowTimePicker(true)} style={{ height: rpxToPx(88), marginTop: rpxToPx(120), width: rpxToPx(80), color: MainColorType.link }}>{time}
                </View>
                <Textarea className="myTextarea" placeholder="What's on your mind?" style={{ flex: 1, color: '#fff', caretColor: getThemeColor(health.mode) }} focus value={desc} onInput={(e) => {
                    setDesc(e.detail.value)
                }} />
                <View className="toolbar2">
                    {
                        imgUrl.length > 0 && <NewButton type={NewButtonType.img} onClick={() => addImage(false)}>
                            <Image src={imgUrl} mode="aspectFill" className="album" />
                        </NewButton>
                    }
                    {
                        imgUrl.length == 0 && <NewButton type={NewButtonType.img} onClick={() => addImage(false)}>
                            <Image src={require('@assets/_health/album.png')} className="album"
                            />
                        </NewButton>
                    }
                    {
                        imgUrl.length == 0 && <NewButton type={NewButtonType.img} onClick={() => addImage(true)}>
                            <Image src={require('@assets/_health/camera.png')} className="album"
                            /></NewButton>
                    }


                    <View style={{ flex: 1 }} />
                    <View className="btn" style={{ backgroundColor: btnDisable ? '#b2b2b2' : getThemeColor(health.mode) }} onClick={tapPost}>发布</View>
                </View>
                <View style={{ height: bottom, flexShrink: 0 }} />
            </View>
        }
        {
            showTimePicker && <NewModal
                title='时间'
                dismiss={() => setShowTimePicker(false)}
                confirm={() => {
                    // props.onChange({
                    //     date: selDate,
                    //     time: time,
                    //     duration: minutes,
                    //     isYesterday: isYesterday
                    // })
                    setTime(selTime)
                    setShowTimePicker(false)
                }}
                themeColor={getThemeColor(health.mode)}>
                <Card>
                    <ChooseDateTime title={null}
                        disable={false}
                        color={getThemeColor(health.mode)}
                        expand={true}
                        time={time}
                        hideFooter={true}
                        timeChange={(e) => {
                            setSelTime(e)
                        }}
                        minTimestamp={new Date().getTime()}
                        date={selDate}
                        dateChange={(e) => {
                            setSelDate(e)
                        }}
                    />
                </Card>
            </NewModal>
        }
    </View>
}