import { View, Text } from "@tarojs/components";
import './Metric.scss'
import { setAuth } from "../hooks/werun";
import { useReady } from "@tarojs/taro";
import { useDispatch, useSelector } from "react-redux";
import { useEffect, useState } from "react";
import Taro from "@tarojs/taro";
import { activityCards, uploadSteps } from "@/services/trackSomething";
import { TimeFormatter } from "@/utils/time_format";
import MetricItem from "./MetricItem";
import { checkFail, checkStart, checkSuccess, setResult } from "@/store/action_results";

export default function Component(props: any) {
    const user = useSelector((state: any) => state.user);
    const checkResult = useSelector((state: any) => state.checkResult);
    const [allowRun, setAllowRun] = useState(false)
    const [stepInfo, setStepInfo] = useState(null)
    const [lastTime, setLastTime] = useState(new Date().getTime())
    const [isCheking, setIsChecking] = useState(false)
    const [strBtnTitle, setStrBtnTitle] = useState('')
    const [list, setList] = useState([])
    const dispatch = useDispatch();
    // const [title, setTitle] = useState('打卡')

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

    useEffect(() => {
        console.log('checkResult.type:' + checkResult.type)
    }, [
        checkResult.type
    ])

    //页面渲染完成后执行一次授权检查
    useReady(() => {
        getCards();
    })

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

    function checkAuth() {
        // Taro.checkSession
        if (user.isLogin) {
            // setAuth()
            Taro.getSetting({
                success: res => {
                    //第一步，检测是否有授权 - 没有授权
                    if (!res.authSetting['scope.werun']) {
                        // setTitle('开启')
                        setAllowRun(false)
                    }
                    else {
                        setAllowRun(true)
                        // setTitle('打卡')
                        //自动打卡流程

                        var time = Taro.getStorageSync('lastUploadStepsTime')
                        if (time) {
                            var now = new Date().getTime()
                            if (now - time >= 30 * 24 * 3600 * 1000) {
                                getWeRunData(true)
                            }
                        }
                        else {
                            getWeRunData(true)
                        }
                    }
                }
            })
        }
        else {
            // Taro.setStorageSync('lastUploadStepsTime', time)
            setAllowRun(false)
            // setTitle('开启');
        }
    }

    function checkout() {
        // console.log('开始获取步数的时间戳：' + new Date().getTime())
        if (allowRun) {
            setIsChecking(true)
            dispatch(checkStart());
        }
        if (user.isLogin) {
            setAuth(getWeRunData, refuseAuth)
        }
        else {
            Taro.navigateTo({
                url: '/pages/ChooseAuth'
            })
        }
    }

    function getWeRunData(autoCheck = false) {
        // setTitle('打卡');
        setAllowRun(true)
        var date = new Date();
        var time = date.getTime()
        var strDate = (date.getFullYear() + '') + (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : (date.getMonth() + 1)) + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate());
        Taro.getWeRunData({
            success: res => {
                // console.log('已获取步数的时间戳：' + new Date().getTime())
                uploadSteps({
                    is_manual: autoCheck ? 0 : 1,
                    timestamp: time,
                    encryptedData: res.encryptedData,
                    iv: res.iv,
                    date: strDate,
                    cloudID: res.cloudID,
                }).then(res => {

                    Taro.setStorageSync('lastUploadStepsTime', time)

                    dispatch(setResult({ isSuccess: true }) as any)
                    setStepInfo((res as any)[(res as any).length - 1])
                    setLastTime(time)
                    setIsChecking(false)
                    getCards();
                }).catch(e => {
                    dispatch(setResult({ isSuccess: false }) as any);
                });
            }
        })
    }

    function refuseAuth() {
        // setTitle('开启');
        setIsChecking(false)
        setAllowRun(false)
    }

    function goDetail() {
        if (user.isLogin) {
            Taro.navigateTo({
                url: '/pages/RecordsHistory?type=activity'
            })
        }
        else {
            Taro.navigateTo({
                url: '/pages/ChooseAuth'
            })
        }

    }

    // checkResult.type == 'ing' && setStrBtnTitle('打卡中...')
    var btnTitle = '';
    var isEnable = true;
    if (allowRun) {
        if (checkResult.type == 'idle') {
            btnTitle = '打卡'
            isEnable = true
        }
        else if (checkResult.type == 'ing') {
            btnTitle = '打卡中...'
            isEnable = false;
        }
        else if (checkResult.type == 'success') {
            btnTitle = '打卡成功'
            isEnable = false
        }
        else if (checkResult.type == 'fail') {
            btnTitle = '打卡失败'
            isEnable = false
        }
        else if (checkResult.type == 'countdown') {
            btnTitle = checkResult.title + 's'
            isEnable = false;
        }
    }
    else {
        btnTitle = '开启';
        isEnable = true;
    }

    return <View>
        {
            list.map((item: any, index) => {
                var value = '0'
                var desc = ''
                if (item.latest_record) {
                    value = item.latest_record.items[0].value
                    if (item.latest_record.timestamp == 0) {
                        desc = '今天待打卡'
                    }
                    else {
                        desc = TimeFormatter.formatTimestamp(item.latest_record.timestamp)
                    }

                }
                else {
                    desc = '今天待打卡'
                }

                if (!allowRun) {
                    value = '未开启'
                    desc = '开启步数仅自己可见'
                }

                return <MetricItem title={item.name}
                    // value={allowRun ? stepInfo ? (stepInfo as any).step : '' : '未开启'}
                    value={value}
                    unit={allowRun ? '步' : ''}
                    desc={desc}
                    btnText={btnTitle}
                    isDisabled={!isEnable}
                    // desc={allowRun ? stepInfo ? TimeFormatter.formatTimestamp(lastTime) : '' : '开启步数仅自己可见'}
                    // btnText={allowRun ? isCheking ? '打卡中...' : '打卡' : '开启'}
                    // isDisabled={isCheking}
                    themeColor={item.theme_color}
                    onClickDetail={goDetail}
                    onClick={checkout}
                />
            })
        }
    </View>

    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>
}