index.vue 14.2 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
<template>
  <view class="min-h-screen flex flex-col bg-white pb-16" style="background-color: #F9FAFB;">
    <!-- Hero section with family name and background image -->
    <view class="relative h-48">
      <image :src="familyCover" alt="Family background" class="w-full h-full object-cover" />
      <view class="absolute inset-0 bg-black bg-opacity-30 flex flex-col justify-end p-5">
        <view class="absolute top-4 right-4 text-white flex items-center" @click="goToProfile">
          <Setting size="24" />
          <text class="ml-2">家庭设置</text>
        </view>
        <h1 class="text-white text-2xl font-bold">{{ familyName }}</h1>
        <p class="text-white opacity-90">{{ familySlogn }}</p>
      </view>
    </view>

    <!-- 微信步数授权组件 -->
    <WeRunAuth
      ref="weRunAuthRef"
      @auth-change="handleAuthChange"
      @steps-synced="handleStepsSynced"
    >
      <template #default>
        <!-- Today's steps section -->
        <!-- TODO: 今日获取的步数怎么同步到下面那个积分池里面去 -->
        <view class="px-5 py-6 bg-white rounded-xl shadow-md mx-4 mt-4">
          <view class="flex justify-between items-center mb-1">
            <span class="text-gray-500">今日</span>
          </view>
          <view class="flex justify-between items-center">
            <view class="flex items-baseline">
              <span class="text-4xl font-bold">
                {{ todaySteps }}
              </span>
              <span class="ml-1 text-gray-500">步</span>
            </view>
            <view class="flex gap-2">
              <!-- <view class="bg-green-500 text-white px-4 py-2 rounded-full text-xs" @click="handleRefreshSteps">
                更新步数
              </view> -->
              <view class="bg-blue-500 text-white px-4 py-2 rounded-full text-sm" @click="handleCollectAll">
                一键收取
              </view>
            </view>
          </view>
        </view>

        <!-- Points circles -->
        <view class="flex justify-between px-5 py-6 my-4 bg-white rounded-xl shadow-md mx-4">
          <template v-if="!showTotalPointsOnly">
            <PointsCollector
              ref="pointsCollectorRef"
              height="30vh"
              :total-points="finalTotalPoints"
              @collection-complete="handleCollectionComplete"
            />
          </template>
          <template v-else>
            <TotalPointsDisplay
              :total-points="finalTotalPoints"
              height="13vh"
            />
          </template>
        </view>

        <!-- Photo button -->
        <view class="px-5 mb-4">
          <view @tap="openCamera" class="w-full bg-blue-500 text-white py-3 rounded-lg flex flex-col items-center justify-center">
            <view class="flex items-center justify-center">
              <Photograph size="20" class="mr-2" />
              拍照留念,奖励积分
            </view>
          </view>
        </view>

        <!-- Family step ranking -->
        <view class="p-5 bg-white rounded-xl shadow-md mx-4">
          <view class="flex justify-between items-center mb-4">
            <h2 class="font-medium text-lg">今日家庭步数排行</h2>
            <span class="text-sm text-gray-500">
              总计 {{ getTotalSteps(totalFamilySteps).toLocaleString() }} 步
            </span>
          </view>
          <view class="grid grid-cols-4 gap-2">
            <view v-for="member in familyMembers" :key="member.id" class="flex flex-col items-center">
              <image :src="member.avatar" :alt="member.name" class="w-16 h-16 rounded-full mb-1" />
              <span class="text-sm text-gray-700">
                {{ member.steps.toLocaleString() }}步
              </span>
            </view>
          </view>
        </view>
      </template>
    </WeRunAuth>

    <!-- 活动排行榜 -->
    <view class="px-5 mb-4 mt-4">
      <view @tap="openFamilyRank" class="w-full bg-blue-500 text-white py-3 rounded-lg flex flex-col items-center justify-center">
        <view class="flex items-center justify-center">
          <Category size="16" class="mr-2" />
          昨日活动步数排行榜
        </view>
      </view>
    </view>

    <!-- Family album -->
    <view class="p-5 mt-4 mb-6 bg-white rounded-xl shadow-md mx-4">
      <view class="flex justify-between items-center mb-2">
        <h2 class="font-medium text-lg">家庭相册</h2>
        <view class="text-blue-500 flex items-center" @click="openAlbumList">
          打开相册
        </view>
      </view>
      <p class="text-sm text-gray-500 mb-3">记录每一个家庭活动瞬间</p>
      <view class="grid grid-cols-2 gap-3">
        <view
          v-for="(item, index) in albumData"
          :key="index"
          class="rounded-lg overflow-hidden h-32 relative cursor-pointer"
          @click="handleMediaClick(item, albumData)"
        >
          <image
            :src="item.type === 'video' ? item.thumbnail : item.url"
            alt="家庭活动照片"
            class="w-full h-full object-cover rounded-lg"
          />
          <!-- 视频标识 -->
          <view
            v-if="item.type === 'video'"
            class="absolute top-2 left-2 px-2 py-1 bg-black bg-opacity-70 rounded text-white text-xs"
          >
            视频
          </view>
        </view>
      </view>
    </view>

    <BottomNav />

    <!-- 图片预览 -->
    <nut-image-preview
      v-model:show="previewVisible"
      :images="previewImages"
      :init-no="previewIndex"
      @close="closePreview"
    />

    <!-- 视频播放器 -->
    <view
      v-if="videoVisible"
      class="fixed inset-0 bg-black"
      style="z-index: 9999;"
      @click="closeVideo"
    >
      <!-- 关闭按钮 -->
      <view
        @click.stop="closeVideo"
        class="absolute top-4 right-4 w-10 h-10 bg-black bg-opacity-50 rounded-full flex items-center justify-center"
        style="z-index: 10000;"
      >
        <Close size="24" class="text-white" />
      </view>

      <!-- 视频播放器 -->
      <video
        v-if="currentVideo"
        :id="'dashboard-video-' + videoId"
        :src="currentVideo.url"
        :poster="currentVideo.thumbnail"
        :controls="true"
        :autoplay="false"
        :show-center-play-btn="true"
        :show-play-btn="true"
        :object-fit="'contain'"
        :show-fullscreen-btn="true"
        style="width: 100vw; height: 100vh; position: absolute; top: 0; left: 0;"
        @click.stop
        @play="handleVideoPlay"
        @pause="handleVideoPause"
        @error="handleVideoError"
        @fullscreenchange="handleFullscreenChange"
      />
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import Taro, { useDidShow, useReady } from '@tarojs/taro';
import { Setting, Photograph, Close, Category } from '@nutui/icons-vue-taro';
import BottomNav from '../../components/BottomNav.vue';
import TotalPointsDisplay from '@/components/TotalPointsDisplay.vue';
import PointsCollector from '@/components/PointsCollector.vue'
import WeRunAuth from '@/components/WeRunAuth.vue'
import { useMediaPreview } from '@/composables/useMediaPreview';
// 默认家庭封面图
const defaultFamilyCover = 'https://cdn.ipadbiz.cn/lls_prog/images/default-family-cover.png';
// 默认头像
const defaultAvatar = 'https://cdn.ipadbiz.cn/mlaj/images/icon_1.jpeg'
// 接口信息
import { getMyFamiliesAPI, getFamilyDashboardAPI } from '@/api/family'

