<template>
  <view class="goods">
    <nav-bar
      title="商品详情"
      bg-status="solid"
      :scroll-top="scrollTop"
      :left-btns="showBackBtn"
      @left-click="leftBtnsClickHandler"
      @getHeight="getHeaerHeight"
    />
    <scroll-view
      v-if="!isLose"
      class="goods-container"
      :style="{ height: scrollViewHeight }"
      scroll-y
      @scroll="pageScroll"
      :scroll-into-view="toView"
      :scroll-with-animation="isAnimate"
      :scroll-top="tabScrollTop"
    >
      <view class="goods-wrapper">
        <view class="goods-carousel">
          <swiper circular="true" duration="400" @change="swiperChange">
            <swiper-item class="goods-carousel-item" v-for="(item, index) in imgList" :key="index">
              <image :src="item" mode="aspectFill"></image>
            </swiper-item>
          </swiper>
          <view class="goods-carousel-dots">
            <text class="">{{ `${swiperCurrent + 1}/${len}` }}</text>
          </view>
        </view>
        <image
          v-if="labelInfo.bannerUrl"
          :src="labelInfo.bannerUrl"
          mode="widthFix"
          @click="jumpToLabel"
          style="width: 100%"
        />

        <view class="goods-info" :class="{ activity: hasActivity }">
          <view class="goods-info-price" :class="{ activity: hasActivity }">
            <view v-if="hasActivity || maxhasActivity" class="Gi-price-activity">
              <image v-if="detailInfo.activityTagImg" :src="detailInfo.activityTagImg" alt="" mode="widthFix"></image>
              <!-- <image v-if="detailInfo.activityTagImg" src="https://img.lkbang.net/xcx/newUser.png" alt="" mode="widthFix" /> -->
              <!-- 活动 - 新人专享价 -->
              <view v-if="detailInfo.activityType == 8" class="new-user-price-info">
                <view class="new-user-price">
                  <view class="new-user-price-sale">
                    <view class="desc">新人专享价</view>
                    <view class="info" v-if="detailInfo.salePrice">
                      <view class="symbol">¥</view>
                      <view class="num">{{detailInfo.salePrice}}</view>
                    </view>
                  </view>
                  <view class="new-user-price-market" v-if="detailInfo.marketPrice">
                    <text class="desc">销售价</text>
                    <text class="symbol">¥</text>
                    <text class="num">{{detailInfo.marketPrice}}</text>
                  </view>
                </view>
                <view class="new-user-limit-count">
                  <view class="new-user-limit-count-content" v-if="detailInfo.activityLimitCount">
                    <text>每人限{{detailInfo.activityLimitCount}}件</text>
                  </view>
                </view>
              </view>
              <!-- 活动 — max会员价 -->
              <view v-if='maxhasActivity' class="Gi-price-maxactivity">
              <view class="Gi-price-left">
                <text>¥</text>
                <text v-if="detailInfo.activityShareInfo.skuInfoSalePrice">{{detailInfo.activityShareInfo.skuInfoSalePrice || ''}}</text>
                <text class="Gi-price-maxprice" >¥{{ detailInfo.activityShareInfo.discountPrice || detailInfo.salePrice || "" }}</text>
                <image
                  :src="detailInfo.activityShareInfo.icon"
                  mode="heightFix"
                  style="height: 28rpx;"
                  class="Gi-price-maxImage"
                />
                <span v-if="detailInfo.activityShareInfo.discountPriceDesc"  @click="open('max-popup')"  class="iconfont icon-info-line"  />
              </view>

              <view>
                <text v-if="detailInfo.saleCount" class="Gi-price-right"
                  >销量:{{ detailInfo.saleCount || "" }}</text
                >
              </view>

              </view>
              <!-- 活动 - 其他活动(目前仅有特价商品) -->
              <view v-if='!maxhasActivity &&detailInfo.activityType !== 8' style="display: flex;justify-content: space-between;align-items: center;">
                <view v-if="detailInfo.salePrice" style="margin-left:30rpx;" :class="detailInfo.activityTagImg ? 'Gi-price-activity-price' : 'Gi-price-left'">
                  <text>¥</text>
                  <text>{{ detailInfo.salePrice || "" }}</text>
                  <!-- <text v-if="detailInfo.marketPrice">¥{{detailInfo.marketPrice || ''}}</text> -->
                  <!-- <img v-if="detailInfo.userBenefitsLabelImgUrl" :src="detailInfo.userBenefitsLabelImgUrl" class="memberImg" /> -->
                  <image
                  v-if="detailInfo.userBenefitsLabelImgUrl"
                  :src="detailInfo.userBenefitsLabelImgUrl"
                  mode="widthFix"
                  class="memberImg"
                />
                </view>
                <view>
                  <text
                    v-if="!detailInfo.activityTagImg && detailInfo.saleCount"
                    style="margin-right: 30rpx"
                    class="Gi-price-right"
                    >销量:{{ detailInfo.saleCount || "" }}</text
                  >
                </view>
              </view>
            </view>
            <view v-else class="Gi-price-noactivity">
              <view v-if="detailInfo.salePrice" class="Gi-price-left">
                <text>¥</text>
                <text>{{ detailInfo.salePrice || "" }}</text>
                <!-- <text v-if="detailInfo.marketPrice">¥{{detailInfo.marketPrice || ''}}</text> -->
                <image
                  v-if="detailInfo.userBenefitsLabelImgUrl"
                  :src="detailInfo.userBenefitsLabelImgUrl"
                  mode="widthFix"
                  class="memberImg"
                />
              </view>
              <text v-if="!hasActivity && detailInfo.saleCount" class="Gi-price-right"
                >销量:{{ detailInfo.saleCount || "" }}</text
              >
            </view>
          </view>

          <view
            class="goods-info-name"
            :class="{ activity: hasActivity }"
            @longpress="copyTxt"
            :data-txt="goodName"
            >{{ goodName }}</view
          >
          <view v-for="(item, index) in skuSubtitleConf" :key="index" class="goods-info-subtitle">
            <view class="goods-info-subtitle-notice" v-if="item.subtitleType === 2" @click="jumpUrl(item, 'notice')">
              <view v-for="(it, i) in item.subtitleDetail" :key="i">
                {{ it }}
              </view>
            </view>
          </view>
          <view v-for="(item, index) in skuSubtitleConf" :key="index" class="goods-info-subtitle">
            <view v-if="item.subtitleType === 1" @click="jumpUrl(item, 'activity')">
              <view v-for="(it, i) in item.subtitleDetail" :key="i" class="goods-info-subtitle-activity">
                <view>{{ it }}
                  <text class="goods-info-subtitle-activity-subfix" v-if="i === item.subtitleDetail.length - 1">查看></text>
                </view>
              </view>
            </view>
          </view>
          <!-- #ifdef MP-WEIXIN -->
          <view class="goods-info-max" v-if="maxMemberInfo && maxMemberInfo.imgUrl">
            <image @click="toMaxMember(maxMemberInfo.jumpUrl, maxMemberInfo.status)" class="goods-info-max-img" :src="maxMemberInfo.imgUrl" mode="widthFix" />
          </view>
          <!-- #endif -->
        </view>
        <view class="goods-sale" v-if="detailInfo.couponText && couponList.length">
          <goods-cell title="优惠" @click="open('coupon-popup')">
            <text class="goods-sale-button">领券</text>
            <text class="goods-sale-content">{{ detailInfo.couponText }}</text>
          </goods-cell>
          <!-- <goods-cell title="活动" noArrows v-if="detailInfo.activityList && detailInfo.activityList.length">
            <text class="goods-sale-button">满减</text>
              <text v-for="(item, index) in detailInfo.activityList" :key="index">
                <text class="goods-sale-contents">{{ detailInfo.activityList[index] }}</text>
                <text style="color: #999;margin: 0 5px" v-if="index !== detailInfo.activityList.length-1"> | </text>
              </text>
          </goods-cell> -->
        </view>
        <view class="goods-activity" v-if="hasActivity">
            <goods-cell title="活动" noArrows>
              <view class="activity-info">
                <template v-if="detailInfo.activityType == 8 && detailInfo.newComersLabel">
                  <!-- 新人专享 -->
                  <view class="content">
                    <image v-if="detailInfo.newComersLabel.icon" :src="detailInfo.newComersLabel.icon" class="newComersIcon" mode="heightFix" />
                    <text class="newComersLabel" v-if="detailInfo.newComersLabel.labels">{{detailInfo.newComersLabel.labels}}</text>
                  </view>
                </template>
                <template v-else>
                  <text v-if="detailInfo.activityTag" class="goods-activity-button">{{detailInfo.activityTag}}</text>
                  <text  v-for="(item, index) in detailInfo.activityList" :key="index" class="goods-sale-contents">
                    {{ detailInfo.activityList[index] }}<template v-if="index != detailInfo.activityList.length - 1">,</template>
                  </text>
                </template>
              </view>
            </goods-cell>
        </view>
        <view class="goods-param">
          <goods-cell title="已选" @click="openPop(0)">
            <text class="goods-param-text">
              <text v-for="(item, index) in specSelected" :key="index">{{ item.attsValue }}</text>
            </text>
            <text v-if="specSelected.length">；</text>
            <text> &nbsp;{{ selectedGoods.skuNum }}件</text>
          </goods-cell>
          <goods-cell class="goods-param-area" title="送至" @click="open('area-popup')">
            <text
              class="iconfont icon-location-line"
              :class="{ noAddr: !selectedAddress.addrFullName }"
            ></text>
            <text>{{ selectedAddress.addrFullName || "添加收货地址" }}</text>
          </goods-cell>
          <goods-cell
            v-if="labelList.length"
            class="goods-param-service"
            title="服务"
            wrap
            @click="open('service-popup')"
          >
            <text v-for="(item, index) in labelList" :key="index">{{ item.labelName }}</text>
          </goods-cell>
        </view>
        <text
          v-if="skuDetailList.length || detailImgList.length"
          id="goodDetail"
          class="goods-divider"
          >宝贝详情</text
        >
        <view v-if="skuDetailList.length" class="goods-detail">
          <detail-info-area
            :skuDetailList="skuDetailList"
            :skuDetailAtts="skuDetailAtts"
          ></detail-info-area>
        </view>
        <view class="goods-detail-imgs">
          <image
            mode="widthFix"
            style="width: 100%;display:block;"
            v-for="(item, index) in detailImgList"
            :key="index"
            :src="item"
          ></image>
        </view>
        <!-- 价格说明 -->
        <view class="price-wrap">
          <view class="price-text">
            <h3>价格说明</h3>
            <ul>
              <li>
                <text class="title">划线价格</text>
                <view class="price-content">
                  <text>1、该划线价可能是商品（含服务）的门市价、零售价（如品牌指导价、建议零售价）、历史标价中的一项。</text>
                  <text>2、由于地区、时间的差异性和市场行情波动，门市价、零售价等可能会与您购买时展示的不一致，该价格仅供您参考。</text>
                </view>
              </li>
              <li>
                <text class="title">未划线价</text>
                <view class="price-content">
                  <text>1、指商品（含服务）的实时标价，不因表述差异改变性质。</text>
                  <text>2、最终成交价可能会因优惠、促销、让利等更低，最终的成交价格以订单结算页价格为准。</text>
                </view> 
              </li>
              <li>
                <text class="title">注意事项</text>
                <view class="price-content">
                  <text>商品（含服务）促销信息以商品详情页中展示的信息为准；商品（含服务）的具体成交价以订单结算页价格为准；如您发现活动商品售价或促销信息有异常，建议购买前先联系商家咨询。此说明仅当出现价格比较时有效，若商家单独对划线价进行说明的，以商家的表述为准。</text>
                </view>
              </li>
            </ul>
          </view>
        </view>
        <view class="goods-list" id="like">
          <goods-card :goodsList.sync="goodsList"></goods-card>
        </view>
      </view>
    </scroll-view>

    <scroll-view
      v-if="isLose"
      class="goods-container goods-container-lose"
      scroll-y
      @scroll="pageScroll"
      :scroll-into-view="toView"
      @scrolltolower="loadData"
      :scroll-with-animation="isAnimate"
      :scroll-top="tabScrollTop"
    >
      <view class="goods-container-lose-container">
        <image class="noImg" mode="widthFix" src="https://img.lkbang.net/xcx/lose.png"></image>
        <view>您查找的商品失效了!</view>
      </view>

      <view class="goods-list">
        <goods-card id="like" :goodsList.sync="goodsList" :title="title"></goods-card>
      </view>
    </scroll-view>
    <view class="goods-buoy goods-share">
      <image :src="shareIcon"></image>
      <button open-type="share" :data-shareinfo="detailInfo.shareInfo"></button>
    </view>
    <!-- 青海移动不展示猜你喜欢 -->
    <view v-if="goodsList.length" class="goods-buoy goods-like" @click="toLike">
      <image src="https://img.lkbang.net/xcx/like.png"></image>
    </view>
    <view class="goods-top">
      <to-top :scrollTop="scrollTop" @toTop="toTop"></to-top>
    </view>
    <template v-if="popupShow">
      <custom-goods-popup ref="popup" type="bottom" :closeable="true" @hide="popupShow = false">
        <view class="goods-popup">
          <view class="goods-popup-selected">
            <image :src="detailInfo.imageUrl"></image>
            <view class="Gp-selected-right">
              <view class="Gps-right-header">
                <view class="Gpsr-header-price" v-if="detailInfo.salePrice">
                  <text>¥</text>
                  <text>{{ detailInfo.salePrice }}</text>
                </view>
                <!-- <view class="Gpsr-header-discount" v-if="detailInfo.marketPrice">
								<text>原价：</text>
								<text >¥{{detailInfo.marketPrice}}</text>
							</view> -->
              </view>
              <view class="Gps-right-selected" v-if="specSelected.length">
                已选：
                <text v-for="(sItem, sIndex) in specSelected" :key="sIndex">
                  {{ sItem.attsValue }}
                </text>
              </view>
            </view>
          </view>
          <view v-for="(item, index) in specList" :key="index" class="goods-popup-param">
            <text class="Gp-param-name">{{ item.attsName }}</text>
            <view class="Gp-param-list">
              <template v-for="(childItem, childIndex) in specChildList">
                <text
                  v-if="childItem.attsCode === item.attsCode"
                  :key="childIndex"
                  class="tit"
                  :disabled="childItem.disabled"
                  :class="{
                    'Gpp-list-selected': childItem.isSelected && !childItem.disabled,
                    'Gpp-list-disabled': childItem.disabled
                  }"
                  @click="selectSpec(childIndex, childItem)"
                >
                  {{ childItem.attsValue }}
                </text>
              </template>
            </view>
          </view>
          <view class="goods-popup-num">
            <text class="Gp-num-name"
              >购买数量：
              <text class="Gp-num-name-limit" v-if="maxCount.type === 4"
                >(仅限购买{{ maxCount.num }}件)</text
              >
              <text class="Gp-num-name-limit" v-else-if="maxCount.type === 3"
                >(每日限购{{ maxCount.num }}件)</text
              >
            </text>
            <uni-number-box
              disabled
              :min="minCount"
              :max="maxCount.num"
              :value="selectedGoods.skuNum"
              @eventChange="numberChange"
              class="Gp-num-step"
            ></uni-number-box>
          </view>
          <view class="btnGroup">
            <button
              v-if="!noOrderBtn && (specType === 1 || specType === 2)"
              class="goods-bottom-confirm"
              @click="specConfirm"
            >
              确认
            </button>
            <button
              v-if="!noOrderBtn && specType === 0"
              class="goods-bottom-car"
              @click="addToCart('spec')"
            >
              加入购物车
            </button>
            <button
              v-if="!noOrderBtn && specType === 0"
              class="goods-bottom-buy"
              @click="goVccOrDetail('spec')"
            >
              立即购买
            </button>
          </view>
        </view>
      </custom-goods-popup>
    </template>

    <custom-goods-popup
      ref="coupon-popup"
      title="领券优惠券"
      type="bottom"
      zIndex="98"
      :closeable="true"
      mode="size-fixed"
      height="860"
      scrollY
    >
      <couponCard :couponList="couponList" @pickupCoupon="pickupCoupon"></couponCard>
    </custom-goods-popup>
    <custom-goods-popup ref="area-popup" title="配送至" type="bottom" :closeable="true">
      <view class="goods-area">
        <view v-if="addressList && addressList.length">
          <view
            class="goods-area-item "
            :class="{
              'goods-area-item_selected': item.addrReceiverId === selectedAddress.addrReceiverId
            }"
            v-for="(item, index) in addressList"
            :key="index"
            @click="changeAddress(item)"
          >
            <text class="iconfont icon-location-line"></text>
            <text class="secondText">{{ item.addrFullName }}</text>
          </view>
        </view>
        <view v-else class="goods-area-none">暂未添加地址哦～</view>
        <view class="goods-area-button" @click="addAddress">
          <button>添加新地址</button>
        </view>
      </view>
    </custom-goods-popup>
    <custom-goods-popup ref="service-popup"  title="服务说明" type="bottom" :closeable="true">
      <view class="goods-service">
        <view class="goods-service-item" v-for="(item, index) in labelList" :key="index">
          <image :src="item.labelImage"></image>
          <view class="Gs-item-right">
            <text>{{ item.labelName }}</text>
            <text>{{ item.labelExplain }}</text>
          </view>
        </view>
        <view class="goods-service-button"  @click="closePop('service-popup')">
          <button>确定</button>
        </view>
      </view>
    </custom-goods-popup>
    <!-- max会员价说明 -->
    <custom-goods-popup
      ref="max-popup"
      title="活动说明"
      type="bottom"
      height="600"
      :closeable="true"
    >
      <scroll-view scroll-y class="goods-service-max">
          <text v-if="detailInfo.activityShareInfo">{{detailInfo.activityShareInfo.discountPriceDesc | textTrim}}</text>
      </scroll-view>
    </custom-goods-popup>

    <view v-if="stockState.areaStockState !== 1">
      <noneStock />
    </view>

    <bottom-nav
      type="shoppingCar"
      @buy="openPop(2)"
      @addToCart="openPop(1)"
      @goLogin="goLogin"
      @goSimilar="goSimilar"
      :goodsId="detailInfo.skuNo"
      :noGoods="noOrderBtn || isLose || stockState.areaStockState !== 1"
    />
    <login-popup ref="login-popup" @login="loginFinish"></login-popup>

    <!-- ka渠道弹层 -->
    <uni-popup ref="commonPopup" closeable @change="change">
      <!-- hide-cancel-btn -->
      <uni-popup-dialog
        type="base"
        content="申请享花卡额度即可免费领取哦~~"
        message=""
        title=" "
        :duration="2000"
        :before-close="true"
        hide-cancel-btn
        confirmTxt="立即开通"
        @confirm="openVcc(true)"
      />
    </uni-popup>

    <uni-popup ref="subPopup">
      <uni-popup-dialog
        type="base"
        content="宝宝真的不考虑免费领取了么？过了这个村就没那个店咯~"
        message=""
        title=" "
        :duration="2000"
        :before-close="true"
        cancelTxt="残忍拒绝"
        confirmTxt="立即开通"
        @confirm="openVcc(false)"
        @cancel="goDoodsDetail"
      />
    </uni-popup>
    <!-- ka渠道弹层 end -->
    <!-- #ifndef MP-BAIDU -->
    <tougdunCanvas />
    <!-- #endif -->

  </view>
