<template>
  <view class="save-money-container">
    <!-- 顶部渐变背景 -->
    <view class="top-bg"></view>

    <!-- 搜索栏 -->
    <view class="search-bar-wrap">
      <u-search 
        placeholder="搜索商品" 
        v-model="keyword" 
        :showAction="false" 
        actionText="搜索"
        bgColor="rgba(255, 255, 255,1)"
        height="32"
        searchIcon="search"
        searchIconSize="20"
        searchIconColor="#999"
        placeholderColor="#999"
        :inputStyle="{ fontSize: '28rpx' }"
        @search="onSearch"
        @custom="onSearch"
        @clear="onClearSearch"
      ></u-search>
    </view>

    <!-- Banner -->
    <!-- <view class="banner-wrap">
      <image class="banner-image" src="https://via.placeholder.com/710x240/FF5A5F/FFFFFF?text=Banner" mode="aspectFill"></image>
    </view> -->

    <!-- 消息通知栏 -->
    <!-- <view class="notice-bar-wrap">
      <view class="notice-left">
        <image class="notice-icon" src="@/static/image/points/icon_msg.png" mode="aspectFit"></image>
        <text class="notice-text">双十一活动已经开始，折扣享不停~</text>
      </view>
      <view class="notice-right">
        <image class="notice-more-icon" src="@/static/image/points/icon_msg_more.png" mode="aspectFit"></image>
      </view>
    </view> -->

    <!-- 主分类 Tabs -->
    <scroll-view class="main-tabs-scroll" scroll-x :show-scrollbar="false" :scroll-into-view="'main-tab-' + currentTab">
      <view class="main-tabs-inner">
        <view 
          v-for="(item, index) in tabList" 
          :key="index"
          :id="'main-tab-' + index"
          class="main-tab-item"
          :class="{ active: currentTab === index }"
          @click="onTabChange(index)"
        >
          {{ item.name }}
        </view>
      </view>
    </scroll-view>

    <!-- 子分类 Tabs (水平滚动) -->
    <scroll-view class="sub-tabs-scroll" scroll-x :show-scrollbar="false" :scroll-into-view="'sub-tab-' + currentSubTab">
      <view class="sub-tabs-inner">
        <view 
          v-for="(item, index) in subTabList" 
          :key="index"
          :id="'sub-tab-' + index"
          class="sub-tab-item"
          :class="{ active: currentSubTab === index }"
          @click="onSubTabChange(index)"
        >
          {{ item.name }}
        </view>
      </view>
    </scroll-view>

    <!-- 商品列表 -->
    <view class="goods-list">
      <template v-if="goodsList.length > 0">
        <view class="goods-item" v-for="(item, index) in goodsList" :key="index" @click="todetail(item.id)">
          <image class="goods-img" :src="item.imageUrl" mode="aspectFill"></image>
          <view class="goods-info">
            <view class="hot-tag">
              <image class="hot-icon" src="@/static/image/points/icon_tag_hot.png" mode="aspectFit"></image>
              <text class="hot-text">近2小时售出{{ item.monthlySales || 0 }}单</text>
            </view>
            <view class="goods-title">{{ item.title }}</view>
            <view class="goods-bottom">
              <view class="price-wrap">
                <text class="price-symbol">￥</text>
                <text class="price-main">{{ item.couponPrice || 0 }}</text>
                <text class="price-old" v-if="item.price">￥{{ item.price }}</text>
              </view>
              <view class="subsidy-tag">
                <image class="subsidy-bg" src="@/static/image/points/btn_price.png" mode="scaleToFill"></image>
                <view class="subsidy-content">
                  <view class="subsidy-left">立享补贴</view>
                  <view class="subsidy-right">￥{{ item.commissionAmount || 0 }}</view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <!-- 加载更多 -->
        <u-loadmore :status="loadStatus" margin-top="20" margin-bottom="20" />
      </template>
      <!-- 空状态 -->
      <view class="empty-state" v-else-if="loadStatus === 'nomore' && goodsList.length === 0">
        <image class="empty-img" src="/pages_im/static/images/search_empty.png" mode="aspectFit"></image>
        <text class="empty-text">暂无更多</text>
      </view>
    </view>
  </view>
</template>

<script>
	import { getSaveCategory,getProductList } from "@/api/makeMoney.js"
