<template>
  <!-- 选择商品规格 -->
  <div class="livedSelectionSpe">
    <van-popup
      :show="show"
      position="bottom"
      custom-style="border-top-left-radius:10px;border-top-right-radius:10px;"
      :close-on-click-overlay="true"
      @close="closeDia"
    >
      <div class="goodsMess">
        <div class="sku">
          <!-- 关闭按钮 -->
          <div class="close" @click="closeDia">
            <van-icon name="cross" />
          </div>
          <!-- 内容 -->
          <div class="cont flex">
            <div class="pic">
              <img width="100%" height="100%" :src="product_goods_info.goodsImgUrl" alt />
            </div>
            <div class="content">
              <div class="price" v-if="product_goods_info.discountPrice">
                <div>¥{{product_goods_info.discountPrice}}</div>
                <div v-if="product_goods_info.singleItemActivityId">
                  <p class="delPrice">¥{{product_goods_info.originalPrice}}</p>
                  <!-- <del style="color:#666;">¥{{product_goods_info.originalPrice}}</!--> 
                </div>
                <div
                  v-else-if="product_goods_info.discountPrice-0<product_goods_info.goodsSuggestedRetailPrice-0"
                >
                  <p class="delPrice">¥{{product_goods_info.goodsSuggestedRetailPrice}}</p>
                  <!-- <del style="color:#666;">¥{{product_goods_info.goodsSuggestedRetailPrice}}</del> -->
                </div>
              </div>
              <template v-else-if="minSale<maxSale">
                <div class="price">¥{{minSale}}-¥{{maxSale}}</div>
                <p  class="delPrice" v-if="(minSale-0<minSuggestedRetailPrice-0)&&(maxSale-0<maxSuggestedRetailPrice-0)">
                  ¥{{minSuggestedRetailPrice}}-¥{{maxSuggestedRetailPrice}}
                </p>
                <!-- <del
                  v-if="(minSale-0<minSuggestedRetailPrice-0)&&(maxSale-0<maxSuggestedRetailPrice-0)"
                >¥{{minSuggestedRetailPrice}}-¥{{maxSuggestedRetailPrice}}</del> -->
              </template>
              <template v-else>
                <div class="price">¥{{minSale}}</div>
              </template>
              <div class="num" v-if="product_goods_info.oversoldFlag==1&&isGetMixId">库存充足</div>
              <div
                class="num"
                v-else-if="product_goods_info.oversoldFlag!=1&&isGetMixId"
              >库存{{product_goods_info.sellMaxQty}}件</div>
              <div class="Choice" v-if="isChoice">【请选择规格】</div>
              <div class="Choice line-clamp1" v-else>
                <span v-for="(item,index) in goodsGuige" :key="index">{{item}}&nbsp;&nbsp;&nbsp;</span>
              </div>
            </div>
          </div>
          <div class="commoditySty">
            <ul>
              <li v-for="(ProductItem,n) in goodsGuiges" :key="n">
                <div class="property">{{ProductItem.specificationName}}</div>
                <div class="specification clearfix">
                  <div
                    v-for="(oItem,index) in ProductItem.specificationValue"
                    :key="index"
                    @click="specificationBtn(oItem.name,n,$event,index)"
                    :class="[oItem.isShow?'':'soldOut',subIndex[n] == index?'active':'']"
                    class="specification-item"
                  >
                    <div>{{oItem.name}}</div>
                  </div>
                </div>
              </li>
            </ul>
          </div>
          <div class="buyQty flex">
            <div class="ti">购买数量</div>
            <van-stepper
              :value="buyQty"
              :min="product_goods_info.productMinCount>0?product_goods_info.productMinCount:1"
              :max="MaxQtyNum"
              :disable-input="true"
              @change="changeQty"
              input-class="ipt"
            />
          </div>
        </div>
        <div v-if="!goodsLowerShelf&&!sellOut" class="bottom flex">
          <div class="addCart van-button" @click="onAddCartClicked">加入购物车</div>
          <div class="toPay van-button" @click="onBuyClicked">立即购买</div>
        </div>
        <div v-else-if="!goodsLowerShelf&&sellOut" class="goodsStand">商品已售罄</div>
        <div v-else class="goodsStand">商品已下架</div>
      </div>
    </van-popup>
  </div>
