<template>
  <view class="Mall4j page-detail">
    <!-- 头部 -->
    <view
      class="det-header"
      :style="{
        opacity: topTabOpacity,
        zIndex: topTabOpacity > 0.2 ? '99' : '-1',
      }"
    >
      <view
        :class="[
          'item',
          topTabSts === 0 && pageScorllTop < heightList[1] && !scrolling
            ? 'active'
            : '',
        ]"
        @tap="onHanleTopTabClick(0)"
      >
        商品
      </view>
      <view
        v-if="shopId !== -1"
        :class="[
          'item',
          topTabSts === 1 ||
            (pageScorllTop > heightList[1] &&
              pageScorllTop < heightList[2] &&
              !scrolling)
            ? 'active'
            : '',
        ]"
        @tap="onHanleTopTabClick(1)"
      >
        评价
      </view>
      <view
        v-if="prodDetail"
        :class="[
          'item',
          topTabSts === 2 || (pageScorllTop > heightList[2] && !scrolling)
            ? 'active'
            : '',
        ]"
        @tap="onHanleTopTabClick(2)"
      >
        详情
      </view>
    </view>

    <!-- 商品视频 & 轮播图 -->
    <view class="video-container">
      <video
        v-if="video && isPlaying"
        id="myVideo"
        :enable-progress-gesture="false"
        objectFit="contain"
        :src="util.addDomain(video)"
        controls
        @ended="playEnd"
      />
      <view
        v-if="video"
        class="play-btn"
        @tap="videoOper"
      >
        <image
          v-if="!isPlaying"
          class="play-icon"
          src="/static/images/play-red.png"
        />
        <text
          v-if="isPlaying"
          :class="'play-text ' + (isPlaying ? 'video-stop' : 'video-play')"
        >
          {{ isPlaying ? '退出播放' : '' }}
        </text>
      </view>
      <!-- 轮播图 -->
      <swiper
        v-if="!isPlaying"
        class="pic-box"
        indicator-dots
        indicator-color="rgba(255,252,255, .3)"
        indicator-active-color="rgba(255,252,255, .6)"
        autoplay
        circular
      >
        <block v-if="imgList?.length">
          <swiper-item
            v-for="(img, imgIdx) in imgList"
            :key="imgIdx"
            class="item"
          >
            <!-- <image :src="img" mode="aspectFit" /> -->
            <img-show
              :src="img"
              img-mode="aspectFit"
            />
          </swiper-item>
        </block>
        <block v-else>
          <swiper-item class="item">
            <!-- <image mode="aspectFit" src="/static/images/def.png" /> -->
          </swiper-item>
        </block>
      </swiper>
    </view>

    <!-- 商品视频 & 轮播图 end -->

    <!-- 直播悬浮按钮 -->
    <view
      v-if="liveRoomParams"
      class="live"
      :data-roomid="liveRoomParams.roomId"
      :data-userid="liveRoomParams.userId"
      @tap="toLivePage"
    >
      <rhythm-beat />
      <view class="live-txt">
        {{ $t('inLive') }}
      </view>
    </view>

    <!-- 预售时间 -->
    <countdown-bar
      v-if="((preSaleType===0&&!isActivityGoods)||preSaleType===1)&&activityGoodsLoad"
      :prod-id="spuId/1"
      :prod-type="preSaleType===0?0:3"
      :activity-info="{}"
      :pre-sell-time="preSaleDeliveryType===-1?preSellTimeShowHandler(preSaleDeliveryTime):'付款成功'+preSaleDeliveryType+'天后'"
      :is-refresh-page="false"
    />

    <!-- 活动信息条 -->
    <view
      v-if="isActivityGoods&&activityGoodsLoad"
      class="activity-bar"
    >
      <view class="bar-left">
        <view class="price-box">
          <view class="dis-price">
            <view class="price">
              <view class="symbol">
                ￥
              </view>
              <view class="big">
                {{
                  wxs.parsePrice(
                    defaultActivitySku.seckillPrice || defaultActivitySku.priceFee
                  )[0]
                }}
              </view>
              <view
                class="symbol"
              >
                .{{
                  wxs.parsePrice(
                    defaultActivitySku.seckillPrice ||
                      defaultActivitySku.priceFee
                  )[1]
                }}
              </view>
            </view>
            <view
              v-if="
                prodInfo.spuType === prodTypeConstant.GROUP &&
                  defaultActivitySku.marketPriceFee > defaultActivitySku.priceFee
              "
              class="dis-number"
            >
              直降{{
                wxs.parsePrice(
                  defaultActivitySku.marketPriceFee -
                    defaultActivitySku.priceFee
                )[0]
              }}.{{
                wxs.parsePrice(
                  defaultActivitySku.marketPriceFee -
                    defaultActivitySku.priceFee
                )[1]
              }}元
            </view>
            <view
              v-if="
                defaultActivitySku.priceFee > defaultActivitySku.seckillPrice
              "
              class="dis-number"
            >
              直降{{
                wxs.parsePrice(
                  defaultActivitySku.priceFee - defaultActivitySku.seckillPrice
                )[0]
              }}.{{
                wxs.parsePrice(
                  defaultActivitySku.priceFee - defaultActivitySku.seckillPrice
                )[1]
              }}元
            </view>
          </view>
          <view
            v-if="
              (defaultActivitySku.priceFee > defaultActivitySku.seckillPrice &&
                prodInfo.spuType === prodTypeConstant.SECOND) ||
                (defaultActivitySku.marketPriceFee >
                  defaultActivitySku.priceFee &&
                  prodInfo.spuType === prodTypeConstant.GROUP)
            "
            class="old-price"
          >
            <view>原价：</view>
            <view
              v-if="prodInfo.spuType === prodTypeConstant.GROUP"
              class="price"
            >
              ￥{{ wxs.parsePrice(defaultActivitySku.marketPriceFee)[0] }}.{{
                wxs.parsePrice(defaultActivitySku.marketPriceFee)[1]
              }}
            </view>
            <view
              v-else
              class="price"
            >
              ￥{{ wxs.parsePrice(defaultActivitySku.priceFee)[0] }}.{{
                wxs.parsePrice(defaultActivitySku.priceFee)[1]
              }}
            </view>
          </view>
        </view>
        <view
          v-if="prodInfo.spuType === prodTypeConstant.SECOND"
          class="sold"
        >
          <view
            class="text"
          >
            已出售{{
              (
                ((seckillActInfo.seckillOriginStocks -
                  seckillActInfo.seckillTotalStocks) /
                  seckillActInfo.seckillOriginStocks) *
                100
              ).toFixed(0)
            }}%
          </view>
          <view class="progress-bar">
            <view
              class="bar"
              :style="{
                width: `${
                  ((seckillActInfo.seckillOriginStocks -
                    seckillActInfo.seckillTotalStocks) /
                    seckillActInfo.seckillOriginStocks) *
                  100
                }%`,
              }"
            />
          </view>
        </view>
      </view>
      <view class="time-box">
        <!-- 秒杀活动状态提示 -->
        <view
          v-if="
            prodInfo.spuType === prodTypeConstant.SECOND &&
              seckillActInfo.activityStatus !== 3
          "
          class="text"
        >
          距离{{
            seckillActInfo.activityStatus === 2 ? '结束' : '开始'
          }}还有
        </view>
        <!-- 团购活动状态提示 -->
        <view
          v-if="
            prodInfo.spuType === prodTypeConstant.GROUP &&
              groupActInfo.status !== 5
          "
          class="text"
        >
          距离{{
            groupActInfo.activityStatus === 2 ? '结束' : '开始'
          }}还有
        </view>
        <!-- 活动结束提示 -->
        <view
          v-if="
            prodInfo.spuType === prodTypeConstant.NORMAL &&
              (seckillActInfo.activityStatus === 3 || groupActInfo.status === 5)
          "
          class="text"
        >
          活动已结束
        </view>
        <view class="time">
          <view
            v-if="countDownInfo.day !== '00'"
            class="num"
          >
            {{
              countDownInfo.day
            }}
          </view>
          <view
            v-if="countDownInfo.day !== '00'"
            class="colon"
          >
            天
          </view>
          <view class="num">
            {{ countDownInfo.hour }}
          </view>
          <view class="colon">
            :
          </view>
          <view class="num">
            {{ countDownInfo.min }}
          </view>
          <view class="colon">
            :
          </view>
          <view class="num">
            {{ countDownInfo.sec }}
          </view>
        </view>
      </view>
    </view>

    <!-- 名称、价格 -->
    <view
      v-if="prodInfo"
      class="name-box"
    >
      <view class="name">
        {{ prodInfo.spuName }}
      </view>
      <view
        v-if="prodInfo.sellingPoint"
        :class="['prod-brief','integral','weixin-prod-brief',briefUnfold?'brief-unfold':'']"
        @tap="briefUnfold=!briefUnfold"
      >
        {{ prodInfo.sellingPoint }}
        <view
          v-if="!briefUnfold&&briefUnfoldUnfoldShow"
          class="right"
        >
          <view class="cmt-more" />
        </view>
        <!-- <text class="text-arrow">更多</text> -->
      </view>
      <view class="action-box">
        <view
          v-if="defaultSku"
          style="flex:1"
        >
          <view
            class="price-box"
            :class="{ activitys: isActivityGoods }"
          >
            <view
              v-if="!isActivityGoods"
              class="price"
            >
              <view class="symbol">
                ￥
              </view>
              <view class="big">
                {{
                  wxs.parsePrice(defaultSku.priceFee)[0]
                }}
              </view>
              <view
                class="symbol"
              >
                .{{ wxs.parsePrice(defaultSku.priceFee)[1] }}
              </view>
              <view
                v-if="
                  defaultSku.priceFee
                    &&defaultSku.marketPriceFee
                    &&defaultSku.marketPriceFee>defaultSku.priceFee"
                class="marketPriceFee"
              >
                {{ wxs.parsePrice(defaultSku.marketPriceFee)[0]+'.'+wxs.parsePrice(defaultSku.marketPriceFee)[1] }}
              </view>
            </view>
            <view
              v-if="
                isActivityGoods && prodInfo.spuType === prodTypeConstant.GROUP
              "
              class="activity-icon"
            >
              {{ groupActInfo.groupNumber }}人团
            </view>
            <!-- 预售icon -->
            <!-- <view v-if="(preSaleType===0&&!isActivityGoods)||preSaleType===1" class="presale-icon">
              预售
            </view> -->
            <!-- <view class="activity-icon" v-if="isActivityGoods">限时秒杀</view>  -->
            <view
              v-if="seckillActInfo && seckillActInfo.activityStatus === 2"
              class="stock only-left"
            >
              仅剩 {{ seckillActInfo.seckillTotalStocks }} 件
            </view>
            <view
              v-else
              class="stock only-left"
            >
              仅剩 {{ prodInfo.totalStock }} 件
            </view>
            <view
              v-if="
                findSku &&
                  (seckillActInfo.maxNum > 0 ||
                    (groupActInfo.maxNum > 0 && groupActInfo.hasMaxNum === 1)) &&
                  (seckillActInfo.activityStatus === 2 ||
                    groupActInfo.activityStatus === 2)
              "
              class="stock"
            >
              ，限购 {{ seckillActInfo.maxNum || groupActInfo.maxNum }} 件
            </view>
          </view>
          <view
            v-if="(preSaleType===0&&isActivityGoods)"
            class="price-box presale"
          >
            <view class="presale-icon">
              全款预售
            </view>
            <view class="stock only-left">
              预计{{ preSaleDeliveryType===-1?preSaleDeliveryTime:'付款成功'+preSaleDeliveryType+'天后' }}发货
            </view>
          </view>
        </view>
      </view>

      <view
        v-if="preSaleType===1"
        class="presale-price"
      >
        定金
        <view
          v-if="!isActivityGoods"
          class="price"
        >
          <view class="symbol">
            ￥
          </view>
          <view class="big">
            {{ wxs.parsePrice(defaultSku.depositAmount)[0] }}
          </view>
          <view class="symbol">
            .{{ wxs.parsePrice(defaultSku.depositAmount)[1] }}
          </view>
        </view>
        <view
          v-if="defaultSku.depositExpansionAmount&&defaultSku.depositExpansionAmount>defaultSku.depositAmount"
          class="price-tab"
        >
          可抵￥{{ wxs.parsePrice(defaultSku.depositExpansionAmount)[0] }}.{{ wxs.parsePrice(defaultSku.depositExpansionAmount)[1] }}
        </view>
      </view>
    </view>

    <!-- 分享and收藏 -->

    <view class="share-collect">
      <view
        class="left"
        @tap="sharePopupShow=true;shareType=1"
      >
        <image
          class="icon"
          src="/static/images/icon_share.png"
        />
        <view
          class="font-text"
        >
          分享
        </view>
      </view>

      <view
        class="right"
        @tap="onCollectGoods"
      >
        <image
          v-if="!isCollect"
          class="icon"
          src="/static/images/collection2.png"
        />
        <image
          v-if="isCollect"
          class="icon"
          src="/static/images/Have-collected.png"
        />
        <view
          class="font-text"
        >
          {{ isCollect?'已收藏':'收藏' }}
        </view>
      </view>
    </view>

    <!--  定金预售商品预售步骤条 -->
    <view
      v-if="preSaleType===1"
      class="presale-steps"
    >
      <view class="title">
        预售流程
      </view>
      <Steps
        :options="[{title: '付定金'}, {title: '付尾款'}, {title: '发货'}]"
        :active="null"
        active-icon="checkbox"
      />
      <view class="tip">
        支付尾款:{{ balanceStartTime }}-{{ balanceEndTime }}
        <block v-if="preSaleDeliveryType===-1">
          , {{ preSaleDeliveryTime.split(' ')[0].replace(/\-/g, '.') }}后发货
        </block>
        <block v-else>
          ,尾款支付 {{ preSaleDeliveryType }}天后发货
        </block>
      </view>
    </view>

    <!-- 优惠、活动 -->
    <view
      v-if="prodInfo.spuType !== prodTypeConstant.SECOND && (couponList?.length || prodDiscountList?.length || giveawayList?.length) && shopId !== -1"
      class="det-con"
    >
      <view
        v-if="couponList?.length"
        class="item"
      >
        <view class="tit">
          领券
        </view>
        <view
          class="con coupons-con"
          @tap="onShowCouponPopup"
        >
          <block
            v-for="(couponItem, couponIdx) in couponList.slice(0, 2)"
            :key="couponIdx"
          >
            <view class="c-item">
              <text
                v-if="couponItem.couponType === 1"
              >
                满{{ wxs.parsePrice(couponItem.cashCondition)[0] }}.{{
                  wxs.parsePrice(couponItem.cashCondition)[1]
                }}元减{{ wxs.parsePrice(couponItem.reduceAmount)[0] }}.{{
                  wxs.parsePrice(couponItem.reduceAmount)[1]
                }}元
              </text>
              <text
                v-if="couponItem.couponType === 2"
              >
                满{{ wxs.parsePrice(couponItem.cashCondition)[0] }}.{{
                  wxs.parsePrice(couponItem.cashCondition)[1]
                }}元打{{ couponItem.couponDiscount }}折
              </text>
            </view>
          </block>
        </view>
      </view>
      <view
        v-if="prodDiscountList?.length || giveawayList?.length"
        class="item"
      >
        <view class="tit">
          优惠
        </view>
        <view
          class="con discount-con"
          @tap="onShowDiscountPopup"
        >
          <block
            v-for="(discountItem, discountIndex) in prodDiscountList.slice(
              0,
              2
            )"
            :key="discountIndex"
          >
            <view class="d-item">
              <text class="d-tag">
                {{
                  discountItem.discountRule === 0 ? '满减' : '满折'
                }}
              </text>
              <text
                class="d-name"
              >
                {{ discountItem.discountName }}，最多优惠{{
                  wxs.parsePrice(discountItem.maxReduceAmount)[0]
                }}.{{ wxs.parsePrice(discountItem.maxReduceAmount)[1] }}
              </text>
            </view>
          </block>
          <block
            v-for="(item, index) in giveawayList"
            :key="index"
          >
            <view class="d-item">
              <text class="d-tag">
                赠品
              </text>
              <text
                class="d-name"
                decode
              >
                {{ item.spuName + '&nbsp;&nbsp;' }}
                <text
                  v-if="item.skuName"
                  decode
                >
                  {{
                    item.skuName + '&nbsp;&nbsp;'
                  }}
                </text>
                x{{ item.giveawayNum }}
              </text>
            </view>
          </block>
        </view>
      </view>
    </view>

    <!-- sku、配送 -->
    <view
      v-if="shopId !== -1"
      class="det-con"
    >
      <view class="item">
        <view class="tit">
          已选
        </view>
        <view
          class="con sku-con"
          @tap="onHandleShowSkuPop(2)"
        >
          <view class="s-item">
            <block
              v-for="(skuItem, skuIndex) in selectedPropShowNew"
              :key="skuIndex"
            >
              <text decode>
                {{
                  skuIndex < selectedPropShowNew?.length - 1
                    ? skuItem + '，'
                    : skuItem + '&nbsp; &nbsp;'
                }}
              </text>
            </block>
            {{ prodNumber }} 件
          </view>
        </view>
      </view>
      <view
        v-if="prodInfo.spuType !== prodTypeConstant.ACTIVITY"
        class="item"
      >
        <view class="tit">
          配送
        </view>
        <view class="con distribution-con">
          <block v-if="(spuMold===0 || spuMold===2)">
            <view class="dis-item">
              <view class="dis-item-icon" />快递配送
            </view>
            <view
              v-if="isCityDelivery && deliveryModeVO.hasCityDelivery"
              class="dis-item"
            >
              <view class="dis-item-icon" />同城配送
            </view>
            <view
              v-if="deliveryModeVO.hasUserPickUp"
              class="dis-item"
            >
              <view class="dis-item-icon" />门店自提
            </view>
          </block>
          <view
            v-if="spuMold===1"
            class="dis-item"
          >
            <view class="dis-item-icon" />无需配送
          </view>
        </view>
      </view>
      <!-- 不支持配送 -->
      <view
        v-if="deliveryAddrInfo && (spuMold===0 || spuMold===2) && prodInfo.spuType !== prodTypeConstant.ACTIVITY"
        class="item"
        @tap="onChangeAddr"
      >
        <view class="tit">
          快递
        </view>
        <view class="delivery-con">
          <view
            v-if="!isDelivery"
            class="delivery-tip"
          >
            不支持配送该地址
          </view>
          <view class="addr-tip">
            配送至: {{ deliveryAddrInfo.province }} {{ deliveryAddrInfo.city }} {{ deliveryAddrInfo.area }} {{ deliveryAddrInfo.addr }}
          </view>
        </view>
      </view>
    </view>

    <!-- 优惠套装列表 -->
    <view
      v-if="comboList?.length>0&&prodInfo.spuType !== prodTypeConstant.SECOND"
      class="discount-package"
    >
      <view
        class="discount-package-title"
      >
        优惠套餐
        <text class="discount-package-title-fu">
          （共{{ comboList?.length }}个）
        </text>
      </view>
      <view class="discount-package-concent">
        <scroll-view scroll-x>
          <view class="discount-package-scroll">
            <view
              v-for="(item, index) in comboList"
              :key="index"
              class="discount-package-item"
              @tap="onToDiscountPackageDetail(item.comboId)"
            >
              <!-- <image mode="aspectFit" :src="item.mainSpu.pic" class="main-image" /> -->
              <view class="main-image">
                <img-show
                  :src="item.mainSpu.pic"
                  img-mode="aspectFit"
                  :class-list="['main-image']"
                />
              </view>
              <view
                v-if="item.matchingSpus?.length"
                class="addFu"
              >
                +
              </view>
              <view
                v-if="item.matchingSpus?.length"
                class="fu-prod"
              >
                <!-- <image :src="item.matchingSpus[0].pic" mode="aspectFit" class="sli-image" /> -->
                <img-show
                  :src="item.matchingSpus[0].pic"
                  img-mode="aspectFit"
                  :class-list="['main-image']"
                />
              </view>
              <view class="discountPackageProd-detail">
                <text>
                  套餐<text class="yuan-number">
                    {{ index + 1 }}
                  </text>,共{{ item.spuCount }}件
                </text>
                <text class="price">
                  ￥{{ item.price/100 }}
                </text>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>
    </view>
    <!-- 优惠套装列表end -->

    <!-- 进行中的拼团、拼团玩法 -->
    <view
      v-if="isActivityGoods && canJionGroupList?.length && !canJionGroupFlag"
      class="det-con group-box"
    >
      <view class="g-tit">
        正在进行的拼团，可直接参与
      </view>
      <view class="g-con">
        <view
          v-for="(groupItem, groupIndex) in canJionGroupList"
          :key="groupIndex"
          class="item"
        >
          <block v-if="groupItem.endOfGroupTime.signs">
            <view class="img">
              <image
                :src="util.checkFileUrl(groupItem.sharePic) || '/static/images/head-sculpture.png'"
                @error="canJionGroupList[groupIndex].sharePic =''"
              />
            </view>
            <view class="text">
              <view class="name">
                {{ groupItem.shareNickName }}
              </view>
              <view class="num-time">
                <view
                  class="num"
                >
                  还差{{ groupItem.groupNumber - groupItem.joinNum }}人成团
                </view>
                <view
                  class="time"
                >
                  ，剩余
                  <text v-if="groupItem.endOfGroupTime.day !== '00'">
                    {{
                      groupItem.endOfGroupTime.day
                    }}
                  </text>{{
                    `${groupItem.endOfGroupTime.hou}:${groupItem.endOfGroupTime.min}:${groupItem.endOfGroupTime.sec}`
                  }}
                </view>
              </view>
            </view>
            <view
              class="btn"
              @tap="onToGroupDet(groupItem.groupTeamId)"
            >
              去参团
            </view>
          </block>
        </view>
      </view>
      <view
        class="rule"
        @tap="onToGroupRules"
      >
        <view class="tit">
          玩法
        </view>
        <view class="text-arrow">
          开团/参团 - 邀请好友 - 人满成团/不满退款
        </view>
      </view>
    </view>

    <!-- 评论 -->
    <view
      v-if="shopId !== -1"
      class="comment-box"
    >
      <view class="c-tit">
        <view class="text">
          <view class="big">
            评价
          </view>
          <view class="small">
            {{ commentData.number || 0 }}
          </view>
        </view>
        <view
          class="more text-arrow"
          @tap="onShowCommentPopup"
        >
          好评率 {{ commentData.positiveRating || 0 }} %
        </view>
      </view>
      <scroll-view
        scroll-x
        class="c-tags"
        @tap="onShowCommentPopup"
      >
        <view class="item">
          全部({{ commentData.number || 0 }})
        </view>
        <view class="item">
          好评({{ commentData.praiseNumber || 0 }})
        </view>
        <view class="item">
          中评({{ commentData.secondaryNumber || 0 }})
        </view>
        <view class="item">
          差评({{ commentData.negativeNumber || 0 }})
        </view>
        <view class="item">
          有图({{ commentData.picNumber || 0 }})
        </view>
      </scroll-view>
      <view class="c-con">
        <block
          v-for="(commentItem, commentIdx) in commentList"
          :key="commentIdx"
        >
          <view
            v-if="commentIdx < 2"
            class="item"
          >
            <view class="user-box">
              <view class="info">
                <view class="img">
                  <image
                    style="border-radius: 20rpx"
                    :src=" commentItem.userPic? util.addDomain(commentItem.userPic): '/static/images/head-sculpture.png'"
                    @error="commentList[commentIdx].userPic = ''"
                  />
                </view>
                <view
                  class="text"
                  style="margin-left: 20rpx"
                >
                  <view class="name">
                    {{
                      commentItem.isWriteOff ?
                        '账号已注销' :
                        (commentItem.isAnonymous === 1
                          ? '匿名用户'
                          : commentItem.nickName)
                    }}
                  </view>
                  <view
                    v-if="commentItem.skuName"
                    class="sku-name"
                  >
                    {{
                      commentItem.skuName
                    }}
                  </view>
                </view>
              </view>
              <view class="time">
                {{ commentItem.createTime }}
              </view>
            </view>
            <view class="stars">
              <block
                v-for="redStars in commentItem.score"
                :key="redStars"
              >
                <view class="star">
                  <image src="/static/images/collect-r.png" />
                </view>
              </block>
              <view
                v-for="grayStars in 5 - commentItem.score"
                :key="grayStars"
              >
                <view class="star">
                  <image src="/static/images/collect-g.png" />
                </view>
              </view>
            </view>
            <view class="comment-text">
              {{ commentItem.content }}
            </view>
            <block v-if="commentItem.pics">
              <view class="comment-img">
                <scroll-view
                  scroll-x
                  class="img-box"
                >
                  <view
                    v-for="(commentImg, imgIdx) in commentItem.pics"
                    :key="imgIdx"
                    class="img"
                    @tap="onPreviewCommentImage(commentItem.pics, imgIdx)"
                  >
                    <img-show :src="commentImg" />
                  </view>
                </scroll-view>
              </view>
            </block>
          </view>
        </block>
      </view>
      <view
        v-if="commentList?.length"
        class="c-btn"
      >
        <view
          class="view-all text-arrow"
          @tap="onShowCommentPopup"
        >
          查看全部评价
        </view>
      </view>
    </view>

    <!-- 店铺 -->
    <view
      v-if="shopId !== -1"
      class="shop-box"
    >
      <view
        class="shop-info"
        @tap="onToShopIndex"
      >
        <view class="info">
          <view class="img">
            <image
              :src="
                shopInfo.shopLogo
                  ? util.addDomain(shopInfo.shopLogo)
                  : '/static/images/default-shop-logo.png'
              "
              @error="shopInfo.shopLogo=''"
            />
          </view>
          <view class="text">
            <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>
        <view class="go-shop">
          进店逛逛
        </view>
      </view>
      <view
        v-if="false"
        class="shop-recommend"
      >
        <view class="prods">
          <scroll-view
            scroll-x
            class="prods-box"
          >
            <view class="item">
              <view class="img">
                <image src="/static/img/goods-12.png" />
              </view>
              <view class="text-box">
                <view class="name">
                  iphone 11 pro max 银色256g手机
                </view>
                <view class="price-box">
                  <view class="price">
                    <view class="symbol">
                      ￥
                    </view>
                    <view class="big">
                      10899
                    </view>
                    <view class="symbol">
                      .00
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="item">
              <view class="img">
                <image src="/static/img/goods-12.png" />
              </view>
              <view class="text-box">
                <view class="name">
                  iphone 11 pro max 银色256g手机
                </view>
                <view class="price-box">
                  <view class="price">
                    <view class="symbol">
                      ￥
                    </view>
                    <view class="big">
                      10899
                    </view>
                    <view class="symbol">
                      .00
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="item">
              <view class="img">
                <image src="/static/img/goods-12.png" />
              </view>
              <view class="text-box">
                <view class="name">
                  iphone 11 pro max 银色256g手机
                </view>
                <view class="price-box">
                  <view class="price">
                    <view class="symbol">
                      ￥
                    </view>
                    <view class="big">
                      10899
                    </view>
                    <view class="symbol">
                      .00
                    </view>
                  </view>
                </view>
              </view>
            </view>
            <view class="item">
              <view class="img">
                <image src="/static/img/goods-12.png" />
              </view>
              <view class="text-box">
                <view class="name">
                  iphone 11 pro max 银色256g手机
                </view>
                <view class="price-box">
                  <view class="price">
                    <view class="symbol">
                      ￥
                    </view>
                    <view class="big">
                      10899
                    </view>
                    <view class="symbol">
                      .00
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </scroll-view>
        </view>
      </view>
    </view>

    <!-- 详情 -->
    <div
      v-show="prodDetail"
      class="det-det"
    >
      <div class="tit">
        商品详情
      </div>
      <div class="con">
        <uv-parse :content="prodDetail" />
      </div>
    </div>

    <!-- 不支持配送地区提示框 -->
    <div
      v-if="(spuMold===0 || spuMold===2) && !isDelivery"
      class="delivery-box"
    >
      <div class="tit">
        此商品不支持在当前地区配送
      </div>
      <div
        class="btn"
        @tap="onChangeAddr"
      >
        更改地址
      </div>
    </div>

    <!-- 底部 -->
    <view class="det-foot">
      <view class="actions">
        <view
          class="item"
          @tap="onToIndex"
        >
          <view class="img">
            <image src="/static/images/detail-index.png" />
          </view>
          <view class="text">
            首页
          </view>
        </view>
        <view
          class="item"
          @tap="onToCart"
        >
          <view class="img">
            <image src="/static/images/detail-cart.png" />
            <view
              v-if="cartCount"
              class="mark"
            >
              {{
                cartCount > 99 ? '99+' : cartCount
              }}
            </view>
          </view>
          <view class="text">
            购物车
          </view>
        </view>
        <view
          v-if="prodInfo.spuType !== prodTypeConstant.ACTIVITY"
          class="item"
          @tap="onHandleCustomService"
        >
          <view class="img">
            <image src="/static/images/detail-service.png" />
          </view>
          <view class="text">
            客服
          </view>
        </view>
      </view>
      <view
        v-if="activityGoodsLoad"
        class="btns"
      >
        <block v-if="preSaleType===1">
          <view
            v-if="PayDepositStatus===0"
            class="btn btn-r pay-deposit pay-deposit-disabled"
          >
            <view>
              <view>支付定金(未开始)</view>
              <view class="price">
                <view class="symbol">
                  ￥
                </view>
                <view class="big">
                  {{ wxs.parsePrice(defaultSku.depositAmount*prodNumber)[0] }}
                </view>
                <view class="symbol">
                  .{{ wxs.parsePrice(defaultSku.depositAmount*prodNumber)[1] }}
                </view>
              </view>
            </view>
          </view>
          <view
            v-if="PayDepositStatus===1"
            class="btn btn-r pay-deposit "
            @tap="onHandleShowSkuPop(1,'buy')"
          >
            <view>
              <view>支付定金</view>
              <view class="price">
                <view class="symbol">
                  ￥
                </view>
                <view class="big">
                  {{ wxs.parsePrice(defaultSku.depositAmount*prodNumber)[0] }}
                </view>
                <view class="symbol">
                  .{{ wxs.parsePrice(defaultSku.depositAmount*prodNumber)[1] }}
                </view>
              </view>
            </view>
          </view>
          <view
            v-if="PayDepositStatus===2"
            class="btn btn-r pay-deposit"
            @tap="onToShopIndex"
          >
            <view>
              <view>活动已结束</view>
              <view>查看店铺其他活动</view>
            </view>
          </view>
        </block>
        <block v-else>
          <view
            v-if="(prodInfo.spuType !== prodTypeConstant.ACTIVITY && !isActivityGoods || groupActInfo.activityStatus===1)"
            class="btn"
            @tap="onHandleShowSkuPop(1,'add')"
          >
            加入购物车
          </view>
          <!-- 秒杀未开始的按钮 -->
          <view
            v-if="
              (prodInfo.spuType !== prodTypeConstant.ACTIVITY &&
                !isActivityGoods) ||
                seckillActInfo.activityStatus === 1 ||
                groupActInfo.activityStatus === 1
            "
            class="btn btn-r"
            @tap="onHandleShowSkuPop(1,'buy')"
          >
            {{ seckillActInfo.activityStatus===1? '原价购买' : '立即购买' }}
          </view>
          <!-- 团购商品的 原价购买 -->
          <view
            v-if="
              isActivityGoods &&
                prodInfo.spuType === prodTypeConstant.GROUP &&
                groupActInfo.activityStatus === 2
            "
            class="btn"
            @tap="onHandleShowSkuPop(2)"
          >
            <view class="price">
              <text>￥</text>
              <text class="big">
                {{
                  wxs.parsePrice(defaultActivitySku.marketPriceFee)[0]
                }}
              </text>
              <text>.{{ wxs.parsePrice(defaultActivitySku.marketPriceFee)[1] }}</text>
            </view>
            <view class="text">
              原价购买
            </view>
          </view>
          <view
            v-if="
              isActivityGoods &&
                (groupActInfo.activityStatus === 2 ||
                  seckillActInfo.activityStatus === 2)
            "
            :class="[
              'btn btn-r',
              seckillActInfo.activityStatus === 1 ||
                groupActInfo.activityStatus === 1
                ? 'gary'
                : '',
            ]"
            @tap="onHandleShowActivitySku"
          >
            <view class="price">
              <text>￥</text>
              <text class="big">
                {{
                  wxs.parsePrice(
                    defaultActivitySku.seckillPrice
                      ? defaultActivitySku.seckillPrice
                      : defaultActivitySku.priceFee
                  )[0]
                }}
              </text>
              <text>
                .{{
                  wxs.parsePrice(
                    defaultActivitySku.seckillPrice
                      ? defaultActivitySku.seckillPrice
                      : defaultActivitySku.priceFee
                  )[1]
                }}
              </text>
            </view>
            <view class="text">
              {{
                prodInfo.spuType === prodTypeConstant.GROUP
                  ? '我要开团'
                  : '立即秒杀'
              }}
            </view>
          </view>
          <!-- 活动商品不可购买 -->
          <view
            v-if="prodInfo.spuType === prodTypeConstant.ACTIVITY"
            class="btn btn-r gary"
          >
            {{ shopId !== -1 ? '活动商品不可购买' : '不可购买' }}
          </view>
        </block>
      </view>
      <!-- 骨架屏：页面加载时占位使用 start-->
      <view
        v-else
        class="btns"
      >
        <view class="btn">
          加入购物车
        </view>
        <view class="btn btn-r">
          立即购买
        </view>
      </view>
      <!-- 骨架屏：页面加载时占位使用 end-->
    </view>

    <!-- 分享弹窗 -->
    <view
      v-if="shareShow"
      class="promo-share"
    >
      <image
        v-if="picture&&showCanvasImg"
        class="picture-img"
        :src="picture"
      />
      <l-painter
        ref="painterRef"
        :board="poster"
        path-type="url"
        hidden
        is-canvas-to-temp-file-path
        @success="pictureSuccess"
      />
      <view
        v-if="showShareBtn"
        class="promo-main"
      >
        <!-- #ifndef H5  -->
        <view class="promo-tit">
          <title>分享当前图片到</title>
        </view>
        <!-- #endif -->
        <!-- #ifdef H5  -->
        <view
          v-if="isWechat"
          class="promo-tit"
        >
          <title>分享当前图片到</title>
        </view>
        <!-- #endif -->
        <view class="promo-icons">
          <!-- #ifdef H5  -->
          <view
            v-if="isWechat"
            class="promo-img1"
            @tap="onShareWay"
          >
            <view class="promo-img1-icon">
              <image
                src="/static/images/wetchat.png"
                mode="aspectFit"
              />
            </view>分享
          </view>
          <view
            v-if="!isWechat"
            class="promo-tit1"
          >
            长按图片保存
          </view>
          <!-- #endif -->
          <!-- #ifndef H5  -->
          <view
            class="promo-img1"
            @tap="onSaveImg"
          >
            <view class="promo-img1-icon">
              <image
                src="/static/images/export.png"
                mode="aspectFit"
              />
            </view>保存图片
          </view>
          <!-- #endif -->
        </view>
        <view
          v-if="shareType===2"
          class="promo-btn"
          @tap="onToDistCenterPage"
        >
          我的分销员中心
        </view>
        <view
          class="promo-close"
          @tap="onCloseEarn"
        >
          取消
        </view>
      </view>
    </view>
    <!-- 分享弹窗 end -->

    <!-- 二维码弹窗 -->
    <view
      v-if="wxCodeShow"
      class="code-popup"
    >
      <view class="code-main">
        <view
          class="close-v"
          @tap.stop="onCloseCodePopup"
        >
          <image
            src="/static/images/close-share.png"
            class="close-png"
          />
        </view>
        <view class="code-v">
          <image
            :src="shareWxCode"
            class="wx-code"
          />
        </view>
        <!-- #ifndef H5 -->
        <view
          class="code-txt"
          @tap="onDownloadImg"
        >
          保存至相册
        </view>
        <!-- #endif -->
      </view>
    </view>
    <!-- 二维码弹窗 end -->

    <!-- 引导分享蒙版 -->
    <view
      v-if="guideShare"
      class="guide-share-mask"
    >
      <view class="mask" />
      <view
        class="guide-share-close"
        @tap="guideShare = false"
      >
        <image
          src="/static/images/close-share.png"
        />
      </view>
      <view class="guide-content">
        <view class="share-img">
          <image src="/static/images/shareIcon.png" />
        </view>
        <view class="share-word">
          <view class="big-word">
            立即分享给好友
          </view>
          <view class="small-word">
            点击屏幕右上角将本商品分享给好友
          </view>
        </view>
      </view>
    </view>
    <!-- 引导分享蒙版 end -->

    <!-- 回到顶部 && 普通分享 -->
    <view class="promo-con">
      <!-- 赚字浮层 -->
      <view
        v-if="isDist && isDistProd"
        class="earn"
        @tap="sharePopupShow=true;shareType=2"
      >
        {{
          '赚'
        }}
      </view>
      <!-- 赚字浮层 end -->
    </view>

    <!-- 优惠券弹窗 -->
    <view
      class="popup"
      :class="{ show: isShowCouponPopup }"
    >
      <view
        class="popup-mask"
        @tap="onClosePopup"
      />
      <view class="popup-con-bottom check-coupon">
        <view class="popup-tit">
          <view class="tit-text">
            优惠券
          </view>
          <view
            class="close"
            @tap="onClosePopup"
          >
            <image src="/static/images/close-share.png" />
          </view>
        </view>
        <view class="con-box">
          <view class="coupon-tit">
            <text class="tit-text">
              可领取优惠券
            </text>
            <text class="tit-des">
              （领券后可用于该商品）
            </text>
          </view>
          <block
            v-for="(couponItem, index) in couponList"
            :key="index"
          >
            <Coupon
              :ref="(el)=>(allCouponItem[index]=el)"
              :index="index"
              :coupon-item-parent="couponItem"
              @receive-coupon-by-coupon-id="onReceiveCouponByCouponId"
            />
          </block>
        </view>
      </view>
    </view>

    <!-- 优惠活动弹窗 -->
    <view
      class="popup"
      :class="{ show: isShowDiscountPopup }"
    >
      <view
        class="popup-mask"
        @tap="onClosePopup"
      />
      <view class="popup-con-bottom check-discount">
        <view class="popup-tit">
          <view class="tit-text">
            优惠活动
          </view>
          <view
            class="close"
            @tap="onClosePopup"
          >
            <image src="/static/images/close-share.png" />
          </view>
        </view>
        <view class="con-box">
          <view
            v-for="(discountItem, discountIndex) in prodDiscountList"
            :key="discountIndex"
            class="discount-item"
            @tap="onToDiscountDetail(discountItem.discountId)"
          >
            <view class="discount-icon">
              {{
                discountItem.discountRule === 0 ? '满减' : '满折'
              }}
            </view>
            <view class="text text-arrow">
              {{ discountItem.discountName }}
            </view>
          </view>
          <view
            v-for="(item, index) in giveawayList"
            :key="index"
            class="discount-item"
            @tap="onToGiveawaysProd(item.spuId)"
          >
            <view class="discount-icon">
              赠品
            </view>
            <view
              class="text text-arrow"
              decode
            >
              {{ item.spuName + '&nbsp;&nbsp;' }}
              <text
                v-if="item.skuName"
                decode
              >
                {{
                  item.skuName + '&nbsp;&nbsp;'
                }}
              </text>
              x{{ item.giveawayNum }}
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 选择sku弹窗 -->
    <view
      class="popup"
      :class="{ show: isShowSkuPopup }"
      @touchmove.stop.prevent="preventHandler"
    >
      <view
        class="popup-mask"
        @tap="onClosePopup"
      />
      <view class="popup-con-bottom check-sku">
        <view class="goods-box">
          <view class="img">
            <image
              :src="util.checkFileUrl(defaultSku.imgUrl || prodInfo.mainImgUrl)"
            />
          </view>
          <view class="info">
            <view class="name">
              {{ prodInfo.spuName }}
            </view>
            <!-- 预售 -->
            <view
              v-if="preSaleType===1"
              class="me-presale-icon"
            >
              定金: ￥{{ isActivityGoods && prodInfo.spuType === prodTypeConstant.GROUP ? wxs.parsePrice(defaultActivitySku.depositAmount)[0] : wxs.parsePrice(defaultSku.depositAmount)[0] }}
              .{{ isActivityGoods && prodInfo.spuType === prodTypeConstant.GROUP ? wxs.parsePrice(defaultActivitySku.depositAmount)[1] : wxs.parsePrice(defaultSku.depositAmount )[1] }}
            </view>
            <view
              v-if="findSku"
              class="price"
            >
              <view class="symbol">
                ￥
              </view>
              <view
                v-if="showSkuType === 0"
                class="big"
              >
                {{
                  isActivityGoods && prodInfo.spuType === prodTypeConstant.GROUP
                    ? wxs.parsePrice(defaultActivitySku.marketPriceFee)[0]
                    : wxs.parsePrice(defaultSku.priceFee)[0]
                }}
              </view>
              <view
                v-if="showSkuType === 0"
                class="symbol"
              >
                .{{
                  isActivityGoods && prodInfo.spuType === prodTypeConstant.GROUP
                    ? wxs.parsePrice(defaultActivitySku.marketPriceFee)[1]
                    : wxs.parsePrice(defaultSku.priceFee)[1]
                }}
              </view>
              <view
                v-if="showSkuType === 1"
                class="big"
              >
                {{
                  wxs.parsePrice(
                    defaultActivitySku.seckillPrice
                      ? defaultActivitySku.seckillPrice
                      : defaultActivitySku.priceFee
                  )[0]
                }}
              </view>
              <view
                v-if="showSkuType === 1"
                class="symbol"
              >
                .{{
                  wxs.parsePrice(
                    defaultActivitySku.seckillPrice
                      ? defaultActivitySku.seckillPrice
                      : defaultActivitySku.priceFee
                  )[1]
                }}
              </view>
              <view
                v-if="showSkuType === 0"
                class="stock"
              >
                库存:
                {{
                  prodInfo.supplierDeliveryType === 1
                    ? defaultSku.supplierStock
                    : defaultSku.stock
                }}
              </view>
              <view
                v-if="showSkuType === 1"
                class="stock"
              >
                库存: {{ defaultActivitySku.stock }}
              </view>
            </view>
            <view
              v-else
              class="sku-not-found"
            >
              无货
            </view>
          </view>
          <view
            class="close"
            @tap="onClosePopup"
          >
            <image src="/static/images/close-share.png" />
          </view>
        </view>
        <scroll-view
          :scroll-y="true"
          class="check-sku-con"
        >
          <!-- 说明（虚拟商品） -->
          <view
            v-if="spuMold===1 && (virtualInfo.writeOffNum !== 0 || (virtualInfo.writeOffNum === 0 && isRefund === 0))"
            class="virtual-goods-tips"
          >
            <text class="vi-t">
              使用说明：
            </text>
            <!-- writeOffNum 0无需核销 1单次核销 -1多次核销 -->
            <block v-if="virtualInfo.writeOffNum !== 0">
              <!-- writeOffTime核销有效期 -1.长期有效 0.自定义 x.x天内有效 -->
              <text v-if="virtualInfo.writeOffTime === -1">
                购买后长期有效
              </text>
              <text v-else-if="virtualInfo.writeOffTime === 0">
                购买后 {{ virtualInfo.writeOffStart }} 至 {{ virtualInfo.writeOffEnd }} <text v-if="!isEn">
                  有效
                </text>
              </text>
              <text v-else-if="virtualInfo.writeOffTime === 1">
                购买后当天24点前有效
              </text>
              <text v-else>
                购买后{{ virtualInfo.writeOffTime }}天内有效
              </text>
            </block>
            <!-- isRefund 0不支持退款 1支持退款 -->
            <text v-if="isRefund===0">
              <text v-if="virtualInfo.writeOffNum !== 0 ">
                ，
              </text>
              不支持申请退款
            </text>
          </view>
          <!-- 说明（虚拟商品）结束 -->

          <!-- 组合商品详情 -->
          <combine-card-list
            v-if="spuMold===2 && defaultSku.skuComboList?.length > 0"
            :new-sku="defaultSku"
            :spu-id="spuId"
            :sku-id="defaultSku.skuId"
          />

          <block
            v-for="(skuGroupItem, skuGroupItemIndex) in skuGroupList"
            :key="skuGroupItemIndex"
          >
            <view class="sku-item">
              <block
                v-for="(skuLine, key) in skuGroupItem"
                :key="key"
              >
                <view class="item-tit">
                  {{ key }}
                </view>
                <view class="item-box">
                  <view
                    v-for="skuLineItem in skuLine"
                    :key="skuLineItem"
                    :class="[
                      'item-item',
                      selectedPropNew.indexOf(key + skuLineItem) !== -1
                        ? 'active'
                        : '',
                      isSkuLineItemNotOptional(
                        allProperties,
                        selectedPropObj,
                        key,
                        skuLineItem,
                        propKeys
                      )
                        ? 'cannot'
                        : '',
                    ]"
                    @tap="onToChooseItem(skuGroupItemIndex, skuLineItem, key)"
                  >
                    {{ skuLineItem }}
                  </view>
                </view>
              </block>
            </view>
          </block>

          <view
            v-if="skuPopConfirmType !== 1"
            class="delivery"
          >
            <view class="item-tit">
              配送方式
            </view>
            <view
              v-if="(spuMold===0 || spuMold===2)"
              class="item-box"
            >
              <view
                :class="['tag', deliveryType === 1 ?'active':'', !isDelivery ? 'disabled' : '']"
                @click="isDelivery ? deliveryType = 1 : ''"
              >
                快递配送
              </view>
              <view
                v-if="deliveryModeVO.hasUserPickUp"
                :class="['tag', deliveryType === 2 ?'active':'']"
                @click="deliveryType = 2"
              >
                门店自提
              </view>
              <view
                v-if="isCityDelivery && deliveryModeVO.hasCityDelivery"
                :class="['tag', deliveryType === 4 ?'active':'']"
                @click="deliveryType = 4"
              >
                同城配送
              </view>
            </view>

            <view
              v-else
              class="item-box"
            >
              <view
                :class="['tag', deliveryType === 3 ?'active':'']"
              >
                无需配送
              </view>
            </view>
          </view>

          <view class="prod-number">
            <view class="item-tit">
              数量
            </view>
            <view class="number-box">
              <view
                :class="['minus', prodNumber <= 1 ? 'limit' : '']"
                @tap="onChangeNumber(-1)"
              />
              <input
                ref="prodNumberRef"
                v-model="prodNumber"
                type="number"
                class="number"
                placeholder="1"
                @blur="onProdNumberChange"
              >
              <view
                :class="['plus', isMaxProdNumber ? 'limit' : '']"
                @tap="onChangeNumber(1)"
              />
            </view>
          </view>
        </scroll-view>

        <view
          v-if="isActivityGoods && showSkuType===1"
          :class="['btn-box',findSku && defaultActivitySku.stock ? '':'btn-box-gray']"
        >
          <view
            v-if="prodInfo.spuType===prodTypeConstant.GROUP"
            class="btn"
            @tap="onGoSubmit('group')"
          >
            开团
          </view>
          <view
            v-if="prodInfo.spuType!==prodTypeConstant.GROUP && prodInfo.spuType!==prodTypeConstant.ACTIVITY && defaultActivitySku.stock"
            class="btn"
            @tap="onGetSeckillOrderPath"
          >
            立即抢购
          </view>
          <view
            v-if="prodInfo.spuType!==prodTypeConstant.GROUP && prodInfo.spuType!==prodTypeConstant.ACTIVITY && !defaultActivitySku.stock"
            class="btn-disable"
          >
            <text>立即抢购</text>
          </view>
        </view>
        <view
          v-else-if="prodInfo.spuType === prodTypeConstant.ACTIVITY"
          class="btn-box btn-box-gray"
        >
          <!-- 活动商品: 仅作为套餐(附属商品)或赠品 不可单独购买 -->
          <view
            class="btn btn-r"
            style="background: #aaa"
          >
            组合商品不可购买
          </view>
        </view>
        <view
          v-else
          :class="['btn-box',findSku && (prodInfo.supplierDeliveryType === 1 ? defaultSku.supplierStock : defaultSku.stock) ?'':'btn-box-gray']"
        >
          <template v-if="preSaleType===1">
            <view
              v-if="PayDepositStatus===0"
              class="btn btn-r pay-deposit pay-deposit-disabled"
            >
              <view>
                <view>支付定金(未开始)</view>
                <view class="price">
                  <view class="symbol">
                    ￥
                  </view>
                  <view class="big">
                    {{ wxs.parsePrice(defaultSku.depositAmount*prodNumber)[0] }}
                  </view>
                  <view class="symbol">
                    .{{ wxs.parsePrice(defaultSku.depositAmount*prodNumber)[1] }}
                  </view>
                </view>
              </view>
            </view>
            <view
              v-if="PayDepositStatus===1"
              class="btn btn-r pay-deposit"
              @tap="onGoSubmit"
            >
              <view>
                <view>支付定金</view>
                <view class="price">
                  <view class="symbol">
                    ￥
                  </view>
                  <view class="big">
                    {{ wxs.parsePrice(defaultSku.depositAmount*prodNumber)[0] }}
                  </view>
                  <view class="symbol">
                    .{{ wxs.parsePrice(defaultSku.depositAmount*prodNumber)[1] }}
                  </view>
                </view>
              </view>
            </view>
            <view
              v-if="PayDepositStatus===2"
              class="btn btn-r"
              @tap="onToShopIndex"
            >
              <view>
                <view>活动已结束(查看店铺其他活动)</view>
              </view>
            </view>
          </template>
          <template v-else>
            <view
              v-if="skuPopBtnType === 1"
              class="btn"
              @tap="onSkuPopupConfirm"
            >
              确定
            </view>
            <view
              v-if="skuPopBtnType === 2"
              class="btn add-cart-btn"
              @tap="onAddCart"
            >
              加入购物车
            </view>
            <view
              v-if="skuPopBtnType === 2"
              class="btn btn-r"
              @tap="onGoSubmit"
            >
              立即购买
            </view>
          </template>
        </view>
      </view>
    </view>

    <confirm-pop
      :show-pop="showPop"
      :pop-content="popContent"
      @handle-pop-confirm="onPopConfirm"
      @handle-pop-cancel="onPopCancel"
    />

    <!-- h5||app分享弹窗 -->
    <view
      v-if="sharePopupShow"
      class="share-popup"
      @tap="sharePopupShow = false"
    >
      <view
        class="share-popup-box share-box"
        @tap.stop
      >
        <view class="share-popup-tit radius">
          <view class="text">
            分享至
          </view>
          <image
            class="img"
            src="/static/images/icon_close.png"
            @tap="sharePopupShow = false"
          />
        </view>
        <view class="share-cnt">
          <view
            class="item left"
            @tap="onShowShare(1)"
          >
            <image
              class="img"
              src="/static/images/icon_Generate.png"
            />
            <view>
              生成图片
            </view>
          </view>

          <!-- #ifndef MP-WEIXIN -->
          <view
            class="item right"
            @tap="copylink"
          >
            <image
              class="img"
              src="/static/images/icon_copy.png"
            />
            <view class="text">
              复制链接
            </view>
          </view>
          <!-- #endif -->

          <!-- #ifdef MP-WEIXIN -->
          <button
            class="item right"
            open-type="share"
          >
            <image
              class="img"
              src="/static/images/icon_copy.png"
            />
            <view class="text">
              分享链接
            </view>
          </button>
          <!-- #endif -->
        </view>
      </view>
    </view>
    <popup-ad
      v-model="popupadShow"
      :popup-info="popupInfo"
      :shop-id="curShopId"
    />
  </view>
