import { View, Text } from "@tarojs/components";
import './Metric.scss'
import { setAuth } from "../hooks/werun";
import { useReady } from "@tarojs/taro";
import { useSelector } from "react-redux";
import { useEffect, 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 { get } from "http";
import Modal from "@/components/Modal";
import PickerViews from "@/components/PickerViews";
import LimitPickers from "@/components/LimitPickers";

export default function Component(props: any) {
    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)

    //未登录<->已登录 状态切换时，执行一次授权检查
    useEffect(() => {
    }, [user.isLogin])

    useReady(() => {
        getCards();
    })

    const openModal = () => {
        setIsModalOpen(true);
    };

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

    function getCards() {
        metricCards().then(res => {
            setList((res as any).cards)
        })
    }

    //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) {
            Taro.navigateTo({
                url: '/pages/RecordsHistory?type=metric&code=' + item.code
            })
        }
        else {
            Taro.navigateTo({
                url: '/pages/ChooseAuth'
            })
        }
    }

    function record(item: any) {

        if (user.isLogin) {
            setMetricItem(item)
            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())
            if (item.schemas[0].type == 'DECIMAL') {
                pointPicker(item.schemas[0])
            }
            else if (item.schemas.length > 1) {

            }
            else {
                singlePicker(item.schemas[0])
            }
        }
        else {
            Taro.navigateTo({
                url: '/pages/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 = 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]]
            console.log(value)


            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]] + ''
            console.log(value)
            params = {
                code: (metricItem as any).code,
                timestamp: time,
                date: strDate,
                items: [{ code: (metricItem as any).schemas[0].code, value: value }]
            }
        }

        uploadMetric(params).then(res => {
            getCards();
        })
    }

    function showTimePicker() {
        setIsTimePickerOpen(true)
    }

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

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

    return <View className="metric_container">
        {
            list.map((item: any, index: number) => {
                var unit = ''
                var value = '无记录'
                var desc = '记录解锁趋势'
                if (item.latest_record) {
                    unit = item.schemas[0].default_unit
                    value = getValues(item.latest_record.items)
                    desc = TimeFormatter.formatTimestamp(item.latest_record.timestamp)
                }
                return <MetricItem title={item.name}
                    value={value}
                    unit={unit}
                    desc={desc}
                    btnText='记录'
                    isDisabled={false}
                    themeColor={item.theme_color}
                    onClickDetail={() => { goDetail(item) }}
                    onClick={() => { record(item) }}
                />
            })
        }
        <View className="space_width" />
        {
            isModalOpen && <Modal dismiss={closeModal}>
                <View style={{
                    backgroundColor: 'white',
                    display: 'flex', flexDirection: 'column',
                    width: '100%', height: '50%', color: '#000'
                }}>
                    <Text style={{ textAlign: 'center' }}>{(metricItem as any).name}</Text>
                    <Text style={{ textAlign: 'center', paddingTop: 10, paddingBottom: 10 }} onClick={showTimePicker}>{strTime}</Text>
                    <View style={{ position: 'relative' }}>
                        <PickerViews onChange={pickerChanged}
                            items={pickerItems}
                            value={pickerValue}
                            height={200} showBtns={true}
                            onCancel={closeModal} />
                        {isPoint && <View style={{
                            position: 'absolute', width: '20%', height: 50, backgroundColor: 'transparent', left: '40%', top: 75,
                            display: 'flex', alignItems: 'center', justifyContent: 'center'
                        }}>
                            <Text style={{ color: '#000', fontSize: 16, fontWeight: 'bold' }}>.</Text>
                        </View>}
                    </View>

                </View>
            </Modal>
        }
        {

            isTimePickerOpen && <Modal dismiss={() => setIsTimePickerOpen(false)}>
                <LimitPickers isRealTime={true} limit={limit} onCancel={() => { setIsTimePickerOpen(false) }} onChange={(e) => {
                    chooseTime(e)
                    //  pickerConfirm(e)
                    //  hidePicker()
                }} />
            </Modal>
        }
    </View>

    /*
    return <MetricItem title="行走"
        value={allowRun ? stepInfo ? (stepInfo as any).step : '' : '未开启'}
        unit={(allowRun && stepInfo) ? '步' : ''}
        desc={allowRun ? stepInfo ? TimeFormatter.formatTimestamp(lastTime) : '' : '开启步数仅自己可见'}
        btnText={allowRun ? isCheking ? '打卡中...' : '打卡' : '开启'}
        isDisabled={isCheking}
        themeColor='#EEC01F'
        onClickDetail={goDetail}
        onClick={checkout}
    />*/

    return <View className="metric_bg">
        <Text className="metric_title">行走</Text>
        {
            !allowRun && <Text className="metric_value">未开启</Text>
        }
        {
            !allowRun && <Text className="mteric_desc">开启步数仅自己可见</Text>
        }
        {
            allowRun && stepInfo && <Text className="metric_value">{(stepInfo as any).step}<Text className="metric_unit">步</Text></Text>
        }
        {
            allowRun && stepInfo && <Text className="mteric_desc">{TimeFormatter.formatTimestamp(lastTime)}</Text>
        }
        <View className="operate" onClick={checkout}>{allowRun ? '打卡' : '开启'}</View>
    </View>
}