<template>
  <z-paging
    ref="pagingRef"
    v-model="multiRowProdListPar"
    default-page-size="10"
    empty-view-text="暂无商品"
    :paging-style="{'top': '0','background-color': '#f2f3f7'}"
    :loading-more-custom-style="{'padding-bottom': '3.13rem', 'margin-top': '-40rpx'}"
    loading-more-no-more-text="没有更多了，看看别的吧"
    @query="queryHotSalesOfShop"
    @list-change="listChange"
  >
    <view class="Mall4j shop-page">
      <view class="shop-index">
        <!-- 头部 -->
        <view class="header">
          <view class="bg">
            <image
              style="width: 100%;height: 100%;"
              :src="util.addDomain(shopInfo.mobileBackgroundPic) || defaultShopBG"
              @error="shopInfo.mobileBackgroundPic=''"
            />
          </view>
          <view
            class="search"
            @tap="toShopSearch"
          >
            <view class="icon">
              <image
                style="width: 100%; height: 100%;"
                src="@/static/images/search.png"
              />
            </view>
            <view class="text">
              搜索您想要的商品
            </view>
          </view>
        </view>
        <!-- 店铺信息 -->
        <view
          class="shop-info"
          :class="{'gradient-bg': !banners.length && !shopInfo.intro}"
        >
          <view class="logo">
            <image
              style="width: 100%; height: 100%;"
              :src="shopInfo.shopLogo ? util.addDomain(shopInfo.shopLogo) : defaultShopLogo"
              @error="shopInfo.shopLogo=''"
            />
          </view>
          <view class="text-box">
            <view class="name">
              {{ shopInfo.shopName }}
            </view>
            <view class="focus-box">
              <view
                v-if="shopInfo.type === 1"
                class="self"
              >
                自营
              </view>
              <view class="focus">
                关注人数：{{ wxs.parseCollectionNumber(shopInfo.collectionNum) }}
              </view>
            </view>
          </view>
          <view
            class="collect"
            @tap="addOrCancelOfCollection"
          >
            <view
              v-if="!isCollected"
              class="img"
            >
              <image
                style="width: 100%; height: 100%;"
                src="@/package-shop/static/images/focus.png"
              />
            </view>
            <view class="text">
              {{ isCollected ? '已关注' : '关注' }}
            </view>
          </view>
        </view>
        <view
          v-if="shopInfo.intro"
          class="shop-des"
        >
          {{ shopInfo.intro }}
        </view>

        <!-- 广告 -->
        <view
          v-if="banners.length > 0"
          class="shop-adv"
        >
          <swiper
            class="img"
            :indicator-dots="true"
            indicator-color="rgba(255,252,255, .3)"
            indicator-active-color="rgba(255,252,255, .6)"
            :autoplay="true"
            :circular="true"
          >
            <swiper-item
              v-for="(imgItem, imgIdx) in banners"
              :key="imgIdx"
              class="item"
              @tap="toProdDetail(imgItem.spuId)"
            >
              <img-show :src="imgItem.imgUrl" />
            </swiper-item>
          </swiper>
        </view>

        <!-- 店铺热销 -->
        <view class="shop-prods">
          <view class="shop-tit">
            <view class="text">
              店铺热销
            </view>
            <view
              class="text-arrow"
              @tap="goShopProds"
            >
              更多
            </view>
          </view>
          <view class="prods">
            <view
              v-for="(prodList,listIndex) in multiRowProdList"
              :key="listIndex"
              class="list"
            >
              <view
                v-for="(prod, index) in prodList"
                :key="index"
                class="item"
                @tap="toProdDetail(prod.spuId)"
              >
                <view class="img">
                  <img-show
                    :src="prod.mainImgUrl"
                    img-mode="aspectFit"
                  />
                </view>
                <view class="text-box">
                  <view
                    style="font-size: 24rpx"
                    class="name"
                  >
                    {{ prod.spuName }}
                  </view>
                  <view
                    v-if="prod.sellingPoint"
                    style="font-size: 24rpx"
                    class="sku"
                  >
                    {{ prod.sellingPoint }}
                  </view>
                  <view
                    v-if="prod.spuActivity.discountList
                      && prod.spuActivity.discountList.length > 0
                      && prod.spuActivity.discountList[0].discountItemList.length > 0"
                    class="discount-box"
                  >
                    <view
                      v-if="prod.spuActivity.discountList[0].discountRule === 0"
                      class="discount"
                    >
                      满减
                    </view>
                    <view
                      v-if="prod.spuActivity.discountList[0].discountRule ===0"
                      class="coupons"
                    >
                      {{
                        '满' + util.accuracyCount(prod.spuActivity.discountList[0].discountItemList[0].needAmount, 100, 3) + '元减' +
                          util.accuracyCount(prod.spuActivity.discountList[0].discountItemList[0].discount, 100, 3) + '元'
                      }}
                    </view>
                    <view
                      v-if="prod.spuActivity.discountList[0].discountRule ===3"
                      class="discount"
                    >
                      满折
                    </view>
                    <view
                      v-if="prod.spuActivity.discountList[0].discountRule ===3"
                      class="coupons"
                    >
                      {{
                        '满' + util.accuracyCount(prod.spuActivity.discountList[0].discountItemList[0].needAmount, 100, 3) + '件打' +
                          util.accuracyCount(prod.spuActivity.discountList[0].discountItemList[0].discount, 100, 3) + '折'
                      }}
                    </view>
                  </view>
                  <view class="price-box">
                    <view class="price">
                      <view class="symbol">
                        ￥
                      </view>
                      <view class="big">
                        {{ parsePrice(prod.priceFee)[0] }}
                      </view>
                      <view class="symbol">
                        .{{ parsePrice(prod.priceFee)[1] }}
                      </view>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
        <popup-ad
          v-model="popupadShow"
          :popup-info="popupInfo"
          :shop-id="shopId"
        />
        <!-- 店铺tabbar -->
        <shop-tabbar
          style="position:fixed;bottom:0;width:100%;left:0;right:0;"
          :shop-id="shopId"
        />
      </view>
    </view>
  </z-paging>
