index.vue 19 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 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586
<template>
  <view class="relative w-full min-h-screen overflow-y-auto overflow-x-hidden bg-[#F9FAFB] pb-[200rpx]">
    <!-- Header Section -->
    <view class="absolute left-0 top-0 w-full h-[544rpx] z-0">
      <image class="w-full h-full" src="https://picsum.photos/seed/header/750/544" mode="aspectFill" />
      <view class="absolute inset-0 bg-gradient-to-b from-blue-600/80 to-transparent"></view>
    </view>

    <view class="relative z-10 px-[32rpx] pt-[180rpx]">
      <text class="block text-white text-[44rpx] font-bold mb-[40rpx] text-center">臻奇荟</text>

      <!-- Search Bar -->
      <view
        class="flex items-center w-full h-[88rpx] bg-white/20 backdrop-blur-md rounded-full px-[32rpx] border border-white/30"
        @tap="go('/pages/search/index')"
      >
        <IconFont name="search" class="text-white/80 mr-[16rpx]" size="18" />
        <text class="text-white/80 text-[28rpx]">搜索培训资料、案例...</text>
      </view>
    </view>

    <!-- Main Content -->
    <view class="relative z-10 mt-[40rpx] px-[24rpx]">
      <!-- Grid Icons -->
      <view class="bg-white rounded-[32rpx] shadow-sm p-[40rpx] mb-[24rpx]">
        <view class="flex flex-wrap">
          <view
            class="flex flex-col items-center w-1/3 mb-[40rpx]"
            v-for="(item, index) in loopNav"
            :key="index"
            @tap="handleGridNav(item)"
          >
            <view class="w-[88rpx] h-[88rpx] rounded-[24rpx] bg-blue-50 flex items-center justify-center mb-[16rpx]">
              <IconFont :name="item.icon" class="text-blue-600" size="24" />
            </view>
            <text class="text-gray-800 text-[26rpx]">{{ item.name }}</text>
          </view>
        </view>
      </view>

      <!-- Hot Products -->
      <view class="bg-white rounded-[32rpx] shadow-sm p-[32rpx] mb-[24rpx]">
        <view class="flex justify-between items-center mb-[24rpx]">
          <text class="text-gray-900 text-[32rpx] font-bold">热卖产品</text>
          <view class="flex items-center text-blue-600" @tap="go('/pages/product-center/index')">
            <text class="text-[26rpx] mr-[4rpx]">查看更多</text>
            <IconFont name="rectRight" size="12" />
          </view>
        </view>

        <!-- 动态产品列表 -->
        <view
          v-for="(product, index) in hotProducts"
          :key="product.id"
          class="bg-gray-50 rounded-[24rpx] p-[28rpx]"
          :class="{ 'mb-[24rpx]': index < hotProducts.length - 1 }"
        >
          <text class="block text-gray-800 text-[28rpx] font-medium mb-[20rpx]">{{ product.product_name }}</text>

          <!-- 动态标签 -->
          <view v-if="product.tags && product.tags.length" class="flex flex-wrap gap-[12rpx] mb-[24rpx]">
            <view
              v-for="tag in product.tags"
              :key="tag.id"
              class="rounded-[8rpx] px-[16rpx] py-[6rpx]"
              :style="{
                backgroundColor: tag.bg_color,
                color: tag.text_color
              }"
            >
              <text class="text-[22rpx]">{{ tag.name }}</text>
            </view>
          </view>

          <view class="flex justify-between gap-[24rpx]">
            <nut-button
              plain
              color="#2563EB"
              class="flex-1 !h-[64rpx] !rounded-[16rpx] !text-[26rpx] !m-0 !border-blue-600"
              @tap="goToProductDetail(product.id)"
            >
              产品详情
            </nut-button>
            <nut-button
              color="#2563EB"
              class="flex-1 !h-[64rpx] !rounded-[16rpx] !text-[26rpx] !m-0"
              @tap="openPlanPopup(product.id)"
            >
              计划书
            </nut-button>
          </view>
        </view>
      </view>

      <!-- Hot Materials -->
      <view v-if="hotMaterials.length > 0" class="bg-white rounded-[32rpx] shadow-md p-[32rpx] mb-[48rpx]">
        <view class="flex justify-between items-center mb-[24rpx]">
          <text class="text-gray-900 text-[32rpx] font-bold">本周热门资料</text>
          <view class="flex items-center text-blue-600" @tap="go('/pages/week-hot-material/index')">
            <text class="text-[26rpx] mr-[4rpx]">查看更多</text>
            <IconFont name="rectRight" size="12" />
          </view>
        </view>

        <!-- Material List -->
        <view class="flex flex-col gap-[24rpx]">
          <!-- Material Items -->
          <view v-for="(item, index) in hotMaterials" :key="item.id || index"
            class="flex flex-row bg-white rounded-[24rpx] p-[24rpx] shadow-md border border-gray-50">

            <!-- 左侧图标 -->
            <view class="w-[88rpx] h-[88rpx] mr-[24rpx] flex-shrink-0 flex items-center justify-center bg-gradient-to-br from-blue-50 to-blue-100 rounded-[20rpx] shadow-inner self-start">
              <image :src="getDocumentIcon(item.fileName)" class="w-[48rpx] h-[48rpx]" mode="aspectFit" />
            </view>

            <!-- 内容区域 -->
            <view class="flex-1 min-w-0">
              <view class="text-[#1F2937] text-[30rpx] font-bold leading-[1.4] mb-[8rpx] line-clamp-2">
                {{ item.title }}
              </view>
              <!-- 学习人数信息 -->
              <view v-if="item.learners" class="flex items-center gap-[12rpx] mb-[16rpx]">
                <view class="inline-flex items-center justify-center px-[12rpx] py-[4rpx] bg-orange-50 text-orange-600 text-[20rpx] font-medium rounded-[8rpx]">
                  <text>{{ item.learners }}</text>
                </view>
                <!-- 学习人数比例 -->
                <view v-if="item.readPeoplePercent !== undefined && item.readPeoplePercent !== null" class="inline-flex items-center justify-center px-[12rpx] py-[4rpx] bg-green-50 text-green-600 text-[20rpx] font-medium rounded-[8rpx]">
                  <text>{{ item.readPeoplePercent }}%热度</text>
                </view>
              </view>
              <!-- 文档类型和文件大小 -->
              <view class="flex items-center gap-[12rpx] mb-[16rpx]">
                <view class="inline-flex items-center justify-center px-[12rpx] py-[4rpx] bg-gray-100 text-gray-500 text-[20rpx] font-medium rounded-[8rpx]">
                  <text>{{ getDocumentLabel(item.fileName) }}</text>
                </view>
                <view v-if="item.fileSize" class="text-[#9CA3AF] text-[22rpx]">
                  {{ item.fileSize }}
                </view>
              </view>

              <!-- 分割线 -->
              <view class="h-[1rpx] bg-gray-100 my-[20rpx]"></view>

              <!-- 操作按钮 -->
              <ListItemActions
                :viewable="true"
                :collectable="true"
                :deletable="false"
                :collected="item.collected"
                @view="onViewMaterial(item)"
                @collect="toggleMaterialCollect(item)"
              />
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- Bottom Tab Bar -->
    <TabBar current="home" />

    <!-- Plan Form Container -->
    <!-- 测试数据:后端接口和字段还没有准备好,使用 PlanFormContainer 进行的前端测试 -->
    <!-- 仅当 selectedProduct 不为 null 时才渲染组件,避免 product prop required 警告 -->
    <PlanFormContainer
      v-if="selectedProduct"
      v-model:visible="showPlanPopup"
      :product="selectedProduct"
      @close="showPlanPopup = false"
      @submit="handlePlanSubmit"
    />
  </view>
