<script setup lang="ts">
import type { LoadMoreState } from 'wot-design-uni/components/wd-loadmore/types'
import selectSku from '../../components/select-sku/index.vue'
import { StaticUrl } from '@/config'
import router from '@/router'

const props = defineProps<{ categoryList: Api.xsbCategories[], hotText: Api.xsbSearchTerm[] }>()
const { statusBarHeight, MenuButtonHeight } = storeToRefs(useSysStore())
const { topNavActive, leftActive, SelectShopInfo } = storeToRefs(useSysXsbStore())
const { userInfo, token } = storeToRefs(useUserStore())
const { getShopTotalNum } = storeToRefs(useSmqjhCartStore())
const classfiylist = computed(() => props.categoryList)
const sortClassBtn = ref(1)
const show = ref(false)
const cartList = ref<Api.xsbCategoriesCartList[]>([])
const cartPopup = ref(false)
const totalProduct = ref<Api.shoppingCartOrderConfirm>()
const priceDetailPopup = ref(false)
const cartIds = computed(() => cartList.value.filter(it => it.isDelete !== '1' && it.shopSkuStocks !== '0').map(it => it.id))
// 勾选状态：只计算勾选商品的价格
const selectedIds = ref<number[]>([])
const isAllSelected = computed(() => cartIds.value.length > 0 && cartIds.value.every(id => selectedIds.value.includes(id)))
const selectedCount = computed(() => selectedIds.value.length)

function toggleSelectAll() {
  if (isAllSelected.value) {
    selectedIds.value = []
  }
  else {
    selectedIds.value = [...cartIds.value]
  }
  getGoodsPrice()
}
async function handleClearCart() {
  useGlobalMessage().confirm({
    title: '提示',
    msg: '确认清空购物车？',
    success: async () => {
      uni.showLoading({ mask: true })
      try {
        const ids = cartList.value.map(it => it.id).join(',')
        if (ids) {
          await Apis.common.deleteShoppingCart({ pathParams: { ids } })
        }
        cartPopup.value = false
        selectedIds.value = []
        totalProduct.value = undefined
        useSmqjhCartStore().getCartList('XSB')
        await getCartCategorList()
        setProductNum()
      }
      finally {
        uni.hideLoading()
      }
    },
  })
}
const showball = ref(false)
const _this = getCurrentInstance()
const selectGoods = ref(false)
// 多规格商品skuid
const selectSkuId = ref(0)
const SelectGoodsNum = ref(1)
const goodsInTo = ref()
const goodsInfo = ref<Api.xsbCategoryProductList | Api.xsbProductDetail | undefined>()

const isTopLoading = ref(false)
const basllObj = ref({
  left: 0,
  top: 0,
  x: -402,
  y: 773,
})
const x = computed(() => `${basllObj.value.x}px`)
const y = computed(() => `${basllObj.value.y}px`)
const left = computed(() => `${basllObj.value.left}px`)
const top = computed(() => `${basllObj.value.top}px`)

const productList = ref<Api.xsbCategoryProductList[]>([])
const topScrollView = ref()
const scrollTop = ref<number | undefined>(0)
const goodsLoading = ref<LoadMoreState>()
const navHeight = computed(() => {
  return (`${Number(MenuButtonHeight.value) + Number(statusBarHeight.value)}px`)
})
function handleTopNavChange(item: Api.xsbCategoriesChildren) {
  topNavActive.value = item.code
  if (!item.children)
    return
  goodsLoading.value = 'loading'
  leftActive.value = item.children[0].code
  show.value = false
  topScrollView.value = null
  nextTick(() => {
    topScrollView.value = item.code
  })
  getProductList()
}