const todaySteps = ref(0);
const isWeRunAuthorized = ref(false);
const pointsCollectorRef = ref(null)
const weRunAuthRef = ref(null)
const showTotalPointsOnly = ref(false)
const finalTotalPoints = ref(0)

const familyName = ref('')
const familySlogn = ref('')
const familyCover = ref('')

// 使用媒体预览 composable
const {
  previewVisible,
  previewImages,
  previewIndex,
  videoVisible,
  currentVideo,
  videoId,
  handleMediaClick,
  closePreview,
  closeVideo,
  handleVideoPlay,
  handleVideoPause,
  handleFullscreenChange,
  handleVideoError
} = useMediaPreview();

// 家庭相册数据
const albumData = ref([
  {
    type: 'image',
    url: 'https://cdn.ipadbiz.cn/hager/0513-1_FsxMk28AGz6N_D1zZFFOl_EaRdss.png',
    createTime: '2024-01-15 10:30'
  },
  {
    type: 'video',
    url: 'https://vjs.zencdn.net/v/oceans.mp4',
    thumbnail: 'https://cdn.ipadbiz.cn/hager/0513-1_FsxMk28AGz6N_D1zZFFOl_EaRdss.png',
    duration: 125,
    createTime: '2024-01-14 16:20'
  }
]);

/**
 * 触发积分收集组件的一键收取
 */
const handleCollectAll = () => {
  if (pointsCollectorRef.value) {
    pointsCollectorRef.value.collectAll()
  }
}

/**
 * 处理积分收集完成事件
 * @param {number} points - 最终的积分
 */
const handleCollectionComplete = (points) => {
  finalTotalPoints.value = points;
  showTotalPointsOnly.value = true;
};

/**
 * 手动刷新微信步数
 */
const handleRefreshSteps = async () => {
  if (weRunAuthRef.value) {
    await weRunAuthRef.value.refreshSteps()
  }
}

/**
 * 处理微信步数授权状态变化
 * @param {boolean} authorized - 授权状态
 */
const handleAuthChange = (authorized) => {
  isWeRunAuthorized.value = authorized
  console.log('微信步数授权状态:', authorized)
}

/**
 * 处理微信步数同步完成事件
 * @param {Object} data - 同步返回的数据
 */
const handleStepsSynced = async (data) => {
  console.log('微信步数同步完成:', data)
  // 步数同步完成后,重新获取家庭数据
  await initPageData()
}

/**
 * 计算总步数(包含用户步数和家庭成员步数)
 * @param {number} userSteps - 用户步数
 * @returns {number} 总步数
 */
