<template>
  <view class="home-list">
    <view v-if="showHeader" class="home-list-header">
      <view v-if="headerType === 'left'">
        <image src="https://img.lkbang.net/xcx/guess_like.png" />
        <span>{{ title }}</span>
      </view>
      <view v-if="headerType === 'center'" class="Hl-header-center">{{ title }}</view>
      <cr-image
        v-if="headerType === 'image'"
        :src="'https://img.lkbang.net/icon-recommend.465d832f185840eaa.465d832f.png' | imogr"
        width="4.53rem"
        height="0.96rem"
        class="Hl-header-image"
      />
    </view>
    <!-- <view class="home-list-container"> -->
    <transition-group name="list-complete" tag="div" class="home-list-container">
      <view
        v-for="(item, index) in goodsList"
        :key="item.goods.goodsId"
        class="Hl-container-item"
        @click="handleToDetail(item.goods, index)"
      >
        <view class="Hl-container-item-img">
          <cr-image
            class="Hlc-item-img"
            :src="item.goods.goodsOrgImage | imogr({ w: 173, h: 173 })"
            lazy-load
            fit="contain"
          />
          <!-- 不感兴趣 -->
          <span v-if="noShare" class="Hlc-item-close" @click.stop="setReport(index, item.goods)">
            ×
          </span>
        </view>
        <view class="Hlc-item-title">
          <span>{{ item.goods.goodsName }}</span>
        </view>
        <view v-if="item.goods.tagList && item.goods.tagList.length" class="Hlc-item-active">
          <view v-for="(itm, idx) in item.goods.tagList" :key="idx">
            <span v-if="itm.name">{{ itm.name }} </span>
          </view>
        </view>
        <view v-if="item.goods.sellPoint" class="Hlc-item-gray">{{ item.goods.sellPoint }}</view>
        <view class="Hlc-item-info">
          <view class="Hlcu-info-left">
            <view class="Hlcu-info-left-price" v-html="goodsSalePrice(item.goods.goodsSalePrice)" />
            <view v-if="item.goods.discountShow" class="Hlcu-info-left-activity">
              <span
                :style="{
                  color: colorJudgment(item.goods.discountShow)
                }"
                >¥{{ item.goods.discountShow.discountPrice }}</span
              >
              <image :src="item.goods.discountShow.icon | imogr" />
            </view>
          </view>
          <!-- 加入购物车 -->
          <view class="Hlcu-info-shopRight">
            <cr-image :src="shopcart" @click.stop="addShopCart(item.goods)" />
          </view>
        </view>
      </view>
    </transition-group>
    <!-- </view> -->
  </view>