</template>

<script type="text/ecmascript-6">
import { DFSImg } from "@/utils/index";
import live from "@/api/live";
export default {
  props: {
    show: Boolean,
    productInfoId: String,
    minSale: String,
    maxSale: String,
    goodsImg: String,
    minSuggestedRetailPrice: String,
    maxSuggestedRetailPrice: String,
    goodsLowerShelf: Boolean
  },
  name: "",
  data() {
    return {
      product_goods_info: {
        afterSaleContent: "",
        goodsImgUrl: "",
        maxQty: "",
        pdtName: "",
        productGoodsId: "",
        productGoodsMixId: "",
        productId: "",
        referencePrice: "",
        marketPrice: "",
        oversoldFlag: Number,
        originalPrice: "",
        sellMaxQty: "",
        limitQty: "",
        specifications: [], //原规格
        discountPrice: ""
      },
      buyQty: 1,
      goodsGuige: [],
      // 对应商品所有规格
      goodsGuiges: [],
      // 规格转json对象
      goodsString: {},
      // 规格对象
      choose: {},
      MaxQtyNum: 0,
      isGetMixId: false, // 是否取价格
      isChoice: true, //显示“请选择规格”
      getProductInfos: [], //产品信息数组
      getProductInfo: {}, //产品信息
      isSingle: false, //是否为单规格商品
      saleStatus: 1, //销售状态,
      goodsStand: 1, //上下架,
      shopItemInfo: {}, //存放要和选中的值进行匹配的数据
      subIndex: [], //是否选中 因为不确定是多规格还是但规格,所以这里定义数组来判断
      isLogin: false, //是否登录
      nonstandardGoods: false, //无规格商品
      selectedPrice: "", // 选中的规格价格
      isChoice: true, //显示“请选择规格”
      productUrl: "", // 产品主图
      sellOut: false, //售罄及无库存且不是超卖
      isGetMixId: false, // 是否取价格
      paramData: "", //埋点数据
      maxSelectedPrice: 0, //  限时特惠选中规格后划线价
      allSellOut: false, //全部售罄标识
      isDefault:false,
    };
  },
  components: {},
  computed: {},
  created() {},
  onLoad(options) {
    if(options.params){
      let params = JSON.parse(options.params);
      this.liveId = params.liveId;  
    }else if(options.scene){
      var scene = decodeURIComponent(options.scene); //参数二维码传递过来的参数
      console.log(scene)
      let sceneInfo = scene.split(',')
      console.log('sceneInfo',sceneInfo)
      this.liveId = sceneInfo[0].split('=')[1]
    }
    this.product_goods_info.goodsImgUrl=this.goodsImg;
    this.init();
  },
  mounted() {},
  methods: {
    // 初始化
    async init() {
      let productInfoId = this.productInfoId;
      await live
        .getProductGoodsByProductInfo(productInfoId)
        .then(res => {
          if (res.data.code == 200) {
            this.getProductInfos = res.data.data;
            this.product_goods_info.productGoodsId = res.data.data[0].productGoodsId;
            this.product_goods_info.goodsId = res.data.data[0].goodsId;
            this.product_goods_info.productGoodsMixId =
              res.data.data[0].productGoodsMixId;
            this.product_goods_info.specifications = res.data.data[0].specifications;
            this.product_goods_info.oversoldFlag = res.data.data[0].oversoldFlag;
          }
        });
      // 获取商品规格
      let productId = this.productInfoId;
      await live.getProductGoodsSpecifications(productId).then(res => {
        if (res.data.code == 200) {
          this.goodsGuiges = res.data.data;
          console.log(this.goodsGuiges,'------------188')
          //做判断如果只有一套规格,直接添加规格 不用弹出选择规格弹窗直接进行下单 4.8建
          let isSingles = [];
          this.goodsGuiges.forEach((item, index) => {
            if (item.specificationValue.length >= 2) {
              isSingles.push(1);
            }
            if (isSingles.length != 0) {
              this.isSingle = false; //多规格
              this.goodsGuige = [];
              this.subIndex.pop();
            } else {
              this.isSingle = true; // 单规格商品
              this.isChoice = false;
              // this.goodsGuige.push(item.specificationValue[0]);
              this.goodsGuige = [];
              this.subIndex.push(0);
              // 通过mixid取价格
            }
          });
          if (this.isSingle == true) {
            this.getMixId(0);
          }

          //  规格数据重组
          for (var i = 0; i < this.goodsGuiges.length; i++) {
            for (
              var j = 0;
              j < this.goodsGuiges[i].specificationValue.length;
              j++
            ) {
              this.goodsGuiges[i].specificationValue[j] = {
                name: this.goodsGuiges[i].specificationValue[j],
                isShow: true
              };
            }
          }

          // console.log(this.specifications,'-------------规格')
          this.getProductInfos.forEach((item, index) => {
            item.twoSpecifications = [];
            item.specifications.forEach((item1, index1) => {
              item.specifications.splice(index1, 1, item1.specificationValue);
              item.twoSpecifications.splice(
                index1,
                1,
                item1.specificationValue
              );
            });
            item.specifications = item.specifications.join("abab@&*");
          });
          for (var i in this.getProductInfos) {
            this.shopItemInfo[
              this.getProductInfos[i].specifications
            ] = this.getProductInfos[i]; //修改数据结构格式,改成键值对的方式,以方便和选中之后的值进行匹配
          }
          // let defaultnoSellOut=this.getProductInfos.filter((item,index)=>{return !((item.oversoldFlag==0&&item.saleQty-0<=0)||item.saleStatus=='0')});
          // 默认选中一个只有一个未售罄的规格
          // this.defaultSelection(defaultnoSellOut[0].twoSpecifications,this.goodsGuiges);
          if (this.goodsGuiges.length == 1) {
            this.goodsGuiges[0].specificationValue.forEach((item, index) => {
              for (var i in this.shopItemInfo) {
                if (item.name == i && this.shopItemInfo[i].saleStatus == "0") {
                  item.isShow = false;
                }
                if (
                  item.name == i &&
                  this.shopItemInfo[i].oversoldFlag == 0 &&
                  this.shopItemInfo[i].saleQty - 0 <= 0
                ) {
                  item.isShow = false;
                }
              }
            });
          }
          // this.checkItem();
        } else if (res.code == -1) {
          this.isSingle = true;
          this.nonstandardGoods = true;
          this.goodsGuige = [];
          this.getMixId(0);
        }
      });
    },
    changeQty(event){
      console.log(event.mp.detail,'------------------------------279')
      this.buyQty=event.mp.detail;
      this.getMixId(1,true);
    },
    // 默认选中一组规格
    // 两个参数goodsSpc,allSpc  sku及所有规格
    defaultSelection(goodsSpc,allSpc){
      // 是默认调取getMixid接口状态
      this.isDefault=true;
      // console.log(goodsSpc,'-------371')
      // console.log(allSpc,'-------372')
      for(let i=0;i<allSpc.length;i++){
        for(let j=0;j<allSpc[i].specificationValue.length;j++){
          for(let k=0;k<goodsSpc.length;k++){
            if(allSpc[i].specificationValue[j].name==goodsSpc[k]){
              this.specificationBtn(allSpc[i].specificationValue[j].name,i,null,j);
              break;
            }
          }
        }
      }
    },
    onAddCartClicked() {
      let productGoodsId = this.product_goods_info.productGoodsId;
      if (
        this.goodsGuige.length < this.goodsGuiges.length ||
        this.checkGoodsGuigeValue()
      ) {
        wx.showToast({
          title: '请选择规格',
          icon: 'none',
        })
      } else if (
        this.product_goods_info.oversoldFlag == 0 &&
        this.product_goods_info.sellMaxQty <= 0
      ) {
        wx.showToast({
          title: '商品暂无库存',
          icon: 'none',
        })
      } else {
        live
          .addCart([{ productGoodsId: productGoodsId, qty: this.buyQty }])
          .then(res => {
            if (res.data.code == 200) {
              wx.showToast({
                title: '加入成功',
                icon: 'success',
              })
              this.showSize = false;
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
              })
            }
          });
      }
    },
    // 立即购买
    onBuyClicked(){
      if (
        this.goodsGuige.length < this.goodsGuiges.length ||
        this.checkGoodsGuigeValue()
      ) {
        wx.showToast({
          title: '请选择规格',
          icon: 'none',
        })
      } else if (
        this.product_goods_info.oversoldFlag == 0 &&
        this.product_goods_info.sellMaxQty <= 0
      ) {
        wx.showToast({
          title: '商品暂无库存',
          icon: 'none',
        })
      } else {
        let query ={};
        query.productGoodsMixId = this.product_goods_info.productGoodsMixId;
        query.productGoodsId = this.product_goods_info.productGoodsId;
        query.goodsId = this.product_goods_info.goodsId;
        query.qty = this.buyQty;
        query.goodsString = JSON.stringify(this.goodsString);
        query.maxQty = this.product_goods_info.maxQty;
        query.productMinCount = this.product_goods_info.productMinCount;
        query.fromLived = 1;
        query.liveId = this.liveId;

        // 将规格转化为json字符串
        this.backPath=`/order/orderConfirm`;
        wx.reLaunch({
          url: `../index/main?from=livedToOrderConfirm&backpath=${
            this.backPath
          }&params=${JSON.stringify(query)}`
        })
      }
    },
    // 取价格
    getMixId(val,getNewPrice) {
      if(!this.isDefault){
        wx.showLoading({
          title: '加载中...',
        })
      }
      this.isDefault=false;
      this.isGetMixId = true;
      let productGoodsMixId=this.product_goods_info.productGoodsMixId
      live
        .getProductGoodsByMixId(productGoodsMixId)
        .then(res => {
          wx.hideLoading()
          if (res.data.code == 200) {
            if (this.nonstandardGoods == false) {
              res.data.data.specifications.forEach((item, index) => {
                if (item.specificationPictureUrl != "") {
                  this.product_goods_info.goodsImgUrl = DFSImg(
                    item.specificationPictureUrl,
                    400,
                    400
                  );
                }
              });
              if (this.product_goods_info.goodsImgUrl == "") {
                this.productUrl = res.data.data.productUrl || "";
                this.product_goods_info.goodsImgUrl =
                  DFSImg(res.data.data.productUrl, 400, 400) || "";
              }
            } else {
              this.productUrl = res.data.data.productUrl || "";
            }
            this.product_goods_info.goodsImgUrl =
              DFSImg(res.data.data.productUrl, 400, 400) || DFSImg("", 400, 400);
            this.product_goods_info.marketPrice = Number(res.data.data.marketPrice);
            this.product_goods_info.originalPrice = Number(res.data.data.originalPrice);
            this.product_goods_info.discountPrice = Number(res.data.data.discountPrice);
            this.product_goods_info.sellMaxQty = Number(res.data.data.sellMaxQty); //可销售库存
            this.product_goods_info.limitQty = Number(res.data.data.limitQty); //  实际库存
            this.product_goods_info.productMinCount = Number(res.data.data.productMinCount); //最小购买数  0不限
            this.product_goods_info.maxQty = Number(res.data.data.maxQty); // 最大购买数   0不限
            this.product_goods_info.oversoldFlag = res.data.data.oversoldFlag; // 1超卖 0不超卖
            this.product_goods_info.goodsSuggestedRetailPrice =
              Number(res.data.data.goodsSuggestedRetailPrice);
            this.product_goods_info.singleItemActivityId =
              res.data.data.singleItemActivityId||'';
            if(!getNewPrice){
              this.buyQty =
                this.product_goods_info.productMinCount > 0 ? this.product_goods_info.productMinCount :1;
            }
            if (
              this.product_goods_info.oversoldFlag != 1 &&
              this.product_goods_info.sellMaxQty - 0 <= 0
            ) {
              this.sellOut = true;
              // console.log(this.sellOut, "cg416");
            } else {
              this.sellOut = false;
            }
            this.getMaxQtyNum(); //更新最大值
            this.$forceUpdate();
          }
        });
    },
    checkGoodsGuigeValue() {
      for (let i = 0; i < this.goodsGuige.length; i++) {
        if (
          this.goodsGuige[i] == "" ||
          this.goodsGuige[i] == "undefined" ||
          this.goodsGuige[i] == undefined
        ) {
          return true;
        }
      }
      return false;
    },
    getMaxQtyNum() {
      let num = 0;
      if (this.product_goods_info.maxQty == "0") {
        //无限制
        if (this.product_goods_info.oversoldFlag == "0") {
          //不允许超卖
          num = this.product_goods_info.sellMaxQty;
        } else {
          num = 999;
        }
      } else {
        if (
          this.product_goods_info.sellMaxQty > this.product_goods_info.maxQty
        ) {
          num = this.product_goods_info.sellMaxQty;
        } else {
          num = this.product_goods_info.maxQty;
        }
      }
      this.MaxQtyNum = num;
    },
    specificationBtn(item, n, event, index) {
      this.isChoice = false;
      if (this.goodsGuige[n] != item) {
        this.goodsGuige[n] = item;
        // this.goodsGuige[n] = item;
        this.subIndex[n] = index;
        this.subIndex.splice(n, 1, index);
      } else {
        this.goodsGuige[n] = "";
        this.subIndex[n] = -1; //去掉选中的颜色
        this.subIndex.splice(n, 1, -1); //去掉选中的颜色
        this.product_goods_info.discountPrice = null;
        this.goodsStand = 1;
        let isChoice = 0;
        // this.product_goods_info.goodsImgUrl=DFSImg(this.goodsImg,400,400);
        this.product_goods_info.goodsImgUrl =
          this.goodsImg || DFSImg("", 1024, 1024);
        this.sellOut = false;
        this.isGetMixId = false;
        this.goodsGuige.forEach((item, index) => {
          if (item == "") {
            isChoice++;
          }
        });
        if (isChoice == this.goodsGuige.length) {
          this.isChoice = true;
          this.goodsGuige = [];
          isChoice = 0;
        } else {
          this.isChoice = false;
        }
      }
      this.checkItem();
      let noStr = 0;
      this.goodsGuige.forEach((item, index) => {
        if (item != "") noStr++;
      });
      if (noStr == this.goodsGuiges.length) {
        this.getMixId(1);
      }
    },
    checkItem() {
      var option = this.goodsGuiges;
      var result = []; //定义数组存储被选中的值
      // console.log(this.goodsGuiges,"cg524")
      for (var i in option) {
        result[i] = this.goodsGuige[i] ? this.goodsGuige[i] : "";
      }
      for (var i in option) {
        var last = result[i]; //把选中的值存放到字符串last去
        for (var k in option[i].specificationValue) {
          result[i] = option[i].specificationValue[k].name; //赋值,存在直接覆盖,不存在往里面添加name值
          option[i].specificationValue[k].isShow = this.isMay(result); //在数据里面添加字段isShow来判断是否可以选择
        }
        result[i] = last; //还原,目的是记录点下去那个值,避免下一次执行循环时避免被覆盖
      }
      this.$forceUpdate(); //重绘
    },
    isMay: function(result) {
      for (var i in result) {
        if (result[i] == "") {
          return true; //如果数组里有为空的值,那直接返回true
        }
      }
      // console.log(result,this.goodsGuige,"cg494")
      for (var i in this.shopItemInfo) {
        let newArr = i.split("abab@&*");
        let isTrue = this.isContained(result, newArr);
        if (isTrue == true) {
          // console.log(newArr,i,result,"cg498")
          if (this.goodsGuige.length == this.goodsGuiges.length) {
            let isGoods = this.isContained(this.goodsGuige, newArr);
            if (isGoods == true) {
              this.product_goods_info.productGoodsMixId = this.shopItemInfo[
                i
              ].productGoodsMixId;
              this.product_goods_info.productGoodsId = this.shopItemInfo[
                i
              ].productGoodsId;
              this.product_goods_info.goodsId = this.shopItemInfo[i].goodsId;
            }
          }
          // 判断上下架、售罄
          console.log(
            this.shopItemInfo[i].saleStatus == 0,
            this.shopItemInfo[i].oversoldFlag == 0 &&
              this.shopItemInfo[i].saleQty - 0 <= 0,
            "-------------------703"
          );
          if (
            this.shopItemInfo[i].saleStatus == 0 ||
            (this.shopItemInfo[i].oversoldFlag == 0 &&
              this.shopItemInfo[i].saleQty - 0 <= 0)
          ) {
            return false;
          } else {
            return true;
          }
        }
      }
    },
    isContained(aa, bb) {
      if (
        !(aa instanceof Array) ||
        !(bb instanceof Array) ||
        aa.length < bb.length
      ) {
        return false;
      }
      for (var i = 0; i < bb.length; i++) {
        var flag = false;
        for (var j = 0; j < aa.length; j++) {
          if (aa[j] == bb[i]) {
            flag = true;
            break;
          }
        }
        if (flag == false) {
          return flag;
        }
      }
      return true;
    },
    //   关闭
    closeDia() {
      this.$emit("closeSpeDia");
    }
  }
};
</script>