const getTotalSteps = (userSteps) => {
  return familyMembers.value.reduce((sum, member) => sum + member.steps, 0) + userSteps
}

// Mock data for family members
const familyMembers = ref([
  {
    id: 1,
    name: '妈妈',
    steps: 7000,
    avatar: 'https://randomuser.me/api/portraits/women/44.jpg'
  },
  {
    id: 2,
    name: '爸爸',
    steps: 6000,
    avatar: 'https://randomuser.me/api/portraits/men/32.jpg'
  },
  {
    id: 3,
    name: '儿子',
    steps: 5000,
    avatar: 'https://randomuser.me/api/portraits/men/22.jpg'
  },
  {
    id: 4,
    name: '女儿',
    steps: 4000,
    avatar: 'https://randomuser.me/api/portraits/women/29.jpg'
  },
  {
    id: 5,
    name: '孙子',
    steps: 3000,
    avatar: 'https://randomuser.me/api/portraits/men/25.jpg'
  },
  {
    id: 6,
    name: '孙女',
    steps: 20000,
    avatar: 'https://randomuser.me/api/portraits/women/27.jpg'
  },
]);

// 注意:totalSteps 计算逻辑已移至 getTotalSteps 方法中

const handleSyncSteps = () => {
  // In a real app, this would sync with a health API
  // For demo purposes, we'll just log and do nothing
  console.log('Syncing steps...');
};

const goToProfile = () => {
  Taro.navigateTo({ url: '/pages/EditFamily/index' });
};

const openAlbumList = () => {
  Taro.navigateTo({ url: '/pages/AlbumList/index' });
};

/**
 * 打开拍照上传页面
 */
const openCamera = () => {
  Taro.navigateTo({ url: '/pages/UploadMedia/index' });
}

/**
 * 打开活动排行榜
 */
const openFamilyRank = () => {
  Taro.navigateTo({ url: '/pages/FamilyRank/index' });
}

const family_id = ref('');
const totalFamilySteps = ref(0);

const initPageData = async () => {
  const { code, data } = await getFamilyDashboardAPI({ family_id: family_id.value });
  if (code) {
    // 获取用户信息
    console.warn(data);
    // 真实情况下 需要重新获取积分列表, 测试随机积分获取状态, 接口有积分列表就显示出来, 没有就不显示
    showTotalPointsOnly.value = !data.pending_points.length;
    // 总积分数量也要从接口获取传进去
    finalTotalPoints.value = 10086;
    // 获取用户信息
    familyName.value = data.family.name;
    familySlogn.value = data.family.note;
    familyCover.value = data.family.avatar_url || defaultFamilyCover;
    // 获取今日我的步数
    todaySteps.value = data.my_today_step;
    // 获取家庭总步数
    totalFamilySteps.value = data.family_today_step;
  }
}

useDidShow(async () => {
  // 获取用户是否加入家庭
  const { code, data } = await getMyFamiliesAPI()
  if (code) {
    // 如果没有加入家庭
    if (!data.length) {
      Taro.redirectTo({ url: '/pages/Welcome/index' });
      return; // 直接返回,不执行后续逻辑
    } else {
      family_id.value = data[0].id;
      // 先初始化基础页面数据(不包含步数相关数据)
      await initPageData();
      // 然后刷新微信步数数据(只有在已加入家庭时才获取)
      if (weRunAuthRef.value) {
        weRunAuthRef.value.checkAuthStatus(true);
      }
    }
  }


})

useReady(async () => {
  // 版本更新检查
  if (!Taro.canIUse("getUpdateManager")) {
    Taro.showModal({
      title: "提示",
      content: "当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试",
      showCancel: false,
    });
    return;
  }

  // https://developers.weixin.qq.com/miniprogram/dev/api/base/update/UpdateManager.html
  const updateManager = Taro.getUpdateManager();

  updateManager.onCheckForUpdate((res) => {
    // 请求完新版本信息的回调
    if (res.hasUpdate) {
      updateManager.onUpdateReady(function () {
        Taro.showModal({
          title: "更新提示",
          content: "新版本已经准备好,是否重启应用?",
          success: function (res) {
            if (res.confirm) {
              // 新的版本已经下载好,调用 applyUpdate 应用新版本并重启
              updateManager.applyUpdate();
            }
          },
        });
      });

      updateManager.onUpdateFailed(function () {
        // 新版本下载失败
        Taro.showModal({
          title: "更新提示",
          content: "新版本已上线,请删除当前小程序,重新搜索打开",
        });
      });
    }
  });
})
</script>

<style lang="less">
.loading-dots {
  display: inline-block;

  .dot {
    display: inline-block;
    animation: loading-bounce 1.4s ease-in-out infinite both;

    &:nth-child(1) {
      animation-delay: -0.32s;
    }

    &:nth-child(2) {
      animation-delay: -0.16s;
    }

    &:nth-child(3) {
      animation-delay: 0s;
    }
  }
}

@keyframes loading-bounce {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}
</style>