</template>

<script setup>
import number from '@/wxs/number'
import defaultShopBG from '@/package-shop/static/images/default-shop-bg.png'
import defaultShopLogo from '@/package-shop/static/images/default-shop-logo.png'
import util from '@/utils/util.js'

const wxs = number()

const shopId = ref(0)
const categoryId = ref('') // 分类ID
const shopSecondaryCategoryId = ref('') // 二级分类ID
onLoad((options) => {
  // options = {...$Route.query}
  shopId.value = options.shopId
  uni.setStorageSync('cloudShopId', shopId.value)
  categoryId.value = options.categoryId || ''
  shopSecondaryCategoryId.value = options.secondCategoryId || ''
  queryShopInfo() // 店铺信息
  queryCollectedStatus() // 根据店铺id获取该店铺是否在收藏夹中
  queryShopBanners() // 轮播图
})

// 获取弹窗广告信息
const popupadShow = ref(false)
const popupInfo = ref({})
const onGetPopupInfo = async () => {
  const info = await util.getPopupInfo({ pageType: 4, shopId: shopId.value })
  if (info) {
    popupInfo.value = info
    popupadShow.value = true
  }
}
const shopInfo = ref({}) // 店铺信息
const queryShopInfo = () => {
  // 获取店铺头部信息
  http.request({
    url: '/tmerclub_admin/ua/shop_detail/head_info',
    method: 'GET',
    data: {
      shopId: shopId.value
    }
  }).then((res) => {
    shopInfo.value = res
    if (shopInfo.value.renovationId) {
      uni.redirectTo({
        url: '/package-shop/shop-page/feature-index/feature-index?shopId=' + shopInfo.value.shopId + '&renovationId=' + shopInfo.value.renovationId
      })
      return
    }
    onGetPopupInfo()
    getShopStatus()
    uni.setStorageSync('cloudShopInfo', res) // 将店铺信息存起来
  }).catch((err) => {
    // 如果不存在店铺或其他错误
    uni.showModal({
      title: '提示',
      content: err.msg,
      showCancel: false,
      success: (res) => {
        if (res.confirm) {
          // 点击确定,返回上一页
          uni.navigateBack()
        }
      }
    })
  })
}

const banners = ref([]) // 轮播图
/**
 * 首页轮播图
 */
const queryShopBanners = () => {
  http.request({
    url: '/tmerclub_admin/ua/index_img/list',
    method: 'GET',
    data: {
      shopId: shopId.value,
      imgType: 0 // 图片类型：0.app(h5) 1.pc
    }
  }).then((res) => {
    // imgType 图片类型 0:小程序 1:pc
    banners.value = []
    res.forEach((item) => {
      if (item.imgType === 0) {
        banners.value.push(item)
      }
    })
  })
}

