<!-- 商品详情 -->
<template>
  <Navbar class="mb-3" />
  <div class="default-width pb-5" v-if="state.goodsInfo && Object.keys(state.goodsInfo).length">
    <v-card class="carousel border-radius-8 white-bgc pa-5" style="width: 100%;">
      <div class=" d-flex">
        <!-- 图片展示-轮播 -->
        <div style="width: 500px; height: 500px;">
          <div v-if="selectedSkuPicUrl" class="selectedSkuImgBox" @mouseover="showSelectedSkuImg = true" @mouseleave="showSelectedSkuImg = false">
            <v-img :src="selectedSkuPicUrl" :aspect-ratio="1" style="border-radius: 8px;"></v-img>
            <v-btn
              v-show="showSelectedSkuImg"
              size="x-small" 
              class="close px-3"
              @click="selectedSkuPicUrl = ''"
            >关闭</v-btn>
          </div>
          <v-carousel v-else show-arrows="hover" cycle :model-value="0" :hide-delimiters="!carouselHover" @mouseover="carouselHover = true" @mouseleave="carouselHover = false">
            <v-carousel-item v-for="(imgUrl, i) in state.goodsInfo.sliderPicUrls" :key="'wareImg'+i" @click="null">
              <v-img :src="imgUrl" :aspect-ratio="1" style="border-radius: 8px;"></v-img>
            </v-carousel-item>
          </v-carousel>
        </div>
        <!-- s-select-sku 商品属性选择 -->
        <div style="flex: 1;" class="pl-10">
          <!-- 大标题 -->
          <div class="title-name">{{ state.goodsInfo?.name || '--' }}</div>
          <!-- 小标题 -->
          <div class="title-introduction">{{ state.goodsInfo?.introduction || '--' }}</div>
          <!-- 价格 -->
          <div class="prices my-5">
            <div class="price mr-5"><span>￥</span>{{ selectedSkuPrice}}</div>
            <div class="marketPrice" v-if="selectedSkuMarketPrice && selectedSkuMarketPrice !== selectedSkuPrice">优惠前￥{{ selectedSkuMarketPrice}}</div>
          </div>
          <!-- 销量 -->
          <div class="salesCount mb-5 parameterColor"><span class="l-s-10">已售</span>：{{ state.goodsInfo?.salesCount || 0 }}</div>
          <!-- 属性选择组件 -->
          <selectSku
            v-if="showSelectSku"
            class="mb-7"
            :goodsInfo="state.goodsInfo"
            @change="onSkuChange"
            @buy="onBuy"
            @addCart="onAddCart"
          ></selectSku>
        </div>
      </div>
    </v-card>
    <!-- 详情描述 detail-content-card -->
    <v-card class="carousel border-radius-8 white-bgc pa-5 mt-3" style="width: 100%;">
      <div>
        <div class="mb-3">
          <v-tabs v-model="describeTab" align-tabs="start" color="primary" bg-color="#f7f8fa" @update:model-value="null">
            <v-tab :value="0">商品介绍</v-tab>
            <v-tab :value="1">商品评价</v-tab>
            <v-tab :value="2" v-if="(id-0)=== 648">房券抽奖活动</v-tab>
          </v-tabs>
        </div>
        <describe v-if="describeTab === 0 && state.goodsInfo?.description" :content="state.goodsInfo.description"></describe>
        <commentCard v-if="describeTab === 1 && state.goodsId" class="detail-comment-selector" :goodsId="state.goodsId" />
        <prizeDrawContent v-if="describeTab === 2" />
      </div>
    </v-card>
  </div>
  
  <!-- 快速登录 -->
  <loginPage v-if="showLogin" @loginSuccess="loginSuccess" @close="loginClose"></loginPage>

  <!-- 结算 -->
  <CtDialog :visible="showSettlement" titleClass="text-h6" :widthType="3" title="订单信息" @submit="handleSubmit" @close="handleClose">
    <confirm ref="confirmRef" :data="skuInfo" @orderCreated="orderCreated"></confirm>
  </CtDialog>
  
  <!-- 支付 -->
  <CtDialog :visible="showPay" titleClass="text-h6" :widthType="3" title="收银台" :footer="false" @close="payCancel">
    <pay ref="payRef" :id="payOrderId" @paySuccess="paySuccess"></pay>
  </CtDialog>
</template>

<script setup>
defineOptions({name: 'goods-details'})
import Navbar from '@/views/mall/components/navbar.vue'
import { getProductDetail } from '@/api/mall/product'
import { addCart } from '@/api/mall/cart'
import selectSku from './details/s-select-sku.vue'
import describe from './details/describe.vue'
import commentCard from './details/detail-comment-card.vue'
import prizeDrawContent from './details/prizeDrawContent.vue'
import confirm from './details/order/confirm.vue'
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import Snackbar from '@/plugins/snackbar'
import { getToken } from '@/utils/auth'
import loginPage from '@/views/common/loginDialog.vue'
import pay from '@/views/mall/components/details/order/pay.vue'

const router = useRouter()
const { id } = router.currentRoute.value.params