const categories = computed(() => {
  return classfiylist.value.find(it => it.code === topNavActive.value)?.children || []
})
const categoriesId = computed(() => {
  return categories.value.find(it => it.code === leftActive.value)?.id
})
async function getCartCategorList() {
  return new Promise((resolve, reject) => {
    Apis.xsb.myShoppingCartCategory({
      data: {
        businessType: 'XSB',
        channelId: unref(userInfo).channelId,
        shopId: unref(SelectShopInfo).shopId,
      },
    }).then((res) => {
      cartList.value = res.data
      console.log(cartList.value, '===================')
      resolve(res)
    }).catch((err) => {
      reject(err)
    })
  })
}
function handleChange({ value }: { value: string }) {
  leftActive.value = value
  getProductList()
}
function handleLeftChange(item: Api.xsbCategories) {
  goodsLoading.value = 'loading'
  handleChange({ value: item.code })
}
async function getProductList() {
  const res = await Apis.xsb.getCategoryProductList({
    data: {
      categoryId: Number(categoriesId.value),
      shopId: Number(SelectShopInfo.value?.shopId) || 1,
      channelId: unref(userInfo).channelId || 1,
    },
  })
  productList.value = res.data
  if (!res.data.length) {
    scrollTop.value = undefined
    nextTick(() => {
      scrollTop.value = 0
    })
  }
  if (!isTopLoading.value) {
    scrollTop.value = undefined
    nextTick(() => {
      scrollTop.value = 0
    })
  }
  else {
    goodsInTo.value = null
    nextTick(() => {
      goodsInTo.value = res.data.length > 4 ? res.data[res.data.length - 4].prodId : null
    })
  }
  goodsLoading.value = 'finished'
  isTopLoading.value = false
  setProductNum()
}

function handlScrollBottom() {
  goodsLoading.value = 'loading'

  const index = categories?.value.findIndex(it => it.code === leftActive.value)
  console.log(index, '-================')
  if (index + 1 === categories.value.length) {
    goodsLoading.value = 'finished'
    return
  }
  if (index !== -1) {
    handleChange({ value: categories.value[index + 1].code })
  }
}
function handleSrollTop() {
  isTopLoading.value = true
  const index = categories?.value.findIndex(it => it.code === leftActive.value)
  if (index !== -1) {
    if (index === 0) {
      nextTick(() => isTopLoading.value = false)
    }
    else {
      handleChange({ value: categories.value[index - 1].code })
    }
  }
}
async function handleAddCart(event: WechatMiniprogram.TouchEvent, item: Api.xsbCategoryProductList) {
  await useUserStore().checkLogin()
  if (item.skuList.length > 1) {
    goodsInfo.value = item
    selectGoods.value = true
    return
  }
  if (showball.value)
    return
  basllObj.value.left = event.detail.x
  basllObj.value.top = event.detail.y
  showball.value = true
  setTimeout(() => {
    showball.value = false
  }, 500)
  const skuId = item.skuList[0].skuId
  await useSmqjhCartStore().addCart(skuId, 1, Number(item.shopId), 'XSB')
  await getCartCategorList()
  setProductNum()
  // 自动选中刚加入的商品，并重新计算价格
  const cartItem = cartList.value.find(it => it.skuId === skuId && it.isDelete !== '1' && it.shopSkuStocks !== '0')
  if (cartItem && !selectedIds.value.includes(cartItem.id)) {
    selectedIds.value.push(cartItem.id)
  }
  await getGoodsPrice()
}
async function handleSubCart(event: WechatMiniprogram.TouchEvent, item: Api.xsbCategoryProductList) {
  const skuId = item.skuList[0].skuId
  if (item.num === 1) {
    useGlobalMessage().confirm({
      msg: '是否删除该商品？',
      success: async () => {
        // 删除前记录 cartId，用于从 selectedIds 中移除
        const cartItem = cartList.value.find(it => it.skuId === skuId)
        await useSmqjhCartStore().addCart(skuId, -1, Number(item.shopId), 'XSB')
        await getCartCategorList()
        setProductNum()
        if (cartItem) {
          selectedIds.value = selectedIds.value.filter(id => id !== cartItem.id)
        }
        await getGoodsPrice()
      },
    })
  }
  else {
    await useSmqjhCartStore().addCart(skuId, -1, Number(item.shopId), 'XSB')
    await getCartCategorList()
    setProductNum()
    await getGoodsPrice()
  }
}

