leon преди 2 години
родител
ревизия
9e21463f58

BIN
src/assets/images/close.png


BIN
src/assets/images/more.png


+ 0 - 0
src/assets/images/placeholder


+ 6 - 2
src/components/LimitPickers.tsx

@@ -1,7 +1,7 @@
 import { PickerView, PickerViewColumn, View, Text } from "@tarojs/components";
 import { useEffect, useState } from "react";
 
-export default function Component(props: { limit: number, onChange: Function, onCancel: Function }) {
+export default function Component(props: { limit: number, onChange: Function, onCancel: Function,isRealTime?:boolean }) {
     const days: string[] = [];
     const today = new Date();
     const [values, setValues] = useState([6, today.getHours(), today.getMinutes()])
@@ -108,7 +108,11 @@ export default function Component(props: { limit: number, onChange: Function, on
     }
 
     function confirm() {
-        const date = new Date(global.set_time);
+        var date = new Date();
+        if (!props.isRealTime) {
+            date = new Date(global.set_time);
+        }
+        
         date.setDate(today.getDate() - (6 - values[0]));
         date.setHours(values[1])
         date.setMinutes(values[2])

+ 48 - 0
src/components/Tooltip.scss

@@ -0,0 +1,48 @@
+.tip_bg {
+    z-index: 1000;
+    display: flex;
+    flex-direction: row;
+    height: 76px;
+    border-radius: 38px;
+    background-color: #505050;
+    padding-left: 28px;
+    padding-right: 28px;
+    align-items: center;
+    position: fixed;
+    right: 20px;
+    top: 20px;
+
+}
+
+.arrow {
+    position: absolute;
+    // width: 40px;
+    // height: 20px;
+    // background-color: #505050;
+    top: -20px;
+    right: 100px;
+
+    width: 0;
+    height: 0;
+    border-left: 25px solid transparent;
+    border-right: 25px solid transparent;
+    border-bottom: 20px solid #505050;
+
+}
+
+.tip_text {
+    color: #fff;
+    font-size: 28px;
+}
+
+.tip_more {
+    padding: 5px;
+    width: 37px;
+    height: 13px;
+}
+
+.tip_close {
+    padding: 5px;
+    width: 37px;
+    height: 37px;
+}

+ 12 - 0
src/components/Tooltip.tsx

@@ -0,0 +1,12 @@
+import { View, Text, Image } from "@tarojs/components";
+import './Tooltip.scss'
+export default function Component(props: { title: string, closeTip: Function }) {
+    return (
+        <View className="tip_bg">
+            <View className="arrow"/>
+            <Image className="tip_more" src={require('@assets/images/more.png')} />
+            <Text className="tip_text">{props.title}</Text>
+            <Image className="tip_close" src={require('@/assets/images/close.png')} onClick={() => {props.closeTip()}} />
+        </View>
+    )
+}

+ 28 - 31
src/features/trackSomething/components/Activity.tsx

@@ -114,22 +114,16 @@ export default function Component(props: any) {
                     date: strDate,
                     cloudID: res.cloudID,
                 }).then(res => {
-                    console.log(res)
+
                     Taro.setStorageSync('lastUploadStepsTime', time)
-                    if ((res as any).length > 0) {
-                        // dispatch(checkSuccess());
-                        dispatch(setResult({ isSuccess: true }) as any)
-                        setStepInfo((res as any)[(res as any).length - 1])
-                        setLastTime(time)
-                        console.log('接口返回的时间戳:' + new Date().getTime())
-                        setIsChecking(false)
-                    }
-                    else {
-                        dispatch(checkFail());
-                    }
+
+                    dispatch(setResult({ isSuccess: true }) as any)
+                    setStepInfo((res as any)[(res as any).length - 1])
+                    setLastTime(time)
+                    setIsChecking(false)
                     getCards();
                 }).catch(e => {
-                    dispatch(checkFail());
+                    dispatch(setResult({ isSuccess: false }) as any);
                 });
             }
         })