const isCollected = ref(false) // 是否收藏
/**
 * 根据店铺id获取该店铺是否在收藏夹中
 */
const queryCollectedStatus = () => {
  if (!uni.getStorageSync('cloudToken') || !shopId.value) {
    return
  }
  http.request({
    url: '/tmerclub_admin/user_collection_shop/ma/is_collection',
    method: 'get',
    data: {
      shopId: shopId.value
    }
  }).then((res) => {
    isCollected.value = res
  })
}

/**
 * 添加收藏/取消收藏
 */
const addOrCancelOfCollection = () => {
  http.request({
    url: '/tmerclub_admin/user_collection_shop/add_or_cancel',
    method: 'post',
    data: shopId.value,
    dontShowLogin: true
  }).then((res) => {
    isCollected.value = res
    queryShopInfo()
  }).catch(() => {
    const pagesPar = getCurrentPages()
    uni.setStorageSync('cloudRouteUrlAfterLogin', pagesPar[pagesPar.length - 1].$page.fullPath)
    uni.navigateTo({
      url: '/package-user/pages/user-login/user-login'
    })
  })
}

const searchKey = null // 搜索关键字
const multiRowProdList = ref([])
const multiRowProdListPar = ref([]) // 多行展示时商品列表
const pagingRef = ref(null)
/**
 * 店铺热销
 */
const queryHotSalesOfShop = (pageNum, pageSize) => {
  http.request({
    url: '/tmerclub_search/ua/search/page',
    method: 'GET',
    data: {
      shopId: shopId.value,
      pageNum,
      pageSize,
      sort: 2,
      keyword: searchKey || '',
      categoryId: categoryId.value,
      shopSecondaryCategoryId: shopSecondaryCategoryId.value,
      needActivity: 1 // 是否需要活动信息 1：需要 0：不需要
    }
  }).then((res) => {
    res.list[0].spus.forEach(item => {
      item.priceFee = util.accuracyCount(item.priceFee, 100, 3)
      item.marketPriceFee = util.accuracyCount(item.priceFee, 100, 3)
    })
    // 将请求结果通过complete传给z-paging处理，同时也代表请求结束，这一行必须调用
    pagingRef.value.complete(res.list[0].spus)
  })
}

const listChange = (list) => {
  // 多列数据展示
  const row1 = []
  const row2 = []
  list.forEach((prod, index) => {
    if (index % 2 === 0) {
      row1.push(prod)
    } else {
      row2.push(prod)
    }
  })

  multiRowProdList.value = [row1, row2]
}

// 查看店铺是否下架
const getShopStatus = () => {
  const startDate = new Date(shopInfo.value.contractStartTime).getTime()
  const endtDate = new Date(shopInfo.value.contractEndTime).getTime()
  const timestamp = Date.parse(new Date())
  if (shopInfo.value.shopStatus === 0) {
    let msg = ''
    if (timestamp < startDate) {
      msg = '商家尚未营业'
    }
    if (timestamp > endtDate) {
      msg = '商家已暂停营业'
    }
    uni.showModal({
      title: '提示',
      content: msg,
      showCancel: false,
      success: (res) => {
        if (res.confirm) {
          // 点击确定,返回上一页
          uni.navigateBack()
        }
      }
    })
  }
  if (shopInfo.value.shopStatus === 2 || shopInfo.value.shopStatus === 6) {
    uni.showModal({
      title: '提示',
      content: '店铺已下线',
      showCancel: false,
      success: (res) => {
        if (res.confirm) {
          // 点击确定,返回上一页
          uni.navigateBack()
        }
      }
    })
  }
}

const goShopProds = () => {
  uni.redirectTo({
    url: '/package-shop/shop-page/shop-prods/shop-prods?navStatus=1&sort=2'
  })
}

const toShopSearch = () => {
  uni.navigateTo({
    url: '/package-shop/shop-page/shop-search/shop-search?shopId=' + shopId.value
  })
}

/**
 * 跳转商品详情
 */
const toProdDetail = (spuId) => {
  if (!spuId) {
    return
  }
  uni.navigateTo({
    url: '/pages/detail/detail?spuId=' + spuId
  })
}

/**
 * 价格处理
 */
const parsePrice = (value) => {
  let val = Number(value)
  if (!val) {
    val = 0
  }
  // 截取小数点后两位，并以小数点为切割点将val转化为数组
  return val.toFixed(2).split('.')
}

</script>

<style lang="scss" scoped>
@use "../shop-page";
</style>
