<template>
  <mescroll-vue
    class="goods-con"
    ref="mescrollRef"
    @init="mescrollInit"
    :down="downOption"
    :up="upOption"
  >
    <goods-header
      :scrollTop="scrollTop"
      @click="handleScrollTo"
      :commRef="$refs.goodsComm"
      :detailRef="$refs.goodsDetail"
    />

    <goods-img-swiper
      :list="goodsDetail.swiperList"
      @previewItem="previewItem"
    />
    <goods-pre-sale-info v-if="goodsTypeObj.comm.preSale" :data="preSaleData" />
    <goods-desc
      :data="goodsDetail.desc"
      :goodsId="goodsId"
      :goodsTypeMap="goodsTypeMap"
      :transferData="transferData"
    />
    <goods-discount
      v-if="goodsTypeObj.comm.discount"
      @click="handleDiscount"
      :data="goodsDetail.discount"
    />
    <goods-sku-addr
      v-if="goodsTypeObj.comm.skuAndAddr"
      :sku="selectSku"
      :addr="selectAddr"
      :skuList="goodsDetail.skuList"
      :goodsTypeMap="goodsTypeMap"
      :transferData="transferData"
      @sku="handleSku"
      @addr="handleAddr"
    />
    <!-- <goods-comment
      ref="goodsComm"
      :goodsId="goodsId"
      :merchant="goodsDetail.merchant"
      @previewItem="previewItem"
    /> -->
    
    <!-- <goods-featured /> -->
    <goods-detail ref="goodsDetail" :data="goodsDetail.details" />
    
    <goods-prop :data="goodsDetail.prop" />
    <goods-shop
      :data="goodsDetail.merchant"
      ref="shopDom"
      :comment="goodsDetail.comment"
    />
    <!-- <goods-service /> -->

    <goods-footer
      @cart="handleCart"
      @buy="handleBuy"
      :merchant="goodsDetail.merchant"
      :goodsType="goodsType"
      :goodsTypeMap="goodsTypeMap"
      :transferData="transferData"
      :goodsDesc="goodsDetail.desc"
      :goodsStatusMap="goodsStatusMap"
    />

    <goods-sku-popup
      v-model="showSku"
      :type="skuPopupType"
      :desc="goodsDetail.desc"
      :skuList="goodsDetail.skuList"
      :skuMap="goodsDetail.skuMap"
      :goodsTypeMap="goodsTypeMap"
      :transferData="transferData"
      :details="goodsDetail.details"
      :goodsStatusMap="goodsStatusMap"
      @skuChange="handleSkuChange"
      @cart="confirmCart"
      @buy="confirmBuy"
    />
    <addr-select-popup
      v-if="goodsTypeObj.comm.skuAndAddr"
      ref="addrSelectPopup"
      v-model="showAddr"
      :requiresAuth="false"
      @confirm="handleAddrSelect"
    />
    <goods-discount-popup
      v-if="goodsTypeObj.comm.discount"
      v-model="showDiscount"
      :data="goodsDetail.discount"
    />
    <!-- <m-preview ref="Preview" /> -->
  </mescroll-vue>
</template>

<script>
import GoodsHeader from "./goods-header.vue";
import GoodsFooter from "./goods-footer.vue";
// import MPreview from "@/pages/components/preview/preview.vue";

import GoodsImgSwiper from "./goods-img-swiper.vue";
import GoodsDesc from "./goods-desc.vue";
import GoodsDiscount from "./goods-discount.vue";
import GoodsSkuAddr from "./goods-sku-addr.vue";
import GoodsComment from "./goods-comment.vue";
import GoodsShop from "./goods-shop.vue";
import GoodsFeatured from "./goods-featured.vue";
import GoodsDetail from "./goods-detail.vue";
import GoodsProp from "./goods-prop.vue";
import GoodsService from "./goods-service.vue";
import GoodsPreSaleInfo from "./goods-pre-sale-info.vue";

import GoodsSkuPopup from "./goods-sku-popup.vue";
import AddrSelectPopup from "@/components/addr-select-popup.vue";
import GoodsDiscountPopup from "./goods-discount-popup.vue";