onMounted(async () => {
  if (token.value) {
    await getCartCategorList()
  }
  if (!topNavActive.value || !leftActive.value) {
    const firstWithChildren = props.categoryList?.find(it => it.children && it.children.length > 0)
    if (firstWithChildren) {
      topNavActive.value = firstWithChildren.code
      leftActive.value = firstWithChildren.children![0].code
    }
  }

  goodsLoading.value = 'loading'
  if (leftActive.value) {
    handleChange({ value: leftActive.value })
  }
  else {
    goodsLoading.value = 'finished'
  }
  if (topNavActive.value) {
    topScrollView.value = null
    nextTick(() => {
      topScrollView.value = topNavActive.value
    })
  }

  getCartBox()
})

function getCartBox() {
  const query = uni.createSelectorQuery().in(_this)
  query.select('.cart-box').boundingClientRect()
  query.exec((res) => {
    basllObj.value.y = res[0].top
    uni.getSystemInfo().then((info) => {
      basllObj.value.x = -(info.screenWidth - res[0].left - 15)
      console.log(basllObj.value.x, basllObj.value.y)
    })
  })
}
function handleGo(item: Api.xsbCategoryProductList) {
  if (!item.prodId) {
    useGlobalToast().show('后端数据异常!')
    return
  }
  router.push({ name: 'xsb-goods', params: { id: String(item.prodId) } })
}

async function getGoodsPrice() {
  if (selectedIds.value.length) {
    const res = await useSmqjhCartStore().getCartAddGoodsPrice(selectedIds.value.join(','))
    totalProduct.value = res
  }
  else {
    totalProduct.value = undefined
  }
}
async function handleSub(item: Api.xsbCategoriesCartList) {
  if (item.num === 1) {
    useGlobalMessage().confirm({
      msg: '是否删除该商品？',
      success: async () => {
        cartPopup.value = false
        await useSmqjhCartStore().addCart(item.skuId, -1, item.shopId, 'XSB')
        await getCartCategorList()
        setProductNum()
        totalProduct.value = undefined
      },
    })
  }
  else {
    await useSmqjhCartStore().addCart(item.skuId, -1, item.shopId, 'XSB')
    getGoodsPrice()
    await getCartCategorList()
    setProductNum()
  }
}
async function handleAdd(item: Api.xsbCategoriesCartList) {
  await useSmqjhCartStore().addCart(item.skuId, 1, item.shopId, 'XSB')
  getGoodsPrice()
  await getCartCategorList()
  setProductNum()
}
onUnmounted(() => {
  console.log('组件卸载')
  topNavActive.value = ''
  leftActive.value = ''
})
async function handleDelCartGoods(item: Api.xsbCategoriesCartList) {
  const msg = item.isDelete ? '商品已被商家删除，是否确认删除该门店下的商品？' : '门店商品库存不足，是否删除该门店下的商品？'
  useGlobalMessage().confirm({
    title: '提示',
    msg,
    success: async () => {
      uni.showLoading({ mask: true })
      try {
        await Apis.common.deleteShoppingCart({
          pathParams: {
            ids: String(item.id),
          },
        })
        await getCartCategorList()
        uni.hideLoading()
      }
      catch {
        uni.hideLoading()
      }
    },
  })
}
function setProductNum() {
  if (!cartList.value.length) {
    productList.value = productList.value.map((goods) => {
      goods.num = undefined
      return goods
    })
    return
  }
  cartList.value.forEach((it) => {
    productList.value = productList.value.map((goods) => {
      if (goods.skuList.length && goods.skuList[0].skuId === it.skuId) {
        goods.num = it.num
      }
      return goods
    })
  })
}
async function handleSkuAddCart() {
  await useSmqjhCartStore().addCart(unref(selectSkuId), unref(SelectGoodsNum), Number(goodsInfo.value?.shopId), 'XSB')
  getGoodsPrice()
  await getCartCategorList()
}
function handlePay() {
  if (!totalProduct.value) {
    useGlobalToast().show('请选择商品')
    return
  }
  const shopSkuStock = totalProduct.value.skuList.filter(it => it.num > Number(it.shopSkuStocks))
  if (shopSkuStock.length) {
    useGlobalToast().show({ msg: `${shopSkuStock[0].skuName}库存不足` })
    return
  }
  cartPopup.value = false
  router.push({ name: 'xsb-confirmOrder', params: { data: JSON.stringify(totalProduct.value) } })
}
function handleOpen() {
  if (!getShopTotalNum.value)
    return
  cartPopup.value = true
  priceDetailPopup.value = false
}
</script>

