<template>
  <div class="select-package">
    <div class="popup-mask"></div>
    <div class="popup-box">
      <div class="tit">
        <div class="text">{{ $t("package.selectPackage") }}</div>
        <div class="close" @click="hidePop"></div>
      </div>
      <div class="con">
        <div class="prod-item" v-if="mainProd">
          <img class="img" :src="mainProdDefaultSku.pic || mainProd.pic" alt="" />
          <div class="prod-info">
            <div class="prod-name">{{ mainProd.prodName }}</div>
            <div class="prod-sku">
              <SelectSku
                v-if="mainProdDefaultSku.skuName && mainProd.skuList.length"
                :sku-id="mainProdDefaultSku.skuId"
                :sku-name="mainProdDefaultSku.skuName"
                @getSku="getMainSku"
                :sku-list="mainProd.skuList"
              />
            </div>
            <div class="prod-price">
              <div class="price-box">
                <span class="price-text"
                  >￥{{ mainProdDefaultSku.matchingPrice | price }}</span
                >
                <span class="old-price" v-if="mainProd.price"
                  >￥{{ mainProdDefaultSku.price | price }}</span
                >
              </div>
              <div class="count">×{{ mainProd.leastNum * packageNum }}</div>
            </div>
          </div>
        </div>
        <div
          class="prod-item"
          v-if="comboInfo.matchingProds"
          v-for="item in comboInfo.matchingProds"
        >
          <img class="img" :src="item.defaultSku.pic || item.pic" alt="" />
          <div class="prod-info">
            <div class="prod-name">{{ item.prodName }}</div>
            <div class="prod-sku">
              <SelectSku
                v-if="item.defaultSku.skuName && item.skuList.length"
                :sku-id="item.defaultSku.skuId"
                :sku-name="item.defaultSku.skuName"
                :sku-list="item.skuList"
                @getSku="getSku"
              />
            </div>
            <div class="prod-price">
              <div class="price-box">
                <span class="price-text"
                  >￥{{ item.defaultSku.matchingPrice | price }}</span
                >
                <span class="old-price">￥{{ item.defaultSku.price | price }}</span>
              </div>
              <div class="count">×{{ item.leastNum * packageNum }}</div>
            </div>
          </div>
        </div>
        <div class="footer">
          <div class="left">
            <div class="text">{{ $t("package.packageNumber") }}:</div>
            <InputNumber v-model="packageNum" />
          </div>
          <div class="right">
            <div class="red-btn btn" @click="buy">{{ $t("buyNow") }}</div>
            <div class="cart-btn btn" @click="addCart">{{ $t("prodDetail.addToCart") }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import SelectSku from './select-sku.vue'
import InputNumber from './input-number.vue'
import Cookie from 'js-cookie'
import bus from '~/plugins/bus'
export default {
  filters: {
    price(value) {
      if (value) {
        return value.toFixed(2)
      }
      return 0.0
    }
  },
  props: {
    shopInfo: {
      type: Object,
      default() {
        return {}
      }
    },
    comboId: {
      type: Number,
      default: 0
    },
    selectMatchIds: {
      type: Array,
      default() {
        return []
      }
    }
  },
  data() {
    return {
      packageNum: 1,
      comboInfo: {},
      mainProdDefaultSku: ''
    }
  },
  components: {
    SelectSku,
    InputNumber
  },
  created() {
    // this.getComboData()
  },
  computed: {
    mainProd() {
      return this.comboInfo.mainProd
    }
  },
  methods: {
    hidePop() {
      this.$emit('hideSelectPackage')
    },
    getComboData(data) {
      this.comboInfo = data
      const mainSkus = this.comboInfo.mainProd.skuList
      if (mainSkus.length > 0) {
        this.setDefaultMainProdSku(mainSkus)
      }
      this.setComboProdDefaultSku(data.matchingProds)
    },
    // 设置主商品的默认sku
    setDefaultMainProdSku(skuList) {
      // debugger
      for (let i = 0; i < skuList.length; i++) {
        if (skuList[i].matchingPrice === this.comboInfo.mainProd.comboPrice) {
          this.mainProdDefaultSku = skuList[i]
          break
        }
      }
    },
    setComboProdDefaultSku(comboList) {
      comboList.forEach(item => {
        let defaultSku = null
        let flag = false
        // debugger
        for (let i = 0; i < item.skuList.length; i++) {
          if (
            item.comboPrice === item.skuList[i].matchingPrice &&
            item.skuList[i].stocks
          ) {
            defaultSku = item.skuList[i]
            flag = true
            break
          }
        }
        if (!flag && item.skuList.length) {
          item.defaultSku = item.skuList[0]
        } else {
          item.defaultSku = defaultSku
        }
      })
    },
    getSku(sku) {
      const matchingProds = this.comboInfo.matchingProds
      for (let i = 0; i < matchingProds.length; i++) {
        if (matchingProds[i].comboProdId === sku.comboProdId) {
          matchingProds[i].defaultSku = sku
          this.$forceUpdate()
          break
        }
      }
    },
    getMainSku(sku) {
      this.mainProdDefaultSku = sku
      this.$forceUpdate()
    },
    addMatchingSkus(matchingProds) {
      let matchingSkuIds = []
      matchingProds.forEach(item => {
        matchingSkuIds.push(item.defaultSku.skuId)
      })
      return matchingSkuIds
    },
    messageStock(prodName) {
      let msg = `[${
        prodName.length > 10 ? prodName.slice(0, 10) + '......' : prodName
      }]`
      this.$message({
        message: msg + this.$t('prodDetail.insufficientInventory'),
        type: 'warning',
        duration: 1000
      })
    },
    validatorStocks() {
      // debugger
      // this.packageNum
      if (
        !this.mainProdDefaultSku.stocks ||
        this.packageNum > this.mainProdDefaultSku.stocks
      ) {
        let prodName = this.comboInfo.mainProd.prodName
        this.messageStock(prodName)
        return false
      }
      const matchingProds = this.comboInfo.matchingProds
      for (let item of matchingProds) {
        if (
          !item.defaultSku.stocks ||
          this.packageNum > item.defaultSku.stocks
        ) {
          let prodName = item.prodName
          this.messageStock(prodName)
          return false
        }
      }
      return true
    },
    /**
     * 立即购买
     */
    buy() {
      if (!this.validatorStocks()) {
        return
      }
      if (this.packageNum < 1) {
        this.$message({
          message: this.$t('prodDetail.pleaseEnterTheCorrectNumberOfItems'),
          type: 'warning',
          duration: 1000
        })
        return
      }
      const matchingSkuIds = this.addMatchingSkus(this.comboInfo.matchingProds)
      const orderItem = {
        prodCount: this.packageNum,
        prodId: this.comboInfo.mainProd.prodId,
        shopId: this.shopInfo.shopId,
        skuId: this.mainProdDefaultSku.skuId,
        comboId: this.comboId,
        matchingSkuIds
      }
      if (!Cookie.get('token')) {
        bus.$emit('showLogin', true)
      } else {
        sessionStorage.setItem('orderItem', JSON.stringify(orderItem))
        this.$router.push({
          path: '/submit-order?orderEntry=1'
        })
      }
    },
    // 加入购物车
    addCart() {
      // {
      //   "basketId": 0,
      //   "comboId": 0,
      //   "count": 0,
      //   "distributionCardNo": "",
      //   "matchingSkuIds": [],
      //   "prodId": 0,
      //   "shopId": 0,
      //   "skuId": 0
      // }
      if (!this.packageNum || this.packageNum <= 0) {
        this.$message({
          message: this.$t('prodDetail.pleaseEnterTheCorrectNumberOfItems'),
          type: 'warning',
          duration: 1000
        })
        return
      }
      if (!this.validatorStocks()) {
        return
      }
      const matchingSkuIds = this.addMatchingSkus(this.comboInfo.matchingProds)
      this.$axios
        .post('/p/shopCart/changeItem', {
          basketId: 0,
          count: this.packageNum,
          prodId: Number(this.$route.params.prodId),
          shopId: this.shopInfo.shopId,
          shopName: this.shopInfo.shopName,
          skuId: this.mainProdDefaultSku.skuId,
          matchingSkuIds: matchingSkuIds,
          comboId: this.comboId
          // distributionCardNo: this.distributionCardNo
        })
        .then(({ data }) => {
          // this.getCartCount()
          this.$message.success(this.$t('prodDetail.successfullyAddedCart'))
          this.$router.push('/cart')
          this.getCartCount()
        })
    },
    /**
     * 获取购物车商品总数
     */
    getCartCount() {
      this.$axios.get('/p/shopCart/prodCount').then(({ data }) => {
        this.$store.commit('cartNumber/changeCartNumber', data)
      })
    },
  }
}
</script>

<style scoped>
.popup-mask {
  z-index: 190 !important;
}
.popup-box {
  z-index: 200 !important;
}
/* .popup-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
} */
.select-package .con .prod-item {
  display: flex;
  margin-bottom: 20px;
}
.select-package .con .prod-item:last-child {
  margin-bottom: 0;
}
.select-package .con .prod-item .img {
  width: 80px;
  height: 80px;
  background: #ffffff;
  border: 1px solid #f2f2f2;
  margin-right: 10px;
}
.select-package .con .prod-item .prod-info {
  width: 345px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 3px 0;
}
.prod-item .prod-info .prod-name {
  font-size: 14px;
  color: #000000;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.prod-price {
  font-size: 12px;
  color: #999999;
  display: flex;
  justify-content: space-between;
}
.prod-price .price-box .price-text {
  color: #e1251b;
}
.prod-price .price-box .old-price {
  text-decoration: line-through;
}
.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.footer .left {
  display: flex;
  align-items: center;
  justify-content: center;
}
.footer .left .text {
  font-size: 12px;
  color: #999999;
  margin-right: 10px;
}
.footer .right {
  display: flex;
}
.footer .right .btn {
  min-width: 92px;
  height: 26px;
  font-size: 12px;
  border-radius: 13px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
}
.footer .right .red-btn {
  background: #e1251b;
  color: #ffffff;
  margin-right: 10px;
  border: 1px solid #e1251b;
}
.footer .right .cart-btn {
  background: #ffecec;
  border: 1px solid #e43130;
  color: #e1251b;
}
</style>
