<template>
  <view class="home-page">
    <!-- 应用头部 -->
    <view class="header" :style="{ paddingTop: statusBarHeight + 'px' }">
      <image class="logo" src="/static/home/logo.png" mode="aspectFit"></image>
    </view>

    <!-- 招募宣传横幅 -->
    <swiper
      class="recruit-banner"
      :indicator-dots="bannerList.length > 1"
      :autoplay="bannerList.length > 1"
      :interval="3000"
      :duration="500"
      indicator-color="rgba(255, 255, 255, 0.5)"
      indicator-active-color="#ffffff"
    >
      <swiper-item
        v-for="(item, index) in bannerList"
        :key="index"
        @click="handleBannerClick(item)"
      >
        <image
          class="banner-image"
          :src="item.coverUrl"
          mode="aspectFit"
        ></image>
      </swiper-item>
    </swiper>

    <!-- 公会福利区 -->
    <view class="benefits-section">
      <view class="section-header">
        <view class="section-title">
          <image
            class="title-icon"
            src="/static/home/gift_icon.png"
            mode="aspectFit"
          ></image>
          <text class="title-text">公会福利</text>
        </view>
        <view class="section-more" @click="handleViewAllBenefits">
          查看全部 >
        </view>
      </view>
      <view class="benefits-list">
        <view
          class="benefit-item"
          v-for="(item, index) in benefitsList"
          :key="index"
          @click="handleBenefitClick(item)"
        >
          <image class="benefit-icon" :src="item.icon" mode="aspectFit"></image>
          <text class="benefit-label">{{ item.label }}</text>
        </view>
      </view>
    </view>

    <!-- 公会活动区 -->
    <view class="activities-section">
      <view class="section-header">
        <view class="section-title">
          <image
            class="title-icon"
            src="/static/home/activity_icon.png"
            mode="aspectFit"
          ></image>
          <text class="title-text">公会活动</text>
        </view>
        <view class="section-more" @click="handleViewAllActivities">
          查看全部 >
        </view>
      </view>
      <view class="activities-list">
        <view
          class="activity-item"
          v-for="(item, index) in activitiesList"
          :key="index"
          @click="handleActivityClick(item)"
        >
          <view class="activity-image-wrapper">
            <image
              class="activity-image"
              :src="item.coverUrl"
              mode="aspectFill"
            ></image>
          </view>
          <view class="activity-content">
            <view class="activity-title">{{ item.title }}</view>
            <view class="activity-desc">{{ item.summary }}</view>
            <view class="activity-time"
              >结束时间:{{ formatTime(item.endTime) }}</view
            >
            <view
              class="join-activity-btn"
              @click.stop="handleJoinActivity(item)"
            >
              <text>立即参与</text>
            </view>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { getHomeData } from "@/api/home.js";
import {
  getGuildBenefits,
  getGuildActivities,
  joinGuild,
  joinActivity,
} from "@/api/index.js";
import { formatTime } from "@/utils/date.js";