@@ -158,47 +152,50 @@ export default function Component(props: any) {
     // checkResult.type == 'ing' && setStrBtnTitle('打卡中...')
     var btnTitle = '';
     var isEnable = true;
-    if (allowRun){
-        if (checkResult.type == 'idle'){
-            btnTitle =  '打卡'
+    if (allowRun) {
+        if (checkResult.type == 'idle') {
+            btnTitle = '打卡'
             isEnable = true
         }
-        else if (checkResult.type == 'ing'){
+        else if (checkResult.type == 'ing') {
             btnTitle = '打卡中...'
             isEnable = false;
         }
-        else if (checkResult.type == 'success'){
+        else if (checkResult.type == 'success') {
             btnTitle = '打卡成功'
             isEnable = false
         }
-        else if (checkResult.type == 'fail'){
+        else if (checkResult.type == 'fail') {
             btnTitle = '打卡失败'
             isEnable = false
         }
-        else if (checkResult.type == 'countdown'){
-            btnTitle = checkResult.title+'s'
+        else if (checkResult.type == 'countdown') {
+            btnTitle = checkResult.title + 's'
             isEnable = false;
         }
     }
     else {
-        btnTitle =  '开启';
+        btnTitle = '开启';
         isEnable = true;
     }
 
     return <View>
         {
-            list.map((item, index) => {
+            list.map((item: any, index) => {
                 var value = '0'
                 var desc = ''
-                if ((item as any).latest_record) {
-                    value = (item as any).latest_record.items[0].value
-                    if ((item as any).latest_record.timestamp==0){
+                if (item.latest_record) {
+                    value = item.latest_record.items[0].value
+                    if (item.latest_record.timestamp == 0) {
                         desc = '今天待打卡'
                     }
                     else {
-                        desc = TimeFormatter.formatTimestamp((item as any).latest_record.timestamp)
+                        desc = TimeFormatter.formatTimestamp(item.latest_record.timestamp)
                     }
-                    
+
+                }
+                else {
+                    desc = '今天待打卡'
                 }
 
                 if (!allowRun) {
@@ -206,17 +203,17 @@ export default function Component(props: any) {
                     desc = '开启步数仅自己可见'
                 }
 
-                return <MetricItem title={(item as any).name}
+                return <MetricItem title={item.name}
                     // value={allowRun ? stepInfo ? (stepInfo as any).step : '' : '未开启'}
                     value={value}
-                    unit={(allowRun && stepInfo) ? '步' : ''}
+                    unit={allowRun ? '步' : ''}
                     desc={desc}
                     btnText={btnTitle}
                     isDisabled={!isEnable}
                     // desc={allowRun ? stepInfo ? TimeFormatter.formatTimestamp(lastTime) : '' : '开启步数仅自己可见'}
                     // btnText={allowRun ? isCheking ? '打卡中...' : '打卡' : '开启'}
                     // isDisabled={isCheking}
-                    themeColor='#EEC01F'
+                    themeColor={item.theme_color}
                     onClickDetail={goDetail}
                     onClick={checkout}
                 />

+ 10 - 0
src/features/trackSomething/components/Metric.scss

@@ -0,0 +1,10 @@
+.metric_container{
+    display: flex;
+    flex-direction: row;
+    flex-wrap: wrap;
+    justify-content: space-around;
+}
+
+.space_width{
+    width: 320px;
+}

+ 227 - 68
src/features/trackSomething/components/Metric.tsx

@@ -5,62 +5,94 @@ import { useReady } from "@tarojs/taro";
 import { useSelector } from "react-redux";
 import { useEffect, useState } from "react";
 import Taro from "@tarojs/taro";
-import { uploadSteps } from "@/services/trackSomething";
+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 [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 [title, setTitle] = useState('打卡')
+    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(() => {
-        checkAuth()
     }, [user.isLogin])
 
-    //页面渲染完成后执行一次授权检查
     useReady(() => {
-        // checkAuth()
+        getCards();
     })
 
-    function checkAuth() {
-        // Taro.checkSession
+    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) {
-            // setAuth()
-            Taro.getSetting({
-                success: res => {
-                    //第一步,检测是否有授权 - 没有授权
-                    if (!res.authSetting['scope.werun']) {
-                        // setTitle('开启')
-                        setAllowRun(false)
-                    }
-                    else {
-                        setAllowRun(true)
-                        // setTitle('打卡')
-                        //自动打卡流程
-                        getWeRunData(true)
-                    }
-                }
+            Taro.navigateTo({
+                url: '/pages/RecordsHistory?type=metric&code=' + item.code
             })
         }
         else {
-            setAllowRun(false)
-            // setTitle('开启');
+            Taro.navigateTo({
+                url: '/pages/ChooseAuth'
+            })
         }
     }
 
-    function checkout() {
-        console.log('开始获取步数的时间戳:' + new Date().getTime())
-        if (allowRun){
-            setIsChecking(true)
-        }
+    function record(item: any) {
+
         if (user.isLogin) {
-            setAuth(getWeRunData, refuseAuth)
+            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({
@@ -69,54 +101,181 @@ export default function Component(props: any) {
         }
     }
 
-    function getWeRunData(autoCheck = false) {
-        // setTitle('打卡');
-        setAllowRun(true)
-        var time = new Date().getTime()
-        Taro.getWeRunData({
-            success: res => {
-                console.log('已获取步数的时间戳:' + new Date().getTime())
-                uploadSteps({
-                    is_manual: autoCheck ? 0 : 1,
-                    timestamp: time,
-                    encryptedData: res.encryptedData,
-                    iv: res.iv,
-                    cloudID: res.cloudID,
-                }).then(res => {
-                    console.log(res)
-                    if ((res as any).length > 0) {
-                        setStepInfo((res as any)[(res as any).length - 1])
-                        setLastTime(time)
-                        console.log('接口返回的时间戳:' + new Date().getTime())
-                        setIsChecking(false)
-                    }
-                });
+    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 refuseAuth() {
-        // setTitle('开启');
-        setIsChecking(false)
-        setAllowRun(false)
+    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 goDetail(){
-        Taro.navigateTo({
-            url:'/pages/RecordsHistory?type=activity'
+    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}
+        btnText={allowRun ? isCheking ? '打卡中...' : '打卡' : '开启'}
+        isDisabled={isCheking}
         themeColor='#EEC01F'
         onClickDetail={goDetail}
         onClick={checkout}
-    />
+    />*/
 
     return <View className="metric_bg">
         <Text className="metric_title">行走</Text>

+ 53 - 4
src/features/trackSomething/components/MetricHistory.tsx

@@ -2,14 +2,63 @@ import { View, Text } from "@tarojs/components";
 import './MetricHistory.scss'
 
 export default function Component(props: { records: any[] }) {
-    return <View style={{display:'flex',flexDirection:'column'}}>
+    function formateDate(date: string) {
+        //yyyyMMdd转换成日期,如果是今天,返回今天,如果是昨天,返回昨天,如果是昨天之前,返回日期
+        const dt = new Date(date.substring(0, 4) + '/' +
+            date.substring(4, 6) + '/' +
+            date.substring(6));
+
+        const now = new Date();
+
+        const diff = now.getTime() - dt.getTime();
+        const day = 1000 * 60 * 60 * 24;
+
+        if (diff < day) {
+            return '今天';
+        } else if (diff < 2 * day) {
+            return '昨天';
+        } else {
+            return date.substring(0, 4) + '-' +
+                date.substring(4, 6) + '-' +
+                date.substring(6)//dt.toISOString().slice(0, 10);
+        }
+    }
+
+    function formateHourMinutes(timestamp: number) {
+        var date = new Date(timestamp)
+        var hour = date.getHours()
+        var minutes = date.getMinutes()
+        return `${hour < 10 ? '0' + hour : hour}:${minutes < 10 ? '0' + minutes : minutes}`
+    }
+
+    return <View style={{ display: 'flex', flexDirection: 'column' }}>
         <View className="operate_view">
             <Text>时间倒序</Text>
-            <View style={{ marginLeft: 5, marginRight: 5, display: 'flex',width:30,backgroundColor:'red',height:'100%' }}>
-                {/* <Text > | </Text> */}
+            <View style={{ marginLeft: 5, marginRight: 5, display: 'flex', height: '100%' }}>
+                <Text > | </Text>
             </View>
-            <Text>时间正序1</Text>
+            <Text>时间正序</Text>
         </View>
+        {
+            (props.records as any).map(item => {
+                return <View style={{ display: 'flex', flexDirection: 'column' }}>
+                    <Text className="operate_day">{formateDate(item.date + '')}</Text>
+                    {
+                        item.records.map(record => {
+                            return <View className="operate_item">
+                                <View className="status_bg">
+                                    {/* <Text className="status_text">{record.type == 'total' ? '总计' : record.type == 'sync' ? '同步' : '打卡'}</Text> */}
+                                </View>
+                                <Text className="value">{record.items[0].value}</Text>
+                                <Text className="unit"></Text>
+                                <View style={{ flex: 1 }} />
+                                <Text className="time">{formateHourMinutes(record.timestamp)}</Text>
+                            </View>
+                        })
+                    }
+                </View>
+            })
+        }
 
     </View>
 }

+ 4 - 0
src/features/trackSomething/components/MetricItem.scss

@@ -8,6 +8,8 @@
     padding-top: 24px;
     padding-bottom: 24px;
     background-color: #1c1c1c;
+    box-sizing: border-box;
+    margin-bottom: 30px;
 }
 
 .metric_title {
@@ -19,6 +21,8 @@
 
 .metric_value_bg{
     height: 50px;
+    margin-top: 10px;
+    margin-bottom: 10px;
 }
 .metric_value {
     font-size: 48px;

+ 9 - 0
src/pages/Metric.tsx

@@ -3,6 +3,7 @@ import { useState } from "react";
 import Modal from "@/components/Modal";
 import PickerViews from "@/components/PickerViews";
 import LimitPickers from "@/components/LimitPickers";
+import Metric from "@/features/trackSomething/components/Metric";
 
 export default function Page() {
     const [isModalOpen, setIsModalOpen] = useState(false);
@@ -106,6 +107,14 @@ export default function Page() {
     function showTimePicker() {
         setIsTimePickerOpen(true)
     }
+
+
+    return <View className="container">
+        <Text>Metric Page</Text>
+            <Metric />
+            <View style={{height:100,flexShrink:0,display:'flex'}}/>
+        </View>
+
     const limit = new Date().getTime() - 7 * 3600 * 1000 * 24;
     return (
         <View className="container">

+ 16 - 1
src/pages/RecordsHistory.tsx

@@ -5,7 +5,7 @@ import { useEffect, useState } from "react";
 import Schedule from '@/features/trackTimeDuration/components/Schedule'
 import MetricHistory from "@/features/trackSomething/components/MetricHistory";
 import ActivityHistory from "@/features/trackSomething/components/ActivityHistory";
-import { activityRecords } from "@/services/trackSomething";
+import { activityRecords, metricRecords } from "@/services/trackSomething";
 
 export default function Page() {
     const router = useRouter();
@@ -92,6 +92,21 @@ export default function Page() {
                 }
             })
         }
+        else if (router.params.type ==  'metric'){
+            metricRecords(
+                {
+                    page: page,
+                    limit: pageSize,
+                    code:router.params.code
+                }
+            ).then(res => {
+                if (pageIndex == 1) {
+                    setRecords((res as any).data)
+                } else {
+                    setRecords(records.concat((res as any).data))
+                }
+            })
+        }
 
     }
 

+ 58 - 16
src/pages/clock.tsx

@@ -9,7 +9,7 @@ import Rings from '@components/Rings';
 import { useDispatch, useSelector } from 'react-redux';
 import { getInfoSuccess, logoutSuccess } from '@/store/user';
 import { wxPubFollow } from '@/services/permission';
-import { gobalConfigs, staticResources } from '@/services/common';
+import { gobalConfigs, staticResources, uploadSessionKey } from '@/services/common';
 import { use } from 'i18next';
 import Clocks from '@/features/trackTimeDuration/components/Clock';
 import Console from '@/features/trackTimeDuration/components/Console';
@@ -22,6 +22,7 @@ import { setScenario } from '@/store/scenario';
 import { setSpecifiedStatus, setSpecifiedState, machine } from '@/store/trackTimeMachine';
 import trackTimeService from '@/store/trackTimeMachine';
 import { setWXPubFollow } from '@/store/permission';
+import Tooltip from '@/components/Tooltip'
 // import TabBar from '../../components/Tabbar';
 
 export default function IndexPage() {
@@ -34,6 +35,7 @@ export default function IndexPage() {
   const common = useSelector((state: any) => state.common);
   const [counter, setCounter] = useState(0)
   const [timerId, setTimerId] = useState(null)
+  const [needShowAddTip, setNeedShowAddTip] = useState(false)
   // const moreRef = useRef<any>(null);
   // global.moreRef = Taro.createRef()
   array.push('ffff');
@@ -56,25 +58,62 @@ export default function IndexPage() {
         getCheckData()
       }
     })
-    checkSession()
+
 
   }, [])
 
+  useEffect(() => {
+    if (user.isLogin) {
+      //检查用户是否添加过小程序
+      checkAddToMini();
+      //检查session是否过期
+      checkSession()
+    }
+  }, [user.isLogin])
+
   function checkSession() {
-    Taro.checkSession({
-      success: function () {
-        //session_key 未过期,并且在本生命周期一直有效
-        console.log('session_key 未过期,并且在本生命周期一直有效')
-      },
-      fail: function () {
-        // session_key 已经失效,需要重新执行登录流程
-        console.log('session_key 已经失效,需要重新执行登录流程')
-        //更新session key,发送给服务器
-        // dispatch(logoutSuccess());
-        // wx.login() //重新登录
-      }
+    if (process.env.TARO_ENV === 'weapp') {
+      Taro.checkSession({
+        success: function () {
+          //session_key 未过期,并且在本生命周期一直有效
+          console.log('session_key 未过期,并且在本生命周期一直有效')
+        },
+        fail: function () {
+          // session_key 已经失效,需要重新执行登录流程
+          console.log('session_key 已经失效,需要重新执行登录流程')
+          //更新session key,发送给服务器
+          // dispatch(logoutSuccess());
+          // wx.login() //重新登录
+          Taro.login({
 
-    })
+          })
+
+
+          Taro.login().then(res => {
+            // code = res.code;
+            uploadSessionKey({ type: 'WX_MP', code: res.code });
+
+          })
+
+        }
+
+      })
+    }
+  }
+
+  function checkAddToMini() {
+    process.env.TARO_ENV == 'weapp' &&
+      wx.checkIsAddedToMyMiniProgram({
+        success: (res) => {
+          console.log(res.added);
+          if (!res.added) {
+            setNeedShowAddTip(true)
+          }
+        },
+        fail: (e) => {
+          console.log(e)
+        }
+      });
   }
 
   useEffect(() => {
@@ -121,7 +160,6 @@ export default function IndexPage() {
     Taro.removeStorage({
       key: 'tempScenario',
       success: function (res) {
-        console.log(res)
       }
     })
   }
@@ -260,6 +298,10 @@ export default function IndexPage() {
 
   return (
     <View style={{ flex: 1, flexDirection: 'column', display: 'flex', backgroundColor: '#000', color: '#fff' }}>
+      {
+        needShowAddTip && <Tooltip title="添加到我的小程序" closeTip={() => { setNeedShowAddTip(false) }} />
+      }
+
       <TitleBar />
       <Clocks />
       <View className='console_box'>

+ 10 - 1
src/services/common.tsx

@@ -1,5 +1,5 @@
 import { setResources,setConfigs } from "@/store/common";
-import { API_GLOBAL_CONFIGS, API_STATIC_RESOURCES } from "./http/api";
+import { API_GLOBAL_CONFIGS, API_STATIC_RESOURCES, API_UPLOAD_SESSION } from "./http/api";
 import { request } from "./http/request";
 
 
@@ -22,4 +22,13 @@ export const gobalConfigs = () =>(dispatch:any) =>{
         // resolve(res);
         dispatch(setConfigs(res));
     })
+}
+
+export const uploadSessionKey = (params) => {
+    request({
+        url: API_UPLOAD_SESSION, method: 'POST', data: {
+            ...params
+        }
+    }).then(res => {
+    })
 }

+ 4 - 1
src/services/http/api.js

@@ -19,6 +19,7 @@ export const API_CLEAR_FAST = `${baseUrl}/api/clear/fasting`
 export const API_CLEAR_SLEEP = `${baseUrl}/api/sleep/clear-my-data`
 export const API_CLEAR_MIX = `${baseUrl}/api/clear-data/FAST_SLEEP`
 export const API_CHECK_UNIQUE = `${baseUrl}/api/user/check-unique`
+export const API_UPLOAD_SESSION = `${baseUrl}/api/thirdparty/wx/session`
 
 //track time duration
 export const API_FAST_PLANS = `${baseUrl}/api/fast/plans`
@@ -31,9 +32,11 @@ export const API_FAST_CALENDARS = `${baseUrl}/api/fast/calendars/`
 
 //track something
 export const API_CLOCK_RECORDS = `${baseUrl}/api/clock/records`
-export const API_UPLOAD_STEPS = `${baseUrl}/api/thirdparty/wx/we-run-data`
+export const API_UPLOAD_STEPS = `${baseUrl}/api/thirdparty/wx/steps`
 export const API_ACTIVITY_CARDS = `${baseUrl}/api/activity/cards`
 export const API_ACTIVITY_RECORDS = `${baseUrl}/api/activity/records`
+export const API_METRIC_CARDS = `${baseUrl}/api/metric/cards`
+export const API_METRIC_RECORDS = `${baseUrl}/api/metric/records`
 
 //journal
 

+ 36 - 1
src/services/trackSomething.tsx

@@ -1,4 +1,4 @@
-import { API_ACTIVITY_CARDS, API_ACTIVITY_RECORDS, API_UPLOAD_STEPS } from './http/api';
+import { API_ACTIVITY_CARDS, API_ACTIVITY_RECORDS, API_METRIC_CARDS, API_METRIC_RECORDS, API_UPLOAD_STEPS } from './http/api';
 import { request } from './http/request';
 
 export const uploadSteps = (params) => {
@@ -35,3 +35,38 @@ export const activityRecords = (params) => {
         })
     })
 }
+
+export const uploadMetric = (params) => {
+    return new Promise((resolve,reject) => {
+        request({
+            url: API_METRIC_RECORDS, method: 'POST', data: { ...params }
+        }).then(res => {
+            resolve(res);
+            // dispatch(loginSuccess(res));
+        }).catch(err => {
+            reject(err)
+        })
+    })
+}
+
+export const metricCards = () => {
+    return new Promise((resolve) => {
+        request({
+            url: API_METRIC_CARDS, method: 'GET', data: {}
+        }).then(res => {
+            resolve(res);
+            // dispatch(loginSuccess(res));
+        })
+    })
+}
+
+export const metricRecords = (params) => {
+    return new Promise((resolve) => {
+        request({
+            url: API_METRIC_RECORDS, method: 'GET', data: { ...params }
+        }).then(res => {
+            resolve(res);
+            // dispatch(loginSuccess(res));
+        })
+    })
+}

+ 0 - 4
src/store/action_results.tsx

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

+ 6 - 0
types/global.d.ts

@@ -11,6 +11,12 @@ declare module '*.scss';
 declare module '*.sass';
 declare module '*.styl';
 
+interface WechatApi{
+  checkIsAddedToMyMiniProgram:(options:any) => void;
+}
+
+declare const wx:WechatApi;
+
 declare namespace NodeJS {
   interface ProcessEnv {
     TARO_ENV: 'weapp' | 'swan' | 'alipay' | 'h5' | 'rn' | 'tt' | 'quickapp' | 'qq' | 'jd'