<style lang="scss" scoped>
.delPrice{
  text-decoration: line-through;
  color: #666;
}
.flex{
  display: flex;
}
/*清除浮动*/
.clearfix {
  zoom: 1;
}

.clearfix:after {
  clear: both;
  content: '.';
  display: block;
  width: 0;
  height: 0;
  visibility: hidden;
}
/* 一行否则出现省略号 */
.line-clamp1 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  -webkit-box-orient: vertical;
}

.line-clamp2 {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 22px;
}
.livedSelectionSpe {
  .goodsMess {
    width: 100%;
    background: rgba(255, 255, 255, 1);
    border-radius: 8px 8px 0px 0px;
    .sku {
      padding: 8px 10px;
      position: relative;
      .close {
        position: absolute;
        right: 8px;
        top: 8px;
        font-size: 20px;
      }
    }
    .cont {
      width: 100%;
      height: 126px;
      border-bottom: 1px solid #e5e5e5;
      .pic {
        width: 100px;
        height: 100px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .content {
        margin-left: 8px;
        width: 65%;
        .price {
          font-size: 13px;
          font-weight: 400;
          color: #ff4240;
          margin-top: 10px;
        }
        .num,
        .size {
          font-size: 11px;
          font-weight: 400;
          color: rgba(146, 146, 146, 1);
        }
        .size {
          color: rgba(41, 41, 41, 1);
        }
        .Choice {
          width: 100%;
          margin-top: 10px;
          font-size: 14px;
          color: #292929;
        }
        .num,
        .soldout {
          margin-top: 10px;
          margin-bottom: 13px;
        }
      }
    }
    .commoditySty {
      border-bottom: 1px solid #e5e5e5;
      // max-height: 240px;
      // overflow-y: scroll;
      ul {
        height: 100%;
        li {
          height: 100%;
          .property {
            margin: 10px 0;
            font-size: 15px;
          }
          .specification {
            div.specification-item {
              font-size: 15px;
              border: 1px solid #606060;
              border-radius: 4px;
              color: #606060;
              text-align: center;
              padding: 2px 4px;
              float: left;
              margin-right: 6px;
              min-width: 30px;
              margin-bottom: 6px;
              box-sizing: content-box;
              div {
                text-align: left;
                display: inline-block;
              }
            }
            div.active {
              color: #fff;
              background-color: #ff4240;
              border-color: #ff4240;
            }
            div.soldOut {
              background-color: #ccc;
              opacity: 0.4;
              color: #000;
              pointer-events: none;
              border-color: #606060;
            }
          }
        }
      }
    }
    .buyQty {
      margin-top: 10px;
      width: 100%;
      height: 60px;
      justify-content: space-between;
      .ti{
        font-size: 14px;
      }
      /deep/.ipt{
        color: #000!important;
      }
    }
    .bottom {
      margin-top: 60px;
      .van-button {
        width: 50vw;
        height: 50px;
        text-align: center;
        line-height: 50px;
        font-size: 14px;
      }
      .toPay {
        background: #ff4240;
        color: #fff;
      }
      .addCart {
        background-color: #fff;
        color: #292929;
      }
    }
    .goodsStand {
      margin-top: 60px;
      background: #606060;
      width: 100%;
      height: 49px;
      text-align: center;
      line-height: 49px;
      color: #fff;
      font-size: 16px;
    }
  }
}
</style>