</template>
<script>
import { Img2Thumb } from '@/filters/img2Thumb.filter';
import { colorJudgment } from '../constants/max.js';
import shopcart from '@/static/images/goods/shopcart.png';
import { mapActions as ShopCartMapActions } from '@/pages/shopCart/shopCartModules.js';
import { getReport } from '@/api/home.api';
export default {
  name: 'GoodsCard',
  filters: {
    Img2Thumb
  },
  props: {
    title: {
      type: String,
      default: '猜你喜欢'
    },
    goodsList: {
      type: Array,
      default: () => []
    },
    showHeader: {
      type: Boolean,
      default: true
    },
    isDelete: {
      type: Boolean,
      default: true
    },
    headerType: {
      type: String,
      default: 'left'
    },
    noShare: {
      type: Boolean,
      default: false
    },
    // 商品点击埋点事件名称
    eventClickName: {
      type: String,
      default: 'H5_2BSelectionPageCommodityCardClick'
    },
    // 商品曝光埋点事件名称
    eventExposureName: {
      type: String,
      default: 'H5_2BSelectionPageCommodityCardExposure'
    },
    // 埋点默认参数
    exposureParams: {
      type: Object,
      default: () => ({})
    },
    top: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      goodsMaskIdx: -1,
      shopcart,
      colorJudgment
    };
  },
  watch: {
    top() {
      this.timeOutExposure();
    },
    goodsList(v, prev) {
      if (prev.length < 1) {
        this.timeOutExposure();
      }
    }
  },
  beforeDestroy() {
    clearTimeout(this.timer);
  },
  methods: {
    ...ShopCartMapActions({
      addToCart: 'add_to_cart'
    }),
    goodsSalePrice(price) {
      let priceList = [];
      if (price.indexOf('.') > -1) {
        priceList = price.split('.');
        return `<span>¥</span><span>${priceList[0]}</span><span>.${priceList[1]}</span>`;
      }

      return `<span>¥</span><span>${price}</span>`;
    },
    addShopCart(params) {
      const { goodsId, skuSource } = params;
      this.addToCart({ skuId: goodsId, skuNum: 1, skuSource });
    },
    delGoods(index) {
      const { goodsList } = this;
      goodsList.splice(index, 1);
      this.$toast('已减少此类信息推荐!');
      this.$emit('update:goodsList', goodsList);
    },
    async setReport(index, goods) {
      const data = {
        dataType: 1, // 数据类型 1：商品不感兴趣
        reportData: {
          skuUnInterestData: {
            pageType: 1, //页面类型，1 - 首页综合信息流（精选页）  2 - 电商首页商品流（发现页）
            selectOption: 1, //1:不感兴趣，2：分享好友
            sourceType: 1, // 1：商品，4：视频 5：图文段子
            sourceId: goods.goodsId || '',
            skuSource: goods.skuSource || ''
          }
        },
        userDeviceInfoData: null
      };
      await getReport(data);
      this.delGoods(index);
    },
    timeOutExposure() {
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        clearTimeout(this.timer);
        this.countItemExposure();
      }, 500);
    },
    // 商品曝光
    exposureGood(item, index) {
      this.$track.registeredEvents(
        this.eventExposureName,
        Object.assign({}, this.exposureParams, {
          commodity_id: item.goods?.goodsId,
          position_number: index
        })
      );
    },
    // 判断是否在可视区域
    getIsView(elTop, elHeight) {
      const viewHeight = window.innerHeight || document.documentElement.clientHeight - 150;
      if (elTop + 100 >= this.top && elTop + elHeight / 2 <= this.top - 100 + viewHeight) {
        return true;
      }
      return false;
    },
    // 计算可曝光商品卡片
    countItemExposure() {
      const els = this.$el.querySelectorAll('.Hl-container-item');
      els.forEach((el, i) => {
        const elTop = el.offsetTop;
        const elHeight = el.offsetHeight;
        const res = this.getIsView(elTop, elHeight);
        if (res) {
          this.exposureGood(this.goodsList[i], i + 1);
        }
      });
    },
    handleToDetail(item, index) {
      this.$track.registeredEvents(
        this.eventClickName,
        Object.assign({}, this.exposureParams, {
          commodity_id: item.goodsId,
          position_number: index + 1
        }),
        () => {
          const params = {
            count: 1,
            goodsName: item.goodsName,
            goodsOrgImage: item.goodsOrgImage
          };
          const query = {
            skuNo: item.goodsId
          };
          this.$router.push({ name: 'goodDetail', params, query });
        }
      );
    }
  }
};
</script>
<style lang="less" scoped>
.home-list {
  &-header {
    display: flex;
    align-items: center;
    padding: @padding-sm @padding-sm 0;
    height: 24px;
    .text-size(18);
    color: @black;
    img {
      margin-right: @padding-x;
      width: 20px;
      height: 20px;
      vertical-align: text-top;
    }
    .Hl-header-image {
      display: block;
      margin: 0 auto @padding-lg;
    }
    .Hl-header-center {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: @padding-md 0;
      width: 100%;
      .text-size(12);
      color: @gray-4;
      text-align: center;
      &:before,
      &:after {
        display: inline-block;
        content: '';
        width: 50px;
        height: 0;
        border-top: 2px solid @gray-2;
        margin-right: @padding-x;
      }
      &:after {
        margin-left: @padding-x;
        margin-right: 0;
      }
    }
  }
  &-container {
    padding-top: @padding-sm;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;

    .Hl-container-item {
      position: relative;
      margin-bottom: @padding-xs;
      width: 172px;
      background: @white;
      border-radius: @border-radius-md;
      // padding-bottom: 36px;
      border-radius: 8px;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      transition: all 0.3s;
      &.list-complete {
        &-enter,
        &-leave-to {
          opacity: 0;
          transform: translateY(30px);
        }
        &-active {
          position: absolute;
        }
      }
      .Hlc-item-close {
        position: absolute;
        top: 8px;
        right: 8px;
        width: 12px;
        height: 12px;
        background: rgba(0, 0, 0, 0.02);
        // background: red;
        font-size: 10px;
        color: #c8c9cc;
        border-radius: 50%;
        text-align: center;
      }
      &-img {
        height: 170px;
        display: flex;
        align-items: center;
        overflow: hidden;
      }
      .Hlc-item-img {
        width: 100%;
        height: 173px;
        border-radius: @border-radius-md;
        overflow: hidden;
      }
      .Hlc-item-title {
        height: 38px;
        padding: @padding-x @padding-xs 0 @padding-xs;
        span {
          .text-size(13);
          color: @black;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }
      }
      .Hlc-item-active {
        font-size: 0;
        margin: @border-radius-sm + 2 @padding-xs 0;
        div {
          display: inline-block;
          span {
            display: inline-block;
            border: 1px solid @border-red;
            font-size: 10px;
            color: @red;
            border-radius: 3px;
            padding: 3px 5px 2px;
            margin-right: 3px;
            margin-top: 2px;
          }
        }
      }
      .Hlc-item-gray {
        .text-size(12);
        color: @gray-4;
        padding: 0 @padding-xs;
      }
      .Hlc-item-info {
        margin: 0 @padding-xs @border-radius-sm + 2 @padding-xs;
        display: flex;
        align-items: center;
        justify-content: space-between;
        // position: absolute;
        // bottom: 0;
        margin-top: auto;
        .Hlcu-info-left {
          &-price {
            /deep/ span {
              font-weight: 500;
              color: @red-light;
              &:nth-child(1) {
                .text-size(12);
              }
              &:nth-child(2) {
                .text-size(18);
              }
              &:nth-child(3) {
                .text-size(12);
              }
            }
          }
          &-activity {
            display: flex;
            align-items: flex-end;
            margin-top: 3px;
            span {
              font-size: 12px;
              color: #ed7d08;
            }
            img {
              width: auto;
              height: 12px;
            }
          }
        }
        .Hlcu-info-shopRight {
          width: 24px;
          height: 24px;
        }
      }
      .Hlc-item-mask {
        position: absolute;
        top: 0;
        bottom: 0;
        right: 0;
        left: 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        background: rgba(0, 0, 0, 0.4);
        border-radius: @border-radius-sm;
        .Hlci-mask-button {
          padding: 0 @padding-xl - 4;
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: 133px;
          height: 30px;
          border-radius: @border-radius-lg;
          .text-size(12);
          color: @black;
          &:first-child {
            margin-bottom: @padding-lg;
          }
          img {
            width: 18px;
            height: 18px;
          }
        }
      }
    }
  }
}
</style>
