import formatMilliseconds from "@/utils/format_time";
import { View, Text, Image } from "@tarojs/components";
import './History.scss'
import Taro from "@tarojs/taro";
import dayjs from "dayjs";
import { useSelector } from "react-redux";
import { getThemeColor } from "./hooks/health_hooks";
import Rings, { RingCommon, BgRing, TargetRing, CurrentDot } from "@/features/trackTimeDuration/components/Rings";
import { MainColorType } from "@/context/themes/color";
import { durationArc, startArc } from "./util";
import { IconLongFast, IconMore } from "@/components/basic/Icons";
import showActionSheet from "@/components/basic/ActionSheet";
import { delRecord, makeDone } from "@/services/health";
import showAlert from "@/components/basic/Alert";
import { rpxToPx } from "@/utils/tools";
import NewButton, { NewButtonType } from "@/_health/base/new_button";
import TimeTitleDesc from "@/_health/components/time_title_desc";
import CoverList from "@/_health/components/cover_list";
import { TimeFormatter } from "@/utils/time_format";
import { jumpPage } from "../trackTimeDuration/hooks/Common";
import TargetProgress from "@/_health/components/target_progress";
import Cell from "@/_health/base/cell";
import { setFirstActiveId, setFirstEatId } from "@/store/health";
import JournalCover from "../journal/components/journal_cover";
import TimelineDate from "@/_health/components/timeline_date";
import { useEffect } from "react";

