<template>
  <div v-if="showSwiper">
    <div ref="mySwiper" class="swiper-container swiper mySwiper">
      <div class="swiper-wrapper">
        <div v-for="(item, index) in secArr" ref="slide" :key="index" class="swiper-slide">
          <div class="img">
            <img :src="item.goodsImage" fit="contain" />
            <div class="picNumber">{{ item.index }}/{{ totalCount }}</div>
          </div>
          <!-- {{ item }} -->
          <div class="goodsInfo">
            <div class="leftPart">
              <div class="goodsName">
                {{ item.goodsName }}
              </div>
              <p class="secStr">
                {{ item.skuAttsStr }}
              </p>
              <div class="price">
                <span>¥</span>
                <span>{{ item.goodsSalePrice | formatNum }}</span>
                <span>{{ item.goodsSalePrice | formatFloat }}</span>
              </div>
            </div>
            <div class="rightPart" @click.stop="addShopCart(item)">
              <div class="shopcartIcon">
                <!-- {{ item }} -->
                <svg-icon icon-class="shopcart" class="shopcart" />
                <div v-if="skuShopCartMap[item.goodsId]" class="shopcartCount">
                  {{ skuShopCartMap[item.goodsId] }}
                </div>
              </div>
              <div class="desc">
                加入购物车
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Swiper from 'swiper/swiper-bundle.js';
//引入css
import 'swiper/swiper-bundle.min.css';
export default {
  filters: {
    formatNum(val) {
      let str = val + '';
      return str.split('.')[0];
    },
    formatFloat(val) {
      let str = val + '';
      const float = str.split('.')[1];
      return float ? '.' + str.split('.')[1] : '';
    }
  },
  props: {
    secArr: {
      type: Array,
      default() {
        return {};
      }
    }
  },
  data() {
    return {
      list: [],
      cacheList: [],
      skuShopCartMap: {},
      totalCount: 0,
      currentIndex: 0,
      showSwiper: true
    };
  },
  watch: {
    secArr: {
      immediate: true,
      handler(val) {
        this.totalCount = val.length;
        this.cacheList = val.map((item, index) => {
          item.index = index + 1;
          return item;
        });
        // this.list = val.slice(0, 3);
        this.showSwiper = false;
        this.$nextTick(() => {
          this.refreshSwiper();
        });
      }
    }
  },
  mounted() {
    this.refreshSwiper();
  },
  methods: {
    addShopCart(goods) {
      const { goodsId: skuId, goodsType: skuSource } = goods;
      this.$track.registeredEvents(
        'APP_FeedCommodityCardCartBtnClick',
        {
          page_name: '搜索结果页'
        },
        async () => {
          const [res, error] = await this.$store.dispatch('shopCart/good_add', {
            type: 'ADD_CART',
            goodInfo: { selected: true, skuId, skuSource, skuNum: 1 }
          });
          if (!error) {
            this.$toast('购物车添加成功');
            this.$store.dispatch('shopCart/saveCartCount', res?.count);

            if (!this.skuShopCartMap[goods.goodsId]) {
              // this.skuShopCartMap[goods.goodsId] = 1;
              this.$set(this.skuShopCartMap, skuId, 1);
            } else {
              let currentCount = this.skuShopCartMap[goods.goodsId];
              this.$set(this.skuShopCartMap, skuId, currentCount + 1);
            }
          }
        }
      );
    },
    refreshSwiper() {
      if (!this.secArr.length) return;
      const init = () => {
        this.$nextTick(() => {
          let totalOpacity = 1.33;
          const opacityStep = 0.33;
          // const index = this.$refs.mySwiper.swiper.activeIndex;
          const slides = Array.from(document.getElementsByClassName('swiper-slide'));
          const index = slides.findIndex(item => {
            return item.className.indexOf('swiper-slide-active') > 0;
          });
          try {
            for (let i = index; i < slides.length; i++) {
              const surplus = totalOpacity - opacityStep;
              slides[i].style.opacity = surplus;
              slides[i].style.zIndex = 100;
              totalOpacity = surplus;
            }
            if (index != 0) {
              for (let i = index - 1; i >= 0; i--) {
                slides[i].style.opacity = 0;
              }
            }
          } catch (err) {
            console.log(err);
          }
        });
      };
      this.showSwiper = true;
      this.$nextTick(() => {
        new Swiper('.swiper', {
          effect: 'cards',
          grabCursor: true,
          loop: true,
          loopedSlides: 10,
          speed: 500,
          cardsEffect: {
            rotate: 0,
            perSlideOffset: 10
          },
          on: {
            init() {
              init();
            },
            slideChange: () => {
              init();
            }
          }
        });
      });
    }
  }
};
</script>
<style lang="less" scoped>
@opacityStep: 0.15;
@containerWidth: 315px;
@itemWidth: 295px;
.swiper {
  width: @itemWidth;
  height: 400px;
}

.swiper-slide {
  display: flex;
  // align-items: center;
  // justify-content: center;
  flex-direction: column;
  border-radius: 12px;
  font-size: 22px;
  font-weight: bold;
  color: #999;
  background: @white;
  .img {
    position: relative;
    width: @itemWidth;
    height: @itemWidth;
    .picNumber {
      display: flex;
      align-items: center;
      justify-content: center;
      position: absolute;
      bottom: 10px;
      right: 10px;
      padding: 2px @padding-x;
      background: rgba(0, 0, 0, 0.4);
      border-radius: 12px;
      color: @white;
      font-size: 10px;
    }
  }
  .img {
    width: 100%;
    height: @itemWidth;
    // border-radius: 12px 12px 0 0;
    overflow: hidden;
    img {
      width: 100%;
      height: 100%;
      display: block;
    }
  }
  .goodsInfo {
    padding: @padding-xs @padding-sm;
    box-sizing: border-box;
    display: flex;
    .leftPart {
      width: calc(100% - 85px);
    }
    .rightPart {
      font-size: 12px;
      width: 85px;
      padding-top: @padding-xs;
      box-sizing: border-box;
      // background: @gray-4;
      display: flex;
      flex-direction: column;
      align-items: center;
      .shopcartIcon {
        position: relative;
        .shopcartCount {
          position: absolute;
          top: -1px;
          right: -1px;
          width: 17px;
          height: 17px;
          border-radius: 50%;
          background: @red;
          color: @white;
          font-size: 13px;
          display: flex;
          align-items: center;
          justify-content: center;
        }
      }
      .desc {
        margin-top: @padding-unit;
        .text-size(12);
      }
    }
  }
  .goodsName {
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 100%;
    .text-size(14);
    color: @black;
    word-break: break-all;
  }
  .secStr {
    .text-size(12);
    color: @gray-4;
    margin-top: @padding-unit / 2;
  }
  .price {
    color: @red;
    margin-top: @padding-unit * 2;
    span {
      font-weight: bold;
      &:nth-child(1) {
        font-size: 12px;
      }
      &:nth-child(2) {
        font-size: 18px;
      }
      &:nth-child(3) {
        font-size: 12px;
      }
    }
  }
}

.shopcart {
  width: 50px;
  height: 50px;
}
</style>