</template>
<script>
import {
  detailInfo,
  addrList,
  getCouponList,
  userPickupCoupon,
  goodsLike,
  hasOrder,
  addSkuToCart
} from "@/api/home.api.js";
import goodsCell from "./components/goodsCell";
import goodsCard from "./components/goodsCard";
import detailInfoArea from "./components/detailInfo";
import uniNumberBox from "@/components/uni-number-box";
import bottomNav from "@/components/goodsDetailNav";
import navBar from "@/components/navBar";
import toTop from "@/components/toTop";
import noneStock from "./components/noneStock";
import loginPopup from "@/components/loginPopup";
import customGoodsPopup from "@/components/customGoodsPopup";
import requestAbortMixin from "@/mixins/requestAbort.mixin";
import couponCard from "@/components/couponCard";
import { saTrackEvent, setRegisterPage } from "@/utils/sa.js";
import uniPopup from "@/components/uni-popup/uni-popup";
import uniPopupDialog from "@/components/uni-popup/uni-popup-dialog";
import { setTimeout } from "timers";
import tougdunCanvas from "@/components/tougdunCanvas.vue";
import { mapState, mapMutations } from "vuex";
import { jumpToUrl } from "@/mixins/common";
import { mpConfig } from "@/utils/mpConfig/types";
import { throtte } from "@/utils/index";
const clickAreaType = {
  "coupon-popup": "优惠券区",
  popup: "规格区",
  "area-popup": "地址区",
  "service-popup": "服务区"
};
let navBarLeftBtns = [{ icon: "arrow-left" }, { icon: "home" }];

