import { View, Text } from "@tarojs/components";
import './move.scss'
import { useDispatch, useSelector } from "react-redux";
import { getScenario, getThemeColor } from "@/features/health/hooks/health_hooks";
import { useEffect, useState } from "react";
import Taro from "@tarojs/taro";
import { checkStart, setResult } from "@/store/action_results";
import RequestType, { thirdPartRequest } from "@/services/thirdPartRequest";
import { setAuth } from "@/features/trackSomething/hooks/werun";
import { useTranslation } from "react-i18next";
import { uploadActiveMoves } from "@/services/health";
import dayjs from "dayjs";

export default function Move() {
    const health = useSelector((state: any) => state.health);
    const [allowRun, setAllowRun] = useState(false)
    const { t } = useTranslation()
    const dispatch = useDispatch()

    useEffect(() => {
        Taro.getSetting({
            success: res => {
                //第一步，检测是否有授权 - 没有授权
                if (!res.authSetting['scope.werun']) {
                    setAllowRun(false)
                    Taro.setStorage({ key: 'auth', data: false })
                }
                else {
                    setAllowRun(true)
                    Taro.setStorage({ key: 'auth', data: true })
                }
            }
        })
    }, [])


    function tapLog() {
        if (allowRun) {
            checkout()
        }
        else {
            setAuth(successAuth, refuseAuth, t)
        }
    }

    function successAuth() {
        Taro.setStorage({ key: 'auth', data: true })
        setAllowRun(true)
    }

    function refuseAuth() {
        // setTitle('开启');
        Taro.setStorage({ key: 'auth', data: false })
        setAllowRun(false)
    }

    function checkout() {
        dispatch(checkStart());
        getWeRunData(false)
    }


    function getWeRunData(autoCheck = false) {
        if (autoCheck) {
            return
        }
        else {
            dispatch(checkStart());
        }

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


        thirdPartRequest(RequestType.RequestTypeWXRunData).then(res => {
            var params = {
                is_manual: autoCheck ? 0 : 1,
                timestamp: time,
                encryptedData: (res as any).encryptedData,
                iv: (res as any).iv,
                date: strDate,
                cloudID: (res as any).cloudID,
            }

            uploadActiveMoves({
                wechat_run:{
                    encryptedData:(res as any).encryptedData,
                    iv:(res as any).iv,
                },
                date:dayjs().format('YYYYMMDD'),
                timestamp:new Date().getTime(),
                schedule_id:getScenario(health.windows,health.mode).window_id
            }).then(res=>{
                Taro.showToast({
                    title:'上报成功',
                    icon:'none'
                })
            })
            // uploadSteps(params).then(res => {
            //     if ((res as any).error_code == 'WX_STEP_PARSE_FAIL') {
            //         retry(params, autoCheck, time)
            //         dispatch(checkRetry())
            //     }
            //     else {

            //         setShowErrorBadge(false)
            //         uploadSuccess(res, autoCheck, time)
            //         setTimeout(() => {
            //             setCount(count + 1)
            //         }, 31000)
            //     }

            // }).catch(e => {
            //     retry(params, autoCheck, time)
            // });
        }).catch(_ => {
            dispatch(setResult({ isSuccess: false }) as any)
        })


    }


    return <View>
        <Text>Move Every Hour</Text>
        <View className="log_btn" style={{ backgroundColor: getThemeColor(health.mode) }} onClick={tapLog}>
            Log
        </View>
    </View>
}