<template>
  <scroll-view class="home-content" :style="{ height: scrollHeight + 'px' }" scroll-y enable-back-to-top
    @scrolltolower="handleLower">

    <view v-if="homeModules && homeModules.item && homeModules.item.length > 0">
      <view v-for="(item, index) in homeModules.item" :key="index">

        <view v-if="item.type === 'banner'" class="module-banner" :style="[item.style]">
          <swiper class="banner-swiper" :style="{ height: item.params.height || '300rpx' }" :indicator-dots="true"
            :circular="true" :autoplay="true" :interval="Number(item.params.interval || 3000)" duration="500">
            <swiper-item v-for="(img, idx) in item.data" :key="idx" @tap="onLinkTap(img.link)">
              <image :src="cdn(img.image)" mode="aspectFill" class="banner-img" />
            </swiper-item>
          </swiper>
        </view>

        <view v-if="item.type === 'menu'" class="module-menu" :style="[item.style]">
          <view class="menu-grid">
            <view class="menu-item" v-for="(m, idx) in item.data" :key="idx" @tap="onLinkTap(m.link)">
              <image :src="cdn(m.image)" mode="aspectFill" class="menu-img" />
              <text class="menu-text">{{ m.text }}</text>
            </view>
          </view>
        </view>

        <view v-if="item.type === 'notice'" class="module-notice" :style="[item.style]">
          <swiper class="notice-swiper" vertical autoplay circular interval="3000" :style="{ height: '60rpx' }">
            <swiper-item v-for="(n, idx) in item.data" :key="idx">
              <text class="notice-text">{{ n.text }}</text>
            </swiper-item>
          </swiper>
        </view>

        <view v-if="item.type === 'image'" class="module-image" :style="[item.style]">
          <image v-for="(img, idx) in item.data" :key="idx" :src="cdn(img.image)" mode="widthFix"
            class="module-full-img" @tap="onLinkTap(img.link)" />
        </view>

        <view v-if="item.type === 'likes'" class="module-likes" :style="[item.style]">
          <mall-product :dataList="likesDataList"
            :dataStyle="'col-' + (item.params.colthree || 2) + '-' + (item.params.colmargin || 20)" />
          <view class="load-more" v-if="likesDataList.length > 0">
            <text v-if="likesLoading">{{ $t('common.loading') }}</text>
            <text v-else-if="likesCurrentPage >= likesLastPage">{{ $t('common.noMore') }}</text>
          </view>
        </view>

        <view v-if="item.type === 'goods'" class="module-goods" :style="[item.style]">
          <mall-product :dataList="goodsDataList"
            :dataStyle="'col-' + (item.params.colthree || 2) + '-' + (item.params.colmargin || 20)" />
        </view>

      </view>
    </view>

    <view class="empty" v-if="(!homeModules || !homeModules.item || homeModules.item.length === 0) && !likesLoading">
      <text>{{ $t('common.empty') }}</text>
    </view>
  </scroll-view>
</template>

<script>
import { pullMallLikes, pullMallPageGoods } from '@/features/mall/mall-gateway'
import appSettings from '@/core/config/app-settings'

function cdn(path) {
  if (!path) return ''
  if (/^https?:\/\//.test(path)) return path
  if (path.startsWith('//')) return 'https:' + path
  var base = (appSettings.cdnurl || '').replace(/\/$/, '')
  return base + (path.startsWith('/') ? path : '/' + path)
}

export default {
  name: 'mall-home-content',
  props: {
    scrollHeight: { type: Number, default: 600 },
    isActive: { type: Boolean, default: false },
    dataStyle: { type: String, default: 'col-2-20' },
    homeModules: { type: Object, default: function () { return {} } }
  },
  data: function () {
    return {
      likesDataList: [],
      likesCurrentPage: 1,
      likesLastPage: 1,
      likesLoading: false,
      goodsDataList: []
    }
  },
  watch: {
    isActive: {
      handler: function (val) {
        if (val) { this.loadAllModules() }
      },
      immediate: true
    },
    homeModules: {
      handler: function () {
        if (this.isActive) { this.loadAllModules() }
      },
      deep: true
    }
  },
  methods: {
    cdn: cdn,
    loadAllModules: function () {
      var items = (this.homeModules && this.homeModules.item) || []
      for (var i = 0; i < items.length; i++) {
        if (items[i].type === 'likes' && this.likesDataList.length === 0) {
          this.loadLikes()
        }
        if (items[i].type === 'goods' && this.goodsDataList.length === 0) {
          this.loadGoods(items[i])
        }
      }
    },
    loadLikes: function () {
      var self = this
      self.likesLoading = true
      pullMallLikes({ page: self.likesCurrentPage }).then(function (res) {
        self.likesDataList = res.rows
        self.likesCurrentPage = res.currentPage
        self.likesLastPage = res.lastPage
      }).catch(function (e) {
        console.error('加载猜你喜欢失败:', e)
      }).finally(function () {
        self.likesLoading = false
      })
    },
    loadGoods: function (item) {
      var self = this
      var ids = []
      var data = item.data || []
      for (var i = 0; i < data.length; i++) {
        if (data[i].goodsLink) ids.push(data[i].goodsLink)
      }
      if (ids.length === 0) return
      pullMallPageGoods({ ids: ids.join(',') }).then(function (res) {
        self.goodsDataList = res
      }).catch(function (e) {
        console.error('加载商品模块失败:', e)
      })
    },
    handleLower: function () {
      if (this.likesLoading || this.likesCurrentPage >= this.likesLastPage) return
      this.likesCurrentPage++
      this.likesLoading = true
      var self = this
      pullMallLikes({ page: self.likesCurrentPage }).then(function (res) {
        self.likesDataList = self.likesDataList.concat(res.rows)
        self.likesCurrentPage = res.currentPage
        self.likesLastPage = res.lastPage
      }).catch(function (e) {
        console.error('加载更多失败:', e)
      }).finally(function () {
        self.likesLoading = false
      })
    },
    onLinkTap: function (link) {
      if (!link) return
      if (link.startsWith('/pages')) {
        uni.navigateTo({ url: link })
      }
    }
  }
}
</script>

<style scoped>
.home-content {
  background: #f5f5f5;
}

.module-banner {
  width: 100%;
}

.banner-swiper {
  width: 100%;
  min-height: 200rpx;
}

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

.module-menu {
  padding: 20rpx 0;
  background: #fff;
}

.menu-grid {
  display: flex;
  flex-wrap: wrap;
}

.menu-item {
  width: 20%;
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 16rpx;
}

.menu-img {
  width: 88rpx;
  height: 88rpx;
  border-radius: 50%;
  margin-bottom: 8rpx;
}

.menu-text {
  font-size: 22rpx;
  color: #666;
}

.module-notice {
  padding: 10rpx 24rpx;
  background: #fffbe8;
}

.notice-swiper {
  width: 100%;
}

.notice-text {
  font-size: 26rpx;
  color: #e6a23c;
  line-height: 60rpx;
}

.module-image {
  width: 100%;
}

.module-full-img {
  width: 100%;
  display: block;
}

.module-likes {
  background: #f5f5f5;
}

.module-goods {
  background: #f5f5f5;
}

.load-more {
  text-align: center;
  padding: 20rpx 0;
  font-size: 24rpx;
  color: #999;
}

.empty {
  text-align: center;
  padding: 100rpx 0;
  color: #999;
}
</style>