import { View, Text, ScrollView } from "@tarojs/components";
import './Metric.scss'
import { useSelector } from "react-redux";
import { useEffect, useRef, useState } from "react";
import Taro from "@tarojs/taro";
import { metricCards, uploadMetric, uploadSteps } from "@/services/trackSomething";
import { TimeFormatter } from "@/utils/time_format";
import MetricItem from "./MetricItem";
import Modal from "@/components/layout/Modal";
import LimitPickers from "@/components/input/LimitPickers";
import SlidngScale from "@/components/input/SlidngScale";
import NoData from "@/components/view/NoData";
import { alphaToHex } from "@/utils/tools";
import Layout from "@/components/layout/layout";
import { NaviBarTitleShowType, TemplateType } from "@/utils/types";
import { useTranslation } from "react-i18next";

let useNavigation;
if (process.env.TARO_ENV == 'rn') {
    useNavigation = require("@react-navigation/native").useNavigation
}

export default function Component(props: any) {
    const { t } = useTranslation()
    const user = useSelector((state: any) => state.user);
    const [list, setList] = useState([])

    const [isModalOpen, setIsModalOpen] = useState(false);
    const [isTimePickerOpen, setIsTimePickerOpen] = useState(false);
    const [pickerValue, setPickerValue] = useState([]);
    const [pickerItems, setPickerItems] = useState([]);
    const [isPoint, setIsPoint] = useState(false)

    const [metricItem, setMetricItem] = useState({})

    const [strTime, setStrTime] = useState('')
    const [time, setTime] = useState(0)

    const [showErrorPage, setErrorPage] = useState(false)

    const [setupTime, setSetupTime] = useState(0)
    const [triggered, setTriggered] = useState(true)
    const limitPickerRef = useRef<any>(null);
    const [count, setCount] = useState(0)




    //未登录<->已登录 状态切换时，执行一次授权检查
    useEffect(() => {
        getCards();
        const now = new Date();
        const nextMidnight = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1, 0, 0, 0);
        const timeUntilMidnight = nextMidnight.getTime() - now.getTime();

        setTimeout(() => {
            setCount(count + 1)
        }, timeUntilMidnight);
    }, [user.isLogin])

    const openModal = () => {
        setSetupTime(new Date().getTime())
        setIsModalOpen(true);
    };

    const closeModal = () => {
        setIsModalOpen(false);
    };

    global.refreshMetric = () => {
        getCards()
    }

    function getCards() {
        setTriggered(true)
        metricCards().then(res => {
            Taro.stopPullDownRefresh()
            setErrorPage(false)
            setList((res as any).cards)
            setTriggered(false)
        }).catch(e => {
            Taro.stopPullDownRefresh()
            if (list.length == 0) {
                setErrorPage(true)
            }
            setTriggered(false)
        })
    }


    //ts 把数组items: [{code: "_walk", value: 2180},{code: "_walk", value: 4444}]中的value取出来,/分割，组成字符串，如2180/4444
    function getValues(items) {
        var values = ''
        items.map((item, index) => {
            if (index == 0) {
                values = item.value
            }
            else {
                values = values + '/' + item.value
            }
        })
        return values
    }
    function goDetail(item) {
        if (user.isLogin) {
            if (!item.latest_record) {
                return
            }
            Taro.navigateTo({
                url: '/pages/common/RecordsHistory?type=metric&refreshList=getCards&code=' + item.code + `&title=${item.name}` + '&themeColor=' + item.theme_color
            })
        }
        else {
            Taro.navigateTo({
                url: '/pages/account/ChooseAuth'
            })
        }
    }

    function record(item: any) {

        if (user.isLogin) {
            var now = new Date();
            var t = (now.getHours() < 10 ? '0' + now.getHours() : now.getHours()) + ":" + (now.getMinutes() < 10 ? '0' + now.getMinutes() : now.getMinutes());
            setStrTime(t)
            setTime(now.getTime())
            setMetricItem(item)
            openModal()
        }
        else {
            Taro.navigateTo({
                url: '/pages/account/ChooseAuth'
            })
        }
    }

    function pointPicker(item: any) {
        var min = item.min
        var max = item.max
        var step = item.step
        var value = item.default_value
        var items: number[] = []
        var items2: number[] = []

        var value0Index = 0
        var value1Index = 0

        for (var i = min; i <= max; i++) {
            if (i == Math.floor(value)) {
                value0Index = i - min
            }
            items.push(i)
            // items2.push(i)
        }

        for (var i = 0; i <= 9; i++) {
            items2.push(i)
        }
        value1Index = Math.round(10 * (value - Math.floor(value)));

        setPickerValue([value0Index, value1Index] as any)
        setPickerItems([items, items2] as any)
        setIsPoint(true)

        openModal()
    }

    function singlePicker(item: any) {
        var min = item.min
        var max = item.max
        var step = 1//item.step
        var value = item.default_value

        var items: number[] = []
        for (var i = min; i <= max; i += step) {
            if (i == value) {
                setPickerValue([i - min] as any)
            }
            items.push(i)
        }

        setPickerItems([items] as any)
        setIsPoint(false)

        openModal()
    }

    function pickerChanged(e) {
        closeModal();
        var params = {}
        var date = new Date(time)
        var strDate = (date.getFullYear() + '') + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());

        if ((metricItem as any).schemas[0].type == 'DECIMAL') {
            var array = pickerItems;
            var value = array[0][e[0]] + '.' + array[1][e[1]]


            params = {
                code: (metricItem as any).code,
                timestamp: time,
                date: strDate,
                items: [{ code: (metricItem as any).schemas[0].code, value: value }]
            }
        }
        else if ((metricItem as any).schemas.length > 1) {

        }
        else {
            var array = pickerItems;
            var value = array[0][e[0]] + ''
            params = {
                code: (metricItem as any).code,
                timestamp: time,
                date: strDate,
                items: [{ code: (metricItem as any).schemas[0].code, value: value }]
            }
        }

        uploadMetric(params).then(res => {
            list.map((item, index) => {
                if ((item as any).code == (res as any).code) {
                    (item as any).latest_record = (res as any).latest_record
                }
            })
            setList(list)

            setTimeout(() => {
                setCount(count + 1)
            }, 31000)
            // getCards();
        })
    }

    function showTimePicker() {
        setIsTimePickerOpen(true)
    }

    function chooseTime(e) {
        setTime(e);
        setStrTime(TimeFormatter.formatTimestamp(e))
        setIsTimePickerOpen(false)
    }

    function cancelModal() {
        (metricItem as any).schemas.map((item, index) => {
            item.tempValue = ''
        })
        closeModal()
    }

    function confirmModal() {
        closeModal()
        var date = new Date(time)
        var strDate = (date.getFullYear() + '') + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());

        var array: any[] = [];
        (metricItem as any).schemas.map((item, index) => {
            array.push({
                code: item.code,
                value: item.tempValue && item.tempValue > 0 ? item.tempValue : item.default_value
            })
        })
        var params = {
            code: (metricItem as any).code,
            timestamp: time,
            date: strDate,
            items: array,
            extra: {
                set_time: setupTime,
                confirm_time: new Date().getTime()
            }
        }

        global.postBtnUpdateStatus('normal');
        uploadMetric(params).then(res => {
            // getCards();
            (metricItem as any).schemas.map((item, index) => {
                item.tempValue = ''
            })

            list.map((item, index) => {
                if ((item as any).code == (res as any).code) {
                    (item as any).latest_record = (res as any).latest_record;
                    (item as any).schemas = (res as any).schemas;
                }
            })
            setList(JSON.parse(JSON.stringify(list)))

            global.postBtnUpdateStatus('idle');
            setTimeout(() => {
                setCount(count + 1)
            }, 31000)

        })
    }

    const limitDay = 500

    const limit = new Date().getTime() - limitDay * 3600 * 1000 * 24;

    function detail() {
        return <View>


            <View className="metric_container">
                {
                    list.map((item: any, index: number) => {
                        var unit = ''
                        var value = t('feature.track_something.metric.no_record')
                        var desc = t('feature.track_something.metric.check_unlock_data')
                        var showDetail = false;
                        if (item.latest_record) {
                            unit = item.schemas[0].default_unit
                            value = getValues(item.latest_record.items)
                            desc = TimeFormatter.dateDescription(item.latest_record.timestamp, true)
                            showDetail = true
                        }

                        if (!user.isLogin) {
                            value = t('feature.track_something.metric.un_login')
                            desc = t('feature.track_something.metric.login_can_check')
                        }
                        return <MetricItem title={item.name}
                            value={value}
                            unit={unit}
                            desc={desc}
                            btnText={t('feature.track_something.btn_record')}
                            isDisabled={false}
                            showDetail={showDetail}
                            themeColor={item.theme_color}
                            onClickDetail={() => { goDetail(item) }}
                            onClick={() => { record(item) }}
                        />
                    })
                }


            </View>
            <View className="space_width" ></View>
        </View>
    }

    function detailContent() {
        // if (process.env.TARO_ENV=='rn'){
        //     return <ScrollView>
        //         {
        //             detail()
        //         }
        //         <View style={{height:150}}/> 
        //     </ScrollView>
        // }
        return detail()
    }

    return <View style={{ position: 'relative' }}>
        <Layout children={showErrorPage ? <NoData refresh={() => { getCards() }} /> : detailContent()}
            title={t('page.metric.title')}
            type={TemplateType.flex}
            refresh={() => { getCards() }}
            triggered={triggered}
            titleShowStyle={NaviBarTitleShowType.scrollToShow}
        />
        {
            isModalOpen && <Modal dismiss={closeModal} title={(metricItem as any).name}
                themeColor={(metricItem as any).theme_color}
                confirm={confirmModal}>
                <View style={{
                    display: 'flex', flexDirection: 'column',
                    width: '100%', color: '#000'
                }}>
                    <Text className='modal_title' style={{ color: (metricItem as any).theme_color }}>{(metricItem as any).name ? (metricItem as any).name : ''}</Text>
                    <View style={{ position: 'relative' }}>
                        {
                            (metricItem as any).schemas.map((item, index) => {
                                return <View key={index}>
                                    {
                                        (metricItem as any).schemas.length > 1 && <Text style={{
                                            textAlign: 'center', width: '100%', display: 'flex',
                                            justifyContent: 'center', color: (metricItem as any).theme_color
                                        }}>{item.name}</Text>
                                    }
                                    <SlidngScale step={item.step} min={item.min} max={item.max} default_value={item.default_value}
                                        unit={item.default_unit}
                                        themeColor={(metricItem as any).theme_color}
                                        changed={(e) => { item.tempValue = e }} />
                                </View>
                            })
                        }
                    </View>
                    <View className="change_time_bg ">
                        <View className="gray1 time_bg" onClick={showTimePicker}>
                            <Text className="time" >{strTime}</Text>
                        </View>

                    </View>
                    <View className='modal_operate'>
                        <View className='modal_btn' style={{ backgroundColor: (metricItem as any).theme_color + alphaToHex(0.4) }} onClick={cancelModal}>
                            <Text className='modal_cancel_text' style={{ color: (metricItem as any).theme_color }}>{
                                t('feature.common.picker_cancel_btn')
                            }</Text>
                        </View>
                        <View className='btn_space' />
                        <View className='modal_btn' style={{ backgroundColor: (metricItem as any).theme_color }} onClick={confirmModal}>
                            <Text className='modal_confirm_text' style={{ color: '#000' }}>{
                                t('feature.common.picker_confirm_btn')
                            }</Text>
                        </View>


                    </View>
                    {/* <View style={{ marginBottom: 20, marginTop: 20, display: 'flex', flexDirection: 'row', width: '100%' }}>
                            <Text style={{ flex: 1, textAlign: 'center', height: 50 }} onClick={cancelModal}>取消</Text>
                            <Text style={{ flex: 1, textAlign: 'center', height: 50 }} onClick={confirmModal}>确认</Text>
                        </View> */}

                </View>
            </Modal>
        }
        {

            isTimePickerOpen && <Modal
                themeColor={(metricItem as any).theme_color}
                dismiss={() => setIsTimePickerOpen(false)} confirm={() => {
                    var picker = limitPickerRef.current;
                    chooseTime((picker as any).getConfirmData());
                    setIsTimePickerOpen(false);
                }}>
                <LimitPickers ref={limitPickerRef}
                    isRealTime={true} time={time} limit={limit}
                    title={t('feature.track_something.picker_datetime')}
                    themeColor={(metricItem as any).theme_color}
                    limitDay={limitDay} onCancel={() => { setIsTimePickerOpen(false) }}
                    onChange={(e) => {
                        chooseTime(e)
                        //  pickerConfirm(e)
                        //  hidePicker()
                    }} />
            </Modal>
        }
    </View>

}