</template>

<script setup>
import { ref, shallowRef } from 'vue';
import Taro, { useShareAppMessage, useLoad, useDidShow } from '@tarojs/taro';
import { useGo } from '@/hooks/useGo';
import { useListItemClick, ListType } from '@/composables/useListItemClick';
import { getDocumentIcon, getDocumentLabel } from '@/utils/documentIcons';
import { useUserStore } from '@/stores/user';
import TabBar from '@/components/TabBar.vue';
import IconFont from '@/components/IconFont.vue';
import PlanFormContainer from '@/components/PlanFormContainer.vue';
import ListItemActions from '@/components/ListItemActions/index.vue';
import { listAPI } from '@/api/get_product';
import { weekHotAPI } from '@/api/file';
import { useCollectOperation } from '@/composables/useCollectOperation';
import { homeIconAPI } from '@/api/home';

// User Store
const userStore = useUserStore();

// Plan Popup State
const showPlanPopup = ref(false);
const selectedProduct = ref(null);

/**
 * 打开计划书弹窗
 * @description 根据产品ID找到对应的产品对象,并打开计划书表单
 * @param {number} productId - 产品ID
 */
const openPlanPopup = (productId) => {
  // 从热卖产品列表中找到对应的产品
  const product = hotProducts.value.find(p => p.id === productId);

  if (!product) {
    Taro.showToast({
      title: '产品不存在',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  // 设置选中的产品
  selectedProduct.value = product;
  showPlanPopup.value = true;
};

/**
 * 处理计划书提交
 * @description 测试环境:前端不调用后端API,直接跳转到结果页
 *              生产环境:需要调用 submitPlanAPI 提交表单数据
 * @param {Object} formData - 表单数据
 */
const handlePlanSubmit = (formData) => {
  console.log('计划书提交:', {
    product_id: selectedProduct.value.id,
    product_name: selectedProduct.value.product_name,
    form_sn: selectedProduct.value.form_sn,
    form_data: formData
  });

  // 关闭弹窗
  showPlanPopup.value = false;

  // TODO: 后端接口还没有准备好,暂时不调用API
  // 测试完成后需要对接 submitPlanAPI
  // const res = await submitPlanAPI({
  //   product_id: selectedProduct.value.id,
  //   template: selectedProduct.value.form_sn,
  //   form_data: formData
  // });

  // 模拟提交成功,跳转到结果页面
  go('/pages/plan-submit-result/index', {
    success: 'true'
  });
};

/**
 * 首页网格导航数据
 *
 * @description 从 API 动态获取,包含图标、名称、路由等信息
 */
const loopNav = shallowRef([]);

/**
 * 获取首页图标列表
 *
 * @description 从 API 获取首页网格导航数据,并解析 link 字段
 */
const fetchHomeIcons = async () => {
  try {
    const res = await homeIconAPI();

    if (res.code === 1 && res.data) {
      // 将 API 数据映射为 loopNav 格式
      loopNav.value = res.data.map(item => {
        // 解析 link 字段,格式: "/pages/category-list/index?cid=3129684"
        const [route, queryStr] = item.link.split('?');
        const params = {};

        // 如果有查询参数,解析为对象
        if (queryStr) {
          queryStr.split('&').forEach(param => {
            const [key, value] = param.split('=');
            params[key] = decodeURIComponent(value);
          });
        }

        // 返回导航项对象
        return {
          id: String(item.id),
          icon: item.icon,
          name: item.name,
          route,
          ...params  // 展开参数(如 cid)
        };
      });
    }
  } catch (err) {
    console.error('获取首页图标失败:', err);
    // 如果 API 调用失败,使用默认配置
    loopNav.value = [
      { id: 'plan', icon: 'order', name: '计划书', route: '/pages/plan/index' },
      { id: 'product-center', icon: 'category', name: '产品中心', route: '/pages/product-center/index' }
    ];
  }
};

/**
 * 热卖产品数据
 *
 * @description 从服务器获取的热卖产品列表
 */
const hotProducts = ref([]);

/**
 * 获取热卖产品列表
 *
 * @description ⚠️ 测试数据:后端接口和字段还没有准备好,暂时使用模拟数据进行测试
 *              测试完成后需要移除,恢复使用真实的API调用
 *              Mock数据包含全部7种产品类型(2种人寿、3种重疾、4种储蓄)
 */
const fetchHotProducts = async () => {
  try {
    // TODO: 测试完成后,移除下面的 mock 数据,恢复使用真实 API
    // const res = await listAPI({
    //   recommend: 'hot'
    // });
    // if (res.code === 1 && res.data && res.data.list) {
    //   hotProducts.value = res.data.list;
    // }

    // ⚠️ 测试数据开始 - 测试完成后需要移除 ⚠️
    hotProducts.value = [
      // 人寿保险产品(2种)
      {
        id: 1,
        product_name: 'WIOP3E 盈传创富保障计划 3 - 优选版',
        form_sn: 'life-insurance-wiop3e',
        recommend: 'hot',
        tags: [
          { id: 1, name: '终身寿险', bg_color: '#DBEAFE', text_color: '#1E40AF' },
          { id: 2, name: '美元', bg_color: '#FEF3C7', text_color: '#92400E' }
        ]
      },
      {
        id: 2,
        product_name: 'WIOP3 - 盈传创富保障计划 3',
        form_sn: 'life-insurance-wiop3',
        recommend: 'hot',
        tags: [
          { id: 1, name: '终身寿险', bg_color: '#DBEAFE', text_color: '#1E40AF' },
          { id: 2, name: '美元', bg_color: '#FEF3C7', text_color: '#92400E' }
        ]
      },
      // 重疾保险产品(3种)
      {
        id: 3,
        product_name: 'MPC 守护无间重疾',
        form_sn: 'critical-illness-mpc',
        recommend: 'hot',
        tags: [
          { id: 1, name: '重疾保障', bg_color: '#FCE7F3', text_color: '#9F1239' },
          { id: 2, name: '人民币', bg_color: '#D1FAE5', text_color: '#065F46' }
        ]
      },
      {
        id: 4,
        product_name: 'MBC PRO 活跃人生重疾保 PRO',
        form_sn: 'critical-illness-mbc-pro',
        recommend: 'hot',
        tags: [
          { id: 1, name: '重疾保障', bg_color: '#FCE7F3', text_color: '#9F1239' },
          { id: 2, name: '人民币', bg_color: '#D1FAE5', text_color: '#065F46' }
        ]
      },
      {
        id: 5,
        product_name: 'MBC2 活跃人生重疾保 2',
        form_sn: 'critical-illness-mbc2',
        recommend: 'hot',
        tags: [
          { id: 1, name: '重疾保障', bg_color: '#FCE7F3', text_color: '#9F1239' },
          { id: 2, name: '人民币', bg_color: '#D1FAE5', text_color: '#065F46' }
        ]
      },
      // 储蓄型产品(4种)- GS, GC, FA, LV2
      {
        id: 6,
        product_name: 'GS - 宏摯傳承保障計劃',
        form_sn: 'savings-gs',
        recommend: 'hot',
        tags: [
          { id: 1, name: '储蓄分红', bg_color: '#E0E7FF', text_color: '#3730A3' },
          { id: 2, name: '美元', bg_color: '#FEF3C7', text_color: '#92400E' }
        ]
      },
      {
        id: 7,
        product_name: 'GC - 宏摯家傳承保險計劃',
        form_sn: 'savings-gc',
        recommend: 'hot',
        tags: [
          { id: 1, name: '储蓄分红', bg_color: '#E0E7FF', text_color: '#3730A3' },
          { id: 2, name: '美元', bg_color: '#FEF3C7', text_color: '#92400E' }
        ]
      },
      {
        id: 8,
        product_name: 'FA - 宏浚傳承保障計劃',
        form_sn: 'savings-fa',
        recommend: 'hot',
        tags: [
          { id: 1, name: '储蓄分红', bg_color: '#E0E7FF', text_color: '#3730A3' },
          { id: 2, name: '美元', bg_color: '#FEF3C7', text_color: '#92400E' }
        ]
      },
      {
        id: 9,
        product_name: 'LV2 - 赤霞珠終身壽險計劃2',
        form_sn: 'savings-lv2',
        recommend: 'hot',
        tags: [
          { id: 1, name: '储蓄型终身寿险', bg_color: '#E0E7FF', text_color: '#3730A3' },
          { id: 2, name: '美元', bg_color: '#FEF3C7', text_color: '#92400E' }
        ]
      }
    ];
    // ⚠️ 测试数据结束 - 测试完成后需要移除 ⚠️

    console.log('⚠️ 使用测试数据:热卖产品列表已 mock,包含全部7种产品类型');
  } catch (err) {
    console.error('获取热卖产品失败:', err);
  }
};

/**
 * 热门资料数据
 *
 * @description 本周热门资料列表数据,从 API 获取
 */
const hotMaterials = ref([]);

/**
 * 热门资料加载状态
 *
 * @description 用于控制加载状态和空状态显示
 */
const hotMaterialsLoading = ref(false);

/**
 * 获取本周热门资料
 *
 * @description 调用 weekHotAPI 获取热门资料列表
 */
const fetchHotMaterials = async () => {
  try {
    hotMaterialsLoading.value = true;
    const res = await weekHotAPI({
      page: 0,
      limit: 10
    });

    if (res.code === 1 && res.data && res.data.list) {
      // 转换 API 数据格式为组件所需格式
      hotMaterials.value = res.data.list.map(item => ({
        id: item.meta_id,
        title: item.name,
        fileName: item.name,
        downloadUrl: item.src,
        fileSize: item.size,
        learners: `${item.read_people_count}人学习`,
        readPeoplePercent: item.read_people_percent, // 学习人数比例
        collected: item.is_favorite
      }));
    } else {
      hotMaterials.value = [];
    }
  } catch (err) {
    console.error('获取本周热门资料失败:', err);
    hotMaterials.value = [];
  } finally {
    hotMaterialsLoading.value = false;
  }
};

// Navigation
const go = useGo();

/**
 * 使用文件列表点击处理器
 *
 * @description 配置为文件类型列表,点击时打开文件预览
 */
const { handleClick: onViewMaterial } = useListItemClick({
  listType: ListType.FILE,
  onAfterClick: (item) => {
    console.log('用户打开了资料:', item.title);
  }
});

// 使用收藏操作 composable
const { toggleCollect: toggleMaterialCollect } = useCollectOperation();

/**
 * 处理网格导航点击
 *
 * @description 根据导航项的路由和参数进行跳转
 * @param {Object} item - 导航项对象
 * @param {string} item.route - 目标路由
 * @param {string} item.name - 导航名称
 * @param {Object} [item.cid] - 可选的分类 ID 参数
 */
const handleGridNav = (item) => {
  if (!item.route) {
    Taro.showToast({
      title: '功能开发中',
      icon: 'none',
      duration: 2000
    });
    return;
  }

  // 提取除 route 以外的所有参数(如 cid)
  const params = { ...item };
  delete params.id;
  delete params.icon;
  delete params.name;
  delete params.route;

  // 如果有参数(如 cid),则带参数跳转
  if (Object.keys(params).length > 0) {
    go(item.route, {
      ...params,
      title: item.name  // 将导航名称作为页面标题
    });
  } else {
    // 无参数,直接跳转
    go(item.route);
  }
};

// 跳转到产品详情页
const goToProductDetail = (productId) => {
  go('/pages/product-detail/index', {
    id: productId
  });
};

// Open webview with URL
const openWebView = (url) => {
  go('/pages/webview/index', {
    url: encodeURIComponent(url)
  });
};

// 页面加载时获取首页图标、热卖产品和热门资料
useLoad(() => {
  fetchHomeIcons();
  fetchHotProducts();
  fetchHotMaterials();
});

// 页面显示时刷新用户信息(更新 TabBar 红点状态)
useDidShow(() => {
  // 只在已登录状态下刷新
  if (userStore.isLoggedIn) {
    userStore.fetchUserInfo().catch(err => {
      console.error('刷新用户信息失败:', err);
    });
  }
});

useShareAppMessage(() => {
  return {
    title: '臻奇智荟圈',
    path: '/pages/index/index'
  };
});
</script>

<style lang="less">
/* 多行文本省略 */
.line-clamp-2 {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  overflow: hidden;
  word-break: break-all;
}
</style>