<script setup lang="ts">
import selectSku from '../components/select-sku/index.vue'
import { StaticUrl } from '@/config'
import router from '@/router'

const { statusBarHeight, MenuButtonHeight } = useSysStore()
definePage({
  name: 'xsb-goods',
  islogin: false,
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '星闪豹商品详情',
  },
})
const selectGoods = ref(false)
const SelectGoodsNum = ref(1)
const specId = ref()
const { userInfo } = storeToRefs(useUserStore())
const { SelectShopInfo } = storeToRefs(useSysXsbStore())
const { getTotalNum } = storeToRefs(useSmqjhCartStore())
// const goodsTab = ref(0)
const current = ref<number>(0)
const currentDetaile = ref(0)
// const goodsTabList = ref([
//   { title: '相似商品', id: 0 },
//   { title: '经常一起买', id: 1 },
// ])
const goodsDetaileTabList = ref([
  { title: '商品', id: 0 },
  { title: '评价', id: 1 },
  { title: '详情', id: 2 },
  { title: '推荐', id: 3 },
])
const goodsTabData = ref([])
const isShowTab = ref(false)
// const currentTabGoods = ref(0)
const goodsId = ref()
onLoad((option: any) => {
  goodsId.value = option.id
  console.log(option, 'option====================')

  if (option.q) {
    const { id, storeId, channelId } = parseUrlParams(option.q)
    goodsId.value = id
    getGoodsDetaile(Number(storeId), Number(channelId))
  }
  else {
    getGoodsDetaile(option.storeId, option.channelId)
  }
})

const goodsInfo = ref<Api.xsbProductDetail>()
const isLoging = ref(false)

const swiperList = computed(() => {
  if (goodsInfo.value) {
    return goodsInfo.value.imgs?.split(',')
  }
  return []
})
const goodsContent = computed(() => {
  if (goodsInfo.value?.content) {
    return goodsInfo.value.content.replace(
      /<img/gi,
      '<img style="max-width:100%;height:auto" ',
    )
  }
  return '暂无数据'
})
onMounted(() => {
  // goodsTabData.value = splitArrayToPages([{ id: 1, name: '商品' }, { id: 2, name: '商品' }, { id: 3, name: '商品' }, { id: 4, name: '商品' }, { id: 8, name: '商品' }, { id: 5, name: '商品' }, { id: 10, name: '商品' }, { id: 6, name: '商品' }, { id: 9, name: '商品' }, { id: 7, name: '商品' }, { id: 11, name: '商品' }])

  console.log(goodsTabData.value, 'goodsTabData')
})
// function splitArrayToPages<T>(arr: T[]): T[][] {
//   const PAGE_SIZE = 6
//   const MAX_PAGES = 3
//   const result: T[][] = []
//   for (let i = 0; i < Math.min(MAX_PAGES, Math.ceil(arr.length / PAGE_SIZE)); i++) {
//     const start = i * PAGE_SIZE
//     const end = start + PAGE_SIZE
//     result.push(arr.slice(start, end))
//   }
//   return result
// }
onPageScroll((e) => {
  if (e.scrollTop >= 315) {
    isShowTab.value = true
  }
  else {
    isShowTab.value = false
  }
})
function handleGoCurren(id: number) {
  currentDetaile.value = id
  uni.pageScrollTo({ selector: `.view-${id}` })
}

