<!-- 新人福利专区页面 -->
<template>
  <div
    class="new-people-area"
    :style="{
      backgroundSize: 'contain',
      backgroundPosition: `100% -30px`,
      backgroundImage: `url(${layoutData.bgImgUrl})`,
      backgroundRepeat: 'no-repeat'
    }"
  >
    <!-- 搜索 -->
    <Search v-if="layoutData.contents" class="search" />
    <!-- 规则 -->
    <Rule
      v-if="layoutData.contents"
      :source-data="{
        activityRulesUrl: layoutData.activityRulesUrl,
        activityRulesImageUrl: layoutData.activityRulesImageUrl
      }"
    />
    <!-- 券包 -->
    <!-- <div class="coupon" @click="getCoupon">
      <cr-image src="https://appsync.lkbang.net/FlIoaO15m5t4qdXSkSNtoLczw6PQ" />
    </div> -->
    <div v-for="(item, index) in layoutData.contents" :key="index">
      <!-- 一键领取+item.elementType === 105 券包 -->
      <GetCoupon v-if="+item.elementType === 105" :source-data="item" @getCoupon="setShow" />
      <!-- 领券弹框 -->
      <PopupCoupon
        v-if="+item.elementType === 105"
        :show="show"
        :source-data="item"
        :getshow.sync="show"
      />
      <!-- 专题  elementType === 107 -->
      <SpecialCrosswise v-if="+item.elementType === 107" :source-data="item" />
      <!-- 导流新人图片组件 elementType== 116 -->
      <div v-if="+item.elementType === 116" class="new-user-guidance">
        <img
          :src="item.picture.img"
          alt=""
          @click="
            handleToDetailsTrack(item.picture, 'NewUserPageImageAssembly', index, {
              assembly_name: item.componentName
            })
          "
        />
      </div>
      <!-- 新人专区商品导航 -->
      <template v-if="+item.elementType === 106">
        <cr-tabs
          sticky
          anchor
          color="#EC1500"
          drop-active-color="#EC1500"
          drop-inactive-color="#333333"
          title-active-color="#EC1500"
          title-inactive-color="#333333"
          sticky-inactive-color="#333333"
          sticky-active-color="#EC1500"
          class="tabs-sticky"
          @change="changeTabs"
        >
          <!-- 过滤sku数量小于8的商品，他们说这样好看！！！ -->
          <cr-tab
            v-for="(itm, idx) in item.navigationInfo.navigations.filter(item => {
              return item && item.skus && item.skus.length >= 8;
            })"
            :key="idx"
            :title="itm.title"
          >
            <div v-if="itm.topImageUrl" class="top-img">
              <img
                :src="itm.topImageUrl"
                alt=""
                @click="handleToDetailsTrack({ jumpUrl: itm.topImageNavUrl }, '', idx)"
              />
            </div>

            <div class="nav-con">
              <cr-grid :border="false" class="nav-con-grid">
                <cr-grid-item
                  v-for="(itmSku, itmIdx) in itm.skus || []"
                  :key="itmIdx"
                  class="card-grid-item"
                >
                  <cr-image
                    width="100%"
                    height="109px"
                    lazy-load
                    :src="itmSku.imageUrl"
                    @click="
                      handleToDetailsTrack(itmSku, 'NewUserPageCommodityCard', idx, {
                        navigation_name: itm.title,
                        position_number: itmIdx,
                        commodity_id: itmSku.skuNo
                      })
                    "
                  />
                  <div class="item-con">
                    <div class="item-top">
                      <img v-if="itmSku.channelImg" :src="itmSku.channelImg" alt="" />
                      {{ itmSku.skuName }}
                    </div>
                    <div class="item-btm">
                      <div class="left">
                        <img
                          v-if="
                            itmSku &&
                              itmSku.tagList &&
                              itmSku.tagList.length &&
                              itmSku.tagList[0].type === 1 &&
                              itmSku.tagList[0].icon
                          "
                          :src="itmSku.tagList[0].icon"
                          alt=""
                        />
                        <div class="money">￥{{ itmSku.price }}</div>
                      </div>
                      <div
                        class="right"
                        @click.stop="
                          {
                            addShopCart(itmSku);
                            handleToDetailsTrack({}, 'NewUserPageCommodityCard', idx, {
                              navigation_name: itm.title,
                              position_number: itmIdx,
                              commodity_id: itmSku.skuNo,
                              buttons_name: '购物车按钮'
                            });
                          }
                        "
                      >
                        <img src="https://img.lkbang.net/gouwuche.57b2aeee.png" alt="" />
                      </div>
                    </div>
                  </div>
                </cr-grid-item>
              </cr-grid>
            </div>
          </cr-tab>
        </cr-tabs>
      </template>
    </div>
  </div>