<script lang="ts">
export default {
  options: {
    styleIsolation: 'shared',
  },
}
</script>

<template>
  <view class="page-xsb">
    <wd-navbar
      title="" custom-style="background-color:#F4FFD1" :bordered="false" :z-index="9999" safe-area-inset-top
      fixed
    >
      <template #left>
        <view class="flex items-center" @click="router.push({ name: 'xsb-search' })">
          <view
            class="h60rpx w-474rpx flex items-center justify-between border-2rpx border-[var(--them-color)] rounded-40rpx border-solid bg-white pr6rpx"
          >
            <view class="flex items-center pb14rpx pl24rpx pt16rpx">
              <wd-icon name="search" size="14" color="#ccc" />
              <view class="search ml12rpx h-full w-full overflow-hidden">
                <wd-notice-bar
                  :text="hotText.map((it) => it.searchName)" custom-class="notice-bar" color="#ccc"
                  background-color="#fff" direction="vertical"
                />
              </view>
            </view>
            <view class="flex items-center pr28rpx">
              <wd-divider vertical />
              <view class="ml6rpx text-28rpx text-[var(--them-color)] font-semibold">
                搜索
              </view>
            </view>
          </view>
        </view>
      </template>
    </wd-navbar>
    <view
      class="h162rpx flex items-center justify-between bg-#F4FFD1 pl24rpx"
      :style="{ paddingTop: `${(Number(statusBarHeight) || 44) + MenuButtonHeight + 12}px` }"
    >
      <scroll-view
        :scroll-into-view-offset="-150" scroll-x enable-passive scroll-with-animation
        class="scrollx w-90% flex-shrink-0 whitespace-nowrap" :scroll-into-view="`id${topScrollView}`"
      >
        <view class="flex items-end pb10rpx">
          <view
            v-for="item in classfiylist" :id="`id${item.code}`" :key="item.code"
            class="mr24rpx flex flex-col items-center justify-center" @click="handleTopNavChange(item)"
          >
            <view class="relative">
              <view
                class="box-border"
                :class="[topNavActive == item.code ? 'overflow-hidden border-solid border-[var(--them-color)] border-2rpx rounded-26rpx h84rpx w-84rpx' : 'h72rpx w-72rpx']"
              >
                <image :src="item.icon" class="h-full w-full" />
              </view>
              <view
                v-if="!item.children"
                class="absolute left-0 top-0 h-full w-full flex items-center justify-center rounded-26rpx bg-[rgba(0,0,0,0.6)] text-16rpx text-white"
              >
                敬请期待
              </view>
            </view>

            <view
              class="mt16rpx text-22rpx"
              :class="[topNavActive == item.code ? 'bg-[var(--them-color)] rounded-18rpx px-8rpx py2rpx text-white text-24rpx' : '']"
            >
              {{ item.name }}
            </view>
          </view>
        </view>
      </scroll-view>
      <view
        class="right-nav box-border h144rpx w64rpx flex flex-shrink-0 flex-col items-center justify-center px20rpx text-24rpx font-semibold"
        @click="show = true"
      >
        展开
        <image :src="`${StaticUrl}/xia.png`" class="mt20rpx h20rpx w20rpx" />
      </view>
      <wd-popup v-model="show" :z-index="9998" position="top" custom-style="border-radius:32rpx;">
        <view
          class="box-border bg-#F4FFD1 p24rpx"
          :style="{ paddingTop: `${(Number(statusBarHeight) || 44) + MenuButtonHeight + 12}px` }"
        >
          <view class="mb24rpx mt24rpx text-28rpx font-semibold">
            全部一级分类
          </view>
          <view class="h400rpx overflow-y-scroll">
            <view class="grid grid-cols-5 box-border gap-x-24rpx gap-y-24rpx">
              <view
                v-for="item in classfiylist" :key="item.code"
                class="box-border h150rpx w114rpx flex flex-col items-center justify-center"
                @click="handleTopNavChange(item)"
              >
                <image
                  :src="item.icon"
                  :class="[topNavActive == item.code ? 'overflow-hidden border-solid border-[var(--them-color)] border-2rpx rounded-26rpx h88rpx w-88rpx' : 'h76rpx w-76rpx']"
                />
                <view
                  class="mt16rpx whitespace-nowrap text-nowrap text-22rpx"
                  :class="[topNavActive == item.code ? 'bg-[var(--them-color)] rounded-18rpx px-8rpx py2rpx text-white text-24rpx' : '']"
                >
                  {{ item.name }}
                </view>
              </view>
            </view>
          </view>
          <view class="mt24rpx w-full flex items-center justify-center" @click="show = false">
            <view class="mr8rpx text-24rpx">
              点击收起
            </view>
            <wd-icon name="arrow-down" size="18px" />
          </view>
        </view>
      </wd-popup>
    </view>
    <view class="wraper">
      <scroll-view
        class="w200rpx" :scroll-into-view-offset="-150" enable-passive scroll-with-animation scroll-y
        :scroll-into-view="`id${leftActive}`"
      >
        <view
          v-for="item in categories" :id="`id${item.code}`" :key="item.code"
          :class="[item.code == leftActive ? 'bg-white' : '']"
          class="relative h100rpx flex items-center justify-center whitespace-nowrap text-28rpx"
          @click="handleLeftChange(item)"
        >
          {{ item.name }}
          <view
            v-if="item.code == leftActive"
            class="absolute left-0 top-20rpx h60rpx w8rpx rounded-4rpx bg-[var(--them-color)]"
          />
        </view>
      </scroll-view>
      <view class="content">
        <view class="p20rpx">
          <image :src="`${StaticUrl}/class.png`" class="h144rpx w-full" @click="useGlobalToast().show('敬请期待 ！')" />
          <view class="my20rpx flex items-center justify-end rounded-16rpx bg-#F6F6F6 px20rpx py8rpx">
            <view class="mr40rpx text-24rpx">
              销量
            </view>
            <wd-sort-button v-model="sortClassBtn" :line="false" title="价格" />
          </view>
        </view>
        <view class="relative">
          <scroll-view
            :lower-threshold="100" :refresher-triggered="isTopLoading" :scroll-top="scrollTop"
            :style="{ height: `calc(100vh - ${navHeight} - 700rpx)` }" enable-passive scroll-y scroll-anchoring
            refresher-enabled :throttle="false" :scroll-into-view="`class${goodsInTo}`"
            @refresherrefresh="handleSrollTop" @scrolltolower="handlScrollBottom"
          >
            <view v-if="productList.length" class="p20rpx">
              <view v-for="item in productList" :id="`class${item.prodId}`" :key="item.id" class="relative">
                <view class="flex" @click="handleGo(item)">
                  <view class="relative mr20rpx h172rpx w172rpx flex-shrink-0 overflow-hidden rounded-16rpx bg-#F6F6F6">
                    <image :src="item.pic" lazy-load class="h-full w-full" />
                    <image :src="`${StaticUrl}/xsb-shui-class.png`" class="absolute left-0 top-0 h-full w-full" />
                  </view>
                  <view class="flex-1">
                    <view class="text-left text-28rpx font-semibold">
                      <!-- <view v-for="i in 2" :key="i" class="mr5px inline-block">
                      <wd-tag type="primary">
                        新品{{ i }}
                      </wd-tag>
                    </view> -->
                      {{ item.prodName }}
                    </view>
                    <view class="text-22rpx text-#AAAAAA">
                      <view class="mt10rpx flex items-center">
                        <view>{{ item.spec }}</view>
                      </view>
                      <view class="mt6rpx">
                        已售 {{ item.soldNum }}+
                      </view>
                    </view>
                    <view class="flex items-center justify-between">
                      <view class="text-#FF4D3A font-semibold">
                        <text class="text-24rpx">
                          ￥
                        </text> <text class="text-36rpx">
                          {{ item.channelProdPrice }}
                        </text>
                      </view>
                      <view v-if="!item.num">
                        <view v-if="item.spuStock" @click.stop="handleAddCart($event, item)">
                          <image :src="`${StaticUrl}/cart-yes.png`" class="h52rpx w52rpx" />
                        </view>
                        <view v-else>
                          <image :src="`${StaticUrl}/cart-no.png`" class="h52rpx w52rpx" />
                        </view>
                      </view>
                      <view v-else>
                        <view class="flex items-center">
                          <image
                            :src="` ${StaticUrl}/sub-cart.png`" class="h44rpx w44rpx"
                            @click.stop="handleSubCart($event, item)"
                          />
                          <view
                            class="box-border h44rpx w84rpx flex items-center justify-center border border-#F0F0F0 border-solid text-24rpx text-#AAAAAA"
                          >
                            {{ item.num }}
                          </view>
                          <image
                            :src="` ${StaticUrl}/add-cart.png`" class="h44rpx w44rpx"
                            @click.stop="handleAddCart($event, item)"
                          />
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
                <view class="line">
                  <wd-divider color="#F0F0F0" />
                </view>
                <view
                  v-if="!item.spuStock"
                  class="absolute left-0 top-0 z-1 h-full w-full flex items-center bg-[rgba(255,255,255,.6)]"
                >
                  <view class="h172rpx w172rpx flex items-center justify-center">
                    <view
                      class="h36rpx w112rpx flex items-center justify-center rounded-16rpx bg-[rgba(0,0,0,.6)] text-28rpx text-white"
                    >
                      已售罄
                    </view>
                  </view>
                </view>
                <view
                  v-if="!item.skuList.some((it) => it.saleStatus)"
                  class="absolute left-0 top-0 z-1 h-full w-full flex items-center bg-[rgba(255,255,255,.6)]"
                >
                  <view class="h172rpx w172rpx flex items-center justify-center">
                    <view
                      class="h36rpx w112rpx flex items-center justify-center rounded-16rpx bg-[rgba(0,0,0,.6)] text-28rpx text-white"
                    >
                      不可售
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <StatusTip v-else tip="暂无内容" />
            <view v-if="goodsLoading == 'finished' || isTopLoading" class="h-40vh" />
          </scroll-view>
          <view
            v-if="goodsLoading == 'loading' || isTopLoading"
            class="absolute left-0 top-0 z-10 h-full w-full flex items-center justify-center bg-white"
          >
            <wd-loading color="#9ED605" :size="20" />
          </view>
        </view>
      </view>
    </view>
    <view
      class="fixedShadow fixed bottom-60rpx left-0 z-100 box-border w-full flex items-center justify-between rounded-t-16rpx bg-white px24rpx pb60rpx pt10rpx"
    >
      <view class="ios w-full flex items-center justify-between">
        <view class="flex items-center">
          <view class="flex items-center" @click="handleOpen">
            <wd-badge :model-value="getShopTotalNum" :top="20">
              <image v-if="getShopTotalNum" :src="`${StaticUrl}/cart-lanzi.png`" class="cart-box h100rpx w100rpx" />
              <image v-else :src="`${StaticUrl}/xsb-cart-disabled.png`" class="cart-box h100rpx w100rpx" />
            </wd-badge>
          </view>
          <view v-if="getShopTotalNum" class="ml40rpx">
            <view class="flex items-center">
              <view class="font-semibold">
                ￥ {{ totalProduct?.amount || 0 }}
              </view>
              <view v-if="totalProduct?.coupon" class="ml10rpx text-24rpx text-#FF4A39">
                共减￥{{ totalProduct?.coupon }}
              </view>
              <view
                v-if="totalProduct?.amount" class="ml10rpx flex items-center text-24rpx text-gray"
                @click="priceDetailPopup = !priceDetailPopup, cartPopup = false"
              >
                明细 <view :class="[priceDetailPopup ? 'rotate-180' : '']" class="flex items-center">
                  <wd-icon name="arrow-up" size="24rpx" color="#aaa" />
                </view>
              </view>
            </view>
            <view class="mt10rpx text-24rpx text-gray">
              配送费：￥{{ totalProduct?.transfee || 0 }}
            </view>
          </view>
          <view v-else class="ml40rpx text-24rpx text-#AAA">
            您还没有添加商品
          </view>
        </view>
        <view class="flex items-center">
          <!-- <view class="flex items-center font-semibold">
            <view class="text-22rpx text-#222">
              总计：
            </view>
            <view class="flex items-baseline text-24rpx text-#FF4A39">
              ￥
              <text class="text-36rpx">
                {{ totalProduct?.price || '0.00' }}
              </text>
            </view>
          </view> -->
          <view class="ml20rpx w160rpx">
            <wd-button block size="large" :disabled="!getShopTotalNum" :type="getShopTotalNum ? 'primary' : 'info'" @click="handlePay">
              结算
            </wd-button>
          </view>
        </view>
      </view>
    </view>
    <!-- 价格明细弹窗 -->
    <Zpopup v-model="priceDetailPopup" :zindex="10" bg="#fff">
      <view class="ios box-border w-full px-40rpx pb-60rpx pt-36rpx">
        <view class="mb-40rpx text-center text-32rpx font-semibold">
          价格明细
        </view>
        <!-- 商品合计 -->
        <view class="flex items-center justify-between py-20rpx">
          <view class="text-30rpx font-semibold">
            商品合计
          </view>
          <view class="text-30rpx font-semibold">
            ￥{{ totalProduct?.amount }}
          </view>
        </view>
        <!-- 商品总价 -->
        <view class="flex items-center justify-between py-20rpx">
          <view class="text-28rpx text-#333">
            商品总价
          </view>
          <view class="text-28rpx text-#333">
            ￥{{ totalProduct?.price }}
          </view>
        </view>
        <!-- 下单用券共减 -->
        <template v-if="totalProduct?.coupon">
          <view class="flex items-center justify-between py-20rpx">
            <view class="text-28rpx text-#333">
              下单用券共减
            </view>
            <view class="text-28rpx text-#FF4A39 font-semibold">
              -￥{{ totalProduct?.coupon }}
            </view>
          </view>
          <!-- 券名称子行 -->
          <view v-if="totalProduct?.activityName || totalProduct?.couponName" class="flex items-center justify-between pb-20rpx">
            <view class="text-24rpx text-#AAAAAA">
              {{ totalProduct?.activityName || totalProduct?.couponName }}
            </view>
            <view class="text-24rpx text-#AAAAAA">
              -￥{{ totalProduct?.coupon }}
            </view>
          </view>
        </template>
        <!-- 配送费 -->
        <view class="flex items-center justify-between py-20rpx">
          <view class="text-28rpx text-#333">
            配送费
          </view>
          <view class="text-28rpx text-#333">
            ￥{{ totalProduct?.transfee }}
          </view>
        </view>
      </view>
      <view class="h200rpx" />
    </Zpopup>
    <Zpopup v-model="cartPopup" :zindex="99">
      <view class="ios overflow-hidden">
        <!-- 头部：全选 + 已选件数 + 清空购物车 -->
        <view class="flex items-center justify-between border-b border-[#F5F5F5] border-solid px-24rpx py-24rpx">
          <view class="flex items-center">
            <wd-checkbox :model-value="isAllSelected" size="large" @change="toggleSelectAll">
              全选
            </wd-checkbox>
            <text class="ml-16rpx text-24rpx text-[#AAAAAA]">
              已选{{ selectedCount }}件,总重量约为{{ totalProduct?.totalWeight || 0 }}kg
            </text>
          </view>
          <view class="text-24rpx text-[#AAAAAA]" @click="handleClearCart">
            <wd-icon name="delete" size="24rpx" /> 清空购物车
          </view>
        </view>
        <!-- 商品列表 -->
        <view class="h-700rpx overflow-y-scroll">
          <view class="p-24rpx">
            <wd-checkbox-group v-model="selectedIds" custom-class="custom-checkbox-group" @change="getGoodsPrice">
              <view
                v-for="item in cartList" :key="item.id"
                class="relative mt-20rpx box-border flex items-center overflow-hidden rounded-16rpx bg-white p-24rpx"
              >
                <!-- 复选框 -->
                <wd-checkbox
                  v-if="item.shopSkuStocks !== '0' && item.isDelete !== '1'" :model-value="item.id"
                  size="large" class="mr-16rpx flex-shrink-0"
                />
                <view v-else class="mr-16rpx h-40rpx w-40rpx flex-shrink-0" />
                <view class="flex flex-1">
                  <image
                    :src="item.pic" class="h206rpx w200rpx flex-shrink-0"
                    @click.stop="router.push({ name: 'xsb-goods', params: { id: String(item.prodId) } })"
                  />
                  <view class="ml20rpx flex-1">
                    <view class="text-left text-28rpx font-semibold">
                      {{ item.skuName }}
                    </view>
                    <view class="mt14rpx text-24rpx text-#AAAAAA">
                      规格：{{ item.spec }}
                    </view>
                    <view class="mt14rpx flex items-center justify-between">
                      <view class="text-36rpx text-#FF4A39 font-semibold">
                        ￥{{ item.price }}
                      </view>
                      <view v-if="item.shopSkuStocks !== '0' && item.isDelete !== '1'" class="flex items-center">
                        <image
                          :src="` ${StaticUrl}/sub-cart.png`" class="h44rpx w44rpx"
                          @click.stop="handleSub(item)"
                        />
                        <view
                          class="box-border h44rpx w84rpx flex items-center justify-center border border-#F0F0F0 border-solid text-24rpx text-#AAAAAA"
                        >
                          {{ item.num }}
                        </view>
                        <image
                          :src="` ${StaticUrl}/add-cart.png`" class="h44rpx w44rpx"
                          @click.stop="handleAdd(item)"
                        />
                      </view>
                    </view>
                  </view>
                </view>
                <view
                  v-if="item.shopSkuStocks == '0' || item.isDelete == '1'"
                  class="absolute left-0 top-0 z-1 h-full w-full bg-[rgba(255,255,255,.6)]"
                >
                  <view class="relative w-full flex items-center justify-center">
                    <view class="rounded-16rpx bg-[rgba(0,0,0,.5)] p20rpx text-white">
                      {{ item.shopSkuStocks == '0' ? '商品已售罄' : '商品已删除' }}
                    </view>
                    <view class="absolute bottom-20rpx right-20rpx">
                      <wd-button @click="handleDelCartGoods(item)">
                        删除商品
                      </wd-button>
                    </view>
                  </view>
                </view>
              </view>
            </wd-checkbox-group>
          </view>
          <StatusTip v-if="!cartList.length" tip="暂无内容" />
          <view class="h320rpx" />
        </view>
      </view>
    </Zpopup>
    <selectSku
      v-model:show="selectGoods" v-model:sku-id="selectSkuId" v-model:select-goods-num="SelectGoodsNum"
      :goods-info="goodsInfo!"
    >
      <template #footer>
        <view class="box-border w-full flex items-center justify-between py20rpx">
          <view class="w-48%">
            <wd-button plain hairline block @click="selectGoods = false">
              取消
            </wd-button>
          </view>
          <view class="w-48%">
            <wd-button block @click="handleSkuAddCart">
              加入购物车
            </wd-button>
          </view>
        </view>
      </template>
    </selectSku>
    <view v-if="showball" class="ball">
      <image :src="`${StaticUrl}/cart-yes.png`" class="cart-img h52rpx w52rpx" />
    </view>
  </view>