</template>

<script setup>
import UvParse from '@/components/uv-parse/components/uv-parse/uv-parse.vue'
import { ProdType } from '@/utils/constant.js'
import Coupon from '@/components/coupon/index'
import CountdownBar from '@/components/countdown-bar/countdown-bar'
import Steps from '@/components/steps/steps.vue'
// #ifdef H5
import Wechat from '@/utils/wechat.js'
// #endif
import Qr from '@/utils/wxqrcode'
import util from '@/utils/util.js'
import CombineCardList from './components/combine-card-list/index.vue'

const wxs = number()
const prodTypeConstant = reactive(ProdType)
const pageScorllTop = ref(0) // 页面滚动的高度
// 配送类型 1:快递 2:自提 3：无需快递 4.同城配送
const deliveryType = ref(1)

/**
 * 生命周期函数--监听页面加载
 */
let scene
const isWechat = ref(false) // 是否为微信环境
const spuId = ref(0) // 商品id
let distributionUserId = null // 分销推荐者id
const deliveryAddrInfo = ref(null)// 当前配送地址信息
let seckillId = '' // 秒杀id

onLoad((options) => {
  // 配送地址信息
  const isDeliveryAddrInfo = uni.getStorageSync('cloudDeliveryAddrInfo')
  if (isDeliveryAddrInfo) {
    deliveryAddrInfo.value = isDeliveryAddrInfo
  } else {
    onGetAddressList()
  }

  // #ifdef H5
  isWechat.value = Wechat.isWechat()
  // #endif
  // #ifdef APP-PLUS
  isWechat.value = false
  // #endif
  // options = { ...$Route.query }
  spuId.value = options.spuId || ''
  seckillId = options.seckillId || ''
  if (options.distributionUserId) {
    // #ifdef MP-WEIXIN
    distributionUserId = decodeURIComponent(
      options.distributionUserId
    )
    // #endif

    // #ifdef H5 || APP-PLUS
    distributionUserId = options.distributionUserId
    // #endif
  }
  // 扫码进入 (小程序)
  if (options.scene) {
    const isScene = decodeURIComponent(options.scene)
    // 如果是微信小程序中下载保存的二维码
    if (isScene.indexOf(',') !== -1) {
      spuId.value = isScene.split(',')[0]
      distributionUserId = isScene.split(',')[1]
      onExecutionFunction()
    } else {
      scene = isScene
      // 根据Ticket获取保存的内容
      onGetContent()
    }
  }
})