export default {
  name: "saveMoney",
  data() {
    return {
      keyword: "",
      currentTab: 0,
      tabList: [],
      currentSubTab: 0,
      subTabList: [],
      goodsList: [],
      page: 1,
      pageSize: 10,
      loadStatus: 'loadmore' // loadmore, loading, nomore
    }
  },
  mounted() {
    // 兼容可能不通过 swiper 切换直接显示的情况
    this.$nextTick(() => {
      if (this.tabList.length === 0) {
        this.initShow();
      }
    });
  },
  methods: {
	  getSaveCategorys(){
		  getSaveCategory().then(res=>{
			  if(res.code==200){
				  const platforms = res.data.platformCategory.map(item => ({
					name: item.platformName,
					platform: item.platform,
          channel: ''
				  }));
				  this.tabList = [
					{ name: '精选好物', channel: 1, platform: '' },
					{ name: '我的关注', channel: 2, platform: '' },
					
					...platforms
				  ];
          
          if (res.data.productCategory) {
            const products = res.data.productCategory.map(item => ({
              name: item.appCategoryName,
              appCategoryId: item.appCategoryId
            }));
            this.subTabList = [
              { name: '全部', appCategoryId: '' },
              ...products
            ];
          }
          
          // 获取完数据后重新渲染 u-tabs 以保证滚动位置正确
          this.currentTab = 0;
          this.currentSubTab = 0;
          
          this.$nextTick(() => {
            // 在获取完分类数据并且视图更新后，初始化商品列表
            if (this.goodsList.length === 0) {
              this.getProductLists();
            }
          });
			  }else{
				  uni.showToast({
				  	icon: 'none',
				  	title: res.msg,
				  });
			  }
		  })
	  },
    onTabChange(index) {
      this.currentTab = index;
      this.resetList();
      this.getProductLists();
    },
    onSubTabChange(index) {
      this.currentSubTab = index;
      this.resetList();
      this.getProductLists();
    },
    onSearch(value) {
      this.keyword = value || this.keyword;
      this.resetList();
      this.getProductLists();
    },
    onClearSearch() {
      this.keyword = '';
      this.resetList();
      this.getProductLists();
    },
    resetList() {
      this.page = 1;
      this.goodsList = [];
      this.loadStatus = 'loadmore';
    },
	getProductLists(){
    if (this.loadStatus === 'loading' || this.loadStatus === 'nomore') return;
    
    this.loadStatus = 'loading';
    const currentTabObj = this.tabList[this.currentTab];
    const currentSubTabObj = this.subTabList[this.currentSubTab];
    
    // 防御性判断，防止报错
    if (!currentTabObj) {
      this.loadStatus = 'loadmore';
      return;
    }
    
		const data={
			appCategoryId: currentSubTabObj ? currentSubTabObj.appCategoryId : '',
      channel: currentTabObj.channel,
      platform: currentTabObj.platform,
      page: this.page,
      pageSize: this.pageSize,
      title: this.keyword
		}
    
		getProductList(data).then(res=>{
			if(res.code==200){
				const list = res.data.list || [];
        this.goodsList = this.page === 1 ? list : this.goodsList.concat(list);
        this.loadStatus = list.length < this.pageSize ? 'nomore' : 'loadmore';
			}else{
        this.loadStatus = 'loadmore';
				uni.showToast({
					icon: 'none',
					title: res.msg,
				});
			}
		}).catch(() => {
      this.loadStatus = 'loadmore';
    })
	},
  scrolltolower() {
    if (this.loadStatus === 'loadmore') {
      this.page++;
      this.getProductLists();
    }
  },
  initShow() {
    // 当该组件所在的 swiper item 被激活时，触发该方法
    if (this.tabList.length === 0) {
      this.getSaveCategorys();
    } else {
      if (this.goodsList.length === 0) {
        this.getProductLists();
      }
    }
  },
	  todetail(id){
		  uni.navigateTo({
		  	url:'/pages/points/shopDetail?id='+id
		  })
	  }
  }
};
</script>

<style lang="scss" scoped>
.save-money-container {
  min-height: 100vh;
  position: relative;
  padding-bottom: 40rpx;
}

.top-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 360rpx;
  z-index: 0;
}

.search-bar-wrap {
  position: relative;
  z-index: 1;
  padding: 20rpx 30rpx;
}

.banner-wrap {
  position: relative;
  z-index: 1;
  padding: 0 30rpx;
  margin-top: 10rpx;
}