</template>

<script>
import Search from './components/Search';
import Rule from './components/Rule.vue';
import SpecialCrosswise from './components/SpecialCrosswise.vue';
import GetCoupon from './components/GetCoupon.vue';
import PopupCoupon from './components/PopupCoupon.vue';
import api from '@/api/newPeopleArea.api';
import mxBll from '../home/mixin/mxBll';
import { TRACK_EVENT_MAP } from './model';
import { getTokenFromApp } from '@/service/yxmLogin.service';
import { maxMember } from '@/api/member.api';
import { isApp } from '@/service/validation.service';
import localStorage from '@/service/localStorage.service';
// import { throttle } from '@/service/utils.service';

export default {
  components: {
    Search,
    Rule,
    SpecialCrosswise,
    GetCoupon,
    PopupCoupon
  },
  mixins: [mxBll],
  data() {
    return {
      show: false,
      layoutData: {},
      skuData: {},
      navigations: []
    };
  },
  created() {
    this.init();
  },
  methods: {
    changeTabs(index) {
      this.$track.registeredEvents('H5_NewUserPageCommodityCardExposure', {
        navigation_name: this.navigations[index] && this.navigations[index].title,
        position_number: index
      });
    },

    // 加购
    async addShopCart(goods) {
      // todo
      if (goods.status === 2) return;
      if (goods.status === 1) {
        this.$toast('来晚了已经卖完了~');
        return;
      }
      try {
        await getTokenFromApp();
        const { skuNo, skuSource } = goods;
        const params = [{ skuId: skuNo, skuNum: 1, skuSource, type: 1 }];
        const [res, err] = await maxMember.addShopCart({
          shopCartBaseList: params,
          selected: true
        });
        if (res) {
          this.$toast.success('添加成功');
        } else if (err.response.businessCode === '401') {
          await getTokenFromApp(true);
        }
        if (isApp) {
          this.editor?.updateShopCartCount();
          this.nativeBridge.run({
            event: 'shopCarAddGoodsNotification',
            data: {
              count: res.count
            }
          });
        }
      } catch (error) {
        console.log(error);
      }
    },
    async init() {
      let [data] = await api.getNewPeopleData();
      if (data) {
        this.layoutData = data;
        // 埋点使用数据 商品曝光
        if (data.contents) {
          this.skuData = data.contents.filter(item => +item.elementType === 106)[0];
          this.navigations =
            this.skuData && this.skuData.navigationInfo && this.skuData.navigationInfo.navigations;
          this.$track.registeredEvents('H5_NewUserPageCommodityCardExposure', {
            navigation_name: this.navigations[0] && this.navigations[0].title,
            position_number: 0
          });
        }
      }
    },
    handleToDetailsTrack(item, area, index, buriedPoint = {}) {
      if (item.needLogin && !localStorage.get('vccToken')) {
        this.$config.signOutFn();
        return;
      }
      const trackInfo = TRACK_EVENT_MAP[area];
      if (trackInfo) {
        this.$track.registeredEvents(
          trackInfo.name,
          {
            position_number: index,
            ...buriedPoint,
            [trackInfo.trackKey]: item[trackInfo.itemKey]
          },
          () => {
            this.mxHandleToDetails({ item, area, index });
          }
        );
      } else {
        this.mxHandleToDetails({ item, area, index });
      }
    },
    // 搜索商品
    searchEnterEvent() {
      this.$store.commit('DEL_KEEP_ALIVE', 'search');
      this.$track.registeredEvents('H5_UserClickSearchTrigger', { page_name: 'home' });
      setTimeout(() => {
        this.$router.push({ name: 'search' });
      }, 200);
    },
    // 获取优惠券
    setShow() {
      this.show = true;
      this.init();
    },
    close() {
      this.show = false;
    }
  }
};
</script>

<style lang="less" src="./style/index.less" scoped></style>
