import { View, Image, Text, Button } from "@tarojs/components";
import './FoodTimelineItem.scss'
import Taro from "@tarojs/taro";
import { useTranslation } from "react-i18next";
import { editFoodJournal } from "@/services/foodJournal";
import { useEffect, useState } from "react";
import LimitPickers from "@/components/input/LimitPickers";
import Modal from "@/components/layout/Modal";
import { ColorType } from "@/context/themes/color";
import { useSelector } from "react-redux";
import PickerViews from "@/components/input/PickerViews";
import { IconShare } from "@/components/basic/Icons";
import { TimeFormatter } from "@/utils/time_format";
import { baseUrl } from "@/services/http/api";

export default function Component(props: { data: any, index: number, delete: Function, preview: Function, update: Function }) {
    const common = useSelector((state: any) => state.common);
    const [detail, setDetail] = useState(props.data)
    const [count, setCount] = useState(0)
    const [showModal, setShowModal] = useState(false)
    const [showTagModal, setShowTagModal] = useState(false)
    const [isStart, setIsStart] = useState(false)
    const { t } = useTranslation()

    useEffect(() => {
        setDetail(props.data)
        if (props.index == 0) {
            global.food_share_img_url = props.data.cover
        }
    }, [props.data])

    function preview() {
        // Taro.previewImage({
        //     current: props.data.cover,
        //     urls: [props.data.cover]
        // })
        props.preview()
    }

    function showActionSheet() {
        Taro.showActionSheet({
            itemList: [t('feature.common.action_sheet.delete')]
        })
            .then(res => {
                switch (res.tapIndex) {
                    case 0:
                        Taro.showModal({
                            title: t('feature.common.modal.delete_item_title'),
                            content: t('feature.common.modal.delete_item_content'),
                            success: function (res) {
                                if (res.confirm) {
                                    props.delete();
                                }
                            }
                        })
                        break;
                }
            })
            .catch(err => {
                console.log(err.errMsg)
            })
    }

    function operateActionSheet() {
        Taro.showActionSheet({
            alertText: t('feature.food.action_sheet.alert_text'),
            itemList: [
                t('feature.food.action_sheet.tag'),
                t('feature.food.action_sheet.start_time'),
                t('feature.food.action_sheet.end_time'),
                t('feature.food.action_sheet.edit_pic'),
                t('feature.food.action_sheet.share_pic')]
        })
            .then(res => {
                switch (res.tapIndex) {
                    case 0:
                        setShowTagModal(true)
                        break;

                    case 1:
                        {
                            global.set_time = new Date().getTime()+24*3600*1000
                            setIsStart(true)
                            setShowModal(true)
                        }
                        break;
                    case 2:
                        {
                            global.set_time = new Date().getTime()+24*3600*1000
                            setIsStart(false)
                            setShowModal(true)
                        }
                        break;
                    case 3:
                        {
                            editPic();
                        };
                        break;
                    case 4:
                        share()
                        break;
                }
            })
            .catch(err => {
                console.log(err.errMsg)
            })
    }

    function editPic() {
        Taro.downloadFile({
            url: detail.cover,
            success: (res) => {
                Taro.editImage({
                    src: res.tempFilePath,
                    success: (res) => {
                        console.log(res.tempFilePath)
                        postPic(res.tempFilePath)
                    }
                })
                // Taro.showShareImageMenu({
                //     path: res.tempFilePath
                // })
            }
        })
    }

    function postPic(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)
                        updatePic(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 updatePic(url) {
        editFoodJournal({
            cover: {
                url: url,
                type: url.indexOf('mp4') != -1 ? 'video' : 'image'
            }
        }, detail.id).then(res => {
            setDetail(res)
            setCount(count + 1)

            props.update(res)
            Taro.hideLoading()
        }).catch(e => {
            Taro.hideLoading()
        })
    }

    function share() {
        Taro.downloadFile({
            url: detail.cover,
            success: (res) => {
                Taro.showShareImageMenu({
                    path: res.tempFilePath
                })
            }
        })
    }

    function updateTag(index) {
        var tag = common.meal_tags[index]
        editFoodJournal({
            meal_tag: {
                code: tag.code
            }
        }, detail.id).then(res => {
            var obj = detail
            // obj.tags = [tag]
            obj.meal_tag = {
                code: tag.code,
                label: tag.label
            }
            setDetail(obj)
            setCount(count + 1)

            props.update(res)
        }).catch(e => {

        })
    }

    function updateTime(e) {
        var date = new Date(e)
        var year = date.getFullYear()
        var month = date.getMonth() + 1
        var day = date.getDate()
        var obj: any;
        obj = {
            start: {
                date: (year + '') + (month < 10 ? '0' + month : month) + (day < 10 ? '0' + day : day),
                timestamp: e
            }
        }
        if (!isStart) {
            obj = {
                end: {
                    date: (year + '') + (month < 10 ? '0' + month : month) + (day < 10 ? '0' + day : day),
                    timestamp: e
                }
            }
        }

        editFoodJournal({
            ...obj
        }, detail.id).then(res => {
            setDetail(res)
            setCount(count + 1)
            props.update(res)
        }).catch(e => {

        })
    }

    function pickerTagIndex() {
        var list = common.meal_tags
        if (detail.meal_tag) {
            for (var i = 0; i < list.length; i++) {
                if (list[i].label == detail.meal_tag.label) {
                    return i;
                }
            }
        }

        return 3;
    }

    function pickerTagItems() {
        var list = common.meal_tags
        var tags: any = []
        list.map(item => {
            tags.push(item.label)
        })
        return [tags];
    }

    function tagChanged(data) {
        setShowTagModal(false)
        updateTag(data[0])
    }

    function getPickerLimit() {
        if (isStart) {
            return new Date().getTime() - 7 * 24 * 3600 * 1000
        }
        else {
            return detail.start.timestamp
        }
    }

    function getPickerInitValue() {
        if (isStart) {
            return detail.start.timestamp
        }
        else {
            return detail.end.timestamp ? detail.end.timestamp : new Date().getTime()
        }
    }

    return <View className="food_timeline_item" onLongPress={showActionSheet}>
        {/* <View className="thumb" style={{backgroundColor:'pink'}}/> */}

        <View style={{ flex: 1 }}>
            {
                props.index == 0 && !detail.meal_tag && <View className="tags">
                    {
                        common.meal_tags.map((item, index) => {
                            return index <= 2 ? <View className="tag-item" onClick={() => updateTag(index)}>
                                <Text style={{ color: ColorType.food }}>{item.label}</Text>
                            </View> : <View />

                        })
                    }
                    <View className="more_tag" onClick={() => { setShowTagModal(true) }}>更多标签</View>
                </View>
            }

        </View>
        <View className="thumb_bg">
            {/* <Image className="thumb" src={detail.cover.url} mode="aspectFill" onClick={preview} /> */}
            <Image className="thumb" src={detail.cover.url+'?x-oss-process=image/resize,w_300,limit_0'} mode="aspectFill" onClick={preview} />
            <View className="food_desc" onClick={operateActionSheet}>
                <Text className="food_desc_text">{detail.start && TimeFormatter.getMonthDayByTimestamp(detail.start.timestamp)}</Text>
                <Text className="food_desc_text">{detail.meal_tag && detail.meal_tag.label}</Text>
                <Text className="food_desc_text">{detail.start && TimeFormatter.getTimeByTimestamp(detail.start.timestamp)}</Text>
                {/* {
                    detail.end.timestamp && <Text>{'-' + getTime(detail.end.timestamp)}</Text>
                } */}
            </View>
        </View>
        {/* <Text className="food_item_date">{detail.start.date}</Text> */}
        <View style={{ flex: 1 }}>
            {
                props.index == 0 && <View className="food_share">
                    <IconShare color={ColorType.food} width={20} height={17} />
                    <Text className="food_share_text">分享</Text>
                    <Button openType="share" className="food_share_btn" />
                </View>
            }
        </View>
        {
            showModal && <Modal dismiss={() => { setShowModal(false) }} confirm={() => { setShowModal(false) }}>
                <View className='modal_content'>
                    <LimitPickers
                        isRealTime={true} time={getPickerInitValue()} limit={getPickerLimit()}
                        title={isStart ? t('feature.food.picker_start_title') : t('feature.food.picker_end_title')}
                        themeColor={ColorType.food}
                        limitDay={7} onCancel={() => { setShowModal(false) }}
                        onChange={(e) => {
                            updateTime(e)
                            setShowModal(false)
                        }} />
                </View>
            </Modal>
        }
        {
            showTagModal && <Modal dismiss={() => { setShowTagModal(false) }} confirm={() => { setShowTagModal(false) }}>
                <PickerViews title={t('feature.food.picker_tag_title')}
                    value={[pickerTagIndex()]}
                    items={pickerTagItems()}
                    onChange={(e) => { tagChanged(e) }}
                    onCancel={() => { setShowTagModal(false) }}
                    themeColor={ColorType.food}

                />
            </Modal>
        }

    </View>
}