<template>
  <div class="detail">
    <!-- 面包屑导航 -->
    <div class="crumbs-shop">
      <div class="content">
        <div class="crumbs"></div>
      </div>
    </div>
    <!-- /面包屑导航 -->
    <div class="content">
      <div class="detail-up">
        <!-- 商品图片 -->
        <div class="img">
          <div class="big-img">
            <img v-if="!prodInfo.video || !showVideo" :src="prodInfo.pic" alt />
            <!-- 商品视频 -->
            <video
              v-show="showVideo"
              id="prodVideo"
              class="big-img prod-video"
              :src="prodInfo.video"
              controls
            ></video>
            <!-- 商品视频end -->
            <div class="oper-btn" v-if="showPlayBtn && prodInfo.video">
              <img
                src="../../../assets/images/play.png"
                @click="playVideo"
                alt="播放"
              />
            </div>
            <div class="close-btn" v-if="!showPlayBtn && showVideo">
              <img
                src="../../../assets/images/close.png"
                alt="关闭"
                @click="stopVideo"
              />
            </div>
          </div>
          <div class="small-img">
            <i class="left-arrow limit">&lt;</i>
            <i class="right-arrow">&gt;</i>
            <div class="img-box">
              <div
                class="item"
                v-for="(item, index) in prodImgs"
                :key="index"
                :class="{ active: item.isActive }"
                @mouseover="changeProdImg(index)"
              >
                <img :src="item.img" alt />
              </div>
            </div>
          </div>
        </div>
        <!-- /商品图片 -->
        <!-- 商品详情 -->
        <div class="info">
          <div class="name-box">
            <div class="name">{{ prodInfo.prodName }}</div>
            <div class="des">{{ prodInfo.brief }}</div>
          </div>
          <div class="price-box">
            <div class="item goods-price">
              <span class="tit">{{$t('price')}}</span>
              <div class="con">
                <div class="price">
                  <span class="big">{{ defaultSku.skuScore }}</span>
                  <span class="text">{{$t('prodDetail.points')}}</span>
                </div>
                <div class="add-symbol" v-if="defaultSku.price">+</div>
                <div class="price" v-if="defaultSku.price">
                  ￥
                  <span class="big">{{ parsePrice(defaultSku.price)[0] }}</span>
                  .{{ parsePrice(defaultSku.price)[1] }}
                </div>
              </div>
              <span v-if="findSku" class="tit">{{$t('prodDetail.remainingInventory')}}</span>
              <div v-if="findSku" class="con">
                {{defaultSku.stocks}}
              </div>
            </div>
            <!-- 销售价大于等于市场价 市场价不展示 -->
            <div v-if="defaultSku.oriPrice > defaultSku.price" class="item goods-price">
              <span class="tit">{{$t('prodDetail.originalPrice')}}</span>
              <div class="con">
                <div class="old-price">
                  ￥{{ defaultSku.oriPrice.toFixed(2) }}
                </div>
              </div>
            </div>
          </div>
          <div class="sku-box" v-if="prodInfo.skuList.length">
            <div
              class="items sku-text"
              v-for="(skuLine, key) in skuGroup"
              :key="key"
            >
              <span class="tit">{{ key }}</span>
              <div class="con">
                <span
                  class="item"
                  @click="toChooseItem(skuLineItem, key, $event)"
                  :class="[
                    selectedProp.find(el => el.key === key && el.value === skuLineItem) ? 'active' : '',
                    isSkuLineItemNotOptional(
                      allProperties,
                      selectedPropObj,
                      key,
                      skuLineItem,
                      propKeys
                    )
                      ? 'not-optional'
                      : ''
                  ]"
                  v-for="skuLineItem in skuLine"
                  :key="skuLineItem"
                  >{{ skuLineItem }}</span
                >
              </div>
            </div>
          </div>
          <!-- 计数器 -->
          <div class="sku-box">
            <div class="items">
              <span class="tit">{{$t('quantity')}}</span>
              <div class="con">
                <div class="goods-number" onselectstart="return false">
                  <span
                    :class="['reduce', this.prohibit1 ? 'limit' : '']"
                    @click="reduce"
                    >-</span
                  >
                  <input
                    type="number"
                    class="number"
                    oninput="value=value.replace(/[^\d]/g,'')"
                    v-model="prodNum"
                    @blur="resetProdNum"
                  />
                  <span
                    :class="['increase', this.prohibit2 ? 'limit' : '']"
                    @click="increase"
                    >+</span
                  >
                </div>
              </div>
            </div>
          </div>
          <div class="btns" v-if="prodInfo.prodType != 1">
            <a
              href="javascript:void(0)"
              class="buy-now"
              @click="buyNow"
              v-if="findSku && defaultSku.stocks"
              >{{$t('buyNow')}}</a
            >
            <a href="javascript:void(0)" class="shortage" v-else-if="!findSku"
              >{{$t('prodDetail.productNotInStock')}}</a
            >
            <a
              href="javascript:void(0)"
              class="shortage"
              v-else-if="!defaultSku.stocks"
              >{{$t('prodDetail.productOutOfStock')}}</a
            >
          </div>
        </div>
        <!-- 商品详情 -->
      </div>
      <div class="detail-down">
        <div class="introduce-box">
          <div class="tab">
            <div class="item active">{{$t('prodDetail.productIntroduction')}}</div>
          </div>
          <!-- 商品介绍 -->
          <div class="introduce">
            <div v-if="prodInfo.content" v-rich="prodInfo.content"></div>
          </div>
          <!-- /商品介绍 -->
        </div>
        <div class="side">
          <!-- 热销产品 -->
          <div class="sale-well">
            <div class="tit">{{$t('prodDetail.recommendGoodies')}}</div>
            <div class="con">
              <div
                class="item"
                v-for="item in scroeList"
                :key="item.prodId"
                @click="toScoreProdDet(item.prodId)"
              >
                <div class="goods-img">
                  <img :src="item.pic" alt />
                </div>
                <div class="goods-msg">
                  <div class="goods-name">{{ item.prodName }}</div>
                  <div class="goods-price">
                    <div class="icon">
                      <img
                        src="~/assets/images/memberPic/integral-icon.png"
                        alt
                      />
                    </div>
                    <div class="integral-price">{{ item.scorePrice }} {{$t('prodDetail.points')}}</div>
                    <div class="add" v-if="item.price > 0">+</div>
                    <div class="price" v-if="item.price > 0">
                      ￥{{ item.price }}
                    </div>
                  </div>
                  <div class="old-price">{{$t('prodDetail.marketPrice')}}￥{{ item.oriPrice }}</div>
                </div>
              </div>
            </div>
          </div>
          <!-- 热销产品 -->
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import util from '~/plugins/util'
import Cookie from 'js-cookie'
import bus from '~/plugins/bus'
export default {
  data () {
    return {
      prodId: this.$route.params.prodId,
      prodName: '',
      prodInfo: {},
      prodImgs: [],
      evaluate: -1,
      defaultSku: {}, // 选中的sku
      skuGroup: [], //
      selectedProp: [],
      findSku: true, // 能不能找得到sku
      prodNum: 1, //计数器数量
      prohibit1: true,  //计数器-是否禁用
      prohibit2: false,  //计数器+是否禁用
      scroeList: [],  //积分商品列表
      showVideo: false, // 是否展示视频
      showPlayBtn: true, // 视频播放按钮
    }
  },
  head () {
    return {
      title: this.$i18n.t('prodDetail.productDetails'),
    }
  },
  //在页面加载之前先加载数据
  async asyncData ({ app, params }) {
    const data = await app.$axios.get('/score/prod/prodInfo', {
      params: {
        prodId: params.prodId
      }
    }).then(({ data }) => {
      return data
    })
    var prodImgs = []
    data.imgs.split(',').forEach(imgStr => {
      prodImgs.push({
        img: imgStr,
        isActive: false
      })
    })
    prodImgs[0].isActive = true
    // data.content = util.formatHtml(data.content) // 去除商品详情富文本样式
    return {
      prodInfo: data,
      prodImgs: prodImgs,
      shopId: data.shopId,
      activityId: data.activityId
    }
  },
  watch: {
    prodNum(nv) {
      if (nv <= 1) {
        this.prohibit1 = true
        if(this.defaultSku.stocks == 0 || nv == this.defaultSku.stocks){
          this.prohibit2 = true
        }
      }else if(nv == this.defaultSku.stocks){
        this.prohibit2 = true
      }else {
        this.prohibit1 = false
        this.prohibit2 = false
      }
    }
  },
  mounted () {

    //获取积分商品列表
    this.$axios.get('/p/score/prodScorePage').then(({ data }) => {
      this.scroeList = data.records
    })

    // 设置网页标题
    document.title = this.$i18n.t('prodDetail.productDetails')

    //选中的sku
    this.groupSkuProp(this.prodInfo.skuList, this.prodInfo.price)

    // 监听页面滚动
    window.addEventListener('scroll', this.scrollToTop);

    if(this.defaultSku.stocks == 0){
      this.prohibit2 = true
    }
    if (this.prodInfo.video) {
      // 获取商品视频
      this.prodVideo = document.getElementById("prodVideo")
      this.showPlayBtn = true
    }
  },

  methods: {

    /**
     * 关闭视频
     */
    stopVideo() {
      this.showVideo = false
      if(this.prodVideo !== undefined) {
        this.prodVideo.pause()
      }
      this.showPlayBtn = true
    },

    /**
     * 播放视频
     */
    playVideo() {
      this.showVideo = true
      this.prodVideo.play(0)
      this.showPlayBtn = false
    },

    // 小图点击事件
    changeProdImg (index) {
      if(this.prodImgs[index].isActive === true) {
        return
      }
      this.prodImgs.forEach(prodImg => {
        prodImg.isActive = false
      })
      this.prodImgs[index].isActive = true
      this.prodInfo.pic = this.prodImgs[index].img
    },

    // 页面滚动事件
    scrollToTop () {
      var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      this.showScrollTab = scrollTop > 750 ? true : false
    },

    // 价格过滤
    parsePrice (value) {
      var val = Number(value)
      if (!val) {
        val = 0;
      }
      // 截取小数点后两位，并以小数点为切割点将val转化为数组
      return val.toFixed(2).split(".");
    },

    // 减少商品数量
    reduce () {
      var prodNum = parseInt(this.prodNum)
      if(prodNum<=1){
        return
      }
      if (this.defaultSku.stocks || this.defaultSku.stocks == 0) {
        if(!prodNum || prodNum <= 1) {
          this.prodNum = prodNum
          this.prohibit1 = true  //禁用
          this.prohibit2 = false
          if(this.defaultSku.stocks == 0){
            this.prohibit2 = true
          }
        }else {
          this.prodNum = prodNum - 1
          this.prohibit1 = false
          this.prohibit2 = false
        }
      }else {
        this.prodNum = 0
        this.prohibit1 = true  //禁用
        this.prohibit2 = true  //禁用
      }
    },

    /**
     * 增加商品数量
     */
    increase () {
      var prodNum = parseInt(this.prodNum)
      if(prodNum==0){
        return
      }
      if(this.defaultSku.stocks || this.defaultSku.stocks == 0) {
        if(!this.prodNum) {
          this.prodNum = 1
          return
        }
        if (prodNum < this.defaultSku.stocks) {
          this.prodNum = prodNum + 1
          this.prohibit2 = false
          this.prohibit1 = false
        } else {
          this.$message({
            message: this.$t('prodDetail.insufficientInventory'),
            type: 'warning',
            duration: 1000
          });
          if(this.defaultSku.stocks <=1 ){
            this.prohibit1 = true
          }else{
            this.prohibit1 = false
            this.prohibit2 = true
          }
        }
      }else {
        this.prodNum = 0
        this.prohibit1 = true  //禁用
        this.prohibit2 = true  //禁用
      }
    },

    // 手动输入数量过滤
    resetProdNum () {
      //失去焦点时
      if(this.defaultSku.stocks || this.defaultSku.stocks == 0) {
        if (this.prodNum > this.defaultSku.stocks) {
          this.$message({
            message: this.$t('prodDetail.insufficientInventory'),
            type: 'warning',
            duration: 1000
          });
          this.prohibit1 = false
          this.prohibit2 = false
          this.prodNum = 1
        } else if (this.prodNum <= 1) {
          this.prodNum = 1
          this.prohibit1 = true
        }else if (this.prodNum == this.defaultSku.stocks){
          this.prohibit2 = true
        }
        else {
          this.prohibit1 = false
          this.prohibit2 = false
        }
      }else {
        this.prodNum = 0
        this.prohibit1 = true  //禁用
        this.prohibit2 = true  //禁用
      }
    },

    // 组装SKU
    groupSkuProp: function (skuList, defaultPrice) {
      if (skuList.length == 1 && !skuList[0].properties) {
        this.defaultSku = skuList[0]
        return;
      }
      var skuGroup = {};
      var allProperties = [];
      var propKeys = [];
      var selectedPropObj = {}
      var defaultSku = null;
      for (var i = 0; i < skuList.length; i++) {
        var isDefault = false;
        if (!defaultSku && skuList[i].price == defaultPrice) { //找到和商品价格一样的那个SKU，作为默认选中的SKU
          defaultSku = skuList[i];
          isDefault = true;
        } else if (!defaultSku && !defaultPrice) {
          // 当商品为纯积分; defaultPrice 为 0
          defaultSku = skuList[i];
          isDefault = true;
        }
        var properties = skuList[i].properties; //版本:公开版;颜色:金色;内存:64GB
        allProperties.push(properties);
        var propList = properties.split(";"); // ["版本:公开版","颜色:金色","内存:64GB"]

        for (var j = 0; j < propList.length; j++) {

          var propval = propList[j].split(":"); //["版本","公开版"]
          var props = skuGroup[propval[0]]; //先取出 版本对应的值数组

          //如果当前是默认选中的sku，把对应的属性值 组装到selectedProp
          if (isDefault) {
            propKeys.push(propval[0]);
            selectedPropObj[propval[0]] = propval[1];
          }

          if (props == undefined) {
            props = []; //假设还没有版本，新建个新的空数组
            props.push(propval[1]); //把 "公开版" 放进空数组
          } else {
            if (props.indexOf(propval[1]) === -1) { //如果数组里面没有"公开版"
              props.push(propval[1]); //把 "公开版" 放进数组
            }
          }
          skuGroup[propval[0]] = props; //最后把数据 放回版本对应的值
        }
      }
      // console.log('defaultSku',defaultSku)
      this.defaultSku = defaultSku
      this.propKeys = propKeys
      this.selectedPropObj = selectedPropObj
      this.parseSelectedObjToVals(skuList);
      this.skuGroup = skuGroup
      this.allProperties = allProperties
    },

    // 将已选的 {key:val,key2:val2}转换成 [val,val2]
    parseSelectedObjToVals: function (skuList) {
      var selectedPropObj = this.selectedPropObj
      var selectedProperties = "";
      var selectedProp = [];
      for (var key in selectedPropObj) {
        // selectedProp.push(selectedPropObj[key]);
        selectedProp.push({key: key, value: selectedPropObj[key] });
        selectedProperties += key + ":" + selectedPropObj[key] + ";";
      }
      selectedProperties = selectedProperties.substring(0, selectedProperties.length - 1);
      this.selectedProp = selectedProp
      this.selectedProperties = selectedProperties
      this.selectedPropObj = selectedPropObj

      var findSku = false;
      for (var i = 0; i < skuList.length; i++) {
        if (
          this.compareArray(selectedProperties.split(';').sort(),
            skuList[i].properties.split(';').sort())
        ) {
          findSku = true;
          this.defaultSku = skuList[i]
          this.changeSkuImg(this.defaultSku.pic);
          break;
        }
        // if (skuList[i].properties == selectedProperties) {
        //   findSku = true;
        //   this.defaultSku = skuList[i]
        //   this.changeSkuImg(this.defaultSku.pic);
        //   break;
        // }
      }
      this.findSku = findSku
    },

    /**
      * 比较两个数组中的元素是否相等
      * @param a1 第一个数组
      * @param a2 第二个数组
      * @return boolean 两个数组中的元素都相等则返回 true，反之返回 false
      */
    compareArray(a1, a2) {
      if (!a1 || !a2) {
        return false;
      }
      if (a1.length !== a2.length) {
        return false;
      }
      for (var i = 0, n = a1.length; i < n; i++) {
        if (a1[i] !== a2[i]) {
          return false;
        }
      }
      return true;
    },

    // 切换SKU图片
    changeSkuImg (skuPic) {
      if (skuPic) {
        if (this.prodImgs[0].sku) {
          this.prodImgs.splice(0, 1)
        }
        this.prodImgs.forEach(prodImg => {
          prodImg.isActive = false
        })
        this.prodImgs.splice(0, 0, {
          img: skuPic,
          isActive: true,
          sku: true
        });
        this.prodInfo.pic = skuPic
      }else {
        this.prodInfo.pic = this.prodInfo.imgs.split(",")[0]
      }
    },

    // 判断当前的规格值 是否可以选
    isSkuLineItemNotOptional (allProperties, selectedPropObj, key, item, propKeys) {
      var selectedPropObj = Object.assign({}, selectedPropObj)
      var properties = "";
      selectedPropObj[key] = item;
      for (var j = 0; j < propKeys.length; j++) {
        properties += propKeys[j] + ":" + selectedPropObj[propKeys[j]] + ";";
      }
      properties = properties.substring(0, properties.length - 1);
      for (var i = 0; i < allProperties.length; i++) {
        if (properties == allProperties[i]) {
          return false;
        }
      }
      for (var i = 0; i < allProperties.length; i++) {
        if (allProperties[i].indexOf(item) >= 0) {
          return true;
        }
      }
      return false;
    },

    // 规格点击事件
    toChooseItem (skuLineItem, key, event) {
      this.selectedPropObj[key] = skuLineItem;
      this.parseSelectedObjToVals(this.prodInfo.skuList);
      if (this.defaultSku.stocks) {
        this.prodNum = 1
        this.prohibit1 = true
        this.prohibit2 = false
        if(this.defaultSku.stocks == 0 || this.defaultSku.stocks ==1){
          this.prohibit2 = true
        }
      }else {
        this.prodNum = 0
        this.prohibit1 = true
        this.prohibit2 = true
      }
    },

    // 立即购买
    buyNow () {
      if (!this.findSku) {
        this.$message.error(this.$t('prodDetail.productNotInStock')+'~')
        return;
      }
      if (!this.prodNum || this.prodNum <= 0 ) {
        this.$message({
          message: this.$t('prodDetail.pleaseEnterTheCorrectNumberOfItems'),
          type: 'warning',
          duration: 1000
        });
        return
      }
      if (!this.prodNum || this.prodNum <= 0  ) {
        this.$message({
          message: this.$t('prodDetail.pleaseEnterTheCorrectNumberOfItems'),
          type: 'warning',
          duration: 1000
        });
        return
      }
      if (!this.defaultSku.stocks || this.prodNum > this.defaultSku.stocks) {
        this.$message({
          message: this.$t('prodDetail.insufficientInventory'),
          type: 'warning',
          duration: 1000
        });
        return
      }
      if (!Cookie.get('token')) {
        bus.$emit("showLogin", true)
      } else {
        sessionStorage.setItem("orderItem", JSON.stringify({
          prodId: this.prodInfo.prodId,
          skuId: this.defaultSku.skuId,
          prodCount: this.prodNum,
          shopId: this.prodInfo.shopId
        }));
        this.$router.push({
          path: '/submit-integral-order?orderEntry=1',
        })
      }
    },

    // 跳转到积分商品详情
    toScoreProdDet (prodId) {
      this.$axios.get('/p/score/prodScorePage').then(({ data }) => {
        this.$router.push({ path: '/member-center/integral-det/' + prodId })
      })
    }
  },
  destroyed () {
    // 页面销毁时移除监听
    window.removeEventListener('scroll', this.scrollToTop);
  }
}
</script>

