<template>
  <!-- 2B商城加入购物车弹窗 -->
  <div class="aaa" :style="{ 'z-index': show ? 999 : -999 }">
    <div class="bg" v-if="show" @click="close"></div>
    <div class="goodsMess" :style="{ 'bottom': show ? 0 : '' }">
      <div class="title">
        <div class="close" @click="close">
          <van-icon name="cross" />
        </div>
      </div>
      <div class="content">
        <div class="item flex" v-for="(item, index) in list" :key="index" v-show="item.saleStatus != 0">
          <div class="img">
            <img :src="item.goodsImgUrl" :onerror="defaultImg" alt="" />
          </div>
          <div class="right">
            <div class="info-top flex">
              <p class="name line-clamp2">{{ item.specificationsStr }}</p>
              <!-- 起购限购量 -->
              <div class="limitCount flex" v-if="item.minLimitPurchaseNum > 0 || item.maxLimitPurchaseNum > 0">
                <p class="minLimitCount" v-if="item.minLimitPurchaseNum > 0">
                  起购量:{{ item.minLimitPurchaseNum | keepIntNum }}
                </p>
                <p class="maxLimitNum" v-if="item.maxLimitPurchaseNum > 0 && item.oversoldFlag == 0">
                  限购量:{{ item.maxLimitPurchaseNum | keepIntNum }}
                </p>
              </div>
            </div>
            <div class="info-center flex">
              <p class="count">
                库存:<span v-if="item.oversoldFlag == 1">充足</span><span v-else>{{ item.saleQty | keepIntNum }}</span>
              </p>
              <van-stepper button-size="24px" integer :min="0"
                :step="item.plusPurchaseMultiple"
                :max="item.maxLimitPurchaseNum > 0 ? item.maxLimitPurchaseNum : 999999"
                @minus="(e) => changeQty(item, e, 'minus')" @plus="(e) => changeQty(item, e, 'plus')"
                @blur="(e) => changeQty(item, e, 'blur')" v-model="item.qty" :disabled="item.disabled" />
            </div>
            <div class="info-bottom flex">
              <p class="price">¥{{ item.discountPrice | keepTwoNum }}</p>
              <!-- 已加购数量 -->
              <p class="purchased" v-if="item.purchased > 0">
                已加购:{{ item.purchased }}
              </p>
            </div>
          </div>
        </div>
      </div>
      <div class="footer-iphonex">
        <div class="isSelect flex">
          <p class="selected" v-if="selectedText">已选:{{ selectedText }}</p>
          <div class="allPrice">
            <p>
              商品金额:<span>¥{{ selectPrice}}</span>
            </p>
            <p v-if="goodsInfoData.wholePurchaseMultiple && goodsInfoData.wholePurchaseMultiple > 1">此款所有规格数量合计 需满足{{goodsInfoData.wholePurchaseMultiple}}的倍数</p>
          </div>
        </div>
        <div class="bottom flex">
          <div :disabled="addCartLoading" class="addCart " @click="addCart">加入购物车</div>
        </div>
      </div>
    </div>
  </div>

</template>

