Leon 2 лет назад
Родитель
Сommit
665b364f64

+ 1 - 2
src/app.config.ts

@@ -1,8 +1,7 @@
 const appConfig = defineAppConfig({
 const appConfig = defineAppConfig({
   pages: [
   pages: [
+    // 'pages/demo',
     'pages/Clock',
     'pages/Clock',
-    'pages/demo',
-    
     'pages/index/index',
     'pages/index/index',
     'pages/Login',
     'pages/Login',
     'pages/Auth',
     'pages/Auth',

+ 135 - 125
src/features/trackSomething/components/Activity.tsx

@@ -8,8 +8,9 @@ import Taro from "@tarojs/taro";
 import { activityCards, uploadSteps } from "@/services/trackSomething";
 import { activityCards, uploadSteps } from "@/services/trackSomething";
 import { TimeFormatter } from "@/utils/time_format";
 import { TimeFormatter } from "@/utils/time_format";
 import MetricItem from "./MetricItem";
 import MetricItem from "./MetricItem";
-import { ResultType, checkFail, checkRetry, checkStart, checkSuccess, setResult } from "@/store/action_results";
+import { ResultType, checkFail, checkRetry, checkStart, checkSuccess, resetStatus, setResult } from "@/store/action_results";
 import { uploadSessionKey } from "@/services/common";
 import { uploadSessionKey } from "@/services/common";
+import RequestType, { thirdPartRequest } from "@/services/thirdPartRequest";
 
 
 export default function Component(props: any) {
 export default function Component(props: any) {
     const user = useSelector((state: any) => state.user);
     const user = useSelector((state: any) => state.user);
@@ -17,96 +18,96 @@ export default function Component(props: any) {
     const [allowRun, setAllowRun] = useState(false)
     const [allowRun, setAllowRun] = useState(false)
     const [stepInfo, setStepInfo] = useState(null)
     const [stepInfo, setStepInfo] = useState(null)
     const [lastTime, setLastTime] = useState(new Date().getTime())
     const [lastTime, setLastTime] = useState(new Date().getTime())
-    const [isCheking, setIsChecking] = useState(false)
     const [list, setList] = useState([])
     const [list, setList] = useState([])
     const dispatch = useDispatch();
     const dispatch = useDispatch();
     const [returnLoginData, setReturnLoginData] = useState(false)
     const [returnLoginData, setReturnLoginData] = useState(false)
     const [showErrorBadge, setShowErrorBadge] = useState(false)
     const [showErrorBadge, setShowErrorBadge] = useState(false)
+    const [latestRecord, setLatestRecord] = useState(null)
     // const [title, setTitle] = useState('打卡')
     // const [title, setTitle] = useState('打卡')
 
 
-    //未登录<->已登录 状态切换时,执行一次授权检查
+    //未登录<->已登录 状态切换时,重新拉取一次列表数据
     useEffect(() => {
     useEffect(() => {
+        dispatch(resetStatus())
         getCards();
         getCards();
-        checkAuth(false)
+        // checkAuth(false)
     }, [user.isLogin])
     }, [user.isLogin])
 
 
+    // useEffect(() => {
+    //     Taro.setStorage({key:'auth',data:allowRun})
+    // },[allowRun])
+
     useEffect(() => {
     useEffect(() => {
-        console.log('checkResult.type:' + checkResult.type)
+        Taro.getStorage({
+            key: 'auth', success: function (res) {
+                setAllowRun(res.data ? res.data : false)
+            }
+        });
     }, [
     }, [
-        checkResult.type
     ])
     ])
 
 
     //页面渲染完成后执行一次授权检查
     //页面渲染完成后执行一次授权检查
     useReady(() => {
     useReady(() => {
-        getCards();
+
     })
     })
 
 
     useDidShow(() => {
     useDidShow(() => {
-        checkAuth(false)
+        if (list.length > 0) {
+            checkAuth()
+        }
     })
     })
 
 
+    global.refreshActivity = () => {
+        getCards()
+    }
+
     function getCards() {
     function getCards() {
         activityCards().then(res => {
         activityCards().then(res => {
-            if (user.isLogin) {
-                setReturnLoginData(true)
-            }
-            else {
-                setReturnLoginData(false)
-            }
+            checkAuth()
             setList((res as any).cards)
             setList((res as any).cards)
+            for (var i = 0; i < (res as any).cards.length; i++) {
+                var obj = (res as any).cards[i];
+                if (obj.code == '_walk') {
+                    setLatestRecord(obj.latest_record)
+                }
+            }
+        }).catch(e => {
+            console.log('请求超时')
         })
         })
     }
     }
 
 
-    function checkAuth(autoCheck = true) {
+    global.activityCardsFunc = getCards
+
+    function checkAuth() {
         console.log(new Date().getTime())
         console.log(new Date().getTime())
         if (user.isLogin) {
         if (user.isLogin) {
-            // setAuth()
             Taro.getSetting({
             Taro.getSetting({
                 success: res => {
                 success: res => {
                     //第一步,检测是否有授权 - 没有授权
                     //第一步,检测是否有授权 - 没有授权
                     if (!res.authSetting['scope.werun']) {
                     if (!res.authSetting['scope.werun']) {
-                        // setTitle('开启')
                         setAllowRun(false)
                         setAllowRun(false)
+                        Taro.setStorage({ key: 'auth', data: false })
                     }
                     }
                     else {
                     else {
                         setAllowRun(true)
                         setAllowRun(true)
-                        // setTitle('打卡')
-                        //自动打卡流程
-                        if (!autoCheck) {
-                            return
-                        }
-                        var time = Taro.getStorageSync('lastUploadStepsTime')
-                        if (time) {
-                            var now = new Date().getTime()
-                            if (now - time >= 30 * 24 * 3600 * 1000) {
-                                console.log('a')
-                                getWeRunData(true)
-                            }
-                        }
-                        else {
-                            console.log('b')
-                            getWeRunData(true)
-                        }
+                        Taro.setStorage({ key: 'auth', data: true })
                     }
                     }
-                    console.log(new Date().getTime())
                 }
                 }
             })
             })
         }
         }
         else {
         else {
-            // Taro.setStorageSync('lastUploadStepsTime', time)
             setAllowRun(false)
             setAllowRun(false)
-            // setTitle('开启');
+            Taro.setStorage({ key: 'auth', data: false })
         }
         }
     }
     }
 
 
-    function checkout() {
-        // console.log('开始获取步数的时间戳:' + new Date().getTime())
-        if (allowRun) {
-            setIsChecking(true)
-            dispatch(checkStart());
-        }
+    function tapBtn() {
         if (user.isLogin) {
         if (user.isLogin) {
-            setAuth(getWeRunData, refuseAuth)
+            if (allowRun) {
+                checkout()
+            }
+            else {
+                setAuth(successAuth, refuseAuth)
+            }
         }
         }
         else {
         else {
             Taro.navigateTo({
             Taro.navigateTo({
@@ -115,11 +116,29 @@ export default function Component(props: any) {
         }
         }
     }
     }
 
 
+    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) {
     function getWeRunData(autoCheck = false) {
-        if (autoCheck){
+        if (autoCheck) {
+            console.log('自动打卡')
             return
             return
         }
         }
         else {
         else {
+            console.log('开始打卡')
             dispatch(checkStart());
             dispatch(checkStart());
         }
         }
 
 
@@ -128,48 +147,39 @@ export default function Component(props: any) {
         var date = new Date();
         var date = new Date();
         var time = date.getTime()
         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());
         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())
-                var params = {
-                    is_manual: autoCheck ? 0 : 1,
-                    timestamp: time,
-                    encryptedData: res.encryptedData,
-                    iv: res.iv,
-                    date: strDate,
-                    cloudID: res.cloudID,
-                }
-                uploadSteps(params).then(res => {
-                    if ((res as any).error_code == 'WX_STEP_PARSE_FAIL') {
-                        retry(params, autoCheck, time)
-                        dispatch(checkRetry())
-                        // if (!autoCheck) {
-                        //     Taro.showToast({
-                        //         icon: 'none',
-                        //         title: (res as any).error_message
-                        //     })
-                        // }
-                    }
-                    else {
-                        setShowErrorBadge(false)
-                        uploadSuccess(res, autoCheck, time)
-                    }
+        console.log('开始取步数的时间戳:' + new Date().getTime())
 
 
-                }).catch(e => {
-                    retry(params, autoCheck, time)
-                    Taro.checkSession({
-                        success: function () {
-                            console.log('打卡后获取session_key 未过期')
-                        },
-                        fail: function () {
-                            console.log('打卡后获取session_key 已过期')
-                        }
-                    })
-                    // if (!autoCheck)
-                    //     dispatch(setResult({ isSuccess: false }) as any);
-                });
+
+        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,
             }
             }
+            uploadSteps(params).then(res => {
+                if ((res as any).error_code == 'WX_STEP_PARSE_FAIL') {
+                    retry(params, autoCheck, time)
+                    dispatch(checkRetry())
+                    console.log('上报失败  ')
+                }
+                else {
+                    console.log('上报成功 ')
+                    setShowErrorBadge(false)
+                    uploadSuccess(res, autoCheck, time)
+                }
+
+            }).catch(e => {
+                retry(params, autoCheck, time)
+            });
+        }).catch(_ => {
+            console.log('回调失败')
+            dispatch(setResult({ isSuccess: false }) as any)
         })
         })
+
+
     }
     }
 
 
     function retry(params, autoCheck, time) {
     function retry(params, autoCheck, time) {
@@ -182,21 +192,24 @@ export default function Component(props: any) {
                     params.cloudID = res2.cloudID
                     params.cloudID = res2.cloudID
                     uploadSteps(params).then(res => {
                     uploadSteps(params).then(res => {
                         if ((res as any).error_code == 'WX_STEP_PARSE_FAIL') {
                         if ((res as any).error_code == 'WX_STEP_PARSE_FAIL') {
-                            if (!autoCheck)
-                            {
+                            if (!autoCheck) {
                                 dispatch(setResult({ isSuccess: false }) as any);
                                 dispatch(setResult({ isSuccess: false }) as any);
                                 setShowErrorBadge(true)
                                 setShowErrorBadge(true)
                             }
                             }
-                                
+
                         }
                         }
                         else {
                         else {
+
                             setShowErrorBadge(false)
                             setShowErrorBadge(false)
                             uploadSuccess(res, autoCheck, time)
                             uploadSuccess(res, autoCheck, time)
                         }
                         }
 
 
                     }).catch(e => {
                     }).catch(e => {
-                        if (!autoCheck)
+                        if (!autoCheck) {
                             dispatch(setResult({ isSuccess: false }) as any);
                             dispatch(setResult({ isSuccess: false }) as any);
+                            setShowErrorBadge(true)
+                        }
+
                     })
                     })
                 }
                 }
             })
             })
@@ -209,23 +222,26 @@ export default function Component(props: any) {
             dispatch(setResult({ isSuccess: true }) as any)
             dispatch(setResult({ isSuccess: true }) as any)
         setStepInfo((res as any)[(res as any).length - 1])
         setStepInfo((res as any)[(res as any).length - 1])
         setLastTime(time)
         setLastTime(time)
-        setIsChecking(false)
-        getCards();
-    }
+        debugger
 
 
-    function refuseAuth() {
-        // setTitle('开启');
-        setIsChecking(false)
-        setAllowRun(false)
+        for (var i = 0; i < list.length; i++) {
+            var obj = list[i];
+            if ((obj as any).code == '_walk') {
+                (obj as any).latest_record = res
+            }
+        }
+        // getCards();
     }
     }
 
 
+
+
     function goDetail() {
     function goDetail() {
         if (user.isLogin) {
         if (user.isLogin) {
-            if (!allowRun){
+            if (!allowRun) {
                 return;
                 return;
             }
             }
             Taro.navigateTo({
             Taro.navigateTo({
-                url: '/pages/RecordsHistory?type=activity'
+                url: '/pages/RecordsHistory?type=activity&refreshList=getCards'
             })
             })
         }
         }
         else {
         else {
@@ -306,19 +322,29 @@ export default function Component(props: any) {
                     desc = '今天待打卡'
                     desc = '今天待打卡'
                 }
                 }
 
 
-                if (!allowRun) {
-                    value = '0'
-                    desc = '开启步数仅自己可见'
-                    unit = ''
-                }
-                else {
-                    unit = '步'
-                }
 
 
-                if (!user.isLogin|| !returnLoginData) {
+
+                if (!user.isLogin) {
                     value = '未登录'
                     value = '未登录'
                     desc = '登录后可开启打卡'
                     desc = '登录后可开启打卡'
-                    unit = ''
+                }
+                else {
+                    if (!allowRun) {
+                        value = '未开启'
+                        desc = '开启后可打卡步数'
+                    }
+                    else {
+                        // unit = '步'
+                        if (item.latest_record) {
+                            value = item.latest_record.items[0].value
+                            desc = TimeFormatter.formatTimestamp(item.latest_record.timestamp)
+                            unit = '步'
+                        }
+                        else {
+                            value = '今日待打卡'
+                            desc = '查看历史记录'
+                        }
+                    }
                 }
                 }
 
 
                 // if (user.isLogin && !allowRun){
                 // if (user.isLogin && !allowRun){
@@ -338,27 +364,11 @@ export default function Component(props: any) {
                     onClickDetail={goDetail}
                     onClickDetail={goDetail}
                     showBadge={showErrorBadge && checkResult.type == 'idle'}
                     showBadge={showErrorBadge && checkResult.type == 'idle'}
                     onClick={() => {
                     onClick={() => {
-                        checkout()
+                        tapBtn()
+                        // checkout()
                     }}
                     }}
                 />
                 />
             })
             })
         }
         }
     </View>
     </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>
 }
 }