export default {
  data() {
    return {
      // 状态栏高度
      statusBarHeight: 0,
      // 导航栏高度（状态栏 + 导航栏内容）
      navBarHeight: 0,
      bannerList: [],
      // 公会福利列表
      benefitsList: [
        {
          id: 1,
          label: "美食",
          icon: "/static/home/food_menu.png",
          type: "food",
        },
        {
          id: 2,
          label: "保险",
          icon: "/static/home/car_insurance.png",
          type: "insurance",
        },
        {
          id: 3,
          label: "维修",
          icon: "/static/home/repair.png",
          type: "repair",
        },
        {
          id: 4,
          label: "健康",
          icon: "/static/home/health.png",
          type: "health",
        },
      ],
      // 公会活动列表
      activitiesList: [],
    };
  },
  onLoad() {
    this.getSystemInfo();
    this.loadHomeData();
    this.loadActivities();
  },
  onPullDownRefresh() {
    this.loadHomeData().finally(() => {
      uni.stopPullDownRefresh();
    });
  },
  methods: {
    // 获取系统信息
    getSystemInfo() {
      // 获取系统信息
      const systemInfo = uni.getSystemInfoSync();
      this.statusBarHeight = systemInfo.statusBarHeight || 0;

      // 导航栏高度 = 状态栏高度 + 导航栏内容高度（通常44px，但不同平台可能不同）
      // 这里可以根据实际需求调整导航栏内容高度
      const navBarContentHeight = 44; // 导航栏内容高度，可根据设计稿调整
      this.navBarHeight = this.statusBarHeight + navBarContentHeight;
    },
    // 加载首页数据
    async loadHomeData() {
      try {
        // 获取首页banner
        const res = await getHomeData({ noticeType: 1 });
        if (res) {
          this.bannerList = res.list || [];
        }
      } catch (error) {
        console.error("加载首页数据失败:", error);
        uni.showToast({
          title: "加载失败，请重试",
          icon: "none",
        });
      }
    },

    // 加载公会福利
    async loadBenefits() {
      try {
        // 后续补充接口调用
        // const res = await getGuildBenefits()
        // if (res.statusCode === 200) {
        // 	this.benefitsList = res.data || this.benefitsList
        // }
      } catch (error) {
        console.error("加载公会福利失败:", error);
      }
    },

    // 加载公会活动
    async loadActivities() {
      try {
        // 后续补充接口调用
        const res = await getHomeData({ page: 1, pageSize: 3, noticeType: 2 });
        if (res) {
          this.activitiesList = res.list || [];
        }
      } catch (error) {
        console.error("加载公会活动失败:", error);
      }
    },

    // 格式化时间戳
    formatTime,

    // 菜单点击
    handleMenuClick() {
      uni.showToast({
        title: "菜单功能",
        icon: "none",
      });
    },

    // 聚焦/关注点击
    handleFocusClick() {
      uni.showToast({
        title: "关注功能",
        icon: "none",
      });
    },

    // banner点击跳转
    handleBannerClick(item) {
      if (item.jumpUrl) {
        // 判断跳转类型
        if (
          item.jumpUrl.startsWith("http://") ||
          item.jumpUrl.startsWith("https://")
        ) {
          // 外部链接，使用web-view或浏览器打开
          // #ifdef H5
          window.open(item.jumpUrl);
          // #endif
          // #ifdef MP-WEIXIN
          uni.navigateTo({
            url: `/pages/webview/webview?url=${encodeURIComponent(
              item.jumpUrl
            )}`,
          });
          // #endif
          // #ifdef APP-PLUS
          plus.runtime.openURL(item.jumpUrl);
          // #endif
        } else {
          // 内部页面跳转
          uni.navigateTo({
            url: item.jumpUrl,
          });
        }
      }
    },

    // 加入工会
    async handleJoinGuild() {
      try {
        // 后续补充接口调用
        // const res = await joinGuild()
        // if (res.statusCode === 200) {
        // 	uni.showToast({
        // 		title: '加入成功',
        // 		icon: 'success'
        // 	})
        // }
        uni.showToast({
          title: "加入工会",
          icon: "none",
        });
      } catch (error) {
        console.error("加入工会失败:", error);
        uni.showToast({
          title: "操作失败，请重试",
          icon: "none",
        });
      }
    },

    // 查看全部福利
    handleViewAllBenefits() {
      // 清除分类信息，跳转到服务页面显示全部
      const app = getApp();
      if (app && app.globalData) {
        app.globalData.serviceCategory = null;
      }
      uni.switchTab({
        url: '/pages/service/service'
      });
    },

    // 福利项点击
    handleBenefitClick(item) {
      // 建立 type 到 value 的映射关系
      const typeToValueMap = {
        food: '0',      // 美食
        insurance: '4', // 保险
        repair: '1',    // 维修
        health: '5'     // 健康
      };
      
      // 获取对应的分类 value
      const categoryValue = typeToValueMap[item.type];

      console.log(categoryValue, 222); 
      
      // 将分类信息存储到 globalData，供 service 页面使用
      const app = getApp();
      if (app && app.globalData && categoryValue) {
        app.globalData.serviceCategory = categoryValue;
      }
      
      // 跳转到服务页面
      uni.switchTab({
        url: '/pages/service/service'
      });
    },

    // 查看全部活动
    handleViewAllActivities() {
      uni.navigateTo({
        url: '/pages/activities/list'
      });
    },

    // 活动项点击
    handleActivityClick(item) {
      // 后续可以跳转到活动详情页
      // uni.navigateTo({
      // 	url: `/pages/activities/detail?id=${item.id}`
      // })
    },

    // 参与活动
    async handleJoinActivity(item) {
      // 跳转到活动详情页
      uni.navigateTo({
        url: `/pages/detail/activitiesDetail?id=${item.id}`
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.home-page {
  min-height: 100vh;
  background-color: #e2e8f1;
  padding-bottom: 100rpx; // 为底部tabBar留出空间
}

/* 应用头部 */
.header {
  display: flex;
  align-items: center;
  padding-left: 34rpx;

  .logo {
    width: 306rpx;
    height: 72rpx;
  }
}

/* 招募宣传横幅 */
.recruit-banner {
  padding: 32rpx 20rpx 20rpx 20rpx;
  height: 398rpx;

  .banner-image {
    width: 100%;
    height: 100%;
  }
}

/* 通用区块样式 */
.section-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 27rpx;

  .section-title {
    display: flex;
    align-items: center;

    .title-icon {
      width: 51rpx;
      height: 51rpx;
      margin-right: 8rpx;
    }

    .title-text {
      font-family: AlibabaPuHuiTi, AlibabaPuHuiTi;
      font-weight: 500;
      font-size: 36rpx;
      color: #1a1819;
    }
  }

  .section-more {
    font-family: PingFang-SC, PingFang-SC;
    font-weight: 500;
    font-size: 22rpx;
    color: #333333;
  }
}

/* 公会福利区 */
.benefits-section {
  margin: 0 20rpx;
  padding: 30rpx 22rpx 27rpx 16rpx;
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 20rpx 20rpx;

  .benefits-list {
    display: flex;
    justify-content: space-around;
    padding: 0 30rpx;

    .benefit-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      cursor: pointer;

      .benefit-icon {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        margin-bottom: 16rpx;
        transition: transform 0.2s;
      }

      .benefit-item:active .benefit-icon {
        transform: scale(0.95);
      }

      .benefit-label {
        font-family: PingFang-SC, PingFang-SC;
        font-weight: 500;
        font-size: 26rpx;
        color: #333333;
      }
    }
  }
}

/* 公会活动区 */
.activities-section {
  margin: 20rpx;
  background-color: #ffffff;
  border-radius: 20rpx 20rpx 20rpx 20rpx;
  padding: 32rpx 20rpx 62rpx 20rpx;

  .activities-list {
    .activity-item {
      display: flex;
      margin-bottom: 30rpx;
      cursor: pointer;
      transition: transform 0.2s, box-shadow 0.2s;

      &:active {
        transform: scale(0.98);
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
      }

      &:last-child {
        margin-bottom: 0;
      }

      .activity-image-wrapper {
        width: 186rpx;
        height: 200rpx;
        flex-shrink: 0;
        border: 1rpx solid #e2e8f1;
        border-radius: 10rpx;

        .activity-image {
          width: 100%;
          height: 100%;
        }

        .activity-image-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          background: linear-gradient(
            to bottom,
            rgba(0, 0, 0, 0.1),
            rgba(0, 0, 0, 0.4)
          );
          padding: 20rpx;

          .overlay-text {
            font-size: 20rpx;
            color: #ffffff;
            font-weight: bold;
            letter-spacing: 2rpx;
            margin-bottom: 10rpx;
          }
        }
      }

      .activity-content {
        flex: 1;
        padding: 0 20rpx;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        position: relative;

        .activity-title {
          font-family: PingFang-SC, PingFang-SC;
          font-weight: bold;
          font-size: 30rpx;
          color: #1a1819;
          margin-bottom: 12rpx;
          overflow: hidden;
          text-overflow: ellipsis;
        }

        .activity-desc {
          font-family: PingFang-SC, PingFang-SC;
          font-weight: 500;
          font-size: 22rpx;
          color: #888888;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
        }

        .activity-time {
          width: 260rpx;
          height: 33rpx;
          padding: 0 10rpx;
          background: rgba(0, 66, 148, 0.1);
          color: #004294;
          font-size: 20rpx;
        }

        .join-activity-btn {
          position: absolute;
          right: 0;
          bottom: 0;
          background: #004294;
          border-radius: 25rpx;
          color: #ffffff;
          font-size: 24rpx;
          padding: 12rpx 24rpx;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