import { mapState, mapGetters, mapMutations } from "vuex";
import { MescrollMixin } from "@/mixins";
import {
  GoodsType,
  GoodsTypeObj,
  OrderConfirmType,
  TransferType,
  GoodsStatus
} from "@/enums";
export default {
  mixins: [MescrollMixin],
  components: {
    GoodsHeader,
    GoodsFooter,

    GoodsImgSwiper,
    GoodsDesc,
    GoodsDiscount,
    GoodsSkuAddr,
    GoodsComment,
    GoodsShop,
    GoodsFeatured,
    GoodsDetail,
    GoodsProp,
    GoodsService,
    GoodsPreSaleInfo,

    GoodsSkuPopup,
    AddrSelectPopup,
    GoodsDiscountPopup,
    // MPreview,
  },
  computed: {
    ...mapState(["accountInfo"]),

    goodsTypeMap() {
      let map = {};
      Object.keys(GoodsType).forEach((key) => {
        map[key] = this.goodsType == GoodsType[key];
      });
      return map;
    },
    goodsTypeObj() {
      return GoodsTypeObj[this.goodsType] || GoodsTypeObj[GoodsType.NORMAL];
    },
    goodsStatusMap() {
      return this.genEnumMap(this.goodsStatus, GoodsStatus);
    },
  },
  data() {
    return {
      GoodsType,
      GoodsTypeObj,
      downOption: {
        use: false,
      },
      upOption: {
        toTop: {
          src: "",
        },
        onScroll: this.handleScroll,
      },
      scrollTop: 0,

      goodsId: "",
      goodsType: GoodsType.NORMAL,
      goodsDetail: {},
      preSaleData: {},
      transferData: {},
      loading: true,

      selectSku: null,
      selectAddr: null,
      selectAddrIndex: null,

      showSku: false,
      skuPopupType: 1,

      showAddr: false,

      showDiscount: false,
      goodsStatus: GoodsStatus.ON_SHELF,
    };
  },
  watch: {
    $route(to, from) {
      if (to.params.goodsId != from.params.goodsId) {
        this.mescroll.scrollTo(0, 0)
        this.goodsId = to.params.goodsId;
        // this.goodsType = to.query.type;
        this.requestData(this.goodsId, this.goodsType);
      }
    },
  },
  methods: {
    ...mapMutations(["setOrderInfo"]),
    previewItem(index, list) {
       this.$PreviewImage({
        sources:list,
        current:index
        })
    },
    handleScroll(mescroll, y, isUp) {
      this.scrollTop = y || 0;
    },
    handleScrollTo(item) {
      this.mescroll.scrollTo(item.position, 200);
    },
    requestData(goodsId, type) {
      let getEmptyP = () => {
        return new Promise((resolve, reject) => {
          resolve();
        });
      };
      let p1 = this.requestGoods(goodsId, type);
      let p2 = this.goodsTypeMap.TRANSFER
        ? this.requestTransfer()
        : getEmptyP();

      Promise.all([p1, p2]).then(() => {
        this.$hideLoading();
      });
    },
    requestGoods(goodsId, type) {
      if (!GoodsTypeObj[type]) {
        type = GoodsType.NORMAL;
      }
      this.$showLoading();
      return this.$api({
        apiName: GoodsTypeObj[type].detailApi,
        postData: goodsId,
        success: (res) => {
          this.initData(res);
          this.$nextTick(() => {
            this.$refs.shopDom.requestData();
          });
        },
      });
    },
    requestTransfer() {
      this.$showLoading();
      return this.$api({
        apiName: "getTransferDetail",
        postData: this.tranId,
        success: (res) => {
          this.transferData = res;
        },
      });
    },
    async initData(res) {
      let goodsVo = {};
      if (this.goodsTypeMap.PRE_SALE) {
        goodsVo = res.goodsVo;
        this.preSaleData = res.preSale;
      } else if (this.goodsTypeMap.NFT) {
        goodsVo = res;
        this.nftData = res.nft;
      } else {
        goodsVo = res;
      }
      let {
        status,
        thumb,
        imgList,
        imgListJson,
        video,
        videoPoster,
        defaultPrice,
        maxPrice,
        name,
        description,
        skus,
        merchantId,
        merchantName,
        nftFile,
        detail,
        hash,
        prop,
        marketingCoupons: couponList,
        promotionVo: promotionData,
        comment,
        shopImage,
        circulation,
        sales,
        preheatStartTime,
        preheatEndTime
      } = goodsVo;
      imgListJson = JSON.parse(imgList);
       this.goodsStatus = status;
      if (this.goodsTypeMap.TRANSFER) {
        let transferSku = skus.find((item) => item.skuId == this.skuId);
        skus = transferSku ? [transferSku] : [];
      }

      let swiperList = imgListJson.map((item) => {
        return {
          type: "img",
          url: item,
        };
      });

      if (video && video.length !== 0) {
        let Poster=""
        try {
            Poster=await this.getVideoBase64(video,158,211)
          } catch (err) {
            console.log(11)
          }
        swiperList.splice(0, 0, {
          type: "video",
          url: Poster,
          video,
        });
      }

      let desc = {
        thumb,
        defaultPrice,
        maxPrice,
        name,
        description,
        nftFile,
        preheatStartTime,
        preheatEndTime
      };

      let merchant = {
        merchantId,
        merchantName,
        comment,
        shopImage,
      };
      let discount = {
        couponList,
        promotionData,
      };
    
      let details = { // nft详情ntf哈希
        detail,
        hash,
        circulation,
        sales
      }
      for(let item of skus){
        item.originalPrice=defaultPrice
      }
      let { skuList, skuMap } = this.genSku(skus);

      this.goodsDetail = {
        swiperList,
        desc,
        skuList,
        skuMap,
        merchant,
        details,
        prop,
        discount,
      };
    },
    genSku(skus) {
      let skuObj = {};
      let skuList = [];
      let skuMap = {};
      for (let sku of skus) {
        let skuDetail = {
          ...sku,
          propObj: {},
        };
        for (let prop of sku.skuProps) {
          let { propKey, propVal } = prop;
          skuDetail.propObj[propKey] = propVal;
          if (!skuObj[propKey]) {
            skuObj[propKey] = {
              [propVal]: true,
            };
          } else {
            skuObj[propKey][propVal] = true;
          }
        }

        let key = sku.skuProps
          .map((p) => `${p.propKey}:${p.propVal}`)
          .join("-");
        skuMap[key] = skuDetail;
      }

      for (let propKey in skuObj) {
        let item = {
          propKey,
          list: [],
        };
        for (let propVal in skuObj[propKey]) {
          item.list.push(propVal);
        }
        skuList.push(item);
      }

      return {
        skuList,
        skuMap,
      };
    },

    handleDiscount() {
      if (!this.checkLogin('back')) return;
      this.showDiscount = true;
    },

    handleSku() {
      this.skuPopupType = 1;
      this.showSku = true;
    },
    handleAddr() {
      if (!this.checkLogin('back')) return;
      this.showAddr = true;
    },

    handleCart() {
      this.skuPopupType = 2;
      this.showSku = true;
    },
    handleBuy() {
      if (
        this.goodsTypeMap.TRANSFER &&
        this.transferData.type == TransferType.PACKAGE
      ) {
        this.confirmBuy();
        return;
      }
      this.skuPopupType = 3;
      this.showSku = true;
    },

    handleSkuChange(sku) {
      this.selectSku = sku;
    },

    handleAddrSelect(index, item) {
      this.selectAddrIndex = index;
      this.selectAddr = item;
    },

    confirmCart() {
      if (!this.checkLogin('back')) return;
      let params = {
        amount: this.selectSku.originalPrice,
        coinName: this.selectSku.coinName,
        goodsId: this.selectSku.goodsId,
        goodsName: this.goodsDetail.desc.name,
        number: this.selectSku.num,
        skuId: this.selectSku.skuId,
        stock: this.selectSku.stock,
        uid: this.accountInfo.userId,
      };
      this.$api({
        apiName: "addUserShoppingCart",
        postData: params,
        success: (res) => {
          this.showSku = false;
          this.$store.dispatch("getShoppingCart");
          this.$toast("添加成功~");
        },
      });
    },
    confirmBuy() {
      if (!this.checkLogin('back')) return;

      let { selectAddrIndex, selectAddr } = this;
      let thumb = this.selectSku.thumb
        ? this.selectSku.thumb
        : this.goodsDetail.desc.thumb;
      let goodsName = this.goodsDetail.desc.name;
      let skuList = [
        {
          ...this.selectSku,
          ...this.goodsDetail.merchant,
          thumb,
          goodsName,
        },
      ];
      let extData = {},
        type = OrderConfirmType.NORMAL;
      if (this.goodsTypeMap.TRANSFER) {
        extData = this.transferData;
        type = OrderConfirmType.TRANSFER;
        let { type: tType, price, stock } = this.transferData;
        skuList[0].originalPrice =
          tType == TransferType.SINGLE ? price : price / stock;
      } else if (this.goodsTypeMap.NFT) {
        type = OrderConfirmType.NFT
      } else if (this.goodsTypeMap.PRE_SALE) {
        extData = this.preSaleData;
        type = OrderConfirmType.PRE_SALE_DEPOSIT;
      }
      this.setOrderInfo({
        selectAddrIndex,
        selectAddr,
        skuList,
        extData,
        type,
      });

      this.$router.push({ name: "order-confirm" });
    },
  },

  created() {
    this.goodsId = this.$route.params.goodsId;
    let { type, skuId, tranId } = this.$route.query;
    this.goodsType = GoodsType.NFT;
    if (this.goodsTypeMap.TRANSFER) {
      this.skuId = skuId;
      this.tranId = tranId;
    }
    this.requestData(this.goodsId, this.goodsType);
  },
};
</script>

<style lang="less">
.goods-con {
  background: #f5f7fb;
  padding-bottom: 60px;
}
</style>