+ 6 - 0
src/features/trackSomething/components/ActivityHistory.tsx

@@ -29,11 +29,17 @@ export default function Component(props: { records: any[] }) {
         var minutes = date.getMinutes()
         var minutes = date.getMinutes()
         return `${hour < 10 ? '0' + hour : hour}:${minutes < 10 ? '0' + minutes : minutes}`
         return `${hour < 10 ? '0' + hour : hour}:${minutes < 10 ? '0' + minutes : minutes}`
     }
     }
+
+    function clear(){
+
+    }
     return <View style={{ display: 'flex', flexDirection: 'column' }}>
     return <View style={{ display: 'flex', flexDirection: 'column' }}>
         <View className="operate_view">
         <View className="operate_view">
             <Text>时间倒序</Text>
             <Text>时间倒序</Text>
             <Text style={{ marginLeft: 5, marginRight: 5 }}> | </Text>
             <Text style={{ marginLeft: 5, marginRight: 5 }}> | </Text>
             <Text>时间正序</Text>
             <Text>时间正序</Text>
+            <View style={{flex:1}}/>
+            {/* <Text onClick={clear}>删除全部</Text> */}
         </View>
         </View>
         {
         {
             (props.records as any).map(item => {
             (props.records as any).map(item => {

+ 7 - 5
src/features/trackSomething/components/Metric.tsx

@@ -34,10 +34,6 @@ export default function Component(props: any) {
         getCards();
         getCards();
     }, [user.isLogin])
     }, [user.isLogin])
 
 
-    useReady(() => {
-        getCards();
-    })
-
     const openModal = () => {
     const openModal = () => {
         setIsModalOpen(true);
         setIsModalOpen(true);
     };
     };
@@ -46,12 +42,18 @@ export default function Component(props: any) {
         setIsModalOpen(false);
         setIsModalOpen(false);
     };
     };
 
 
+    global.refreshMetric = () => {
+        getCards()
+    }
+
     function getCards() {
     function getCards() {
+        console.log('get Cards')
         metricCards().then(res => {
         metricCards().then(res => {
             setList((res as any).cards)
             setList((res as any).cards)
         })
         })
     }
     }
 
 
+
     //ts 把数组items: [{code: "_walk", value: 2180},{code: "_walk", value: 4444}]中的value取出来,/分割,组成字符串,如2180/4444
     //ts 把数组items: [{code: "_walk", value: 2180},{code: "_walk", value: 4444}]中的value取出来,/分割,组成字符串,如2180/4444
     function getValues(items) {
     function getValues(items) {
         var values = ''
         var values = ''
@@ -71,7 +73,7 @@ export default function Component(props: any) {
                 return
                 return
             }
             }
             Taro.navigateTo({
             Taro.navigateTo({
-                url: '/pages/RecordsHistory?type=metric&code=' + item.code
+                url: '/pages/RecordsHistory?type=metric&refreshList=getCards&code=' + item.code
             })
             })
         }
         }
         else {
         else {

+ 370 - 0
src/features/trackSomething/components/activity_backup.tsx

@@ -0,0 +1,370 @@
+import { View, Text } from "@tarojs/components";
+import './Metric.scss'
+import { setAuth } from "../hooks/werun";
+import { useDidShow, 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 { ResultType, checkFail, checkRetry, checkStart, checkSuccess, setResult } from "@/store/action_results";
+import { uploadSessionKey } from "@/services/common";
+
+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 [list, setList] = useState([])
+    const dispatch = useDispatch();
+    const [returnLoginData, setReturnLoginData] = useState(false)
+    const [showErrorBadge, setShowErrorBadge] = useState(false)
+    // const [title, setTitle] = useState('打卡')
+
+    //未登录<->已登录 状态切换时,执行一次授权检查
+    useEffect(() => {
+        getCards();
+        // checkAuth(false)
+    }, [user.isLogin])
+
+    useEffect(() => {
+        console.log('checkResult.type:' + checkResult.type)
+    }, [
+        checkResult.type
+    ])
+
+    //页面渲染完成后执行一次授权检查
+    useReady(() => {
+        // getCards();
+    })
+
+    useDidShow(() => {
+        if (list.length > 0) {
+            checkAuth(false)
+        }
+        // 
+    })
+
+    function getCards() {
+        activityCards().then(res => {
+            if (user.isLogin) {
+                setReturnLoginData(true)
+            }
+            else {
+                setReturnLoginData(false)
+            }
+
+            checkAuth(false)
+            setList((res as any).cards)
+        })
+    }
+
+    function checkAuth(autoCheck = true) {
+        console.log(new Date().getTime())
+        if (user.isLogin) {
+            // setAuth()
+            Taro.getSetting({
+                success: res => {
+                    //第一步,检测是否有授权 - 没有授权
+                    if (!res.authSetting['scope.werun']) {
+                        // setTitle('开启')
+                        setAllowRun(false)
+                    }
+                    else {
+                        setAllowRun(true)
+                        // setTitle('打卡')
+                        //自动打卡流程
+                        // if (!autoCheck) {
+                        //     return
+                        // }
+                        // var time = Taro.getStorageSync('lastUploadStepsTime')
+                        // if (time) {
+                        //     var now = new Date().getTime()
+                        //     if (now - time >= 30 * 24 * 3600 * 1000) {
+                        //         console.log('a')
+                        //         getWeRunData(true)
+                        //     }
+                        // }
+                        // else {
+                        //     console.log('b')
+                        //     getWeRunData(true)
+                        // }
+                    }
+                    console.log(new Date().getTime())
+                }
+            })
+        }
+        else {
+            // Taro.setStorageSync('lastUploadStepsTime', time)
+            setAllowRun(false)
+            // setTitle('开启');
+        }
+    }
+
+    function checkout() {
+        // console.log('开始获取步数的时间戳:' + new Date().getTime())
+        if (allowRun) {
+            setIsChecking(true)
+            dispatch(checkStart());
+
+            getWeRunData(false)
+        }
+        if (user.isLogin) {
+            setAuth(getWeRunData, refuseAuth)
+        }
+        else {
+            Taro.navigateTo({
+                url: '/pages/ChooseAuth'
+            })
+        }
+    }
+
+    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());
+        Taro.getWeRunData({
+            success: res => {
+                // console.log('已获取步数的时间戳:' + new Date().getTime())
+                var params = {
+                    is_manual: autoCheck ? 0 : 1,
+                    timestamp: time,
+                    encryptedData: res.encryptedData,
+                    iv: res.iv,
+                    date: strDate,
+                    cloudID: res.cloudID,
+                }
+                uploadSteps(params).then(res => {
+                    if ((res as any).error_code == 'WX_STEP_PARSE_FAIL') {
+                        retry(params, autoCheck, time)
+                        dispatch(checkRetry())
+                        // if (!autoCheck) {
+                        //     Taro.showToast({
+                        //         icon: 'none',
+                        //         title: (res as any).error_message
+                        //     })
+                        // }
+                    }
+                    else {
+                        setShowErrorBadge(false)
+                        uploadSuccess(res, autoCheck, time)
+                    }
+
+                }).catch(e => {
+                    retry(params, autoCheck, time)
+                    Taro.checkSession({
+                        success: function () {
+                            console.log('打卡后获取session_key 未过期')
+                        },
+                        fail: function () {
+                            console.log('打卡后获取session_key 已过期')
+                        }
+                    })
+                    // if (!autoCheck)
+                    //     dispatch(setResult({ isSuccess: false }) as any);
+                });
+            }
+        })
+    }
+
+    function retry(params, autoCheck, time) {
+        Taro.login().then(res => {
+            Taro.getWeRunData({
+                success: res2 => {
+                    params.code = res.code;
+                    params.encryptedData = res2.encryptedData
+                    params.iv = res2.iv
+                    params.cloudID = res2.cloudID
+                    uploadSteps(params).then(res => {
+                        if ((res as any).error_code == 'WX_STEP_PARSE_FAIL') {
+                            if (!autoCheck) {
+                                dispatch(setResult({ isSuccess: false }) as any);
+                                setShowErrorBadge(true)
+                            }
+
+                        }
+                        else {
+                            setShowErrorBadge(false)
+                            uploadSuccess(res, autoCheck, time)
+                        }
+
+                    }).catch(e => {
+                        if (!autoCheck)
+                            dispatch(setResult({ isSuccess: false }) as any);
+                    })
+                }
+            })
+        })
+    }
+
+    function uploadSuccess(res, autoCheck, time) {
+        Taro.setStorageSync('lastUploadStepsTime', time)
+        if (!autoCheck)
+            dispatch(setResult({ isSuccess: true }) as any)
+        setStepInfo((res as any)[(res as any).length - 1])
+        setLastTime(time)
+        setIsChecking(false)
+        getCards();
+    }
+
+    function refuseAuth() {
+        // setTitle('开启');
+        setIsChecking(false)
+        setAllowRun(false)
+    }
+
+    function goDetail() {
+        if (user.isLogin) {
+            if (!allowRun) {
+                return;
+            }
+            Taro.navigateTo({
+                url: '/pages/RecordsHistory?type=activity'
+            })
+        }
+        else {
+            Taro.navigateTo({
+                url: '/pages/ChooseAuth'
+            })
+        }
+
+    }
+
+    // checkResult.type == 'ing' && setStrBtnTitle('打卡中...')
+    var btnTitle = '';
+    var isEnable = true;
+    if (allowRun) {
+        switch (checkResult.type) {
+            case ResultType.idle:
+                {
+                    btnTitle = '打卡'
+                    isEnable = true
+                }
+                break;
+            case ResultType.ing:
+                {
+                    btnTitle = '打卡中...'
+                    isEnable = false
+                }
+                break;
+            case ResultType.retry:
+                {
+                    btnTitle = '仍在打卡中...'
+                    isEnable = false
+                }
+                break;
+            case ResultType.success:
+                {
+                    btnTitle = '打卡成功'
+                    isEnable = false
+                }
+                break;
+            case ResultType.fail:
+                {
+                    btnTitle = '打卡失败'
+                    isEnable = false
+                }
+                break;
+            case ResultType.countdown:
+                {
+                    btnTitle = checkResult.title + 's'
+                    isEnable = false
+                }
+                break;
+            default:
+                break;
+        }
+    }
+    else {
+        btnTitle = '开启';
+        isEnable = true;
+    }
+
+    return <View>
+        {
+            list.map((item: any, index) => {
+                var value = '0'
+                var desc = ''
+                var unit = ''
+                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 = '0'
+                    desc = '开启步数仅自己可见'
+                    unit = ''
+                }
+                else {
+                    unit = '步'
+                }
+
+                if (!user.isLogin || !returnLoginData) {
+                    value = '未登录'
+                    desc = '登录后可开启打卡'
+                    unit = ''
+                }
+
+                // if (user.isLogin && !allowRun){
+                //     value = '0'
+                //     desc = '开启步数仅自己可见'
+                //     unit = ''
+                // }
+
+                return <MetricItem title={item.name}
+                    // value={allowRun ? stepInfo ? (stepInfo as any).step : '' : '未开启'}
+                    value={value}
+                    unit={unit}
+                    desc={desc}
+                    btnText={btnTitle}
+                    isDisabled={!isEnable}
+                    themeColor={item.theme_color}
+                    onClickDetail={goDetail}
+                    showBadge={showErrorBadge && checkResult.type == 'idle'}
+                    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>
+}

+ 1 - 0
src/features/trackTimeDuration/components/SetSchedule.tsx

@@ -19,6 +19,7 @@ export default function Component() {
   const isFastFirst = false;
   const isFastFirst = false;
   const dispatch = useDispatch();
   const dispatch = useDispatch();
 
 
+  debugger
   const [scenario] = useState(useSelector((state: any) => state.scenario))
   const [scenario] = useState(useSelector((state: any) => state.scenario))
   // const scenario = useSelector((state: any) => state.scenario);
   // const scenario = useSelector((state: any) => state.scenario);
   const common = useSelector((state: any) => state.common);
   const common = useSelector((state: any) => state.common);

+ 4 - 0
src/pages/Activity.tsx

@@ -9,6 +9,10 @@ export default function Page(){
             
             
     //     })
     //     })
     // })
     // })
+
+    function refresh(){
+        console.log('refresh')
+    }
     return (
     return (
         <View className="container activity">
         <View className="container activity">
             <Text>Activity Page</Text>
             <Text>Activity Page</Text>

+ 6 - 0
src/pages/Metric.tsx

@@ -12,6 +12,12 @@ export default function Page() {
     const [pickerItems, setPickerItems] = useState([]);
     const [pickerItems, setPickerItems] = useState([]);
     const [isPoint, setIsPoint] = useState(false)
     const [isPoint, setIsPoint] = useState(false)
 
 
+    global.refresh=()=>{
+        debugger
+        console.log('refresh')
+    }
+
+
     const openModal = () => {
     const openModal = () => {
         setIsModalOpen(true);
         setIsModalOpen(true);
     };
     };

+ 51 - 7
src/pages/RecordsHistory.tsx

@@ -5,7 +5,8 @@ import { useEffect, useState } from "react";
 import Schedule from '@/features/trackTimeDuration/components/Schedule'
 import Schedule from '@/features/trackTimeDuration/components/Schedule'
 import MetricHistory from "@/features/trackSomething/components/MetricHistory";
 import MetricHistory from "@/features/trackSomething/components/MetricHistory";
 import ActivityHistory from "@/features/trackSomething/components/ActivityHistory";
 import ActivityHistory from "@/features/trackSomething/components/ActivityHistory";
-import { activityRecords, metricRecords } from "@/services/trackSomething";
+import { activityRecords, clearMetricRecords, cleartActivityRecords, metricRecords } from "@/services/trackSomething";
+import Taro from "@tarojs/taro";
 
 
 export default function Page() {
 export default function Page() {
     const router = useRouter();
     const router = useRouter();
@@ -14,6 +15,7 @@ export default function Page() {
     const [records, setRecords] = useState<any[]>([])
     const [records, setRecords] = useState<any[]>([])
     const [counter, setCounter] = useState(0)
     const [counter, setCounter] = useState(0)
     const [timerId, setTimerId] = useState(null)
     const [timerId, setTimerId] = useState(null)
+    const {refreshList} = router.params
 
 
     useEffect(() => {
     useEffect(() => {
         startTimer();
         startTimer();
@@ -40,10 +42,11 @@ export default function Page() {
 
 
 
 
     useReady(() => {
     useReady(() => {
-        getHistory()
+        refresh()
     })
     })
 
 
     usePullDownRefresh(() => {
     usePullDownRefresh(() => {
+        console.log('aaa')
         refresh()
         refresh()
     })
     })
 
 
@@ -53,7 +56,6 @@ export default function Page() {
     // })
     // })
 
 
     function refresh() {
     function refresh() {
-        debugger
         setPageIndex(1)
         setPageIndex(1)
         getHistory(1)
         getHistory(1)
     }
     }
@@ -65,7 +67,7 @@ export default function Page() {
     }
     }
 
 
     function getHistory(page = pageIndex) {
     function getHistory(page = pageIndex) {
-        
+        // debugger
         if (router.params.type == 'time') {
         if (router.params.type == 'time') {
             getClockRecords({
             getClockRecords({
                 page: page,
                 page: page,
@@ -84,7 +86,7 @@ export default function Page() {
                 {
                 {
                     page: page,
                     page: page,
                     limit: pageSize,
                     limit: pageSize,
-                    code:'_walk'
+                    code: '_walk'
                 }
                 }
             ).then(res => {
             ).then(res => {
                 if (page == 1) {
                 if (page == 1) {
@@ -94,12 +96,12 @@ export default function Page() {
                 }
                 }
             })
             })
         }
         }
-        else if (router.params.type ==  'metric'){
+        else if (router.params.type == 'metric') {
             metricRecords(
             metricRecords(
                 {
                 {
                     page: page,
                     page: page,
                     limit: pageSize,
                     limit: pageSize,
-                    code:router.params.code
+                    code: router.params.code
                 }
                 }
             ).then(res => {
             ).then(res => {
                 if (page == 1) {
                 if (page == 1) {
@@ -116,7 +118,49 @@ export default function Page() {
         setRecords(records.filter(i => i.id != item.id))
         setRecords(records.filter(i => i.id != item.id))
     }
     }
 
 
+    function clear() {
+        // var page = Taro.getCurrentPages()[0]
+        // debugger
+        // page.refresh()
+        Taro.showModal({
+            title: '提示',
+            content: '确认删除全部记录?',
+            success: (res) => {
+                if (res.confirm) {
+                    doClear()
+                }
+            }
+        })
+
+    }
+
+    function doClear() {
+        if (router.params.type == 'activity') {
+            cleartActivityRecords({
+                code: '_walk'
+            }).then(res => {
+                refresh()
+                global.refreshActivity()
+                // router.params.refreshList()
+                // Taro.getCurrentPages()[0].refresh()
+            })
+        }
+        else if (router.params.type == 'metric') {
+            clearMetricRecords({
+                code: router.params.code
+            }).then(res => {
+                refresh()
+                global.refreshMetric()
+                // Taro.getCurrentPages()[0].refresh()
+            })
+        }
+    }
+
     return <View className="container">
     return <View className="container">
+
+        {
+            (router.params.type == 'metric' || router.params.type == 'activity') && <View style={{ height: 50, fontSize: 30, color: '#fff' }} onClick={clear}>删除全部</View>
+        }
         <ScrollView scrollY style={{ height: '100vh', display: 'flex', flexDirection: 'column' }}
         <ScrollView scrollY style={{ height: '100vh', display: 'flex', flexDirection: 'column' }}
             onScrollToLower={more} enableFlex
             onScrollToLower={more} enableFlex
         // onRefresh={refresh}
         // onRefresh={refresh}

+ 10 - 13
src/pages/clock.tsx

@@ -23,6 +23,7 @@ import { setSpecifiedStatus, setSpecifiedState, machine } from '@/store/trackTim
 import trackTimeService from '@/store/trackTimeMachine';
 import trackTimeService from '@/store/trackTimeMachine';
 import { setWXFollow } from '@/store/permission';
 import { setWXFollow } from '@/store/permission';
 import Tooltip from '@/components/Tooltip'
 import Tooltip from '@/components/Tooltip'
+import RequestType, { thirdPartRequest } from '@/services/thirdPartRequest'
 // import TabBar from '../../components/Tabbar';
 // import TabBar from '../../components/Tabbar';
 
 
 export default function IndexPage() {
 export default function IndexPage() {
@@ -74,18 +75,14 @@ export default function IndexPage() {
     // })
     // })
     // return
     // return
     if (process.env.TARO_ENV === 'weapp') {
     if (process.env.TARO_ENV === 'weapp') {
-      Taro.checkSession({
-        success: function () {
-          //session_key 未过期,并且在本生命周期一直有效
-          console.log('session_key 未过期,并且在本生命周期一直有效')
-        },
-        fail: function () {
-          console.log('session_key 已经失效,需要更新登录code')
-          Taro.login().then(res => {
-            // code = res.code;
-            uploadSessionKey({ type: 'WX_MP', code: res.code });
-          })
-        }
+      console.log('session request')
+      thirdPartRequest(RequestType.RequestTypeCheckSession).then(res => {
+        console.log('session_key 未过期,并且在本生命周期一直有效')
+      }).catch(err => {
+        console.log('session_key 已经失效,需要更新登录code')
+        thirdPartRequest(RequestType.RequestTypeWXLogin).then(result => {
+          uploadSessionKey({ type: 'WX_MP', code: (result as any).code });
+        })
       })
       })
     }
     }
   }
   }
@@ -234,7 +231,7 @@ export default function IndexPage() {
 
 
   function checkWXPubFollow() {
   function checkWXPubFollow() {
     wxPubFollow().then(res => {
     wxPubFollow().then(res => {
-        dispatch(setWXFollow((res as any).wx_pub_followed));
+      dispatch(setWXFollow((res as any).wx_pub_followed));
     })
     })
   }
   }
 
 

+ 65 - 7
src/pages/demo.tsx

@@ -1,10 +1,68 @@
-import { View,Text } from "@tarojs/components";
-import SlidngScale from "@components/SlidngScale";
+import Taro from '@tarojs/taro';
+import { View, Canvas } from '@tarojs/components';
+import { useRef, useState } from 'react';
 
 
+function MyComponent() {
+  const [ringX, setRingX] = useState(150);
+  const [ringY, setRingY] = useState(150);
+  const [dotX, setDotX] = useState(150);
+  const [dotY, setDotY] = useState(50);
+  const touchStartRef = useRef({ x: 0, y: 0 });
+  const dotRef = useRef<any>(null);
+  const canvasRef = useRef<any>(null);
 
 
-export default function Page(){
-    return <View style={{color:'#fff'}}>
-        <Text>SlidngScale Demo</Text>
-        {/* <SlidngScale /> */}
+  const handleTouchStart = (e) => {
+    const { clientX, clientY } = e.touches[0];
+    touchStartRef.current = { x: clientX, y: clientY };
+  };
+
+  const handleTouchMove = (e) => {
+    const { clientX, clientY } = e.touches[0];
+    const deltaX = clientX - touchStartRef.current.x;
+    const deltaY = clientY - touchStartRef.current.y;
+    const newDotX = dotX + deltaX;
+    const newDotY = dotY + deltaY;
+    const distance = Math.sqrt((newDotX - ringX) ** 2 + (newDotY - ringY) ** 2);
+
+    if (distance <= 50) {
+      setDotX(newDotX);
+      setDotY(newDotY);
+    }
+
+    touchStartRef.current = { x: clientX, y: clientY };
+    drawRingAndDot();
+  };
+
+  const drawRingAndDot = () => {
+    const context = Taro.createCanvasContext('myCanvas', this.$scope);
+    context.clearRect(0, 0, 300, 300);
+    context.beginPath();
+    context.arc(ringX, ringY, 50, 0, 2 * Math.PI);
+    context.setStrokeStyle('gray');
+    context.setLineWidth(10);
+    context.stroke();
+    context.closePath();
+
+    context.beginPath();
+    context.arc(dotX, dotY, 10, 0, 2 * Math.PI);
+    context.setFillStyle('red');
+    context.fill();
+    context.closePath();
+
+    context.draw();
+  };
+
+  return (
+    <View>
+      <Canvas
+        id="myCanvas"
+        style={{ width: '300px', height: '300px' }}
+        onTouchStart={handleTouchStart}
+        onTouchMove={handleTouchMove}
+        ref={canvasRef}
+      />
     </View>
     </View>
-}
+  );
+}
+
+export default MyComponent;

+ 75 - 116
src/services/http/request.ts

@@ -17,154 +17,113 @@ interface Resp {
     errMsg?: string;
     errMsg?: string;
 };
 };
 
 
-async function getStorage(key:string) {
+async function getStorage(key: string) {
     try {
     try {
         const res = await Taro.getStorage({ key });
         const res = await Taro.getStorage({ key });
         return res.data;
         return res.data;
     } catch {
     } catch {
         return '';
         return '';
     }
     }
-  }
+}
+
+//X-Language:语言,X-Device-Id:设备唯一码,X-Platform:小程序/android/ios,X-Location:地区,X-Device:登录设备
+// header['X-Language'] = ''
+// header['X-Device-Id'] = ''
+// header['X-Platform'] = ''
+// header['X-Location'] = ''
+// header['X-Device'] = ''
+// header['X-Time-Zone-Id'] = Intl.DateTimeFormat().resolvedOptions().timeZone
+// header['Authorization'] = 'Bearer ' + wx.getStorageSync('token');
+// header['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiMmQ5OWNlYzI0ZDFlMzE0Y2U1MjhlODM4MWMzYzk0MzgiLCJpc3MiOiJDT0RFUEFBUy5DT00iLCJuaWNrbmFtZSI6IueOi-a4nSIsInR5cCI6IkJlYXJlciIsInNlc3Npb25fc3RhdGUiOiIyN2RjNmU4ZDdjMWU1MTVmNDQwNzVjZTFlODk2ZmUzNCIsImV4cCI6MTcxNjY0Mzk5MSwiaWF0IjoxNjg1MDIxNTkxfQ.fmFj0OVNRzjLkdebSyGJyk8EScPJFpDiz0L25W35zoA'
+
+
 
 
 export async function request<T>(param: RequestParam): Promise<T> {
 export async function request<T>(param: RequestParam): Promise<T> {
-    const { url, method, data } = param;
-    let header: any = {};
+    const kTimeout = 2000;
+    const kRetryCount = 3;
 
 
-    const token = global.token?global.token:''//await getStorage('token')
+    let retryCount = 0;
 
 
-    var split = new Date().toString().split(' ');
-    var timeZoneFormatted = split[split.length - 2];
+    
 
 
-    header['X-Time-Zone'] = timeZoneFormatted; //new Date().getTimezoneOffset() / 60
-    if (token.length>0){
-        header['Authorization'] = `Bearer ${token}`
-    }
-    //X-Language:语言,X-Device-Id:设备唯一码,X-Platform:小程序/android/ios,X-Location:地区,X-Device:登录设备
-    // header['X-Language'] = ''
-    // header['X-Device-Id'] = ''
-    // header['X-Platform'] = ''
-    // header['X-Location'] = ''
-    // header['X-Device'] = ''
-    // header['X-Time-Zone-Id'] = Intl.DateTimeFormat().resolvedOptions().timeZone
-    // header['Authorization'] = 'Bearer ' + wx.getStorageSync('token');
-    // header['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiMmQ5OWNlYzI0ZDFlMzE0Y2U1MjhlODM4MWMzYzk0MzgiLCJpc3MiOiJDT0RFUEFBUy5DT00iLCJuaWNrbmFtZSI6IueOi-a4nSIsInR5cCI6IkJlYXJlciIsInNlc3Npb25fc3RhdGUiOiIyN2RjNmU4ZDdjMWU1MTVmNDQwNzVjZTFlODk2ZmUzNCIsImV4cCI6MTcxNjY0Mzk5MSwiaWF0IjoxNjg1MDIxNTkxfQ.fmFj0OVNRzjLkdebSyGJyk8EScPJFpDiz0L25W35zoA'
-
-    return new Promise((resolve, reject) => {
-        Taro.request({
+    function performRequest(resolve: (value?: T | PromiseLike<T>) => void, reject: (reason?: any) => void) {
+        const { url, method, data } = param;
+        var requestTask: any = null;
+        let header: any = {};
+
+        const token = global.token ? global.token : ''; //await getStorage('token')
+
+        var split = new Date().toString().split(' ');
+        var timeZoneFormatted = split[split.length - 2];
+
+        header['X-Time-Zone'] = timeZoneFormatted; //new Date().getTimezoneOffset() / 60
+        if (token.length > 0) {
+            header['Authorization'] = `Bearer ${token}`;
+        }
+
+
+        const timer = setTimeout(() => {
+            requestTask && requestTask.abort();
+            console.log('timeout');
+            if (retryCount < kRetryCount) {
+                // Retry the request
+                console.log(`Retrying request (${retryCount + 1}/3)...`);
+                retryCount++;
+                performRequest(resolve, reject);
+                return;
+            }
+            Taro.showToast({
+                icon:'none',
+                title: method=='GET'?'网络连接失败,请检查网络':'操作失败,请检查网络',
+            })
+            reject('timeout');
+        }, kTimeout);
+
+        requestTask = Taro.request({
             url: url,
             url: url,
             method: method,
             method: method,
             header: header,
             header: header,
+            // timeout: kTimeout,
             data: data || {},
             data: data || {},
             success: (response: Resp | { [key: string]: any }) => {
             success: (response: Resp | { [key: string]: any }) => {
+                clearTimeout(timer);
                 const { statusCode, data } = response;
                 const { statusCode, data } = response;
-                if (statusCode >=200 && statusCode < 300){
+
+                if (statusCode >= 200 && statusCode < 300) {
+                    //正常数据返回
                     var resp = {} as T;
                     var resp = {} as T;
-                    if (response.data){
+                    if (response.data) {
                         resp = response.data as T;
                         resp = response.data as T;
                     }
                     }
-                    
                     resolve(resp);
                     resolve(resp);
-                }
-                else if (statusCode == 401) {
+
+                } else if (statusCode == 401) {
+                    //未登录或挤下线处理
                     global.dispatch(logoutSuccess());
                     global.dispatch(logoutSuccess());
-                }
-                else if (statusCode == 500 && response.data.error_code == 'WX_STEP_PARSE_FAIL'){
+                } else if (statusCode == 500 && response.data.error_code == 'WX_STEP_PARSE_FAIL') {
+                    //单独对计步第一次请求失败处理
                     resolve(response.data);
                     resolve(response.data);
-                }
-                else {
+                } else {
+                    //通用错误处理
                     Taro.showToast({
                     Taro.showToast({
                         icon: 'none',
                         icon: 'none',
-                        title:data.error_message
-                    })
+                        title: data.error_message,
+                    });
                     reject(data);
                     reject(data);
                 }
                 }
-                // if (statusCode == 204){
-                //     resolve({} as T);
-                // }
-                // if (statusCode != 200) {
-                //     reject(data);
-                // }
-                // const { error_code } = response.data || {};
-                // if (error_code === 'NOT_LOGIN') {
-                //     // new UserManager().logout();
-                // }
-
-                //200-299 正常resolve
-                //401 未登录
-                //400-499 业务错误 reject
             },
             },
             fail: err => {
             fail: err => {
-                if (err.errMsg == 'request:fail timeout') {
-                    // wx.showToast({
-                    //     title: '请求超时',
-                    //     icon: 'none',
-                    // });
-                }
-                reject(err);
+                // console.log('oppsu');
+                // clearTimeout(timer);
+                // reject(err);
             },
             },
-            complete: () => {},
         });
         });
-    });
-}
-
-// import axios from 'axios';
-
-// const kTimeout = 6000;
-// const kRetry = 3;
 
 
-// const axiosInstance = axios.create({
-//     timeout: kTimeout,
-// });
 
 
-// axios.interceptors.request.use(
-//     function (config) {
-//         var split = new Date().toString().split(' ');
-//         var timeZoneFormatted = split[split.length - 2];
 
 
-//         config.headers['X-Time-Zone'] = timeZoneFormatted;
-//         // config.headers['channel'] = 'mini program'
-//         return config
-//     },
-//     function (error) {
-//         return Promise.reject(error)
-//     }
-// )
-
-// axiosInstance.interceptors.response.use(
-//     response => response,
-//     error => Promise.reject(error)
-// );
+    }
+    return new Promise<T>((resolve, reject) => {
+        performRequest(resolve, reject);
+    });
+}
 
 
-// export const request = async (url, method = 'post', data = {}, options = {}) => {
-    
-//     const { timeout = kTimeout, retry = kRetry } = options;
-
-//     axiosInstance.defaults.timeout = timeout;
-
-//     let retries = 0;
-//     while (retries < retry) {
-//         try {
-//             const response = await axiosInstance({
-//                 url,
-//                 method,
-//                 data,
-//             });
-//             return response.data;
-//         } catch (error) {
-//             console.log(error)
-//             if (axios.isCancel(error)) {
-//                 // 请求被取消
-//                 console.log('Request canceled');
-//                 break;
-//             }
-
-//             if (retries === retry - 1) {
-//                 // 达到最大重试次数
-//                 throw error;
-//             }
-
-//             console.log('Request failed. Retrying...');
-//             retries++;
-//         }
-//     }
-// };

+ 111 - 0
src/services/http/request_backup.ts

@@ -0,0 +1,111 @@
+import { logoutSuccess } from "@/store/user";
+import Taro from "@tarojs/taro";
+import { useDispatch } from "react-redux";
+
+
+interface RequestParam {
+    url: string;
+    method: 'POST' | 'GET' | 'DELETE' | 'PUT';
+    data?: Record<string, any>;
+    showAlert?: boolean;
+}
+
+interface Resp {
+    statusCode?: number;
+    header?: any;
+    data?: any;
+    errMsg?: string;
+};
+
+async function getStorage(key: string) {
+    try {
+        const res = await Taro.getStorage({ key });
+        return res.data;
+    } catch {
+        return '';
+    }
+}
+
+//X-Language:语言,X-Device-Id:设备唯一码,X-Platform:小程序/android/ios,X-Location:地区,X-Device:登录设备
+// header['X-Language'] = ''
+// header['X-Device-Id'] = ''
+// header['X-Platform'] = ''
+// header['X-Location'] = ''
+// header['X-Device'] = ''
+// header['X-Time-Zone-Id'] = Intl.DateTimeFormat().resolvedOptions().timeZone
+// header['Authorization'] = 'Bearer ' + wx.getStorageSync('token');
+// header['Authorization'] = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhY2NvdW50Iiwic3ViIjoiMmQ5OWNlYzI0ZDFlMzE0Y2U1MjhlODM4MWMzYzk0MzgiLCJpc3MiOiJDT0RFUEFBUy5DT00iLCJuaWNrbmFtZSI6IueOi-a4nSIsInR5cCI6IkJlYXJlciIsInNlc3Npb25fc3RhdGUiOiIyN2RjNmU4ZDdjMWU1MTVmNDQwNzVjZTFlODk2ZmUzNCIsImV4cCI6MTcxNjY0Mzk5MSwiaWF0IjoxNjg1MDIxNTkxfQ.fmFj0OVNRzjLkdebSyGJyk8EScPJFpDiz0L25W35zoA'
+
+
+export async function request<T>(param: RequestParam): Promise<T> {
+    const { url, method, data } = param;
+    let header: any = {};
+
+    const token = global.token ? global.token : ''; //await getStorage('token')
+
+    var split = new Date().toString().split(' ');
+    var timeZoneFormatted = split[split.length - 2];
+
+    header['X-Time-Zone'] = timeZoneFormatted; //new Date().getTimezoneOffset() / 60
+    if (token.length > 0) {
+        header['Authorization'] = `Bearer ${token}`;
+    }
+
+    const kTimeout = 5000;
+    const kRetryCount = 3;
+    return new Promise<T>((resolve, reject,complete?:any) => {
+        const requestWithRetry = (retryCount: number) => {
+            Taro.request({
+                url: url,
+                method: method,
+                header: header,
+                timeout: kTimeout,
+                data: data || {},
+                success: (response: Resp | { [key: string]: any }) => {
+                    const { statusCode, data } = response;
+                    
+                    if (statusCode >= 200 && statusCode < 300) {
+                        //正常数据返回
+                        var resp = {} as T;
+                        if (response.data) {
+                            resp = response.data as T;
+                        }
+                        resolve(resp);
+
+                    } else if (statusCode == 401) {
+                        //未登录或挤下线处理
+                        global.dispatch(logoutSuccess());
+                    } else if (statusCode == 500 && response.data.error_code == 'WX_STEP_PARSE_FAIL') {
+                        //单独对计步第一次请求失败处理
+                        resolve(response.data);
+                    } else {
+                        //通用错误处理
+                        Taro.showToast({
+                            icon: 'none',
+                            title: data.error_message,
+                        });
+                        reject(data);
+                    }
+                },
+                fail: err => {
+                    //超时、无网等情况的处理
+                    if (err) {
+                        if (retryCount < kRetryCount) {
+                            // Retry the request
+                            console.log(`Retrying request (${retryCount + 1}/3)...`);
+                            requestWithRetry(retryCount + 1);
+                            return;
+                        }
+                    }
+                    reject(err);
+                },
+                complete: () => { 
+                    complete && complete()
+                    // console.log('complete');
+                },
+            });
+        };
+
+        requestWithRetry(0);
+    });
+}

+ 70 - 0
src/services/thirdPartRequest.tsx

@@ -0,0 +1,70 @@
+import Taro from "@tarojs/taro";
+
+enum RequestType {
+    RequestTypeWXRunData,
+    RequestTypeWXLogin,
+    RequestTypeCheckSession
+}
+
+export default RequestType;
+
+const kTimeOut  = 5000;
+export const thirdPartRequest = (type: RequestType) => {
+    
+    return new Promise((resolve, reject) => {
+        var timer = setTimeout(() => {
+            reject('timeout');
+        }, kTimeOut);
+        switch (type) {
+            case RequestType.RequestTypeWXRunData:
+                {
+                    clearTimeout(timer);
+                    console.log('开始获取微信步数')
+                    Taro.getWeRunData({
+                        success: (res) => {
+                            console.log('获取微信步数成功')
+                            resolve(res);
+                        },
+                        fail: (err) => {
+                            console.log('获取微信步数失败 ')
+                            reject(err);
+                        },
+                        complete: () => {
+                            console.log('获取微信步数完成  ')
+                        }
+                    })
+                }
+                break;
+            case RequestType.RequestTypeWXLogin:
+                {
+                    clearTimeout(timer);
+                    Taro.login({
+                        success: (res) => {
+                            resolve(res);
+                        },
+                        fail: (err) => {
+                            reject(err);
+                        },
+                        complete: () => {
+
+                        }
+                    })
+                }
+                break;
+            case RequestType.RequestTypeCheckSession:
+                {
+                    clearTimeout(timer);
+                    Taro.checkSession({
+                        success: () => {
+                            resolve(null);
+                        },
+                        fail: () => {
+                            reject();
+                        }
+                    })
+                };
+                break;
+
+        }
+    });
+}

+ 30 - 3
src/services/trackSomething.tsx

@@ -2,7 +2,7 @@ import { API_ACTIVITY_CARDS, API_ACTIVITY_RECORDS, API_METRIC_CARDS, API_METRIC_
 import { request } from './http/request';
 import { request } from './http/request';
 
 
 export const uploadSteps = (params) => {
 export const uploadSteps = (params) => {
-    return new Promise((resolve,reject) => {
+    return new Promise((resolve, reject) => {
         request({
         request({
             url: API_UPLOAD_STEPS, method: 'POST', data: { ...params }
             url: API_UPLOAD_STEPS, method: 'POST', data: { ...params }
         }).then(res => {
         }).then(res => {
@@ -15,12 +15,14 @@ export const uploadSteps = (params) => {
 }
 }
 
 
 export const activityCards = () => {
 export const activityCards = () => {
-    return new Promise((resolve) => {
+    return new Promise((resolve, reject) => {
         request({
         request({
             url: API_ACTIVITY_CARDS, method: 'GET', data: {}
             url: API_ACTIVITY_CARDS, method: 'GET', data: {}
         }).then(res => {
         }).then(res => {
             resolve(res);
             resolve(res);
             // dispatch(loginSuccess(res));
             // dispatch(loginSuccess(res));
+        }).catch(e => {
+            reject(e)
         })
         })
     })
     })
 }
 }
@@ -36,8 +38,33 @@ export const activityRecords = (params) => {
     })
     })
 }
 }
 
 
+export const cleartActivityRecords = (params) => {
+    return new Promise((resolve) => {
+        request({
+            url: API_ACTIVITY_RECORDS + '?code=' + params.code, method: 'DELETE', data: { ...params }
+        }).then(res => {
+            resolve(res);
+            // dispatch(loginSuccess(res));
+        })
+    })
+
+}
+
+export const clearMetricRecords = (params) => {
+    return new Promise((resolve) => {
+        request({
+            url: API_METRIC_RECORDS + '?code=' + params.code, method: 'DELETE', data: { ...params }
+        }).then(res => {
+            resolve(res);
+            // dispatch(loginSuccess(res));
+        })
+    })
+
+
+}
+
 export const uploadMetric = (params) => {
 export const uploadMetric = (params) => {
-    return new Promise((resolve,reject) => {
+    return new Promise((resolve, reject) => {
         request({
         request({
             url: API_METRIC_RECORDS, method: 'POST', data: { ...params }
             url: API_METRIC_RECORDS, method: 'POST', data: { ...params }
         }).then(res => {
         }).then(res => {

+ 1 - 0
src/store/action_results.tsx

@@ -80,6 +80,7 @@ export const setResult = createAsyncThunk('result/action', async (payload: {isSu
     else {
     else {
         dispatch(checkFail());
         dispatch(checkFail());
         setTimeout(()=>{
         setTimeout(()=>{
+            debugger
             dispatch(resetStatus());
             dispatch(resetStatus());
         },resultTime*1000)
         },resultTime*1000)
     }
     }