/**
 * 生命周期函数--监听页面显示
 */
onShow(() => {
  prodNumber.value = 1
  // 置顶滚动条
  uni.pageScrollTo({
    scrollTop: 1, // 距离页面顶部的距离
    duration: 0 // 滚动动画时长
  })

  if (spuId.value) {
    setTimeout(() => {
      onExecutionFunction()
    }, 100)
  }

  const addrInfo = uni.getStorageSync('cloudStationAddress')
  if (addrInfo) {
    uni.setStorageSync('cloudDeliveryAddrInfo', addrInfo)
    deliveryAddrInfo.value = addrInfo
    onGetProdInfo()
    uni.removeStorageSync('cloudStationAddress')
  }
})

/**
 * 生命周期函数--监听页面隐藏
 */
let joinGroupListTimer = false
let canJionGroupListTimer = '' // 可参加的团列表定时器
let activityTimer = '' // 秒杀活动轮询定时器(活动未开始才有)
let countDownTimer = '' // 倒计时定时器
const isPlaying = ref(false) // 商品视频

onHide(() => {
  if (isPlaying.value) {
    onStopPlay()
  }
  // 隐藏弹窗
  onClosePopup()
  // 清除定时器
  clearTimeout(countDownTimer)
  clearTimeout(activityTimer)
  clearTimeout(canJionGroupListTimer)
  clearTimeout(joinGroupListTimer)
})