export default function HistoryItem(props: {
    data: any,
    preData: any,
    index: number,
    onClick: Function,
    isArchived?: boolean,
    refresh?: Function,
    mode: string,
    fast_type?: string,
    hideLine?: boolean,
    type?: string
}) {
    const health = useSelector((state: any) => state.health);
    const scale = '?x-oss-process=image/format,webp/resize,w_400'

    useEffect(()=>{
        return ()=>{
            console.log('dealloc history item')
        }
    },[])

    function goDetail(event_id?: any) {
        // debugger
        if (props.mode == 'EAT' || props.mode == 'ACTIVE') {
            // jumpPage(`/_health/pages/timeline_detail?event_id=${event_id}&fast_type=${props.fast_type}&isfastsleep=0`)
        }
        else {
            jumpPage(`/_health/pages/timeline_detail?disable_edit=1&window_id=${props.data.window_id}&fast_type=${props.fast_type}&type=recent&isfastsleep=${props.mode == 'FAST,SLEEP' ? 1 : 0}`)
        }

    }

    function singleItem(type, url, obj, key,urls=[]) {
        return <View
            onClick={(e) => {
                if (process.env.TARO_ENV == 'weapp') {
                    e.stopPropagation()
                }
                if (type == 'PIC') {
                    var temp: any = null
                    props.data.events.map(item => {
                        item.moments && item.moments.map(moment => {
                            if (moment.media && moment.media.length > 0) {
                                if (moment.media[0].url == url) {
                                    temp = item
                                }
                            }
                        })
                    })
                    if (temp) {
                        jumpPage(`/_health/pages/timeline_detail?disable_edit=1&event_id=${temp.id}&isfastsleep=0`)
                    }
                }
                else {
                    jumpPage(`/_health/pages/timeline_detail?disable_edit=1&event_id=${obj.event_id}&isfastsleep=0`)
                }
            }}
            style={{ display: 'flex', flexDirection: 'row', marginBottom: rpxToPx(12), flex: 1 }} key={key * 1000}>
            {
                type == 'TEXT' && <View style={{
                    display: 'flex',
                    flex: 1,
                    flexShrink: 0,
                    flexDirection: 'column',
                    backgroundColor: '#fafafa',
                    paddingLeft: rpxToPx(20),
                    paddingRight: rpxToPx(20),
                    paddingTop: rpxToPx(12),
                    paddingBottom: rpxToPx(12)
                }}><TimeTitleDesc
                        className={'line3'}
                        time=''
                        title={obj.title}
                        desc={obj.description}
                    />
                </View>
            }
            {
                type == 'PIC' && <CoverList imgs={[url]} count={1} />
            }
            {
                type == 'PIC_TEXT' && <View  onClick={(e) => {
                    if (process.env.TARO_ENV == 'weapp') {
                        e.stopPropagation()
                    }
                    Taro.previewImage({
                        current: urls[0],
                        urls: urls
                    })
                }}>
                    <JournalCover imgs={urls} />
                </View>
                
                // <Image
                //     className="gray_bg"
                //     style={{ width: rpxToPx(178), height: rpxToPx(178), marginRight: rpxToPx(7), flexShrink: 0 }}
                //     src={url+scale}
                //     onClick={(e) => {
                //         if (process.env.TARO_ENV == 'weapp') {
                //             e.stopPropagation()
                //         }
                //         Taro.previewImage({
                //             current: url,
                //             urls: [url]
                //         })
                //     }}
                //     mode="aspectFill" />

            }
            {
                type == 'PIC_TEXT' && <View style={{
                    display: 'flex',
                    flex: 1,
                    flexShrink: 0,
                    flexDirection: 'column',
                    backgroundColor: 'transparent',
                    // paddingLeft: rpxToPx(17),
                    paddingRight: 0,
                    paddingTop: 0,
                    paddingBottom: 0
                }}>
                    <TimeTitleDesc
                        className={'line3'}
                        time=''
                        title={obj.title}
                        desc={obj.description}
                    />
                </View>
            }
        </View>
    }

    function imgText() {
        if (props.data.texts.length == 0 && props.data.pics.length == 0) {
            return <View />
        }

        return <View style={{
            display: 'flex', flexDirection: 'row',
            // backgroundColor:'pink', 
            marginBottom: rpxToPx(12),
            overflow: 'hidden',
            width: rpxToPx(554),
            flex: 1
        }}>

            {
                props.data.pics.length > 0 && <JournalCover imgs={props.data.pics} />
            }

            <View style={{
                display: 'flex',
                flexDirection: 'column',
                flex: 1,
                overflow: 'hidden',
                backgroundColor: props.data.pics.length == 0 ? '#fafafa' : 'transparent',
                paddingLeft: props.data.pics.length == 0 ? rpxToPx(20) : 0,
                paddingRight: props.data.pics.length == 0 ? rpxToPx(40) : 0,
                paddingTop: props.data.pics.length == 0 ? rpxToPx(12) : 0,
                paddingBottom: props.data.pics.length == 0 ? rpxToPx(12) : 0,
                // marginRight: rpxToPx(40),
                flexShrink: 0
            }}>
                {

                    props.data.texts.map((item2, index2) => {
                        return <TimeTitleDesc
                            key={index2 * 1000}
                            className='line1'//{item.pics.length == 0 ? 'line2' : 'line3'}
                            // style={{ width: props.data.pics.length > 0 ? rpxToPx(310) : rpxToPx(512) }}
                            time=''
                            title={item2.title}
                            desc={item2.description}
                        />
                    })
                }




            </View>
        </View>
    }

    return <View className="history_item2" onClick={goDetail}>
        <TimelineDate timestamp={props.data.window_range.start_timestamp}
            pre_timestamp={props.preData ? props.preData.window_range.start_timestamp : null}
        />
        <View className="history_content" style={{ paddingTop: rpxToPx(0) }}>
            {
                props.mode != 'EAT' && props.mode != 'ACTIVE' && props.data.dataArray.map((content, i) => {
                    var urlArray:any = []
                    if (content.type == 'PIC_TEXT'){
                        urlArray = content.data[0].urls.map(obj => obj.url);
                    }
                    

                    return <View style={{ display: 'flex', flexDirection: 'row', marginBottom: rpxToPx(12), flex: 1 }} key={i}>
                        {
                            content.type == 'TEXT' && <View style={{
                                display: 'flex',
                                flex: 1,
                                flexShrink: 0,
                                flexDirection: 'column',
                                backgroundColor: '#fafafa',
                                paddingLeft: rpxToPx(20),
                                paddingRight: rpxToPx(20),
                                paddingTop: rpxToPx(12),
                                paddingBottom: rpxToPx(12)
                            }}>{content.data.map((detail, j) => {
                                return <TimeTitleDesc
                                    key={j * 100}
                                    className={'line2'}
                                    time=''
                                    title={detail.title}
                                    desc={detail.description}
                                />
                            })}</View>
                        }
                        {
                            content.type == 'PIC' && <CoverList imgs={content.data} count={content.data.length} />
                        }
                        {
                            
                            content.type == 'PIC_TEXT' && <View style={{marginRight: rpxToPx(7)}} onClick={(e) => {
                                if (process.env.TARO_ENV == 'weapp') {
                                    e.stopPropagation()
                                }
                                Taro.previewImage({
                                    current: urlArray[0],
                                    urls: urlArray
                                })
                            }}>
                                <JournalCover imgs={urlArray} />
                            </View>
                            // <Image
                            //     className="gray_bg"
                            //     style={{ width: rpxToPx(178), height: rpxToPx(178), marginRight: rpxToPx(7), flexShrink: 0 }}
                            //     src={content.data[0].url+scale}
                            //     onClick={(e) => {
                            //         if (process.env.TARO_ENV == 'weapp') {
                            //             e.stopPropagation()
                            //         }
                            //         Taro.previewImage({
                            //             current: content.data[0].url,
                            //             urls: [content.data[0].url]
                            //         })
                            //     }}
                            //     mode="aspectFill" />
                        }
                        {
                            content.type == 'PIC_TEXT' && <View style={{
                                display: 'flex',
                                flex: 1,
                                flexShrink: 0,
                                flexDirection: 'column',
                                backgroundColor: 'transparent',
                                paddingLeft: rpxToPx(17),
                                paddingRight: 0,
                                paddingTop: 0,
                                paddingBottom: 0
                            }}>
                                <TimeTitleDesc
                                    className={'line3'}
                                    time=''
                                    title={content.data[0].title}
                                    desc={content.data[0].description}
                                />
                            </View>
                        }
                    </View>

                })
            }

            {
                props.mode != 'EAT' && props.mode != 'ACTIVE' && imgText()
            }

            {
                (props.mode == 'EAT' || props.mode == 'ACTIVE') && props.data.dataArray.map((content, i) => {
                    switch (content.type) {
                        case 'TEXT':
                            {
                                return content.data.map((detail, j) => {
                                    return singleItem('TEXT', '', detail, j * 10)
                                })
                            }
                            break
                        case 'PIC':
                            {
                                return content.data.map((detail, j) => {
                                    return singleItem('PIC', detail, '', j * 10)
                                })
                            }
                            break
                        case 'PIC_TEXT':
                            const urlArray = content.data[0].urls.map(obj => obj.url);
                            return singleItem('PIC_TEXT', content.data[0].url, content.data[0], i,urlArray)
                            break
                    }
                })
            }

            {
                props.type != 'FAST,SLEEP' && props.mode != 'EAT' && props.mode != 'ACTIVE' && props.data.windows.map((item, index) => {
                    return <TargetProgress key={index} showLine={index < props.data.windows.length - 1}
                        color={getThemeColor(item.window)}
                        showRing={props.fast_type != 'LF'}
                        desc={item.description}
                        icon={
                            props.fast_type == 'LF' ? <IconLongFast color={MainColorType.fast} width={rpxToPx(32)} /> : null
                        }
                        canvasId={`${item.window}${item.window_range.start_timestamp}${index}`}
                        startTimestamp={item.window_range.start_timestamp}
                        endTimerstamp={item.window_range.end_timestamp}
                    />
                })
            }

            {
                props.type == 'FAST,SLEEP' && props.data.windows.length >= 2 && <TargetProgress
                    showRing={true}
                    doubleRing={true}
                    first={props.data.windows[0]}
                    second={props.data.windows[1]}
                    canvasId={`double_${props.data.windows[0].window_range.start_timestamp}`}
                />
            }
            {/* fast_sleep双环无法展示时，显示一个placeholder 骨架图 */}
            {
                props.type == 'FAST,SLEEP' && props.data.windows.length < 2 && <View className='history_duration_bg' />
            }
            <View style={{ height: rpxToPx(0), flexShrink: 0 }} />
        </View>

    </View>
}