<template>
  <mescroll-vue
    class="blind-box-goods-con"
    ref="mescrollRef"
    @init="mescrollInit"
    :down="downOption"
    :up="upOption"
  >
  <div class="blind-page">
    <blind-header
      :scrollTop="scrollTop"
      @click="handleScrollTo"
      :commRef="$refs.goodsComm"
      :detailRef="$refs.goodsDetail"
    />
    <blind-img-swiper
      :list="goodsDetail.swiperList"
      @previewItem="previewItem"
    />
    <blind-desc
      :data="goodsDetail.desc"
      :goodsId="goodsId"
      :goodsTypeMap="goodsTypeMap"
      :transferData="transferData"
      :skus="goodsDetail.skus"

    />
    <blind-sku 
      :skuList="goodsDetail.skuList"
      :skuMap="goodsDetail.skuMap"
      :skus="goodsDetail.skus"
      :data="goodsDetail.desc"
      @buy="confirmBuy"
    />
    <blind-detail ref="goodsDetail" :data="goodsDetail.details" />
    </div>
  </mescroll-vue>
</template>
<script>
import BlindHeader from "./blind-header.vue";
import BlindImgSwiper from "./blind-img-swiper.vue";
import BlindDesc from "./blind-desc.vue";
import BlindSku from "./blind-sku.vue"
import BlindDetail from "./blind-detail.vue";
import { mapState, mapGetters, mapMutations } from "vuex";
import { MescrollMixin } from "@/mixins";
import {
  GoodsType,
  GoodsTypeObj,
  OrderConfirmType,
  TransferType,
} from "@/enums";
export default {
  mixins: [MescrollMixin],
  components: {
    BlindHeader,
    BlindImgSwiper,
    BlindDesc,
    BlindSku,
    BlindDetail
  },
  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];
    },
    selectSku() {
       this.goodsDetail.skus.forEach((item) => {
        item.num = 1
      })
      return this.goodsDetail.skus[0]
    },
    isHasStock() {
      return this.goodsDetail.skus.some((item) => {
        return item.stock
      })
    }
  },
  data() {
    return {
      GoodsType,
      GoodsTypeObj,
      downOption: {
        use: false,
      },
      upOption: {
        toTop: {
          src: "",
        },
        onScroll: this.handleScroll,
      },
      scrollTop: 0,

      goodsId: "",
      goodsType: GoodsType.NORMAL,
      goodsDetail: {},
      transferData: {},
    };
  },
  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.requestGoods(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);
    },
    requestGoods(goodsId, type) {
      if (!GoodsTypeObj[type]) {
        type = GoodsType.NORMAL;
      }
      this.$showLoading();
      console.log(GoodsTypeObj,type)
      return this.$api({
        apiName: GoodsTypeObj[type].detailApi,
        postData: goodsId,
        success: (res) => {
          this.$hideLoading();
          this.initData(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 {
        thumb,
        imgList,
        imgListJson,
        video,
        videoPoster,
        defaultPrice,
        maxPrice,
        name,
        description,
        skus,
        merchantId,
        merchantName,
        nftFile,
        detail,
        hash,
        prop,
        comment,
        shopImage,
        circulation,
        sales,
        salesType,
        blindBoxRule,
        preheatEndTime
      } = goodsVo;
      imgListJson = JSON.parse(imgList);

      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,
        preheatEndTime
      };
      let merchant = {
        merchantId,
        merchantName,
        comment,
        shopImage,
      };

      let details = {
        detail,
        merchantName,
        merchantId,
        circulation,
        blindBoxRule
      };

      let { skuList, skuMap } = this.genSku(skus);

      this.goodsDetail = {
        swiperList,
        desc,
        skuList,
        skuMap,
        merchant,
        details,
        prop,
        skus,
        salesType
      };
      console.log(this.goodsDetail)
    },
    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,
      };
    },
    confirmBuy() {
      if (!this.checkLogin("back")) return;
      let { selectAddrIndex, selectAddr } = this;
      let thumb =  this.goodsDetail.desc.thumb;
      let goodsName = this.goodsDetail.desc.name;
      console.log(this.goodsDetail.desc.defaultPrice)
      let skuList = [
        {
          ...this.selectSku,
          ...this.goodsDetail.merchant,
          thumb,
          goodsName,
          originalPrice:this.goodsDetail.desc.defaultPrice
        },
      ];
      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,
        salesType:this.goodsDetail.salesType
      });
      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.requestGoods(this.goodsId, this.goodsType);
  },
};
</script>
<style lang="less" scoped>
.blind-box-goods-con {
    // background: #F6FAFF;
    // background-size: 100% ;
}
.blind-page {
     background: url("~@/assets/img/blind-box-bg.png") no-repeat;
     background-size: 100%;
}
</style>