import { View, Text, Image } from "@tarojs/components";
import './guide.scss'
import '@/_health/pages/schedules.scss'
import NewHeader, { NewHeaderType } from "../components/new_header";
import { useEffect, useState } from "react";
import { createSchedule, delSchedule, getLabelsEvent, getSchedules } from "@/services/health";
import { setFooter, setSchedules } from "@/store/health";
import { useDispatch, useSelector } from "react-redux";
import Card from "../components/card";
import { rpxToPx } from "@/utils/tools";
import { getScenario, getThemeColor } from "@/features/health/hooks/health_hooks";
import Modal from "@/components/layout/Modal.weapp";
import TimePicker from "@/features/common/TimePicker";
import NewButton, { NewButtonType } from "../base/new_button";
import { MainColorType } from "@/context/themes/color";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import { IconAdd } from "@/components/basic/Icons";
import AddLabel from "../components/add_label";
import ScheduleItem from "../components/schedule_item";
import { useTranslation } from "react-i18next";
import showAlert from "@/components/basic/Alert";
import CellFooter, { CellFooterType } from "../base/cell_footer";
import CellFooterText from "../base/cell_footer_text";
import StatusIndicator, { StatusType } from "../base/status_indicator";
import Taro from "@tarojs/taro";

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 GuideEat() {
    const systemInfo: any = Taro.getWindowInfo();
    const navigationBarHeight = systemInfo.statusBarHeight + 44;
    const user = useSelector((state: any) => state.user);
    const health = useSelector((state: any) => state.health);
    const [list, setList] = useState<any>(health.schedules)
    const [errors, setErrors] = useState<any>([])
    const [highlight, setHighlight] = useState(true)
    const [showModal, setShowModal] = useState(false)
    const [labels, setLabels] = useState<any>([])
    const { t } = useTranslation()

    let navigation, showActionSheetWithOptions;

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


    const dispatch = useDispatch()
    const selMode = 'EAT'
    useEffect(() => {
        getLabelsEvent({ window: 'EAT' }).then(res => {
            setLabels((res as any).labels)
        })
        setTimeout(() => {
            setHighlight(false)
        }, 2000)

    }, [])

    function check(array, tapDone = false) {
        createSchedule({
            schedules: array,
            only_check: true,
            return_all: true,
            op_page: 'SCHEDULE_WALKTHROUGH_3', sort_by: 'EVENT'
        }).then(res => {

            if ((res as any).result) {
                dispatch(setSchedules((res as any).schedules))
                dispatch(setFooter((res as any).footer))
                setList((res as any).schedules)
                setErrors([])
                if (tapDone) {
                    jumpPage('./guide_active')
                }
            }
            else {
                setList((res as any).schedules)
                dispatch(setFooter((res as any).footer))
                setErrors((res as any).error_messages ? (res as any).error_messages : [])
            }
        })
    }

    function add() {
        const scenario = getScenario(health.windows, 'EAT')
        var items = list.filter(item => item.window == 'EAT')
        if (scenario.access.max <= items.length) {
            showAlert({
                title: '会员',
                content: '会员desc',
                showCancel: true,
                confirm: () => {
                    jumpPage('/pages/store/product_list', 'ProductList', navigation)
                }
            })
            return;
        }

        setShowModal(true)
    }

    function isDisable(obj) {
        if ((obj.window == 'FAST' || obj.window == 'SLEEP') && !obj.is_conflict) {
            return true
        }
        return false
    }

    function footerTitle() {
        if (health.footer) {
            return health.footer.eat.title
        }
        return ''
    }

    function footerDesc() {
        if (health.footer) {
            return health.footer.eat.description
        }
        return ''
    }



    function items() {
        var items = list.filter(item => item.window == 'EAT')
        return <Card>
            {
                errors.map((item1, index) => {
                    return <View key={index} className='error_tip'>{item1}</View>
                })
            }
            {
                items.map((obj, i) => {
                    return <ScheduleItem
                        index={i}
                        count={items.length+1}
                        key={i * 100}
                        obj={obj}
                        highlight={highlight ? obj.window == 'EAT' : false}
                        showLine={true}
                        errors={errors}
                        selMode={selMode}
                        disable={isDisable(obj)}
                        gray={isDisable(obj)}
                        days={obj.plus_days != 0 ? obj.plus_days : null}
                        hideReminderIcon={true}
                        onDelete={() => {
                            const scenario = getScenario(health.windows, 'EAT')
                            if (scenario.access.min >= items.length) {
                                showAlert({
                                    title: '删除',
                                    content: '最少保留' + items.length + '个',
                                    showCancel: true,
                                    confirm: () => {
                                    }
                                })
                                return
                            }
                            delSchedule(obj.id).then(res => {
                                dispatch(setFooter((res as any).footer))
                                var array = JSON.parse(JSON.stringify(list))
                                for (var j = 0; j < array.length; j++) {
                                    if (array[j].id == obj.id) {
                                        array.splice(j, 1)
                                    }
                                }
                                setList(array)
                                global.refreshWindow()
                            })
                        }}
                        onChange={(time) => {
                            var array = JSON.parse(JSON.stringify(list))
                            array.map(item => {
                                if (item.id == obj.id) {
                                    item.time = time
                                    item.op_ms = new Date().getTime()
                                }
                            })
                            dispatch(setSchedules(array))

                            check(array)
                        }}
                    />
                })
            }
            <View className='item_add'
                onClick={() => add()}>
                <StatusIndicator type={StatusType.img} text={t('health.add_meal')}
                    color={MainColorType.eat} fontColor={MainColorType.eat} fontSize={rpxToPx(34)} >
                        <IconAdd color="#fff" width={rpxToPx(20)} />
                    </StatusIndicator>
                <View style={{ flex: 1 }} />
            </View>
        </Card>
    }

    function fastSleepItems() {
        var items = list.filter(item => item.window == 'FAST' || item.window == 'SLEEP')
        return <Card>
            {
                items.map((obj, i) => {
                    return <ScheduleItem
                        index={i}
                        count={items.length+1}
                        key={i * 100}
                        obj={obj}
                        highlight={false}
                        showLine={i < items.length - 1}
                        errors={errors}
                        selMode={selMode}
                        disable={isDisable(obj)}
                        gray={isDisable(obj)}
                        days={obj.plus_days != 0 ? obj.plus_days : null}
                        hideReminderIcon={true}
                        onDelete={() => {
                            var array = JSON.parse(JSON.stringify(list))
                            for (var j = 0; j < array.length; j++) {
                                if (array[j].id == obj.id) {
                                    array.splice(j, 1)
                                }
                            }
                            setList(array)
                            check(array)
                            global.refreshWindow()
                        }}
                        onChange={(time) => {
                            var array = JSON.parse(JSON.stringify(list))
                            array.map(item => {
                                if (item.id == obj.id) {
                                    item.time = time
                                    item.op_ms = new Date().getTime()
                                }
                            })
                            setList(array)

                            check(array)
                        }}
                    />
                })
            }
        </Card>
    }
    return <View style={{ flex: 1, display: 'flex', flexDirection: 'column', height: '100vh' }}>
        <View style={{ height: navigationBarHeight, backgroundColor: MainColorType.g05,flexShrink:0 }} />
        <View className="navi-bar" style={{ height: navigationBarHeight, zIndex: 1000, backgroundColor: MainColorType.g05 }}>

            <View style={{
                position: 'absolute',
                left: 0,
                right: 0,
                bottom: 0,
                height: 44,
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center'
            }}>
                <Image src={require('@assets/_health/navi_back.png')} style={{
                    position: 'absolute',
                    width: rpxToPx(92),
                    height: rpxToPx(64),
                    left: 0,
                    top: 22 - rpxToPx(32)
                }}
                    onClick={() => {
                        Taro.navigateBack()
                    }}
                />
                <Image src={user.avatar} mode="aspectFill" style={{
                    background: user.isLogin ? 'transparent' : '#fff',
                    width: rpxToPx(64),
                    height: rpxToPx(64),
                    borderRadius: rpxToPx(32)
                }} />
            </View>


        </View>
        <NewHeader type={NewHeaderType.center_subtitle} title={t('health.guide_2_title')} subtitle={t('health.guide_2_desc')} />
        {
            items()
        }
        <CellFooter type={CellFooterType.left}>
            <View style={{ display: 'flex', flexDirection: 'column' }}>
                <CellFooterText text={footerTitle()} isBold />
                <CellFooterText text={footerDesc()} />
            </View>
        </CellFooter>
        <View style={{ height: 20, flexShrink: 0 }} />
        {
            fastSleepItems()
        }
        <View style={{ height: 300, flexShrink: 0 }} />
        <View style={{ flex: 1 }} />
        <View className="main_footer">

            <NewButton
                type={NewButtonType.fill}
                title="下一步"
                disable={errors.length > 0}
                color={MainColorType.eat}
                width={rpxToPx(646)}
                height={rpxToPx(96)}
                onClick={() => {
                    check(list, true)
                }}
            />
        </View>
        {
            showModal && <AddLabel labels={labels}
                window='EAT'
                disMiss={() => setShowModal(false)}
                onlyCheck={true}
                schedules={list}
                confirm={(res) => {
                    setShowModal(false)
                    if ((res as any).result) {
                        dispatch(setSchedules((res as any).schedules))
                        dispatch(setFooter((res as any).footer))
                        setList((res as any).schedules)
                        setErrors([])
                    }
                    else {
                        setList((res as any).schedules)
                        dispatch(setFooter((res as any).footer))
                        setErrors((res as any).error_messages ? (res as any).error_messages : [])
                    }
                }}
                color={MainColorType.eat} />
        }
        {/* {
            showModal && <Modal testInfo={null}
                dismiss={() => {
                    setShowModal(false)
                }}
                confirm={() => { }}>
                <AddLabel labels={labels}
                    window='EAT'
                    disMiss={() => setShowModal(false)}
                    onlyCheck={true}
                    schedules={list}
                    confirm={(res) => {
                        if ((res as any).result) {
                            dispatch(setSchedules((res as any).schedules))
                            dispatch(setFooter((res as any).footer))
                            setList((res as any).schedules)
                            setErrors([])
                        }
                        else {
                            setList((res as any).schedules)
                            dispatch(setFooter((res as any).footer))
                            setErrors((res as any).error_messages ? (res as any).error_messages : [])
                        }
                    }}
                    color={MainColorType.eat} />
            </Modal>
        } */}
    </View>
}