/**
 * 生命周期函数--监听页面卸载
 */
onUnload(() => {
  // 清除定时器
  clearTimeout(countDownTimer)
  clearTimeout(activityTimer)
  clearTimeout(canJionGroupListTimer)
  clearTimeout(joinGroupListTimer)
})

onUnmounted(() => {
  if (isShowPreview) {
    uni.closePreviewImage({
      success: () => {
        isShowPreview = false
      }
    })
  }
})

/**
 * 页面滚动事件
 */
const heightList = ref([0])
const topTabOpacity = ref(0) // 顶部 topTab 的透明度
const topTabSts = ref(0) // 顶部 topTab 选中的项目
const scrolling = ref(false)

onPageScroll((e) => {
  topTabOpacity.value = e.scrollTop / 46
  if (!scrolling.value) {
    topTabSts.value =
      e.scrollTop < heightList.value[1] ? 0 : e.scrollTop < heightList.value[2] ? 1 : 2
  }
  if (e.scrollTop > 325 && isPlaying.value) {
    onStopPlay()
  }
})
/**
 * 用户点击微信图标转发
 */
let spuName = null // 商品名称
let mainImgUrl = null

onShareAppMessage((res) => {
  sharePopupShow.value = false

  if (res.from === 'button') {
    const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
    return {
      title: spuName,
      path:
        '/pages/detail/detail?spuId=' +
        spuId.value +
        '&distributionUserId=' +
        distributionUserId,
      imageUrl: mainImgUrl
    }
  } else {
    return {
      title: spuName,
      path: '/pages/detail/detail?spuId=' + spuId.value,
      imageUrl: mainImgUrl
    }
  }
})