const describeTab = ref(2)
const selectedSkuPicUrl = ref('')
const selectedSkuPrice = ref('')
const selectedSkuMarketPrice = ref('')
const showSelectSku = ref(false)
const carouselHover = ref(false)
const showSelectedSkuImg = ref(false)
// 获取商品详情
const getData = async () => {
  const obj = await getProductDetail({ id })
  if (!obj) return Snackbar.warning('未找到商品!')
  //
  // 加载到商品
  obj.sliderPicUrls = obj.sliderPicUrls || []
  state.skeletonLoading = false;
  state.goodsInfo = obj
  showSelectSku.value = true
}
getData()

const calcPrice = (price) => { return price && (price-0) ? (price-0)/100 : '--' }

const state = reactive({
  goodsId: id || 0,
  skeletonLoading: true, // SPU 加载中
  goodsInfo: {}, // SPU 信息
  showSelectSku: false, // 是否展示 SKU 选择弹窗
  selectedSku: {}, // 选中的 SKU
  settlementSku: {}, // 结算的 SKU：由于 selectedSku 不进行默认选中，所以初始使用结算价格最低的 SKU 作为基础展示
  showModel: false, // 是否展示 Coupon 优惠劵的弹窗
  couponInfo: [], // 可领取的 Coupon 优惠劵的列表
  showActivityModel: false, // 【满减送/限时折扣】是否展示 Activity 营销活动的弹窗
  rewardActivity: {}, // 【满减送】活动
  activityList: [], // 【秒杀/拼团/砍价】可参与的 Activity 营销活动的列表
});

// 规格变更
function onSkuChange(e) {
  state.selectedSku = e;
  state.settlementSku = e;
  // console.log('onSkuChange:', e)
  selectedSkuPicUrl.value = state.selectedSku?.picUrl || ''
  if (selectedSkuPicUrl.value) showSelectedSkuImg.value = true
  selectedSkuPrice.value = calcPrice(state.selectedSku?.price || state.goodsInfo.price)
  selectedSkuMarketPrice.value = calcPrice(state.selectedSku?.marketPrice || state.goodsInfo.marketPrice)
}

const showSettlement = ref(false)
const skuInfo = ref(null) // 购买商品规格信息
const onBuy = async (e) => {
  if (!getToken()) return handleLogin()
  if (!e?.id) return Snackbar.warning('请选择商品规格!')
  // console.log('购买规格信息:', e)
  //
  skuInfo.value = JSON.stringify({
    items: [{ skuId: e.id, count: e.goods_num, categoryId: state.goodsInfo.categoryId, }]
  })
  showSettlement.value = true
}

// 创建订单完成
const payRef = ref()
const showPay = ref(false)
const payOrderId = ref('')
const orderCreated = (id) => {
  showSettlement.value = false
  payOrderId.value = id
  showPay.value = true
}
// 
const payCancel = () => {
  Snackbar.warning('您已取消支付！')
  showPay.value = false
  setTimeout(() => { router.push({ path: '/mall/user/order', query: { tab: 0 } }) }, 500);
}
const paySuccess = (e) => {
  // Snackbar.success('支付成功，请前往我的订单查看！')
  // showPay.value = false
  router.push({ path: '/mall/payOver', query: { price: e.price }})
}

// 添加购物车
const onAddCart = async (e) => {
  if (!getToken()) return handleLogin()
  if (!e.id) {
    Snackbar.warning('请选择商品规格')
    return;
  }
  await addCart({ skuId: e.id, count: e.goods_num })
  Snackbar.success('已添加到购物车~')
  // 刷新购物车列表
}

const confirmRef = ref()
const handleSubmit = () => {
  if (confirmRef.value) confirmRef.value.onConfirm()
}
const handleClose = () => {
  showSettlement.value = false
}

const showLogin = ref(false)
const handleLogin = () => {
  Snackbar.warning('您还未登录，请先登录后再试')
  showLogin.value = true // 打开快速登录弹窗
}

// 快速登录
const loginSuccess = () => {
  showLogin.value = false
  Snackbar.success('登录成功')
  // router.go(0)
}

const loginClose = () => {
  showLogin.value = false
  Snackbar.warning('您已取消登录')
}

</script>
<style lang="scss" scoped>
.border-radius-8 {
  border-radius: 8px;
}
.title-name {
  font-size: 24px;
  line-height: 1.25;
  color: #000;
  margin-bottom: 12px;
  font-weight: bold;
}
.title-introduction {
  font-size: 18px;
  line-height: 1.5;
  color: #6b6b6b;
}
.parameterColor {
  color: #7a7a7a;
}
.prices {
  display: flex;
  align-items: flex-end;
  color: #ff5000;
  font-size: 28px;
  margin: 8px 0;
}
.price {
  font-weight: 600;
  span {
    font-size: 16px;
  }
}
.marketPrice {
  color: #b7b7b7;
  font-size: 16px;
  line-height: 34px;
  // text-decoration: line-through;
}
.selectedSkuImgBox {
  position: relative;
  .close {
    position: absolute;
    bottom: 10px;
    right: 10px;
  }
}
</style>