async function getGoodsDetaile(shopId: number, channelId: number) {
  const res = await Apis.xsb.getProductDetail({ data: { id: goodsId.value, shopId: Number(SelectShopInfo.value?.shopId) || shopId || 2, channelId: userInfo.value.channelId || channelId || 1 } })
  console.log(res, '请求')
  if (!res.data) {
    useGlobalToast().show('暂无该商品查看权限！')
    return
  }
  goodsInfo.value = res.data
  specId.value = res.data.skuList?.[0].skuId
}
async function handleConfimOrder() {
  if (Number(unref(goodsInfo)?.spuStock) < unref(SelectGoodsNum)) {
    useGlobalToast().show('库存不足，请调整购买数量')
    return
  }
  await useUserStore().checkLogin()
  isLoging.value = true
  const res = await Apis.xsb.skuOrderConfirm({
    data: {
      skuId: specId.value,
      num: SelectGoodsNum.value,
      channelId: unref(userInfo).channelId,
      shopId: unref(goodsInfo)?.shopId || 2,
    },
  })
  if (Number(res.data.sku?.shopSkuStocks) < unref(SelectGoodsNum)) {
    useGlobalToast().show('库存不足，请调整购买数量')
    isLoging.value = false
    return
  }
  router.push({
    name: 'xsb-confirmOrder',
    params: { data: JSON.stringify({ ...res.data, skuList: [{ ...res.data.sku, num: SelectGoodsNum.value, shopId: unref(goodsInfo)?.shopId || 2 }] }) },
  })
  isLoging.value = false
}
async function handleAddCart() {
  if (Number(unref(goodsInfo)?.spuStock) < unref(SelectGoodsNum)) {
    useGlobalToast().show('库存不足，请调整购买数量')
    return
  }
  isLoging.value = true
  try {
    await useSmqjhCartStore().addCart(specId.value, unref(SelectGoodsNum), unref(SelectShopInfo.value.shopId || 2), 'XSB')
    selectGoods.value = false
    useGlobalToast().show('添加成功')
    isLoging.value = false
  }
  catch (error) {
    isLoging.value = false
    console.log(error)
  }
}
function handleClick() {
  uni.previewImage({ urls: swiperList.value as string[] })
}
</script>