</template>

<style scoped lang="scss">
.right-nav {
  background: linear-gradient(180deg, #FAFFEC 0%, #F6FFDE 11%, #E7FFA5 100%);
  box-shadow: -10rpx 0rpx 12rpx 2rpx rgba(0, 0, 0, 0.07);
}

.fixedShadow {
  box-shadow: 0rpx -6rpx 12rpx 2rpx rgba(0, 0, 0, 0.05);
}

.wraper {
  display: flex;
  height: calc(100vh - var(--window-top) - v-bind(navHeight) - 390rpx - var(--window-bottom));
  height: calc(100vh - var(--window-top) - constant(safe-area-inset-bottom) - v-bind(navHeight) - 390rpx - var(--window-bottom));
  height: calc(100vh - var(--window-top) - env(safe-area-inset-bottom) - v-bind(navHeight) - 390rpx - var(--window-bottom));
}

.content {
  flex: 1;
  background: #fff;

}

@keyframes moveX {
  to {
    transform: translateX(v-bind(x));
  }
}

@keyframes moveY {
  to {
    transform: translateY(v-bind(y));
  }
}

.ball {
  position: fixed;
  z-index: 80;
  left: v-bind(left);
  top: v-bind(top);
  animation: moveX .5s linear forwards;
}

.cart-img {
  animation: moveY .5s cubic-bezier(1, -1.26, 1, 1) forwards;
}
:deep(.wd-checkbox-group){
  background-color: transparent !important;
}
</style>