const prodNumberRef = ref(null)
const isMaxProdNumber = ref(false) // 是否达到限购或达到最大库存
const prodNumber = ref(1) // 商品数量
const showSkuType = ref(0) // 规格展示类型: 0普通sku; 1商品活动sku
const defaultActivitySku = ref('')
const defaultSku = ref('')
const prodInfo = ref({}) // 商品详情

watch(() => prodNumber.value, (nv) => {
  let stock =
    prodInfo.value.supplierDeliveryType === 1 ? defaultSku.value.supplierStock : defaultSku.value.stock
  // 秒杀/团购的商品库存
  if (showSkuType.value !== 0) {
    stock = defaultActivitySku.value.stock
  }
  if (nv >= stock) {
    isMaxProdNumber.value = true
    nextTick(() => {
      prodNumber.value = stock || 1
    })
    prodNumberRef.value.valueSync = stock || 1
  } else {
    isMaxProdNumber.value = false
  }
})

watch(() => showSkuType.value, () => {
  prodNumber.value = 1
})

onMounted(() => {
  nextTick(() => {
    // 获取评价、详情在页面的高度
    onGetHeightList()
  })
})

// 更改配送地址
const onChangeAddr = () => {
  uni.navigateTo({
    url: '/package-user/pages/address-list/address-list?selectAddress=1'
  })
}
/**
 * 获取用户地址列表
 */
const onGetAddressList = () => {
  http.request({
    url: '/tmerclub_user/user_addr/list',
    method: 'GET',
    dontShowLogin: true,
    data: {}
  }).then(res => {
    for (const addr of res) {
      if (addr.isDefault) {
        deliveryAddrInfo.value = addr
        break
      }
    }
  }).catch(() => {})
}
// 需要加载的函数
const onExecutionFunction = () => {
  // 获取商品详情
  onGetProdInfo()
  // 获取商品收藏状态
  onGetCollectionInfo()
  // 获取购物车数字
  onGetCartCount()
  // 获取商品评论数据
  onGetProdCommentData()
  // 获取商品评论列表
  onGetProdCommentList()
  // 是否是分销商品
  onGetDistInfo()
  // 检测当前商品是否正在直播
  onCheckProdLiveStatus()
}
/**
 * 去往优惠套餐详情
 */
let shopId = 0
const onToDiscountPackageDetail = (id) => {
  uni.navigateTo({
    url: '/pages/discount-package-detail/discount-package-detail?comboId=' + id + '&shopId=' + shopId
  })
}

let isShowPreview = false
/**
 * 点击评论图片查看大图
 */
const onPreviewCommentImage = (imgs, imgIndex) => {
  const urls = imgs.map(item => {
    item = util.checkFileUrl(item)
    return item
  })
  uni.previewImage({
    current: imgIndex,
    urls,
    success: () => {
      isShowPreview = true
    }
  })
}

/**
 * 可加入的团列表倒计时
 */
const canJionGroupList = ref([]) // 可加入的团列表
const canJionGroupFlag = ref(false)
const onHandleCanJionGroupListCountDown = (isCanJionGroupList) => {
  let signsNum = 0
  isCanJionGroupList.forEach((item) => {
    item.endOfGroupTime = util.endOfStartTime(
      new Date().getTime(),
      util.dateToTimestamp(item.endTime)
    )
    if (!item.endOfGroupTime.signs) {
      signsNum++
      clearTimeout(joinGroupListTimer)
      joinGroupListTimer = setTimeout(onGetJoinGroupList, 1000)
    }
  })
  if (signsNum > 0) {
    canJionGroupFlag.value = isCanJionGroupList?.length === signsNum
    return
  }
  canJionGroupList.value = isCanJionGroupList
  canJionGroupListTimer = setTimeout(() => {
    onHandleCanJionGroupListCountDown(canJionGroupList.value)
  }, 1000)
}

/**
 * 获取可加入的团列表
 */
const groupActInfo = ref({}) // 团购活动详情

const onGetJoinGroupList = () => {
  http.request({
    url: '/tmerclub_group/ua/group_activity/join_group_list',
    method: 'GET',
    data: {
      groupActivityId: groupActInfo.value.groupActivityId
    }
  }).then((res) => {
    canJionGroupList.value = res
    // 加载可参团列表倒计时
    if (res && res.length > 0) {
      onHandleCanJionGroupListCountDown(res)
    }
  })
}

/**
 * 请求秒杀活动详情
 */
const isActivityGoods = ref(false) // 是否参加活动
const activityGoodsLoad = ref(false) // 商品活动是否加载完成
let hadGotDefaultSku = false // 是否已经组装默认sku(非活动sku)
const seckillActInfo = ref({}) // 秒杀活动详情
const maxNum = ref(0) // 限购数量(仅活动商品)

const onGetSeckillInfo = (selfLoading = false) => {
  http.request({
    url: '/tmerclub_seckill/ua/seckill/prod',
    method: 'GET',
    data: {
      seckillId
    },
    selfLoading
  }).then((res) => {
    activityGoodsLoad.value = true
    if (res.activityStatus < 3) {
      isActivityGoods.value = true
      seckillActInfo.value = res
      maxNum.value = res.maxNum
      // 组装活动sku
      // onSetDefaultActivitySku()
      // 秒杀未开始
      if (res.activityStatus === 1) {
        if (!hadGotDefaultSku) {
          onGroupSkuProp(prodInfo.value.skus, prodInfo.value.priceFee)
          hadGotDefaultSku = true
        }
        clearTimeout(countDownTimer)
        activityTimer = setTimeout(() => {
          onGetSeckillInfo(true)
        }, 5000)
      } else {
        clearTimeout(activityTimer)
        onGroupSkuProp(res.seckillSkuList, res.seckillPrice)
      }
      // 启动倒计时
      onCountingDown()
    }
  }).catch(() => {
    activityGoodsLoad.value = true
    onGroupSkuProp(prodInfo.value.skus, prodInfo.value.priceFee)
  })
}

/**
 * 请求团购活动详情
 */
const onGetGroupInfo = () => {
  http.request({
    url: '/tmerclub_group/ua/group_activity/info',
    method: 'GET',
    data: {
      spuId: spuId.value
    }
  }).then((res) => {
    activityGoodsLoad.value = true
    isActivityGoods.value =
        res.activityStatus === 2 ||
        (res.activityStatus === 1 && res.isPreheat)
    groupActInfo.value = res
    maxNum.value = res.maxNum
    // 拼团商品stock即为供应商库存
    res.groupSkuList.forEach(el => {
      el.supplierStock = el.stock
    })

    if (res.activityStatus === 2) {
      onGroupSkuProp(res.groupSkuList, res.price, false)
    }

    // 组装活动sku
    onSetDefaultActivitySku(1, 'group')
    // 启动倒计时
    if (countDownTimer) {
      clearTimeout(countDownTimer)
      onCountingDown()
    } else {
      onCountingDown()
    }
    // 活动已开始且开启凑团模式
    if (res.hasGroupTip && res.activityStatus === 2) {
      // 获取可参团列表
      onGetJoinGroupList()
    }
  }).catch(() => {
    activityGoodsLoad.value = true
  })
}

/**
 * 倒计时
 */
const countDownInfo = ref({}) // 活动倒计时
const onCountingDown = () => {
  // 团购 倒计时归零
  if (
    prodInfo.value.spuType === ProdType.GROUP &&
    (groupActInfo.value.startIn === 0 || groupActInfo.value.expiresIn === 0)
  ) {
    uni.redirectTo({
      url: '/pages/detail/detail?spuId=' + spuId.value
    })
    return
  }

  // 秒杀 倒计时归零
  if (
    prodInfo.value.spuType === ProdType.SECOND &&
    (seckillActInfo.value.startIn === 0 ||
      seckillActInfo.value.expiresIn === 0)
  ) {
    uni.redirectTo({
      url:
        '/pages/detail/detail?spuId=' +
        spuId.value +
        '&seckillId=' +
        seckillId
    })
    return
  }
  countDownInfo.value =
    prodInfo.value.spuType === ProdType.GROUP ? util.countDown(
      groupActInfo.value.activityStatus === 2 ? groupActInfo.value.expiresIn-- : groupActInfo.value.startIn--
    ) : util.countDown(
      seckillActInfo.value.activityStatus === 2 ? seckillActInfo.value.expiresIn-- : seckillActInfo.value.startIn--
    )
  countDownTimer = setTimeout(onCountingDown, 1000)
}

/**
 * 库存校验
 */
const onCheckStock = () => {
  let flag = true
  const val = Number(prodNumber.value)
  // 活动商品sku弹窗
  if (showSkuType.value !== 0) {
    // 是否限购
    const isRestriction = maxNum.value && maxNum.value !== -1
    // limit 最大可购买数量: 活动商品不限购则为当前sku库存；活动商品限购时，当库存大于限购数量则为限购数量，否则为库存数量
    const limit = !isRestriction ? defaultActivitySku.value.stock : defaultActivitySku.value.stock > maxNum.value ? maxNum.value : defaultActivitySku.value.stock
    if (val > limit) {
      uni.showToast({
        title: isRestriction ? defaultActivitySku.value.stock > maxNum.value ? `限购${limit}件` : (limit > 0 ? `库存剩余${limit}件` : '库存不足') : '库存不足',
        icon: 'none'
      })
      flag = false
    }
  } else {
    const stock = prodInfo.value.supplierDeliveryType === 1 ? defaultSku.value.supplierStock : defaultSku.value.stock
    // 普通商品
    if (val > stock) {
      uni.showToast({
        title: '库存不足',
        icon: 'none'
      })
      flag = false
    }
  }
  return flag
}

/**
 * 获取店铺信息
 */
let shopInfo = reactive({})
const onGetShopInfo = () => {
  http.request({
    url: '/tmerclub_admin/ua/shop_detail/head_info',
    method: 'GET',
    data: {
      shopId
    }
  }).then((res) => {
    shopInfo = res
  })
}

/**
 * 跳转满减活动详情
 */
const onToDiscountDetail = (discountId) => {
  uni.navigateTo({
    url:
      '/package-activities/pages/discount-detail/discount-detail?discountId=' +
      discountId
  })
}

/**
 * 跳转赠品详情
 */
const onToGiveawaysProd = (id) => {
  uni.navigateTo({
    url: '/pages/detail/detail?spuId=' + id
  })
}

/**
 * 咨询客服
 */
const onHandleCustomService = () => {
  util.checkAuthInfo(() => {
    uni.navigateTo({
      url:
        '/package-user/pages/my-chat/my-chat?shopid=' +
        shopId +
        '&prodid=' +
        spuId.value
    })
  })
}

/**
 * 通过商品id获取商品所有促销活动
 */
const prodDiscountList = ref([]) // 满减折促销活动
const onGetProdDiscountList = () => {
  http.request({
    url: '/tmerclub_marketing/ua/discount/get_discount_list',
    method: 'GET',
    data: {
      shopId,
      spuId: spuId.value
    }
  }).then((res) => {
    prodDiscountList.value = res
  })
}

// 保存商品游览记录
const onSaveProdBrowseRecord = (categoryId) => {
  http.request({
    url: '/tmerclub_product/spu_browse_log',
    method: 'POST',
    data: {
      spuId: Number(spuId.value),
      categoryId
    }
  })
}

/**
 * 规格弹窗底部确定按钮
 */