<script type="text/ecmascript-6">
import live from "@/api/live";
import goods from "@/api/goods";
import { DFSImg } from "@/utils/index";
const app = getApp();
export default {
  name: "TwoBAddCart",
  data() {
    return {
      show: false,
      productId: "",
      list: [],
      addCartLoading: false,
      defaultImg: `this.src="https://cdn.mayi888.com/product/85pdScJ5ch.jpg?x-oss-process=image/resize,m_pad,limit_0,w_800,h_800"`,
      selectList: [],
      goodsInfoData:{}
    };
  },
  components: {},
  computed: {
    selectPrice() {
      let allPrice = 0;
      this.selectList.forEach((item) => {
        allPrice += item.qty * item.discountPrice;
      });
      return allPrice.toFixed(2);
    },
    // 已选
    selectedText() {
      let val = this.selectList.length;
      let species = this.selectList.reduce((pre, cur) => { return pre + (cur.qty - 0) }, 0)
      if (val > 0) {
        return `${val}种${species}件`
      }
      return ``
    }
  },
  created() { },
  mounted() {
    let _this = this;
    app.openTwoBAddCart = (val) => {
      console.log("----打开2B弹窗");
      _this.open(val);
    }
  },
  methods: {
    open(val) {
      if (val.productNature == 5) {
        return wx.showToast({
          title: '电子卡券不可加入购物车',
          icon: 'none',
        });
      }
      if (val.productNature == 3) {
        return wx.showToast({
          title: '会员卡不可加入购物车',
          icon: 'none',
        });
      }
      if (val.productNature == 2) {
        return wx.showToast({
          title: '虚拟商品不可加入购物车',
          icon: 'none',
        });
      }
      this.productId = val.productId;
      let query = {
        productInfoId: val.productId,
        terminalProductId: val.terminalProductId,
      }
      live.getProductGoodsByProductInfo(query).then(res1 => {
        let res = res1.data;
        if (res.code == 200) {
          this.init({ list: res.data || [] });
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      })

      live.getProductInfoTwo(query).then(res2 => {
        let res = res2.data;
        if (res.code == 200) {
          this.goodsInfoData = res.data
        } else {
           wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      })
    },
    close() {
      this.show = false;
    },
    init({ list }) {
      console.log(list, "----list");
      list.forEach((item) => {
        item.qty = 0;
        item.disabled = false;
        item.minLimitPurchaseNum = item.minLimitPurchaseNum - 0;
        item.maxLimitPurchaseNum = item.maxLimitPurchaseNum - 0;
        item.plusPurchaseMultiple = item.plusPurchaseMultiple - 0;
        item.discountPrice = item.discountPrice - 0;
        item.goodsImgUrl = DFSImg(item.goodsImgUrl);
        item.purchased = 0;
        let specificationsStr = "";
        if (item.specifications) {
          specificationsStr = item.specifications.map((item) => {
            return item.specificationValue
          })
          item.specificationsStr = specificationsStr.join(",")
        }
      });
      // 查询已加购数量
      this.query_goods_cart_info();
      this.list = list;
      this.show = true;
    },
    query_goods_cart_info() {
      goods
        .query_goods_cart_info([this.productId])
        .then((res1) => {
          let res = res1.data;
          if (res.code == 200 && res.data) {
            this.cartList = res.data;
            this.list.forEach((item) => {
              this.cartList.forEach((item1) => {
                if (item.goodsId == item1.goodsId) {
                  this.$set(item, "purchased", item1.qty - 0);
                }
              });
            });
            this.$forceUpdate();
          }
        });
    },
    // 改变数值
    changeQty(data, el = null, type = "") {
      let { qty } = data;
      console.log("changeQty", qty, type);
      // TODO 减1<起购量直接赋值0、加1<起购量直接赋值起购量
      if (type == "minus") {
        if (
          data.minLimitPurchaseNum > 0 &&
          qty - data.minLimitPurchaseNum == 0
        ) {
          qty = 0;
        } else {
          if (qty - data.plusPurchaseMultiple < data.minLimitPurchaseNum && data.minLimitPurchaseNum > 0) {
            qty = data.minLimitPurchaseNum;
          } else {
            qty -= (data.plusPurchaseMultiple - 0 || 1)
          }
        }
      } else if (type == "plus") {
        if (data.minLimitPurchaseNum > 0 && qty == 0) {
          qty = data.minLimitPurchaseNum<data.plusPurchaseMultiple?data.plusPurchaseMultiple:data.minLimitPurchaseNum;
        } else {
          qty += (data.plusPurchaseMultiple - 0 || 1)
        }
      } else if (type == "blur") {
        if (
          data.minLimitPurchaseNum > 0 &&
          qty < data.minLimitPurchaseNum
        ) {
          qty = data.minLimitPurchaseNum;
        }
      }
      console.log(qty);
      this.$set(data, "qty", qty);
      this.selectList = this.list.filter((item) => item.qty > 0) || [];
    },
    addCart() {
      let selectList = this.list.filter((item) => item.qty > 0) || [];
      let query = [];
      if (selectList.length > 0) {
        query = selectList.map((item) => {
          return {
            productGoodsId: item.productGoodsId,
            qty: item.qty,
          };
        });
      } else {
        return wx.showToast({
          title: "未选择加购商品数量",
          icon: 'none',
        });
      }
      wx.showLoading({
        title: '加购中...',
      })
      live.addCart(query).then((res1) => {
        wx.hideLoading()
        let res = res1.data;
        if (res.code == 200) {
          wx.showToast({
            title: res.data,
            icon: 'none',
          });
          setTimeout(() => {
            this.close();
            this.selectList = [];
          }, 500);
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
          });
        }
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.aaa {
  position: fixed;
  width: 100%;
  bottom: 0;
  display: flex;
  overflow: hidden;
  justify-content: flex-end;
}

.bg {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(#000000, 0.75);
}

.goodsMess {
  width: 100%;
  background: rgba(255, 255, 255, 1);
  border-radius: 8px 8px 0px 0px;
  bottom: -100vh;
  transition: all 0.3s linear;
  background: #fff;
  position: relative;
  overflow-y: auto;
}


.title,
.content {
  padding: 0 16px;
  position: relative;
}

.title {
  padding-top: 16px;
  padding-bottom: 16px;

  .price {
    color: var(--main-color);
    font-size: 18px;
    text-align: center;
  }

  .close {
    position: absolute;
    right: 6px;
    top: 6px;
    font-size: 20px;
  }
}

.content {
  min-height: 30vh;
  max-height: 60vh;
  overflow-y: auto;

  .item {
    margin-bottom: 16px;
    background: #fff;
    border-radius: 10px;
    padding: 6px;
    justify-content: space-between;
    align-items: center;

    .img {
      width: 80px;
      height: 80px;
      display: flex;
      justify-content: center;
      align-items: center;
      background: #f5f5f5;
      border-radius: 10px;
      overflow: hidden;
      flex-shrink: 0;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
    }

    .right {
      flex: 1;
      margin-left: 10px;

      &>div {
        justify-content: space-between;
        margin-bottom: 6px;
      }

      .info-top {
        align-items: center;

        .name {
          font-size: 14px;
          color: #333;
          width: 24vw;
        }

        .limitCount {
          margin-left: 30px;
          justify-content: space-between;
          margin-bottom: 6px;
          color: #666;

          .maxLimitNum {
            margin-left: 10px;
          }
        }
      }

      .info-center {
        .count {
          color: #333;
          font-size: 12px;
        }

        .van-stepper__input {
          width: 70px !important;
        }
      }

      .info-bottom {
        .price {
          color: var(--main-color);
          margin-top: 4px;
        }

        .purchased {}
      }
    }
  }
}

.isSelect {
  border-top: 1px solid #eee;
  background: #fff;
  padding: 4px 16px;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;

  .selected {
    color: #666;
  }

  .allPrice {
    color: #333;

    span {
      font-size: 14px;
      color: var(--main-color);
    }
  }
}

.bottom {
  height: 49px;
  align-items: center;
  background: #fff;

  .addCart {
    width: 100%;
    height: 38px;
    border-radius: 18px;
    line-height: 38px;
    margin: 0 10px;
    background-color: var(--main-color);
    color: #fff;
    text-align: center;
  }
}
</style>