<style scoped>
@import '~/assets/css/detail.css';

.detail .detail-up .info .price-box .item.goods-price .con .old-price {
  font-family: '微软雅黑';
  margin-left: 0;
}

.detail .detail-up .info .price-box .item.goods-price .con .icon {
  width: 14px;
  height: 14px;
  font-size: 0;
  margin-right: 5px;
}

.detail .detail-up .info .price-box .item.goods-price .con .icon img {
  width: 100%;
  height: 100%;
}

.detail .detail-up .info .price-box .item.goods-price .con .add-symbol {
  margin: 0 5px;
  color: #e1251b;
  font-size: 14px;
}

.detail .detail-up .info .price-box .item.goods-price .con .price .text {
  font-size: 14px;
}

.detail .detail-down .side .sale-well {
  margin-top: 0;
}

.detail .detail-down .side .sale-well .con .item .goods-msg .goods-price {
  margin: 7px 0 3px;
}

.detail .detail-down .side .sale-well .con .item .goods-msg .goods-price .icon {
  width: 14px;
  height: 14px;
  font-size: 0;
  margin-right: 5px;
}

.detail
  .detail-down
  .side
  .sale-well
  .con
  .item
  .goods-msg
  .goods-price
  .icon
  img {
  width: 100%;
  height: 100%;
}

.detail
  .detail-down
  .side
  .sale-well
  .con
  .item
  .goods-msg
  .goods-price
  .integral-price {
  color: #e1251b;
  font-family: arial;
}

.detail .detail-down .side .sale-well .con .item .goods-msg .goods-price .add {
  margin: 0 5px;
  color: #e1251b;
  font-family: arial;
}

.detail .detail-down .side .sale-well .con .item .goods-msg .old-price {
  color: #999;
  text-decoration: line-through;
}
</style>
