import { View, Text, ScrollView } from "@tarojs/components";
import './Metric.scss'
import { setAuth } from "../hooks/werun";
import { usePullDownRefresh, useReady } from "@tarojs/taro";
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 { get } from "http";
import Modal from "@/components/layout/Modal";
import PickerViews from "@/components/input/PickerViews";
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";

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);


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

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

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

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

    function getCards() {
        setTriggered(true)
        console.log('get Cards')
        metricCards().then(res => {
            setErrorPage(false)
            setList((res as any).cards)
            setTriggered(false)
        }).catch(e => {
            if (list.length == 0) {
                setErrorPage(true)
            }
            setTriggered(false)
            // console.log('请求超时')
        })
    }


    //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}`
            })
        }
        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()
            console.log(item)
        }
        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
        console.log(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)));
        console.log(value1Index)

        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 => {
            list.map((item, index) => {
                if ((item as any).code == (res as any).code) {
                    (item as any).latest_record = (res as any).latest_record
                }
            })
            debugger
            setList(list)
            // 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.length > 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()
            }
        }
        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
                }
            })
            setList(JSON.parse(JSON.stringify(list)))

        })
    }

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

    function detail() {
        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" />

        </View>
    }

    // return showErrorPage ? <NoData refresh={() => { getCards() }} /> : detail()

    return <View style={{ display: 'flex', flex: 1, height: '100%' }}>
        <Layout children={showErrorPage ? <NoData refresh={() => { getCards() }} /> : detail()}
            title={t('page.metric.title')}
            type={TemplateType.grid}
            refresh={() => { getCards() }}
            triggered={triggered}
            more={() => { getCards() }}
            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 }}>{props.title ? props.title : '测试标题 '}</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 }}>取消</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' }}>确定</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} limitDay={180} onCancel={() => { setIsTimePickerOpen(false) }} onChange={(e) => {
                    chooseTime(e)
                    //  pickerConfirm(e)
                    //  hidePicker()
                }} />
            </Modal>
        }
    </View>

}