const skuPopConfirmType = ref(0) // sku弹窗确认类型: 1加入购物车; 2立即购买
const findSku = ref(false)
const onSkuPopupConfirm = () => {
  if (Number(prodNumber.value) < 1) {
    uni.showToast({
      title: '请输入正确的商品数量',
      duration: 1200,
      icon: 'none',
      mask: true
    })
    return
  }
  if (!findSku.value) {
    uni.showToast({
      title: '所选规格无货',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  const stock =
    prodInfo.value.supplierDeliveryType === 1 ? defaultSku.value.supplierStock : defaultSku.value.stock
  if (!stock) {
    uni.showToast({
      title: '库存不足',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  skuPopConfirmType.value === 1 ? onAddCart() : onGoSubmit()
  onClosePopup()
}

/**
 * 加入购物车按钮
 */
const onAddCart = () => {
  if (!findSku.value) {
    uni.showToast({
      title: '所选规格无货',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  const stock =
    prodInfo.value.supplierDeliveryType === 1 ? defaultSku.value.supplierStock : defaultSku.value.stock
  if (!stock) {
    uni.showToast({
      title: '库存不足',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  util.checkAuthInfo(() => {
    const tempDistributionUserId = distributionUserId ? { distributionUserId } : {}
    http.request({
      url: '/tmerclub_product/shop_cart/change_item',
      method: 'POST',
      data: {
        skuId: defaultSku.value.skuId,
        spuId: defaultSku.value.spuId,
        count: prodNumber.value,
        oldSkuId: '',
        ...tempDistributionUserId
      }
    }).then(() => {
      util.tapLog(2, { n: prodNumber.value, sid: shopId, bid: spuId.value })
      uni.showToast({
        title: '加入购物车成功~',
        duration: 2000,
        icon: 'none'
      })
      onClosePopup()
      onGetCartCount()
    })
  })
}

/**
 * 修改商品数量
 */
const onChangeNumber = (num) => {
  let isProdNumber = parseInt(prodNumber.value)
  if (num < 0) {
    // 点击数量-
    if (isProdNumber <= 1) {
      return
    } else {
      isProdNumber += num
    }
  } else {
    // 点击数量+
    if (showSkuType.value !== 0) {
      // 是否限购
      const isRestriction = maxNum.value && maxNum.value !== -1
      const limit = !isRestriction ? defaultActivitySku.value.stock : defaultActivitySku.value.stock > maxNum.value ? maxNum.value : defaultActivitySku.value.stock
      // limit 最大可购买数量: 活动商品不限购则为当前sku库存；活动商品限购时，当库存大于限购数量则为限购数量，否则为库存数量
      if (isProdNumber >= limit) {
        uni.showToast({
          title: isRestriction && limit ? `限购${limit}件` : '库存不足',
          icon: 'none'
        })
      }
      isProdNumber = (isProdNumber >= limit ? limit : isProdNumber + 1) || 1
    } else {
      const stock =
        prodInfo.value.supplierDeliveryType === 1 ? defaultSku.value.supplierStock : defaultSku.value.stock
      // 普通商品
      if (isProdNumber >= stock) {
        uni.showToast({
          title: '库存不足',
          icon: 'none'
        })
        prodNumber.value = stock || 1
      } else {
        isProdNumber += 1
      }
    }
  }
  prodNumber.value = isProdNumber || 1
}

const onProdNumberChange = () => {
  if (prodNumber.value < 1) {
    prodNumber.value = 1
  } else {
    prodNumber.value = typeof prodNumber.value === 'string' ? Number(prodNumber.value.replace(/[^\d]/g, '')) : prodNumber.value
  }
}

/**
 * 领取优惠券
 */
// 动态获取组件
const allCouponItem = ref([])
const onReceiveCouponByCouponId = (e) => {
  util.checkAuthInfo(() => {
    http.request({
      url: '/tmerclub_marketing/my_coupon/receive',
      method: 'POST',
      data: String(e.couponId)
    }).then((res) => {
      uni.showToast({
        title: res,
        duration: 2000,
        icon: 'none'
      })
      allCouponItem.value[e.index].changeCouponReceiveStatus()
    })
  })
}

/**
 * 获取商品可以的优惠券(店铺)
 */
const couponList = ref([]) // 优惠券
const onGetProdCoupons = () => {
  http.request({
    url: '/tmerclub_marketing/ma/coupon/get_shop_or_spu_coupon_list',
    method: 'GET',
    data: {
      shopId,
      spuId: spuId.value
    }
  }).then((res) => {
    couponList.value = res
  })
}

/**
 * 获取商品详情
 */
const briefUnfold = ref(true) // 卖点展开
const briefUnfoldUnfoldShow = ref(true)
const comboList = ref([]) // 套餐列表
const giveawayList = ref([]) // 赠品列表
let sellingPoint = null
const isCityDelivery = ref(true) // 当前店铺是否可同城
let isImgList = []
let userId = null
let virtualInfo = reactive({})
const isRefund = ref(null) // 0不支持退款 1支持退款
const spuMold = ref('') // 1 虚拟商品
const PayDepositStatus = ref(1) // 支付定金状态  0:未开始  1:开始   2:结束
const balanceEndTime = ref(null) // 尾款结束支付时间
const balanceStartTime = ref(null) // 尾款开始支付时间
const preSaleType = ref(-1) //  预售类型 -1：未开启 0.全款预售 1.定金预售
const preSaleDeliveryType = ref(null) // 预售发货类型 0.固定时间 x.尾款支付后x天发货
const preSaleDeliveryTime = ref(null) //  预售发货时间
let videoContext = ''
const popContent = ref({})
const showPop = ref(false)
let skuList = []
const prodDetail = ref('') // 商品详情富文本
const imgList = ref([]) // 商品轮播图
const deliveryModeVO = ref({}) // 商品配送方式
const video = ref('')
const instance = getCurrentInstance() // 获取组件实例
const curShopId = ref(0)
let isLoadPopupAd = true
const onGetProdInfo = () => {
  userId = uni.getStorageSync('cloudToken') && uni.getStorageSync('cloudUserDetails') ? uni.getStorageSync('cloudUserDetails').userId : undefined
  isActivityGoods.value = false
  activityGoodsLoad.value = false
  http.request({
    url: '/tmerclub_product/ma/spu/prod_info',
    method: 'GET',
    withoutPrompting: true,
    data: {
      spuId: spuId.value,
      userId: userId || '',
      addrId: deliveryAddrInfo.value?.addrId || ''
    },
    selfLoading: true
  }).then((res) => {
    if (uni.getStorageSync('cloudFlowDteail')) {
      util.tapLog(1, { sid: res.shopId, bid: spuId.value })
      uni.setStorageSync('cloudFlowDteail', false)
    }
    isImgList = res.imgUrls ? res.imgUrls.split(',') : ['/static/images/def.png']
    shopId = res.shopId
    curShopId.value = res.shopId
    if (isLoadPopupAd) {
      onGetPopupInfo()
    }
    spuName = res.spuName
    mainImgUrl = res.mainImgUrl
    comboList.value = res.comboList || []
    sellingPoint = res.sellingPoint
    if (res.shopId === -1) res.spuType = prodTypeConstant.ACTIVITY
    prodInfo.value = res
    deliveryModeVO.value = res.deliveryModeVO
    prodDetail.value = util.formatHtml(res.detail)
    imgList.value = isImgList
    deliveryModeVO.value = JSON.parse(res.deliveryMode)
    skuList = res.skus
    video.value = res.video
    spuMold.value = res.spuMold
    isRefund.value = res.isRefund
    isDelivery.value = res.isDelivery
    isCityDelivery.value = res.cityDelivery
    briefUnfold.value = true
    if (res.spuName && res.sellingPoint) { // 买点是否超过一行
      nextTick(() => {
        const query = uni.createSelectorQuery().in(instance)
        query.select('.prod-brief').boundingClientRect(data => {
          uni.getSystemInfo({
            success (res) {
              // px转换到rpx的比例
              const pxToRpxScale = 750 / res.windowWidth
              const FONT_SIZE = 24 // 字体大小
              briefUnfold.value = false
              briefUnfoldUnfoldShow.value = !(pxToRpxScale * data.height <= FONT_SIZE * 2)
            }
          })
        }).exec()
      })
    }
    if (res.spuMold === 1) {
      virtualInfo = {
        virtualRemarks: res.virtualRemark ? JSON.parse(res.virtualRemark) : [], // 留言
        isRefund: res.isRefund, // 0不支持退款 1支持退款
        writeOffTime: res.writeOffTime, // 核销有效期 -1.长期有效 0.自定义 x.x天内有效
        writeOffNum: res.writeOffNum, // 核销次数 -1.多次核销 0.无需核销 1.单次核销
        writeOffStart: res.writeOffStart, // 核销有效期开始时间
        writeOffEnd: res.writeOffEnd, // 核销有效期结束时间
        prodParameterList: res.prodParameterList
      }

      // 虚拟商品，无需配送
      deliveryType.value = 3
    }
    giveawayList.value = res.giveaway ? res.giveaway.giveawaySpus : [] // 赠品商品栏

    // 预售出来处理
    onHandlePreSale(res)

    if (shopId !== -1) onGetShopInfo()
    if (res.spuType === 3) {
      uni.redirectTo({
        url:
          '/package-activities/pages/score-prod-detail/score-prod-detail?spuId=' +
          spuId.value
      })
    }
    // 获取商品优惠券
    onGetProdCoupons()
    // 获取商品所有促销活动
    onGetProdDiscountList()

    // 获取团购活动详情
    if (res.spuType === 1) {
      onGroupSkuProp(res.skus, res.priceFee)
      onGetGroupInfo()
    }
    if (res.spuType !== ProdType.SECOND) {
      onGroupSkuProp(res.skus, res.priceFee)
    }
    // 获取秒杀活动详情
    if (res.spuType === 2) {
      seckillId = res.activityId
      onGetSeckillInfo()
    }
    if (res.spuType !== 1 && res.spuType !== 2) {
      activityGoodsLoad.value = true
    }
    // 初始化商品视频, 如有
    if (res.video) {
      nextTick(() => {
        videoContext = uni.createVideoContext('myVideo', instance)
      })
    }
    // 把访问的商品分类写进缓存,用作推荐列表的参数
    uni.setStorageSync('cloudBrowseCategoryId', res.categoryId)
    if (uni.getStorageSync('cloudToken')) {
      // 保存商品游览记录
      onSaveProdBrowseRecord(res.categoryId)
    }
    if (isWechat.value) {
      onShareWay(false)
    }
  }).catch((errMsg) => {
    showPop.value = true
    popContent.value.content = errMsg.msg ? errMsg.msg : '商品已下架'
    popContent.value.cancelText = '逛逛首页'
    popContent.value.confirmText = '搜索商品'
  })
}

// 获取弹窗广告信息
const popupadShow = ref(false)
const popupInfo = ref({})
const onGetPopupInfo = async () => {
  const info = await util.getPopupInfo({ pageType: 5, shopId, spuId: spuId.value })
  if (info) {
    popupInfo.value = info
    popupadShow.value = true
  }
  isLoadPopupAd = false
}

const onHandlePreSale = (res) => {
  if (res.preSaleType === 1 || res.preSaleType === 0) { // 预售
    preSaleType.value = res.preSaleType
    preSaleDeliveryTime.value = res.preSaleDeliveryTime
    preSaleDeliveryType.value = res.preSaleDeliveryType
    balanceEndTime.value = res.balanceEndTime ? res.balanceEndTime.split(' ')[0].replace(/-/g, '.') : null
    balanceStartTime.value = res.balanceStartTime ? res.balanceStartTime.split(' ')[0].replace(/-/g, '.') : null

    if (res.preSaleType === 1) { // 定金预售
      onGroupSkuProp(res.skus, res.priceFee)
      // 定金开始开始
      const depositStartTime = new Date(res ? res.depositStartTime ? res.depositStartTime.replace(/-/g, '/') : null : null).getTime() // 结束时间（时间戳）
      // 定金结束时间
      const depositEndTime = new Date(res ? res.depositEndTime ? res.depositEndTime.replace(/-/g, '/') : null : null).getTime()
      const nowTime = Date.now()// 现在时间（时间戳）
      const isDepositStartTime = (depositStartTime - nowTime) // 距离开始的毫秒数
      const isDepositEndTime = (depositEndTime - nowTime) // 距离结束的毫秒数
      // 预售未开始
      if (isDepositStartTime > 0) {
        PayDepositStatus.value = 0
        setTimeout(() => {
          onGetProdInfo()
        }, Math.abs(isDepositStartTime))
      }
      // 预售开始
      if (isDepositStartTime <= 0 && isDepositEndTime >= 0) {
        PayDepositStatus.value = 1
        setTimeout(() => {
          onGetProdInfo()
        }, Math.abs(isDepositEndTime) < 86400000 ? Math.abs(isDepositEndTime) : 86400000)
      }
      // 预售未开始
      if (isDepositEndTime < 0) {
        PayDepositStatus.value = 2
      }
    }
  }
}

// 检测当前商品是否存在直播
const liveRoomParams = ref(null)
const onCheckProdLiveStatus = () => {
  http.request({
    url: '/tmerclub_marketing/ua/live_room/get_spu_live_room_info',
    method: 'GET',
    data: {
      spuId: spuId.value
    }
  }).then((res) => {
    if (res) {
      liveRoomParams.value = res
    }
  })
}

/**
 * 前往直播页面
 */
const toLivePage = (e) => {
  const roomId = e.currentTarget.dataset.roomid // 填写具体的房间号
  const liveUserId = e.currentTarget.dataset.userid
  const curUserId = uni.getStorageSync('cloudUserDetails')?.userId
  const type = String(liveUserId) === String(curUserId) ? 1 : 2
  util.gotoLiveRoom(type, roomId, liveUserId)
}

/**
 * 组装SKU
 */
const selectedPropNew = ref([])
const skuGroupList = ref([])
const skuGroup = ref({})
const allProperties = ref([])
const propKeys = ref([])
const selectedPropObj = ref({})

const onGroupSkuProp = (skuListPar, defaultPrice, isChange = true) => {
  skuListPar = skuListPar.filter((item) => {
    return item.skuId
  })
  if (skuListPar?.length === 1 && !skuListPar[0].properties) {
    defaultSku.value = skuListPar[0]
    findSku.value = true
    onSetDefaultActivitySku()
    return
  }
  const isSkuGroupList = []
  const isSkuGroup = {}
  const isAllProperties = []
  const isPropKeys = []
  const isSelectedPropObj = {}
  const isSelectedPropObjList = []
  let isDefaultSku = null

  skuListPar = skuListPar.filter((item) => {
    return item.properties
  })
  for (let i = 0; i < skuListPar?.length; i++) {
    let isDefault = false
    if (skuListPar?.length === 1) {
      isDefaultSku = skuListPar[0]
      isDefault = true
    }
    if (
      !isDefaultSku &&
      (skuListPar[i].priceFee === defaultPrice ||
        skuListPar[i].seckillPrice === defaultPrice)
    ) {
      // 找到和商品价格一样的那个SKU，作为默认选中的SKU
      isDefaultSku = skuListPar[i]
      isDefault = true
    }
    const properties = skuListPar[i].properties // 版本:公开版;颜色:金色;内存:64GB
    isAllProperties.push(properties)
    const propList = properties.split(';') // ["版本:公开版","颜色:金色","内存:64GB"]
    for (let j = 0; j < propList?.length; j++) {
      const index = propList[j].indexOf(':')
      const propval = [propList[j].slice(0, index), propList[j].substring(index + 1)] // ["版本","公开版"]
      let props = isSkuGroup[propval[0]] // 先取出 版本对应的值数组
      // 如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
      if (isDefault) {
        isPropKeys.push(propval[0])
        isSelectedPropObj[propval[0]] = propval[1]
        const selectedPropObjItem = {}
        selectedPropObjItem[propval[0]] = propval[1]
        isSelectedPropObjList.push(selectedPropObjItem)
      }
      if (props === undefined) {
        props = [] // 假设还没有版本，新建个新的空数组
        props.push(propval[1]) // 把 "公开版" 放进空数组
      } else {
        if (props.indexOf(propval[1]) === -1) {
          // 如果数组里面没有"公开版"
          props.push(propval[1]) // 把 "公开版" 放进数组
        }
      }
      isSkuGroup[propval[0]] = props // 最后把数据 放回版本对应的值
      const propListItem = {}
      propListItem[propval[0]] = props
      isSkuGroupList.push(propListItem)
    }
  }
  if (isChange) {
    defaultSku.value = isDefaultSku || {}
  }
  propKeys.value = isPropKeys.length > 0 ? isPropKeys : propKeys.value
  selectedPropObj.value = isSelectedPropObj || selectedPropObj.value
  selectedPropObjList.value = isSelectedPropObjList.length > 0 ? isSelectedPropObjList : selectedPropObjList.value
  skuGroup.value = isSkuGroup
  skuGroupList.value = unique(isSkuGroupList)
  allProperties.value = isAllProperties
  onSetDefaultActivitySku()
  onParseSelectedObjToVals(skuListPar, isChange)
}

/**
 * 将已选的 {key:val,key2:val2}转换成 [val,val2]
 */
const selectedPropertiesNew = ref('')
const selectedPropObjList = ref([])

const selectedPropShowNew = ref([])
const onParseSelectedObjToVals = (skuListPar, isChange = true) => {
  const isSelectedPropObjList = selectedPropObjList.value
  let isSelectedPropertiesNew = ''
  const isSelectedPropNew = []
  const isSelectedPropShowNew = []
  for (let i = 0; i < isSelectedPropObjList?.length; i++) {
    const selectedPropObjItem = isSelectedPropObjList[i]
    for (const key in selectedPropObjItem) {
      if (Object.hasOwnProperty.call(selectedPropObjItem, key)) {
        isSelectedPropNew.push(key + selectedPropObjItem[key])
        isSelectedPropShowNew.push(selectedPropObjItem[key])
        isSelectedPropertiesNew += key + ':' + selectedPropObjItem[key] + ';'
      }
    }
  }
  isSelectedPropertiesNew = isSelectedPropertiesNew.substring(
    0,
    isSelectedPropertiesNew?.length - 1
  )
  selectedPropNew.value = isSelectedPropNew
  selectedPropShowNew.value = isSelectedPropShowNew
  selectedPropertiesNew.value = isSelectedPropertiesNew
  selectedPropObjList.value = isSelectedPropObjList
  let isFindSku = false
  for (let i = 0; i < skuListPar?.length; i++) {
    if (skuListPar[i].properties === isSelectedPropertiesNew && isChange) {
      isFindSku = true
      defaultSku.value = skuListPar[i]
      break
    }
  }
  findSku.value = isFindSku
  onSetDefaultActivitySku()
}

/**
 * 判断当前的规格值 是否可以选
 */
const isSkuLineItemNotOptional = (
  allProperties,
  isSelectedPropObj,
  key,
  item,
  propKeys
) => {
  const selectedPropObj = Object.assign({}, isSelectedPropObj)
  let properties = ''
  selectedPropObj[key] = item
  for (let j = 0; j < propKeys?.length; j++) {
    properties += propKeys[j] + ':' + selectedPropObj[propKeys[j]] + ';'
  }
  properties = properties.substring(0, properties?.length - 1)
  for (let i = 0; i < allProperties?.length; i++) {
    if (properties === allProperties[i]) {
      return false
    }
  }
  for (let i = 0; i < allProperties?.length; i++) {
    if (allProperties[i].indexOf(item) >= 0) {
      return true
    }
  }
  return false
}

/**
 * 规格点击事件
 */
const onToChooseItem = (skuGroupItemIndex, skuLineItem, key) => {
  selectedPropObjList.value[skuGroupItemIndex] =
    selectedPropObjList.value[skuGroupItemIndex] || {}
  selectedPropObjList.value[skuGroupItemIndex][key] = skuLineItem
  selectedPropObj.value[key] = skuLineItem
  onParseSelectedObjToVals(skuList)
  prodNumber.value = 1
}

/**
 * 设置选中的商品活动sku
 */
let originalPriceBuySec
const onSetDefaultActivitySku = (start = 0, type) => {
  let prodActivitySku =
    prodInfo.value.spuType === ProdType.GROUP ? groupActInfo.value.groupSkuList : seckillActInfo.value.seckillSkuList
  if (!prodActivitySku || originalPriceBuySec) {
    return
  }
  prodActivitySku = prodActivitySku.filter((item) => {
    return item.skuId
  })
  let flag = false
  if (prodActivitySku) {
    if (prodActivitySku?.length === 1) {
      flag = true
      defaultActivitySku.value = prodActivitySku[0]
      findSku.value = true
      return
    }
    if (start === 1) {
      flag = true
      let priceFeeList = []
      if (type === 'group') {
        priceFeeList = prodActivitySku.map((item) => {
          return item.priceFee
        })
      } else if (type === 'seckill') {
        priceFeeList = prodActivitySku.map((item) => {
          return item.seckillPrice
        })
      }
      defaultActivitySku.value = prodActivitySku[priceFeeList.indexOf(Math.min(...priceFeeList))]
    } else {
      for (let i = 0; i < prodActivitySku?.length; i++) {
        if (prodActivitySku[i].properties === selectedPropertiesNew.value) {
          flag = true
          defaultActivitySku.value = prodActivitySku[i]
          break
        }
      }
    }
  }
  // 未开始时且找不到sku, 设置默认活动sku为第一个商品sku
  // 仅秒杀活动可禁用sku
  if (!flag && seckillActInfo.value.activityStatus === 1) {
    defaultActivitySku.value = prodActivitySku[0]
    flag = true
  }
  findSku.value = flag
}

/**
 * 去重
 */
const unique = (arr) => {
  const map = {}
  arr.forEach((item) => {
    const obj = {}
    Object.keys(item)
      .sort()
      .map((key) => (obj[key] = item[key]))
    map[JSON.stringify(obj)] = item
  })
  return Object.keys(map).map((key) => JSON.parse(key))
}

/**
 * 查询分销相关信息
 */
const onGetDistInfo = () => {
  // 查询分销开关是否开启
  http.request({
    url: '/tmerclub_marketing/distribution_set/info',
    method: 'GET',
    dontShowLogin: true
  }).then((res) => {
    if (res.distributionSwitch === 1) {
      onGetIsDistInfo()
    }
  }).catch(() => {})
}

/**
 * 查询用户 是否为分销员
 */
const isDist = ref(false) // 是否分销员
const onGetIsDistInfo = () => {
  http.request({
    url: '/tmerclub_marketing/distribution_user/distribution_user_info',
    method: 'GET'
  }).then((res) => {
    if (res && res.state === 1) {
      isDist.value = true
      onGetIsDistProd()
      uni.setStorageSync('cloudDistributionUserId', res.distributionUserId)
    }
  })
}

/**
 * 查询是否为分销商品
 */
const isDistProd = ref(false) // 是否分销商品
const onGetIsDistProd = () => {
  http.request({
    url: '/tmerclub_marketing/ua/distribution_spu/is_state',
    method: 'GET',
    data: {
      spuId: spuId.value,
      state: 1
    }
  }).then((res) => {
    if (res) {
      isDistProd.value = true
    }
  })
}

/**
 * 获取商品收藏状态
 */
const isCollect = ref(false) // 是否收藏
const onGetCollectionInfo = () => {
  if (!uni.getStorageSync('cloudToken')) {
    return
  }
  http.request({
    url: '/tmerclub_product/spu_collection/ma/is_collection',
    method: 'GET',
    data: {
      spuId: spuId.value
    }
  }).then((res) => {
    isCollect.value = res
  })
}

/**
 * 获取高度
 */
let scrollTop = 0
const onGetHeightList = () => {
  const classNameList = ['.comment-box', '.det-det']
  const isHeightList = heightList.value
  for (let i = 0; i < classNameList?.length; i++) {
    uni.createSelectorQuery().select(classNameList[i]).boundingClientRect((data) => {
      // 目标节点
      uni.createSelectorQuery().select('.page-detail').boundingClientRect((res) => {
        // 最外层盒子节点
        if (data.top < 0) {
          scrollTop = Math.abs(res.top) - Math.abs(data.top)
        } else {
          scrollTop = Math.abs(res.top) + Math.abs(data.top)
        }
        isHeightList.push(scrollTop)
      }).exec()
    }).exec()
  }
  heightList.value = isHeightList
}

/**
 * 顶部Tab栏点击，页面滚动至指定位置
 * @param {number} type 0页面置顶; 1滚动至评价; 2滚动至详情
 */
let className = ''
let scrollTop2 = 0
const onHanleTopTabClick = (type) => {
  topTabSts.value = type
  scrolling.value = true
  if (type === 0) {
    uni.pageScrollTo({
      scrollTop: 0,
      duration: 100
    })
  } else {
    className = type === 1 ? 'comment-box' : 'det-det'
    uni.createSelectorQuery().select('.' + className).boundingClientRect((data) => {
      // 目标节点
      uni.createSelectorQuery().select('.page-detail').boundingClientRect((res) => {
        // 最外层盒子节点
        if (data.top < 0) {
          scrollTop2 = Math.abs(res.top) - Math.abs(data.top) - 60
        } else {
          scrollTop2 = Math.abs(res.top) + Math.abs(data.top) - 60
        }
        uni.pageScrollTo({
          duration: 100,
          scrollTop: scrollTop2
        })
      })
        .exec()
    })
      .exec()
  }
  setTimeout(() => {
    scrolling.value = false
  }, 500)
}
/**
 * 获取商品评论数据: 总评论数量,好中差有图评价数量
 */
const commentData = ref({}) // 评论整体数据: 总数,好中差有图 各个数量

const onGetProdCommentData = () => {
  http.request({
    url: '/tmerclub_product/spu_comm/ua/prod_comm_data',
    method: 'GET',
    data: {
      spuId: spuId.value
    }
  }).then((res) => {
    commentData.value = res
  })
}

/**
 * 获取商品评论列表
 */
const commentType = 0 // 评论类型 null/0 全部，1好评 2中评 3差评 4有图
const commentList = ref([]) // 评论列表

const onGetProdCommentList = () => {
  http.request({
    url: '/tmerclub_product/spu_comm/ua/page',
    method: 'GET',
    data: {
      evaluate: commentType,
      pageNum: 1,
      pageSize: 5,
      spuId: spuId.value
    }

  }).then((res) => {
    res.list.forEach((item) => {
      item.createTime = item.createTime.split(' ')[0]
    })
    const currentCommentList = res.list
    for (let i = 0; i < currentCommentList?.length; i++) {
      const commentItem = currentCommentList[i]
      if (commentItem.pics) {
        commentItem.pics = commentItem.pics.split(',')
      }
    }
    commentList.value = currentCommentList
  })
}

/**
 * 收藏/取消收藏 商品
 */
const onCollectGoods = () => {
  util.checkAuthInfo(() => {
    http.request({
      url: '/tmerclub_product/spu_collection/add_or_cancel',
      method: 'POST',
      data: spuId.value
    }).then((res) => {
      if (res) {
        util.tapLog(3, { sid: shopId, bid: spuId.value })
      }
      isCollect.value = res
      uni.showToast({
        title: res ? '收藏成功' : '取消成功',
        duration: 2000,
        icon: 'none'
      })
    })
  })
}

const preventHandler = () => {}

/**
 * 生成小程序二维码
 */

let code = ''
const shareShow = ref(false) // 分享弹窗
const shareWxCode = ref('') // 分享二维码图片路径
const onGenWeixinCode = () => {
  uni.showToast({
    icon: 'loading',
    mask: true,
    duration: 10000,
    title: '海报绘制中'
  })
  const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
  const content = JSON.stringify({
    spuId: spuId.value,
    distributionUserId
  })

  // #ifdef H5 || APP-PLUS
  if (shareType.value === 1) {
    code = `${import.meta.env.VITE_APP_DOMAIN_ADDRESS}/pages/detail/detail?spuId=${spuId.value}`
  } else {
    code = `${import.meta.env.VITE_APP_DOMAIN_ADDRESS}/pages/detail/detail?spuId=${spuId.value}&distributionUserId=${distributionUserId}`
  }
  shareWxCode.value = Qr.createQrCodeImg(code, { size: 250 })
  poster.value = util.getPoster(mainImgUrl, prodInfo.value.priceFee, spuName, shareWxCode.value)

  // #endif
  // #ifdef MP-WEIXIN
  http.request({
    url: '/tmerclub_biz/ua/qrcode_ticket/mini_qrcode',
    method: 'GET',
    responseType: 'arraybuffer',
    data: {
      content,
      type: 2
    }
  }).then((res) => {
    // 微信小程序
    shareWxCode.value = uni.arrayBufferToBase64(res)
    util.base64src(shareWxCode.value).then(res => {
      shareWxCode.value = res
      poster.value = util.getPoster(mainImgUrl, prodInfo.value.priceFee, spuName, shareWxCode.value)
      shareShow.value = true
      showCanvasImg.value = false
    })
  })
  // #endif
}

/**
 * 保存图片至相册
 */
const wxCodeShow = ref(false) // 是否显示二维码弹层
const onDownloadImg = () => {
  uni.showLoading({
    mask: true
  })
  // #ifdef APP-PLUS
  const bitmap = new plus.nativeObj.Bitmap('test')
  bitmap.loadBase64Data(
    shareWxCode.value,
    () => {
      const url = '_doc/' + new Date() + '.png' // url建议用时间戳命名方式
      bitmap.save(
        url,
        {
          overwrite: true
        },
        () => {
          uni.saveImageToPhotosAlbum({
            filePath: url,
            success: () => {
              uni.hideLoading()
              wxCodeShow.value = false
              uni.showToast({
                title: $t('downloadComplete')
              })
              bitmap.clear()
            }
          })
        },
        () => {
          uni.hideLoading()
          bitmap.clear()
        }
      )
    },
    () => {
      uni.hideLoading()
      bitmap.clear()
    }
  )
  // #endif

  // #ifdef MP-WEIXIN
  const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
  uni.downloadFile({
    header: {
      Authorization: uni.getStorageSync('cloudToken')
    },
    url:
      import.meta.env.VITE_APP_BASE_API +
      '/tmerclub_marketing/ua/distribution_qrcode/invitation?page=pages/detail/detail&distributionUserId=' +
      spuId.value +
      ',' +
      distributionUserId,
    success: (res) => {
      uni.hideLoading()
      // 图片保存到本地
      uni.getSetting({
        success: (settingData) => {
          const flag = settingData.authSetting['scope.writePhotosAlbum']
          if (flag === true || flag === undefined) {
            uni.saveImageToPhotosAlbum({
              filePath: res.tempFilePath,
              success: () => {
                wxCodeShow.value = false
                uni.showToast({
                  title: $t('downloadComplete'),
                  icon: 'success',
                  duration: 2000
                })
              },
              fail: () => {
                uni.showToast({
                  title: $t('failedSaveTips'),
                  icon: 'none',
                  duration: 2000
                })
              }
            })
          } else {
            uni.openSetting({
              success: (settingData) => {
                if (settingData.authSetting['scope.writePhotosAlbum']) {
                  uni.showToast({
                    title: $t('failedSave'),
                    icon: 'none',
                    duration: 2000
                  })
                } else {
                  uni.showToast({
                    title: $t('failedSaveTips'),
                    icon: 'none',
                    duration: 2000
                  })
                }
              }
            })
          }
        }
      })
    }
  })
  // #endif
}

/**
 * 分销弹窗相关
 */
const guideShare = ref(false)

const onShareWay = (isShow = true) => {
  const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
  const sharedata = {
    title: spuName, // 分享标题
    imgUrl: mainImgUrl, // 分享图标
    link:
      import.meta.env.VITE_APP_DOMAIN_ADDRESS +
      '/pages/detail/detail?spuId=' +
      spuId.value +
      '&distributionUserId=' +
      distributionUserId, // 分享链接
    desc: sellingPoint || '这个商品不错，快来看看吧！', // 分享描述
    type: '', // 分享类型,music、video或link，不填默认为link
    dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
    dontShowLogin: !isShow
  }
  Wechat.callWexinShare(
    sharedata,
    () => {
      if (isShow) {
        shareShow.value = false
        guideShare.value = true
      }
    }
  )
}
const shareImgUrl = ref('')

/* 保存图片 */
const painterRef = ref(null)
const onSaveImg = () => {
  // #ifndef H5
  painterRef.value.canvasToTempFilePath().then(res => {
    uni.saveImageToPhotosAlbum({
      filePath: res.tempFilePath,
      success () {
        uni.showToast({
          icon: 'none',
          mask: true,
          title: '保存成功'
        })
      },
      fail () {
        uni.showToast({
          icon: 'none',
          mask: true,
          title: '保存失败'
        })
      }
    })
  })
  // #endif
}

/**
 * 显示分享弹窗
 */
const shareType = ref(1) // 1 普通分享 2 分销员分享
const sharePopupShow = ref(false)
const showCanvasImg = ref(true) // 海报图片（小程序不显示）
const showShareBtn = ref(false) // 分享栏

const onShowShare = () => {
  sharePopupShow.value = false
  shareImgUrl.value = ''
  shareShow.value = true
  // #ifndef MP-WEIXIN
  showShareBtn.value = true
  // #endif
  // #ifdef MP-WEIXIN
  showCanvasImg.value = false
  // #endif
  // 从缓存获取分销员卡号，如果没有则去接口获取，以备转发时使用
  const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
  if (!distributionUserId && shareType.value !== 1) {
    http.request({
      url: '/tmerclub_marketing/distribution_user/distribution_user_info',
      method: 'GET'
    }).then(res => {
      uni.setStorageSync('cloudDistributionUserId', res.distributionUserId)
      onGenWeixinCode()
    })
  } else {
    onGenWeixinCode()
  }
}
const onCloseEarn = () => {
  shareShow.value = false
}
/**
 * 关闭二维码弹窗
 */
const onCloseCodePopup = () => {
  wxCodeShow.value = false
}
const onToDistCenterPage = () => {
  uni.navigateTo({
    url: '/package-activities/pages/distribution-center/distribution-center'
  })
}

/**
 * 显示优惠券弹窗
 */
const isShowCouponPopup = ref(false) // 显示优惠券弹窗
const onShowCouponPopup = () => {
  isShowCouponPopup.value = true
}

/**
 * 显示活动优惠弹窗
 */
const isShowDiscountPopup = ref(false) // 显示活动优惠弹窗
const onShowDiscountPopup = () => {
  isShowDiscountPopup.value = true
}

// 不支持配送提示
const onShowNoDeliveryTips = () => {
  uni.showToast({
    title: '此商品不支持在当前地区配送',
    duration: 1200,
    mask: true,
    icon: 'none'
  })
}

/**
 * 显示sku弹窗
 */
const isDelivery = ref(true) // 当前地址是否可配送
const onHandleShowSkuPop = (type, target) => {
  if (!isDelivery.value && deliveryType.value === 1) {
    deliveryType.value = 2
  }
  if (spuMold.value !== 1 && !isDelivery.value && target !== 'add' && !deliveryModeVO.value.hasUserPickUp && !deliveryModeVO.value.hasUserPickUp) {
    onShowNoDeliveryTips()
    return
  }
  // 秒杀原价购买提示框
  if (seckillActInfo.value.activityStatus === 1) {
    popContent.value.content = '秒杀活动即将开始，是否原价购买此商品？'
    popContent.value.cancelText = '取消'
    popContent.value.confirmText = '确认'
    showPop.value = true
    originalPriceBuySec = true
    return
  }
  // 秒杀活动进行时，显示秒杀活动sku
  if (seckillActInfo.value.activityStatus === 2) {
    onHandleShowActivitySku()
    return
  }
  onShowPopEvent(type, target)
}
/**
 * 显示sku弹窗
 */
const isShowSkuPopup = ref(false) // 显示sku弹窗
const skuPopBtnType = ref(1)

const onShowPopEvent = (type, target) => {
  if (target) {
    skuPopConfirmType.value = target === 'add' ? 1 : 2
  }
  showSkuType.value = 0
  skuPopBtnType.value = type
  isShowSkuPopup.value = true
}

/**
 * 显示商品活动sku
 */
const onHandleShowActivitySku = () => {
  //
  if (!isDelivery.value) {
    onShowNoDeliveryTips()
    return
  }
  if (
    seckillActInfo.value.activityStatus === 1 ||
    groupActInfo.value.activityStatus === 1
  ) {
    uni.showToast({
      title: '活动未开始',
      duration: 1200,
      mask: true,
      icon: 'none'
    })
    return
  }
  showSkuType.value = 1
  onSetDefaultActivitySku()
  isShowSkuPopup.value = true
}

/**
 * 显示评论弹窗
 */
const onShowCommentPopup = () => {
  uni.navigateTo({
    url: '/package-user/pages/comment-page/comment-page?spuId=' + spuId.value
  })
}

/**
 * 提示弹窗确认
 */
const onPopConfirm = () => {
  showPop.value = false
  if (
    seckillActInfo.value.activityStatus === 1 &&
    originalPriceBuySec
  ) {
    onShowPopEvent(1, 'buy')
    return
  }
  uni.navigateTo({ url: '/pages/search-page/search-page' })
}

/**
 * 提示弹窗取消
 */
const onPopCancel = () => {
  showPop.value = false
  if (seckillActInfo.value.activityStatus === 1) {
    return
  }
  uni.switchTab({ url: '/pages/index/index' })
}

/**
 * 隐藏弹窗
 */
const onClosePopup = () => {
  isShowCouponPopup.value = false
  isShowDiscountPopup.value = false
  isShowSkuPopup.value = false
  skuPopConfirmType.value = 0
}

/**
 * 去拼团玩法
 */
const onToGroupRules = () => {
  uni.navigateTo({
    url: '/package-activities/pages/group-rules/group-rules'
  })
}

/**
 * 去拼团详情
 */
const onToGroupDet = (groupTeamId) => {
  util.checkAuthInfo(() => {
    uni.navigateTo({
      url:
        '/package-activities/pages/group-detail/group-detail?groupTeamId=' +
        groupTeamId +
        '&spuId=' +
        spuId.value
    })
  })
}

/**
 * 立即购买
 */
let seckillOrderPath = '' // 秒杀订单路径
const onGoSubmit = (orderType) => {
  if (!findSku.value) {
    uni.showToast({
      title: '所选规格无货',
      duration: 2000,
      icon: 'none'
    })
    return
  }
  if (!onCheckStock()) {
    return
  }
  util.checkAuthInfo(() => {
    uni.setStorageSync(
      'cloudShopCartItem',
      JSON.stringify({
        count: prodNumber.value,
        groupSkuId:
          orderType === 'group' ? defaultActivitySku.value.groupSkuId : undefined,
        seckillSkuId:
          orderType === 'seckill' ? defaultActivitySku.value.seckillSkuId : undefined,
        seckillId:
          orderType === 'seckill' ? defaultActivitySku.value.seckillSkuId : undefined,
        distributionUserId: Number(distributionUserId),
        shopId: prodInfo.value.shopId,
        skuId: defaultSku.value.skuId,
        spuId: spuId.value
      })
    )
    uni.navigateTo({
      url: '/package-user/pages/submit-order/submit-order?orderEntry=1' +
        (orderType === 'group' ? '&orderType=1' : (orderType === 'seckill' ? ('&orderType=2&seckillOrderPath=' + seckillOrderPath) : '')) +
        '&spuMold=' + spuMold.value + '&deliveryType=' + deliveryType.value
    })
  })
}

/**
 * 获取秒杀订单路径
 */
const onGetSeckillOrderPath = () => {
  if (!findSku.value) {
    return
  }
  const stock = defaultActivitySku.value.stock
  if (stock < prodNumber.value) {
    uni.showToast({
      title: '库存不足',
      icon: 'none'
    })
    return
  }
  util.checkAuthInfo(() => {
    http.request({
      url: '/tmerclub_seckill/seckill_order/order_path',
      method: 'GET',
      data: {
        spuId: spuId.value
      }
    }).then((res) => {
      seckillOrderPath = res
      onGoSubmit('seckill')
    })
  })
}

/**
 * 获取/更新购物车数据
 */
const cartCount = ref(0)
const onGetCartCount = () => {
  if (uni.getStorageSync('cloudToken')) {
    http.request({
      url: '/tmerclub_product/shop_cart/ma/prod_count',
      method: 'GET',
      data: {}
    }).then((res) => {
      if (res) {
        cartCount.value = res
      }
    })
  }
}

/**
 * 去首页
 */
const onToIndex = () => {
  uni.switchTab({
    url: '/pages/index/index'
  })
}

/**
 * 去购物车
 */
const onToCart = () => {
  uni.switchTab({
    url: '/pages/cart/cart'
  })
}

/**
 * 去店铺首页
 */
let url = ''
const onToShopIndex = () => {
  if (shopInfo.renovationId) {
    url =
      '/package-shop/shop-page/feature-index/feature-index?shopId=' +
      shopInfo.shopId +
      '&renovationId=' +
      shopInfo.renovationId
  } else {
    url = '/package-shop/shop-page/shop-index/shop-index?shopId=' + shopId
  }
  uni.navigateTo({
    url
  })
}

/**
 * 视频的方法
 */
const videoOper = () => {
  if (isPlaying.value) {
    onStopPlay()
  } else {
    startPlay()
  }
}
const playEnd = () => {
  onStopPlay()
}
const startPlay = () => {
  isPlaying.value = true
  setTimeout(() => {
    videoContext.seek(0)
    videoContext.play()
  }, 200)
}
const onStopPlay = () => {
  isPlaying.value = false
  setTimeout(() => {
    videoContext.seek(0)
    videoContext.stop()
  }, 200)
}

/**
 * 根据Ticket获取保存的内容
 */
const onGetContent = () => {
  http.request({
    url: '/tmerclub_biz/ua/qrcode_ticket/get_content',
    method: 'GET',
    data: {
      ticket: scene
    }
  }).then((res) => {
    const content = JSON.parse(res.content)
    const ids = JSON.parse(content.content)
    if (res.type === 1) {
      // pc团购二维码跳转
      spuId.value = ids.spuId
    } else if (res.type === 2) {
      spuId.value = ids.spuId
      distributionUserId = ids.distributionUserId
    }
    onExecutionFunction() // 所有需要加载的函数
  })
}

// 复制链接
const copylink = () => {
  if (shareType.value === 1) { // 普通分享
    const code = `${import.meta.env.VITE_APP_DOMAIN_ADDRESS}/pages/detail/detail?spuId=${spuId.value}`
    uni.setClipboardData({
      data: code,
      showToast: false,
      success: function () {
        uni.showToast({
          title: '复制成功',
          icon: 'none'
        })
        sharePopupShow.value = false
      }
    })
  } else { // 分销分享
    const distributionUserId = uni.getStorageSync('cloudDistributionUserId')
    if (distributionUserId) { // 有分销码
      const code = `${import.meta.env.VITE_APP_DOMAIN_ADDRESS}/pages/detail/detail?spuId=${spuId.value}&distributionUserId=${distributionUserId}`
      uni.setClipboardData({
        data: code,
        showToast: false,
        success: function () {
          uni.showToast({
            title: '复制成功',
            icon: 'none'
          })
          sharePopupShow.value = false
        }
      })
    } else { // 无分销码
      http.request({
        url: '/tmerclub_marketing/distribution_user/distribution_user_info',
        method: 'GET',
        selfLoading: true
      }).then(res => {
        uni.setStorageSync('cloudDistributionUserId', res.distributionUserId)
        const code = `${import.meta.env.VITE_APP_DOMAIN_ADDRESS}/pages/detail/detail?spuId=${spuId.value}&distributionUserId=${res.distributionUserId}`
        uni.setClipboardData({
          data: code,
          showToast: false,
          success: function () {
            uni.showToast({
              title: '复制成功',
              icon: 'none'
            })
            sharePopupShow.value = false
          }
        })
      })
    }
  }
}

const poster = ref('')
const picture = ref(null)

const pictureSuccess = (e) => {
  uni.hideToast()
  picture.value = e
  // #ifdef MP-WEIXIN
  shareShow.value = false
  completeDraw()
  // #endif
}

// 海报绘制完成
const completeDraw = () => {
  // #ifdef MP-WEIXIN
  uni.showShareImageMenu({
    path: picture.value,
    success: () => {
      shareShow.value = false
    },
    fail: () => {
      shareShow.value = false
    }
  })
  // #endif
}

/**
 * 预售时间显示为 ’YYYY-MM-DD‘
 */
const preSellTimeShowHandler = (val) => {
  if (!val) return val
  return val.slice(0, -8).trim()
}

</script>

<style lang="scss" scoped>
@use './detail.scss';
@use '@/popup.scss';
</style>
