import { View, Text, Image, Switch, Input, ScrollView } from "@tarojs/components";
import './schedules_edit.scss'
import { useEffect, useState } from "react";
import { useSelector } from "react-redux";
import { createSchedule, getLabelsEvent, getSchedules } from "@/services/health";
import { rpxToPx } from "@/utils/tools";
import { getThemeColor } from "@/features/health/hooks/health_hooks";
import Modal from "@/components/layout/Modal.weapp";
import TimePicker from "@/features/common/TimePicker";
import { AtSwipeAction } from "taro-ui"
import Taro, { useRouter } from "@tarojs/taro";
import showAlert from "@/components/basic/Alert";
import { jumpPage } from "@/features/trackTimeDuration/hooks/Common";
import StatusIndicator, { StatusType } from "../base/status_indicator";
import NewButton, { NewButtonType } from "../base/new_button";
import { MainColorType } from "@/context/themes/color";
import { IconNotification, IconNotificationOff } from "@/components/basic/Icons";
import NewHeader, { NewHeaderType } from "../components/new_header";

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 SchedulesEdit() {
    let navigation, showActionSheetWithOptions;

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

    if (process.env.TARO_ENV == 'rn') {
        router = useRoute()
    }
    else {
        router = useRouter()
    }
    const selMode = router.params.mode;
    const [list, setList] = useState<any>([])
    const [labels, setLabels] = useState<any>([])
    const [showDel, setShowDel] = useState(false)
    const health = useSelector((state: any) => state.health);
    const [showTimePicker, setShowTimePicker] = useState(false)
    const [selItem, setSelItem] = useState<any>(null)
    const [editIndex, setEditIndex] = useState({ row: -1, index: -1 })
    const [delIds, setDelIds] = useState<any>([])

    useEffect(() => {
        schedules()
    }, [])

    global.refreshSchedules = () => {
        schedules()
    }

    function schedules() {
        let windows = ''
        switch (selMode) {
            case 'FAST':
                windows = 'FAST,EAT';
                break
            case 'EAT':
                windows = 'EAT,FAST';
                break
            case 'SLEEP':
                windows = 'SLEEP,ACTIVE';
                break
            case 'ACTIVE':
                windows = 'ACTIVE,SLEEP';
                break
            case 'DAY':
                windows = 'DAY,NIGHT';
                break
            case 'NIGHT':
                windows = 'NIGHT,DAY';
                break
        }
        getSchedules({ window: windows }).then(res => {
            if ((res as any).data && (res as any).data.length > 0) {
                // setList((res as any).data)

                let grouped: any = {};
                (res as any).data.forEach(item => {
                    const window = item.window;

                    if (!grouped[window]) {
                        grouped[window] = { window: window, list: [] };
                    }
                    grouped[window].list.push(item);
                });
                // console.log(Object.values(grouped))
                setList(Object.values(grouped))
            }
        }).catch(e => {

        })

        getLabelsEvent({ window: health.mode }).then(res => {
            setLabels((res as any).labels)
        })
    }

    function changeTime(item) {
        setSelItem(item)
        setShowTimePicker(true)
    }

    function modalContent() {
        const strTime = selItem.time

        var title = selItem.title
        var color = getThemeColor(selItem.window)

        return <TimePicker time={strTime}
            color={color}
            title={title}
            confirm={(e) => {
                selItem.time = e

                setSelItem(selItem)
                setShowTimePicker(false)
                orderList(list)
                // confirmPickerTime(e)
            }}
            cancel={() => {
                setShowTimePicker(false)
            }} />
    }

    function orderList(list) {
        var array = JSON.parse(JSON.stringify(list))
        array.map(item => {
            if (item.window == 'EAT' || item.window == 'ACTIVE') {
                // 自定义排序函数
                const sortedArray = item.list.sort((a, b) => {
                    // 如果 a 没有 time 字段，排在前面
                    if (!a.time && !b.time) return 0; // 都没有时，返回相等
                    if (!a.time) return -1; // a 没有 time，排在前面
                    if (!b.time) return 1;  // b 没有 time，排在前面

                    // 比较时间
                    return a.time.localeCompare(b.time);
                });
                item.list = sortedArray
            }
        })
        setList(array)
    }

    function tapDone() {
        var array: any = []
        list.map((obj) => {
            obj.list.map(item => {
                array.push({
                    id: item.id,
                    time: item.time,
                    event: item.event,
                    title: item.title,
                    reminder: item.reminder
                })
            })

        })

        createSchedule({
            schedules: array,
            delete_ids: delIds
        }).then(res => {
            if ((res as any).result) {
                global.refreshWindow()
                if (global.refreshSchedules) {
                    global.refreshSchedules()
                }

                if (global.tempRefresh) {
                    global.tempRefresh()
                }
                if (global.refreshSchedules2) {
                    global.refreshSchedules2()
                }
                if (process.env.TARO_ENV == 'weapp') {
                    Taro.navigateBack()
                }
            }
            else {
                showAlert({
                    title: '弹窗标题',
                    content: '冲突描述',
                    showCancel: false,
                    confirm: () => {
                        jumpPage(`./schedules_conflict?schedules=${JSON.stringify((res as any).schedules)}&errors=${JSON.stringify((res as any).error_messages)}`)
                    }
                })

            }

        })
    }

    function delItem(index, i) {
        var array = JSON.parse(JSON.stringify(list))
        var ids = JSON.parse(JSON.stringify(delIds))
        ids.push(array[index].list[i].id)
        array[index].list.splice(i, 1)

        setList(array)
        setDelIds(ids)
    }

    function reminder(obj) {
        if (obj.specific_time || health.mode == 'DAY' || health.mode == 'NIGHT') {
            return <View style={{ display: 'flex', flexDirection: 'row', alignItems: 'center' }}>
                {
                    obj.reminder ? <IconNotification color={MainColorType.g03} width={rpxToPx(28)} /> : <IconNotificationOff color={MainColorType.g03} width={rpxToPx(28)} />
                }
                <View style={{ width: rpxToPx(12) }} />
                <Switch checked={obj.reminder}
                    color={getThemeColor(obj.window)}
                    onChange={e => {
                        if (process.env.TARO_ENV == 'weapp') {
                            e.stopPropagation()
                        }

                        obj.reminder = e.detail.value;
                        setList([...list])
                    }} />
            </View>
        }
        return <View />
    }

    function editName(item, obj, index, i) {
        if ((item.window == 'EAT' || item.window == 'ACTIVE') &&
            !(editIndex.row == index && editIndex.index == i)) {
            return <View>
                <NewButton type={NewButtonType.link}
                    title="更改"
                    onClick={() => {
                        setSelItem(obj)
                        setEditIndex({
                            row: index,
                            index: i
                        })
                    }}
                />
            </View>
        }
        return <View />
    }
    return <View className='schedule_list_bg'>
        <ScrollView enableFlex style={{ height: Taro.getWindowInfo().screenHeight - 220 }} scrollY>
            <NewHeader title="日程设置" type={NewHeaderType.left} />
            <View style={{ display: 'flex', flexDirection: 'column' }}>
                {
                    list.map((item, index) => {
                        return <View key={index} style={{ display: 'flex', flexDirection: 'column', marginBottom: rpxToPx(36) }}>
                            {
                                item.list.map((obj, i) => {
                                    return <AtSwipeAction key={i * 100}
                                        isOpened={false}
                                        autoClose
                                        disabled={item.window != 'EAT' && item.window != 'ACTIVE'}
                                        options={[
                                            {
                                                text: '删除',
                                                style: {
                                                    backgroundColor: '#FF4949'
                                                }
                                            }
                                        ]}
                                        onClick={() => {
                                            if (item.window == 'ACTIVE' || item.window == 'EAT') {
                                                if (item.list.length == 1) {
                                                    Taro.showToast({
                                                        title: '至少保留一项',
                                                        icon: 'none'
                                                    })
                                                    return;
                                                }
                                            }
                                            showAlert({
                                                title: '删除',
                                                content: '确认删除此计划',
                                                showCancel: true,
                                                cancel: () => {
                                                    console.log('cancel')
                                                },
                                                confirm: () => {
                                                    delItem(index, i)
                                                }
                                            })
                                        }}
                                    >

                                        <View className='schedule_item' style={{ width: rpxToPx(750), boxSizing: 'border-box' }}>
                                            <View style={{ display: 'flex', flexDirection: 'column', justifyContent: 'flex-start', flex: 1 }}>
                                                <View className='item_left2'>
                                                    <StatusIndicator type={StatusType.normal} color={getThemeColor(obj.window)} />

                                                    {
                                                        editIndex.row == index && editIndex.index == i ?
                                                            <Input className='item_name' style={{ flex: 1 }}
                                                                value={selItem.title}
                                                                autoFocus={true}
                                                                focus={true}
                                                                onBlur={() => {
                                                                    setEditIndex({
                                                                        row: -1,
                                                                        index: -1
                                                                    })
                                                                }}
                                                                onInput={(e) => {
                                                                    var temp = JSON.parse(JSON.stringify(selItem))
                                                                    temp.title = e.detail.value
                                                                    obj.title = e.detail.value
                                                                    setSelItem(temp)
                                                                }} /> : <Text className='item_name'>{obj.title}</Text>
                                                    }

                                                    {/* {
                                                        (item.window == 'EAT' || item.window == 'ACTIVE') &&
                                                        !(editIndex.row == index && editIndex.index == i) &&
                                                        <Image src={require('@assets/_health/edit.png')}
                                                            className="edit_icon"
                                                            onClick={(e) => {
                                                                if (process.env.TARO_ENV == 'weapp') {
                                                                    e.stopPropagation()
                                                                }
                                                                setSelItem(obj)
                                                                setEditIndex({
                                                                    row: index,
                                                                    index: i
                                                                })
                                                            }}
                                                        />
                                                    } */}
                                                </View>
                                                {
                                                    obj.specific_time && <View className="h22" style={{ color: MainColorType.g02 }}>{obj.time}</View>
                                                }
                                            </View>
                                            {
                                                router.params.type == 'reminder' ? reminder(obj) : editName(item, obj, index, i)
                                            }

                                            {/* {router.params.type == 'reminder' && (obj.specific_time || health.mode == 'DAY' || health.mode == 'NIGHT') && <Switch checked={obj.reminder}
                                                color={getThemeColor(obj.window)}
                                                onChange={e => {
                                                    if (process.env.TARO_ENV == 'weapp') {
                                                        e.stopPropagation()
                                                    }

                                                    obj.reminder = e.detail.value;
                                                    setList([...list])
                                                }} />} */}
                                            {
                                                i < item.list.length - 1 && <View className='border_footer_line' />
                                            }

                                        </View>
                                    </AtSwipeAction>
                                })
                            }
                        </View>

                    })
                }
            </View>
        </ScrollView>
        <View className="main_footer">
            <NewButton
                type={NewButtonType.fill}
                title="完成"
                color={getThemeColor(health.mode)}
                width={rpxToPx(670)}
                height={rpxToPx(96)}
                onClick={tapDone}
            />
        </View>

        {/* <View className="edit_footer_btn" style={{ color: getThemeColor(health.mode), backgroundColor: getThemeColor(health.mode) + '33' }} onClick={tapDone}>完成</View> */}
        {
            showTimePicker && <Modal
                testInfo={null}
                dismiss={() => {
                    setShowTimePicker(false)
                }}
                confirm={() => { }}>
                {
                    modalContent()
                }
            </Modal>
        }
    </View>
}