export default {
  components: {
    goodsCell,
    goodsCard,
    couponCard,
    uniNumberBox,
    bottomNav,
    navBar,
    toTop,
    noneStock,
    loginPopup,
    customGoodsPopup,
    detailInfoArea,
    uniPopup,
    uniPopupDialog,
    tougdunCanvas
  },
  mixins: [requestAbortMixin],
  filters: {
    textTrim(val) {
      return typeof val === 'string' ? val.trim(): val;
    }
  },
  computed: {
    ...mapState(["cartCount"]),
    goodName() {
      return this.detailParam.goodsName || this.detailInfo.skuName;
    },
    skuDetailList() {
      let arr = [];
      this.skuDetailAtts &&
        this.skuDetailAtts.forEach(item => {
          arr = arr.concat(item.groupAtts);
        });
      if (arr <= 5) {
        return arr;
      }
      return arr.slice(0, 5);
    },
    title() {
      return this.isLose ? "猜你喜欢" : "你可能还喜欢";
    },
    shopBtnName() {
      return this.isLose ? "商品失效" : "立即购买";
    },
    minCount() {
      return this.detailInfo.stock ? 1 : 0;
    },
    len() {
      return this.imgList.length;
    },
    maxCount() {
      const v = this.detailInfo;
      let num = 999999999;
      let type = 1; // 1库存，2普通限购，3，每日限购，4活动限购
      // 库存
      if (v.stock && v.stock > 0) {
        num = Math.min(v.stock + 1, num);
      }
      // 活动限购数量
      if (v.activityLimitCount) {
        num = Math.min(v.activityLimitCount, num);
        type = 4;
      }
      // 每日限购
      else if (v.commonLimitCount) {
        num = Math.min(v.commonLimitCount, num);
        type = 3;
      }
      // 普通限购
      else if (v.limitCount) {
        num = Math.min(v.limitCount, num);
        type = 2;
      }
      return {
        num,
        type
      };
    }
  },

  data() {
    return {
      isAnimate: mpConfig.isAnimate,
      shareIcon: mpConfig.shareIcon,
      popupShow: false,
      noOrderBtn: true, // 是否展示 ‘立即购买’ 按钮：true 禁止（默认）false 放开
      isLose: false, // 商品是否已经失效
      specType: null, // 选择规格弹起时机：0--选择规格时弹起，1--点击bottomNav中的加入购物车，2--点击bottomNav中的立即购买
      tabScrollTop: 0,
      detailParam: {
        skuNo: "",
        receiverId: "",
        count: 1
      },
      old: {
        scrollTop: 0
      },
      toView: "",
      hasActivity: false,
      specSelected: [],
      scrollTop: 0,
      scrollViewHeight: '',
      detailInfo: {
        activityShareInfo: {},
      },
      favorite: true,
      labelList: [], // 服务标签
      imgList: [],
      skuSubtitleConf: [],
      labelInfo: {},
      detailImgList: [], // 商品详情图像展示
      selectedGoods: {
        skuNum: 1,
        skuId: ""
      },
      skuDetailAtts: [],
      addressList: [],
      selectedAddress: {},
      specList: [],
      specChildList: [],
      swiperCurrent: 0,
      goodsList: [],
      searchData: {
        goodsId: "",
        appPrePage: ""
      },
      couponList: [],
      channelState: "",
      popupSwitch: true,
      vccChannel: "",
      sonVccChannel: "",
      showBackBtn: navBarLeftBtns,
      stockState: {
        areaStockState: 1 // 0-无货 1-有货（现货） 2-采购中
      }, //库存状态
      maxMemberInfo: null, // max 会员相关信息
      maxhasActivity:false // max 会员
    };
  },
  watch: {
    detailInfo: {
      deep: true,
      immediate: true,
      handler(val) {
        console.log(val, "33333333");
      }
    },
    skuSubtitleConf: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val.length) {
          val.forEach(item => {
            console.log(item);
            item.subtitleDetail = typeof(item.subtitleDetail) === 'string' ? item.subtitleDetail.split('\n') || [] : item.subtitleDetail;
          })
        }
      }
    }
  },
  onShareAppMessage(res) {
    const that = this;
    saTrackEvent("PD_YXMMAEC_UserClickCommodityDetailShareBtn", {
      commodity_id: that.detailInfo.skuNo
    });
    uni.reportAnalytics("c_commoditydetailsharebtn", {
      commodity_id: that.detailInfo.skuNo
    });
    const dataset = res.target ? res.target.dataset.shareinfo : this.detailInfo;
    return {
      title: dataset.shareTitle || dataset.skuName,
      // #ifdef MP-BAIDU
      content: dataset.shareDesc || "",
      // #endif
      // #ifdef MP-ALIPAY
      desc: dataset.shareDesc || "",
      // #endif
      path: `/pages/product/goodDetail?skuNo=${this.detailInfo.skuNo}&count=1`, //目前商品只有一个sku,可以直接用detailInfo.skuNo
      imageUrl: dataset.shareImgUrl || dataset.imageUrl
    };
  },
  async onLoad(option) {
    this.channelState = option.channel;
    if (option.goodsName) option.goodsName = decodeURIComponent(option.goodsName);
    if (option.scene) {
      this.detailParam.skuNo = JSON.stringify(option.scene).match(/qrSkuNo\*\*(\S*)%3B/)[1];
    } else {
      this.detailParam = { ...this.detailParam, ...option };
    }

    option.goodsImage && this.imgList.push(option.goodsImage);
    // 是否展示立即支付按钮
    [this.noOrderBtn] = await hasOrder();
    // this.showBackBtn = getCurrentPages().length > 1 ? navBarLeftBtns : false;

    // 猜你喜欢
    this.loadData();
    // 收货地址
    this.getAddr();
    uni.$on("login", data => {
      this.$refs["area-popup"].close();
      uni.$emit("cartUpdate");
      this.init(this.detailParam);
      this.getAddr();

      this.getCoupon(this.detailInfo);
    });
    uni.$on("addrAddInfo", data => {
      this.detailParam.receiverId = data.addrReceiverId;
      this.$refs["area-popup"].close();
      this.init(this.detailParam);
      this.getAddr();
    });
  },
  async onShow() {
    console.log(typeof this.tenantId, this.tenantId, "tenantId");
    this.selectedGoods.skuNum = 1;
    this.specSelected = [];
    this.vccChannel = uni.getStorageSync("vccChannel") || "";
    this.sonVccChannel = uni.getStorageSync("sonVccChannel") || "";
    setRegisterPage({
      parent_channelid: this.vccChannel,
      son_channelid: this.sonVccChannel
    });
    console.log("this.detailParam :>> ", this.detailParam);
    await this.init(this.detailParam);
    //选择的商品规格
    this.getSelectedSkuNo(this.specSelected);
    //优惠券列表
    this.getCoupon(this.detailInfo);

    // #ifdef MP-ALIPAY
    uni?.hideBackHome();
    // #endif

  },
  onUnload() {
    uni.$off("login");
    uni.$off("addrAddInfo");
  },
  methods: {
    ...mapMutations(["saveCartCount"]),
    async addToCart(fromSpec) {
      if (fromSpec) {
        saTrackEvent("MINI_CommodityDetailPageStandardColumnPopupWindowBtnClick", {
          sku_no: this.detailInfo.skuNo,
          buttons_name: "加入购物车"
        });
      }
      // this.saveCartCount(this.cartCount + 1);
      const { skuId, skuNum } = this.selectedGoods;
      const { skuSource } = this.detailInfo;
      const params = {
        shopCartBaseList: [
          {
            skuId,
            skuNum,
            skuSource,
            type: 1
          }
        ],
        selected: true
      };
      const [data] = await addSkuToCart(params);
      if (data) {
        uni.$emit("cartUpdate");

        // this.$refs['popup'].close();
        // this.popupShow=false
        this.$set(this, "popupShow", false);

        uni.showToast({
          title: "购物车添加成功",
          icon: "none"
        });
      }
    },
    jumpToLabel() {
      const url = decodeURIComponent(this.labelInfo.bannerJumpUrl.split("url=")[1]);
      if (this.labelInfo.bannerJumpUrl === "" || url === '""') {
        return;
      }
      if (this.labelInfo.bannerJumpUrl === "/pages/index/index") {
        uni.switchTab({
          url: this.labelInfo.bannerJumpUrl
        });
      } else {
        uni.navigateTo({
          url: this.labelInfo.bannerJumpUrl
        });
      }
    },
    // 弹框关闭
    closePop(key){
      this.$refs[key].close();
    },
    openPop(specType) {
      this.specType = specType;
      this.$set(this, "popupShow", true);
      this.$nextTick(() => {
        this.open("popup");
      }, 100);
    },
    goSimilar() {
      const des =
        this.stockState.areaStockState !== 1
          ? "当前区域无库存,不能购买"
          : this.isLose
          ? "商品已失效，不能购买"
          : "";
      uni.navigateTo({
        url: `/pages/product/similar?skuNo=${this.detailInfo.skuNo}&goodsName=${this.goodName}&goodsImage=${this.detailInfo.imageUrl}&des=${des}`
      });
    },
    specConfirm() {
      //specType 1--点击bottomNav中的加入购物车，2--点击bottomNav中的立即购买
      if (this.specType === 1) {
        saTrackEvent("MINI_CommodityDetailPageAddShoppingCartPopupWindowConfirmBtnClick", {
          sku_no: this.detailInfo.skuNo
        });
        this.addToCart();
      }
      if (this.specType === 2) {
        saTrackEvent("MINI_CommodityDetailPageBuyNowPopupWindowConfirmBtnClick", {
          sku_no: this.detailInfo.skuNo
        });
        this.goVccOrDetail();
      }
    },
    isSelectSpecifications() {
      // 如果2种规格都超过2种需要都选中才能提交
      // 如果没有规格直接提交
      // 如果1种规格只有1种状态直接提交
      let isOne = false;
      let isSelect = true;
      if (this.specList.length === 1) {
        isOne = true;
      }
      this.specList.forEach(pItem => {
        if (pItem.attsValues.length === 1) {
          isOne = true;
        }
      });
      if (!isOne && this.specSelected.length && this.specSelected.length < 2) {
        isSelect = false;
      }
      return isSelect;
    },
    // ka渠道逻辑
    goVccOrDetail(fromSpec) {
      // 点击立即购买
      if (fromSpec) {
        saTrackEvent("MINI_CommodityDetailPageStandardColumnPopupWindowBtnClick", {
          sku_no: this.detailInfo.skuNo,
          buttons_name: "立即购买"
        });
      }
      console.log(this.channelState);
      const isSelect = this.isSelectSpecifications();
      if (!isSelect) {
        uni.showToast({
          title: "请选择规格",
          icon: "none"
        });
        return;
      }
      if (this.channelState === "ka") {
        this.goVcc();
      } else {
        this.toOrder();
      }
    },
    openVcc(type) {
      const vm = this;
      vm.popupSwitch = false;
      if (type) {
        saTrackEvent("MINI_KAChannelActivityPageApplyVccPopupBtnClick", {
          page_url: "pages/product/goodDetail",
          parent_channel_id: uni.getStorageSync("vccChannel") || "",
          son_channel_id: uni.getStorageSync("sonVccChannel") || "",
          buttons_name: "立即开通"
        });
      } else {
        saTrackEvent("MINI_KAChannelActivityPageVccRetainPopupBtnClick", {
          page_url: "pages/product/goodDetail",
          parent_channel_id: uni.getStorageSync("vccChannel") || "",
          son_channel_id: uni.getStorageSync("sonVccChannel") || "",
          buttons_name: "立即开通"
        });
      }
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/webview/webview?channel=ka&vccChannel=${vm.vccChannel}&sonVccChannel=${vm.sonVccChannel}`
        });
      }, 500);
    },
    change(val) {
      console.log(val);
      console.log(this.popupSwitch);
      if (!val.show && this.popupSwitch) {
        this.$refs["subPopup"].open();
        saTrackEvent("MINI_KAChannelActivityPagePopupExposure", {
          page_url: "pages/product/goodDetail",
          parent_channel_id: uni.getStorageSync("vccChannel") || "",
          son_channel_id: uni.getStorageSync("sonVccChannel") || "",
          buttons_name: "挽留"
        });
        saTrackEvent("MINI_KAChannelActivityPageApplyVccPopupBtnClick", {
          page_url: "pages/product/goodDetail",
          parent_channel_id: uni.getStorageSync("vccChannel") || "",
          son_channel_id: uni.getStorageSync("sonVccChannel") || "",
          buttons_name: "取消"
        });
        this.popupSwitch = true;
      }
    },
    goVcc() {
      this.popupSwitch = true;
      this.$refs["commonPopup"].open();
      saTrackEvent("MINI_KAChannelActivityPagePopupExposure", {
        page_url: "pages/product/goodDetail",
        parent_channel_id: uni.getStorageSync("vccChannel") || "",
        son_channel_id: uni.getStorageSync("sonVccChannel") || "",
        buttons_name: "申请享花卡"
      });
    },
    goDoodsDetail() {
      saTrackEvent("MINI_KAChannelActivityPageVccRetainPopupBtnClick", {
        page_url: "pages/product/goodDetail",
        parent_channel_id: uni.getStorageSync("vccChannel") || "",
        son_channel_id: uni.getStorageSync("sonVccChannel") || "",
        buttons_name: "残忍拒绝"
      });
      this.goVccOrDetail();
    },
    // ka渠道逻辑 end
    async init(detailParam) {
      const [res, err] = await detailInfo(detailParam);
      console.log("ka渠道逻辑", res, err);
      if (err) {
        if (err.response && +err.response.businessCode === 6041) {
          this.isLose = true;
        }
        // if (!res || !res.skuNo) {
        //   this.isLose = true;
        // }
        return;
      }
      (this.stockState = res.stockState || {}), (this.imgList = res.imageList || []);
      (this.detailImgList = res.detailImages || []), (this.labelList = res.labelList || []);
      this.skuSubtitleConf = res.skuSubtitleConf || [];
      this.detailInfo = res;
      this.labelInfo = res.labelInfo || {};
      this.maxMemberInfo = res.maxMemberInfo || null;
      saTrackEvent("PD_YXMMAEC_CommodityDetailPageExposure", {
        commodity_id: this.detailInfo.skuNo
      });
      if (res.stock === 0) {
        this.detailInfo.limitCount = 1;
        this.detailInfo.activityLimitCount = 0;
        uni.showToast({
          title: "库存不足！",
          duration: 2000,
          icon: "none"
        });
      }
      this.hasActivity = (this.detailInfo.activityList && this.detailInfo.activityList.length>0) || this.detailInfo.activityType == 8 ? true : false;
      this.maxhasActivity = this.detailInfo.activityShareInfo &&this.detailInfo.activityShareInfo.discountType === 9 ? true : false;
      this.skuDetailAtts = res.skuDetailAtts;
      this.selectedAddress = res.receiverInfo || {};
      this.specList = res.skuAtts || [];
      let li = [];
      this.specSelected = [];
      this.specList.forEach(item => {
        item.attsValues.forEach(i => {
          i.attsCode = item.attsCode;
          if (i.isSelected) {
            this.specSelected.push(i);
          }
        });
        li = li.concat(item.attsValues);
      });
      this.specChildList = li;
    },

    async getAddr() {
      const token = uni.getStorageSync("token") || "";
      if (token) {
        const [addressInfo] = await addrList();
        this.addressList = (addressInfo && addressInfo.addrReceiverList) || [];
      }
    },

    async getCoupon(detailInfo) {
      if (this.isLose || !detailInfo.skuNo) return false;
      const [couponInfo] = await getCouponList({
        skuNo: detailInfo.skuNo || "",
        skuSource: detailInfo.skuSource || "",
        businessType: detailInfo.businessType || 1, // 1-无息，2-现金贷
        couponId: detailInfo.couponId || ""
      });
      this.couponList = couponInfo && couponInfo.coupons;
    },
    //领取优惠券
    async pickupCoupon(coupon) {
      const token = uni.getStorageSync("token") || "";
      if (!token) {
        this.$refs["login-popup"].open();
        return;
      }
      const that = this;
      try {
        const [res, error] = await userPickupCoupon({
          couponId: coupon.id,
          couponType: coupon.couponCategory,
          sourceId: that.detailInfo.skuNo, //场景为1时，表示商品的skuNo
          couponLimitScope: 1, // 优惠券场景限制：1：商品
        });

        saTrackEvent("PD_YXMMAEC_UserClickCommodityDetailCouponCollectionBtn", {
          commodity_id: that.detailInfo.skuNo,
          coupon_id: coupon.id
        });
        if (error) return;
        uni.showToast({
          title: "领取成功！",
          duration: 1000,
          icon: "none"
        });
        setTimeout(() => {
          that.getCoupon(that.detailInfo);
        }, 1000);
      } catch (err) {
        console.log(err);
      }
    },
    loginFinish() {
      console.log("登录弯沉");
      Object.keys(this.$refs).forEach(key => {
        this.$refs[key].close();
      });

      uni.$emit("cartUpdate");
      this.init(this.detailParam);
    },
    //数量
    numberChange(data) {
      console.log("data.number :>> ", data.number);
      this.selectedGoods.skuNum = data.number;
    },
    goLogin() {
      this.$refs["login-popup"].open();
    },
    addAddress() {
      const token = uni.getStorageSync("token") || "";
      if (!token) {
        this.$refs["login-popup"].open();
        return;
      }
      this.$refs["area-popup"].close();
      uni.navigateTo({
        url: "/subPackages/common/address/addressManage"
      });
    },
    jumpUrl(item, type) {
      if (item.jumpUrl) {
        jumpToUrl(item.jumpUrl);
      }
      if (type === 'activity') {
        saTrackEvent("MINI_CommodityDetailSubtitleClick", {
          commodity_id: this.detailInfo.skuNo,
          isLogin: !!uni.getStorageSync("token"),
        });
      }
    },
    toOrder() {
      console.log(this.channelState);

      if (this.noOrderBtn) {
        return;
      }
      if (this.detailInfo.stock === 0) {
        uni.showToast({
          title: "库存不足！",
          duration: 2000,
          icon: "none"
        });
        return;
      }
      this.$refs["popup"].close();

      if (this.isLose) {
        uni.showToast({
          title: "商品已失效",
          duration: 2000,
          icon: "none"
        });
        return;
      }

      const that = this;
      saTrackEvent("PD_YXMMAEC_UserClickCommodityDetailBuyNowBtn", {
        commodity_id: that.selectedGoods.skuId
      });
      uni.reportAnalytics("c_commoditydetailbuynowbtn", {
        commodity_id: that.selectedGoods.skuId,
        uuid: uni.getStorageSync("userAuthInfo").uuid || "",
        channel_id: uni.getStorageSync("vccChannel") || ""
      });
      const token = uni.getStorageSync("token") || "";
      if (!token) {
        that.$refs["login-popup"].open();
        return;
      }
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/order/createOrder`,
          success: function(res) {
            res.eventChannel.emit("onDetailConfirmInfo", {
              addrReceiverId: that.selectedAddress.addrReceiverId,
              selectedSkuList: [
                {
                  skuId: that.selectedGoods.skuId,
                  skuNum: that.selectedGoods.skuNum,
                  skuSource: that.detailInfo.skuSource
                }
              ],
              defaultUseCoupon: true,
              defaultUseFreightFeeCoupon: true,
              defaultUseCashCoupon: true,
              defaultUseActivityCoupon: true,
              defaultUseGiftCard: true,
              couponActivityUseIdList: []
            });
          }
        });
      }, 200);
    },
    pageScroll: throtte(function(val) {
      this.toView = "";
      this.scrollTop = val.detail.scrollTop;
      this.old.scrollTop = val.detail.scrollTop;
    }, 1000),

    async loadData() {
      // 商品详情没有无限流 只有20条数据
      this.searchData.goodsId = this.detailParam.skuNo || "";
      if (this.searchData.goodsId && this.searchData.goodsId !== 'undefined') {
        const [res] = await goodsLike(this.searchData);
        this.goodsList = this.goodsList.concat((res && res.goodsList) || []);
      }
    },

    changeAddress(address) {
      // 选取规格需要清空，init会重新赋值
      this.specSelected = [];
      this.goodsList = [];
      this.detailParam = {
        count: this.selectedGoods.skuNum,
        skuNo: this.selectedGoods.skuId,
        receiverId: address.addrReceiverId
      };
      this.$refs["area-popup"].close();
      this.init(this.detailParam);
      this.loadData();
    },
    // 定位到猜你喜欢
    toLike() {
      this.$nextTick(() => {
        this.toView = "like";
        console.log("==============================", this.toView);
      });
    },
    //滚动到顶部
    toTop() {
      this.tabScrollTop = this.old.scrollTop;
      this.$nextTick(function() {
        this.tabScrollTop = 0;
      });
    },
    getArrEqual(arr1, arr2) {
      let newArr = [];
      for (let i = 0; i < arr2.length; i++) {
        for (let j = 0; j < arr1.length; j++) {
          if (arr1[j] === arr2[i]) {
            newArr.push(arr1[j]);
          }
        }
      }
      return newArr;
    },
    getSelectedSkuNo(specSelected) {
      if (!specSelected || !specSelected.length) {
        this.selectedGoods.skuId = this.detailInfo.skuNo;
        return;
      }
      // console.log('thiisspecSelected',list)
      let list = JSON.parse(JSON.stringify(specSelected));
      if (specSelected.length === 1) {
        this.selectedGoods.skuId = specSelected[0].skuNos[0];
      } else {
        this.selectedGoods.skuId =
          this.getArrEqual(specSelected[0].skuNos, specSelected[1].skuNos)[0] || "";
      }

      const itemPrice = this.detailInfo.skuNoPriceVOS?.filter(p => {
        return p.skuNo === this.selectedGoods.skuId;
      }) || [];
      if (itemPrice.length) {
        // this.detailInfo.marketPrice = itemPrice[0].marketPrice;
        this.detailInfo.salePrice = itemPrice[0].salePrice;
      }
    },

    //选择规格
    selectSpec(index, sku) {
      if (sku.isSelected || sku.disabled) {
        return;
      }
      let list = this.specChildList;
      list.forEach(item => {
        // item.isSelected = false;
        this.$set(item, "disabled", true);
        if (item.attsCode === sku.attsCode) {
          this.$set(item, "isSelected", false);
        }
        item.skuNos.forEach(i => {
          if (sku.skuNos?.indexOf(i) !== -1 || item.attsCode === sku.attsCode) {
            this.$set(item, "disabled", false);
          }
        });
        if (item.disabled) {
          item.isSelected = false;
        }
      });

      this.$set(list[index], "isSelected", true);
      this.specSelected = [];
      list.forEach(item => {
        if (item.isSelected) {
          this.specSelected.push(item);
        }
      });
      this.getSelectedSkuNo(this.specSelected);
      this.selectedGoods.skuNum = 1;
      this.detailParam = {
        count: this.selectedGoods.skuNum,
        skuNo: this.selectedGoods.skuId,
        receiverId: this.detailParam.receiverId
      };
      this.init(this.detailParam);
      this.loadData();
    },
    toFavorite() {
      this.favorite = !this.favorite;
    },
    swiperChange(e) {
      const index = e.detail.current;
      console.log("index :>> ", index);
      this.swiperCurrent = index;
    },
    open(ref) {
      const token = uni.getStorageSync("token") || "";
      if (clickAreaType[ref]) {
        saTrackEvent("PD_YXMMAEC_UserClickCommodityDetailCommodityAttribute", {
          commodity_id: this.detailInfo.skuNo,
          attribute_type: clickAreaType[ref]
        });
      }
      if (ref === "area-popup" && !token) {
        this.$refs["login-popup"].open();
        return;
      }
      if (ref === "popup" && this.detailInfo.stock === 0) {
        uni.showToast({
          title: "库存不足！",
          duration: 2000,
          icon: "none"
        });
        return;
      }
      this.$refs[ref].open();
    },
    copyTxt(e) {
      saTrackEvent("PD_YXMMAEC_UserCopyCommodityDetailContent", {
        copy_content: e.currentTarget.dataset.txt,
        sku_no: this.detailParam.skuNo
      });
      uni.setClipboardData({
        data: e.currentTarget.dataset.txt,
        success: () => {
          /* #ifdef MP-ALIPAY */
          uni.showToast({
            title: "复制成功",
            icon: "none"
          });
          /* #endif */
        }
      });
    },
    leftBtnsClickHandler(e) {
      if (e.item.icon === 'arrow-left') {
        const routeLength = getCurrentPages().length;
        routeLength > 1
          ? uni.navigateBack({ delta: 1 })
          : uni.switchTab({
              url: "/pages/index/index"
            });
      } else if (e.item.icon === 'home') {
        uni.switchTab({
          url: "/pages/index/index"
        });
      }
    },
    jumpToUrl,
    toMaxMember(url, status) {
      saTrackEvent("MINI_MaxMemberEntryBtnClick", {
        entry_btn_status: status,
        page_name: "商品详情页",
        commodity_id: this.detailInfo.skuNo || ''
      });
      jumpToUrl(url);
    },
    getHeaerHeight(h) {
      this.scrollViewHeight = `calc(100% - ${h}px)`;
    }
  }
};
</script>
<style lang="scss" scoped>
@import "./goodDetail.scss";
</style>