.banner-image {
  width: 100%;
  height: 240rpx;
  border-radius: 20rpx;
  background-color: #fff;
}

.notice-bar-wrap {
  position: relative;
  z-index: 1;
  margin: 20rpx 30rpx;
  background-color: #FFEADF;
  border-radius: 16rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16rpx 20rpx;
}

.notice-left {
  display: flex;
  align-items: center;
}

.notice-icon {
  width: 44rpx;
  height: 44rpx;
}

.notice-text {
  font-size: 26rpx;
  color: #E75932;
  margin-left: 16rpx;
}

.notice-right {
  display: flex;
  align-items: center;
  border-left: 1px dashed rgba(231, 89, 50, 0.3);
  padding-left: 20rpx;
}

.notice-more-icon {
  width: 44rpx;
  height: 44rpx;
}

.main-tabs-scroll {
  position: relative;
  z-index: 1;
  width: 100%;
  white-space: nowrap;
  padding: 10rpx 0 20rpx 0;
  background-color: transparent;
}

.main-tabs-inner {
  display: inline-flex;
  padding: 0 30rpx;
}

.main-tab-item {
  display: inline-block;
  font-size: 30rpx;
  color: #666;
  font-weight: 500;
  padding: 0 20rpx;
  height: 80rpx;
  line-height: 80rpx;
}

.main-tab-item.active {
  color: #FF5A1F;
  font-size: 34rpx;
  font-weight: bold;
}

.sub-tabs-scroll {
  position: relative;
  z-index: 1;
  width: 100%;
  white-space: nowrap;
  padding: 0 0 20rpx 0;
}

.sub-tabs-inner {
  display: inline-flex;
  padding: 0 30rpx;
}

.sub-tab-item {
  display: inline-block;
  padding: 8rpx 24rpx;
  background-color: #fff;
  border-radius: 26rpx;
  font-size: 26rpx;
  color: #666;
  margin-right: 20rpx;
}

.sub-tab-item.active {
  color: #FF5A1F;
  border: 1px solid #FF5A1F;
  background-color: rgba(255, 90, 31, 0.05);
}

.goods-list {
  position: relative;
  z-index: 1;
  padding: 0 30rpx;
  min-height: 400rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}

.empty-img {
  width: 280rpx;
  height: 280rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.goods-item {
  display: flex;
  background-color: #fff;
  border-radius: 20rpx;
  padding: 20rpx;
  margin-bottom: 20rpx;
}

.goods-img {
  width: 220rpx;
  height: 220rpx;
  border-radius: 12rpx;
  background-color: #f5f5f5;
  flex-shrink: 0;
}

.goods-info {
  flex: 1;
  margin-left: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.hot-tag {
  display: inline-flex;
  align-items: center;
  background-color: #FFEFE5;
  border-radius: 8rpx;
  padding: 4rpx 10rpx;
  align-self: flex-start;
}

.hot-icon {
  width: 24rpx;
  height: 24rpx;
}

.hot-text {
  font-size: 22rpx;
  color: #FF5A1F;
  margin-left: 6rpx;
}

.goods-title {
  font-size: 28rpx;
  color: #333;
  line-height: 40rpx;
  font-weight: bold;
  margin-top: 10rpx;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.goods-bottom {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-top: 16rpx;
}

.price-wrap {
  display: flex;
  align-items: baseline;
}

.price-symbol {
  font-size: 24rpx;
  color: #FF3B30;
  font-weight: bold;
}

.price-main {
  font-size: 36rpx;
  color: #FF3B30;
  font-weight: bold;
}

.price-old {
  font-size: 22rpx;
  color: #999;
  text-decoration: line-through;
  margin-left: 10rpx;
}

.subsidy-tag {
  position: relative;
  display: flex;
  height: 48rpx;
  width: 200rpx;
}

.subsidy-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 0;
}

.subsidy-content {
  position: relative;
  z-index: 1;
  display: flex;
  width: 100%;
  height: 100%;
  align-items: center;
}

.subsidy-left {
  flex: 1;
  color: #FF5A1F;
  font-size: 20rpx;
  text-align: center;
  padding-left: 10rpx;
}

.subsidy-right {
  flex: 1;
  color: #fff;
  font-size: 22rpx;
  text-align: center;
  font-weight: bold;
}
</style>