<template>
  <page-meta :page-style="selectGoods ? 'overflow: hidden;' : '' " />
  <view class="page-xsb">
    <wd-navbar
      title="商品详情" :custom-style="`background-color:${isShowTab ? '#FFF !important' : 'transparent !important'}`" :bordered="false" :z-index="99"
      safe-area-inset-top left-arrow fixed @click-left="router.back()"
    />
    <template v-if="goodsInfo">
      <wd-swiper v-model:current="current" :list="swiperList" :autoplay="false" :height="375" @click="handleClick">
        <template #indicator="{ current: currentIndex, total }">
          <view class="custom-indicator absolute bottom-60rpx right-20rpx px26rpx">
            {{ currentIndex + 1 }}/{{ total }}
          </view>
        </template>
      </wd-swiper>
      <view class="view-0 header relative z-3 rounded-t-32rpx px24rpx pt24rpx -mt30rpx">
        <view class="flex items-center justify-between">
          <view class="flex items-end text-#FF4D3A font-semibold">
            <view class="text-24rpx">
              ￥
            </view>
            <view class="text-36rpx line-height-[36rpx]">
              {{ goodsInfo?.channelProdPrice }}
            </view>
          </view>
        <!-- <view>
          <image class="h40rpx w40rpx" :src="`${StaticUrl}/collect-yes.png`" />
        </view> -->
        </view>
      </view>
      <view class="sticky left-0 z-99 box-border h84rpx w-full flex items-center justify-between bg-white px24rpx" :style="{ top: `${statusBarHeight + MenuButtonHeight}px`, opacity: isShowTab ? 1 : 0 }" :class="[isShowTab ? '' : '']">
        <view v-for="item in goodsDetaileTabList" :key="item.id" class="relative flex items-center text-32rpx font-semibold" @click="handleGoCurren(item.id)">
          {{ item.title }}
          <view v-show="currentDetaile == item.id" class="line absolute left-50% h12rpx w40rpx rounded-8rpx bg-[var(--them-color)] -bottom-15rpx -translate-x-50%" />
        </view>
      </view>
      <view class="px24rpx">
        <view class="-mt64rpx">
          <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> -->
            {{ goodsInfo.prodName }}
          </view>
        </view>
        <!-- <view class="mt16rpx text-24rpx text-#AAAAAA">
        优选产地，皮薄核小，维c满满
      </view> -->
        <!-- <view class="mt20rpx flex items-center">
        <view
          v-for="item in 2" :key="item"
          class="mr16rpx flex items-center justify-center border-1rpx border-#BC9264 rounded-8rpx border-solid bg-[#FFF5E9] px16rpx py6rpx text-24rpx text-#BC9264 font-semibold"
        >
          一口化渣{{ item }}
        </view>
      </view> -->

        <view class="mt20rpx flex items-center justify-between rounded-16rpx bg-white p24rpx">
          <view class="flex items-center">
            <view class="flex-shrink-0">
              <view class="text-28rpx font-semibold">
                {{ goodsInfo.brandName }}
              </view>
              <view class="mt16rpx text-24rpx text-#AAAAAA">
                品牌
              </view>
            </view>
          </view>
          <view class="mx24rpx">
            <wd-divider vertical color="#F0F0F0" />
          </view>
          <view class="flex items-center">
            <view class="flex-shrink-0">
              <view class="text-28rpx font-semibold">
                {{ goodsInfo.skuList[0].weight }}g
              </view>
              <view class="mt16rpx text-24rpx text-#AAAAAA">
                重量
              </view>
            </view>
          </view>
          <view class="mx24rpx">
            <wd-divider vertical color="#F0F0F0" />
          </view>
          <view class="flex items-center">
            <view class="flex-shrink-0">
              <view class="text-28rpx font-semibold">
                {{ goodsInfo.skuList[0].weightUnit }}
              </view>
              <view class="mt16rpx text-24rpx text-#AAAAAA">
                单位
              </view>
            </view>
          </view>
          <wd-icon name="chevron-right" size="22px" color="#AAAAAA" />
        </view>
      <!-- <view class="view-1 mt20rpx flex items-center rounded-16rpx bg-white p24rpx">
        <view class="w-full flex items-center justify-between">
          <view class="text-32rpx font-semibold">
            评价（10万+）
          </view>
          <view class="flex items-center">
            <view class="mr10rpx flex items-center text-28rpx text-#FF4D3A">
              <view>好评率</view>
              <view class="ml5rpx font-semibold">
                99.8%
              </view>
            </view>
            <wd-icon name="chevron-right" size="22px" color="#AAAAAA" />
          </view>
        </view>
      </view> -->

      <!-- <view class="mt20rpx rounded-16rpx bg-white p24rpx">
        <wd-tabs v-model="goodsTab">
          <block v-for="item in goodsTabList" :key="item.id">
            <wd-tab :title="item.title" />
          </block>
        </wd-tabs>
        <swiper class="mt20rpx h900rpx" indicator-active-color="var(--them-color)" @change="(e) => currentTabGoods = e.detail.current">
          <swiper-item
            v-for="items in goodsTabData" :key="items"
            class="grid grid-cols-3 items-start gap-x-16rpx gap-y-16rpx pb20rpx"
          >
            <view
              v-for="goods in items" :key="goods"
              class="box-border w204rpx border border-2rpx border-#F0F0F0 rounded-16rpx border-solid px4rpx py8rpx"
            >
              <image lazy-load :src="`${StaticUrl}/shu.png`" class="h188rpx w198rpx" />
              <view class="mt20rpx px16rpx text-24rpx font-semibold">
                新鲜现宰杀肋排200g
              </view>
              <view class="mt12rpx truncate px16rpx text-24rpx text-#AAAAAA">
                维c满满，营养qweqwe
              </view>
              <view class="my20rpx flex items-center justify-between px16rpx">
                <view class="flex items-end text-#FF4D3A font-semibold">
                  <view class="text-24rpx">
                    ￥
                  </view>
                  <view class="text-32rpx line-height-[32rpx]">
                    1.395
                  </view>
                </view>
                <image :src="`${StaticUrl}/cart-yes.png`" class="h44rpx w44rpx" />
              </view>
            </view>
          </swiper-item>
        </swiper>
        <view class="mt24rpx flex items-center justify-center">
          <view v-for="item, idx in goodsTabData" :key="idx" class="mr14rpx transition-all transition-duration-400 ease-in" :class="[currentTabGoods == idx ? 'rounded-12rpx w-40rpx h12rpx bg-[var(--them-color)]' : 'w12rpx h12rpx rounded-50% bg-#F0F0F0']" />
        </view>
      </view> -->
      </view>

      <view class="view-2 mt20rpx bg-white">
        <view class="p24rpx text-32rpx font-semibold">
          商品详情
          <rich-text :nodes="goodsContent" />
        </view>
      </view>
      <!-- <view class="view-3 mt28rpx flex items-center justify-center">
      <view class="flex items-center">
        <image
          :src="`${StaticUrl}/goods-recommend.png`"
          class="mr12rpx h25rpx w26rpx"
        />
        <view class="text-36rpx text-[var(--them-color)] font-semibold">
          为你推荐
        </view>
        <image
          :src="`${StaticUrl}/goods-recommend.png`"
          class="ml12rpx h25rpx w26rpx"
        />
      </view>
    </view> -->
      <view class="h180rpx" />
      <view class="ios shadow-fixed fixed bottom-0 left-0 w-full rounded-t-32rpx bg-white">
        <view class="flex items-center justify-between px24rpx py20rpx">
          <view class="mr36rpx" @click="router.replace({ name: 'xsb-homeTabbar' })">
            <image
              :src="`${StaticUrl}/goods-home.png`"
              class="h44rpx w44rpx"
            />
            <view class="text-20rpx">
              首页
            </view>
          </view>
          <view class="relative mr36rpx">
            <image
              :src="`${StaticUrl}/goods-kf.png`"
              class="h44rpx w44rpx"
            />
            <Zcontact>
              <view class="text-20rpx">
                客服
              </view>
            </Zcontact>
          </view>
          <wd-badge :model-value="getTotalNum">
            <view @click="router.replace({ name: 'xsb-homeTabbar', animationType: 'fade-out', params: { name: 'xsb-cart' } })">
              <image
                :src="`${StaticUrl}/goods-cart.png`"
                class="h44rpx w44rpx"
              />
              <view class="text-20rpx">
                购物车
              </view>
            </view>
          </wd-badge>

          <view class="flex items-center">
            <view class="w220rpx">
              <wd-button hairline plain block @click="selectGoods = true">
                加入购物车
              </wd-button>
            </view>
            <view class="ml20rpx w220rpx" @click="selectGoods = true">
              <wd-button block class="w-full">
                立即购买
              </wd-button>
            </view>
          </view>
        </view>
      </view>
      <selectSku v-model:show="selectGoods" v-model:sku-id="specId" 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 :loading="isLoging" loading-color="#9ED605" @click="handleAddCart">
                加入购物车
              </wd-button>
            </view>
            <view class="w-48%">
              <wd-button block :loading="isLoging" loading-color="#9ED605" @click="handleConfimOrder">
                立即购买
              </wd-button>
            </view>
          </view>
        </template>
      </selectSku>
    </template>
  </view>
</template>

<style scoped lang="scss">
.custom-indicator {
  border-radius: 16rpx;
  background: rgba(0, 0, 0, 0.5);
  color: #ffffff;
  font-size: 24rpx;
}
.shadow-fixed{
  box-shadow: 0rpx -6rpx 12rpx 2rpx rgba(0,0,0,0.09);
}
.header {
  background: linear-gradient(180deg, #FFFFFF 0%, #FFFFFF 62%, #F6F6F6 100%);
}

.page-xsb {
  :deep() {
    .wd-tabs__nav-container .wd-tabs__nav-item:nth-child(2){
      width: 220rpx !important ;
    }
    .wd-tabs__nav-item {
      flex:unset !important;
      .wd-tabs__nav-item-text {
        font-size: 32rpx !important;
      }
    }
    .ios .wd-button{
      min-width: unset !important;
    }
    .wd-radio-group.is-button{
      padding: 0!important;
    }
  }
}
</style>
