<template>
  <view class="home">
    <!-- <navigator :url="testUrl" hover-class="navigator-hover">
      <button type="default">跳转到新页面</button>
    </navigator> -->
    <view class="home-header">
      <view class="home-header-search" @click="navToSearch">
        <text class="iconfont icon-search" />
        <text :class="{ 'anim-opacity': animStatr }">{{ borderTxt }}</text>
      </view>
    </view>
    <scroll-view
      class="home-container"
      scroll-y
      :trap-scroll="true"
      :scroll-top="tabScrollTop"
      :scroll-left="scrollPosition"
      :scroll-with-animation="isAnimate"
      :refresher-threshold="100"
      @scrolltolower="loadData"
      @scroll="pageScroll"
    >
      <!-- 轮播图开始 -->
      <view class="home-banner">
        <swiper class="home-banner-swiper" autoplay circular @change="swiperChange">
          <swiper-item v-for="(item, index) in carouselList" :key="index" class="Hb-swiper-item">
            <image
              class="Hbs-item-img"
              :src="item.img"
              @click="navToActivityPage(item, 'Banner', index)"
            />
          </swiper-item>
        </swiper>
        <!-- 轮播图计数 -->
        <view class="home-banner-dots">
          <view
            v-for="(d, i) in carouselList"
            :key="i"
            class="Hb-dots-item"
            :class="[swiperCurrent == i ? 'Hb-dots-item_selected' : '']"
          />
        </view>
      </view>
      <!-- 轮播图结束 -->
      <view class="home-container-body">
        <!-- 金刚区 -->
        <view v-if="navList.length > 0" class="home-nav">
          <view class="home-nav-body">
            <view
              v-for="(item, index) in navList[0].items"
              :key="index"
              class="Hn-body-item"
              @click="navToActivityPage(item, 'KingKongPosition', index)"
            >
              <image :src="item.img" />
              <text>{{ item.name }}</text>
            </view>
          </view>
        </view>
        <!-- 运营专区横向 -->
        <view v-if="rowList.length > 0" class="home-welfare">
          <image
            v-for="(item, index) in rowList[0].items"
            :key="index"
            :src="item.img"
            @click="navToActivityPage(item, 'OperationPromotion_across', index)"
          />
        </view>
        <!-- 通栏 -->
        <view v-if="layoutList.length" class="home-ads">
          <image
            v-for="(item, index) in layoutList[0].items"
            :key="index"
            :src="item.img"
            @click="navToActivityPage(item, 'ExtensionBanner', index)"
          />
        </view>
        <!-- 运营专区竖向 -->
        <view v-if="colList.length > 0" class="home-find">
          <image
            v-for="(item, index) in colList[0].items"
            :key="index"
            :src="item.img"
            @click="navToActivityPage(item, 'OperationPromotion_vertical', index)"
          />
        </view>
        <!-- 首页双排 -->
        <goods-card
          v-if="goodsList.length"
          ref="goodsCard"
          :goods-list.sync="goodsList"
          :show-header="false"
        />
        <!-- 加载更多 -->
        <uni-load-more :status="loadingType" />
      </view>
    </scroll-view>
    <!-- 登陆弹窗 -->
    <login-popup ref="login-popup" />
    <!-- 回到顶部 -->
    <view class="goods-top">
      <to-top :scroll-top="scrollTop" @toTop="toTop" />
    </view>
    <skeleton v-if="allLoading" />
    <activityModal
      v-if="Object.keys(activityModalData).length > 0"
      :modal-data="activityModalData"
      page-name="首页"
      @close="closeActivityModal"
      @goto="jumpToWebView(activityModalData)"
    />
    <!-- 合规 -->
    <TipModal
      ref="tipCurrent"
      :title="mpTitle"
      :close-able="false"
      :mode="tipPrivacyMode"
      @cancel="cancelEvent"
      @confirm="tipConfirmEvent"
    >
      <TipContentMp />
    </TipModal>
  </view>
</template>

<script>
import {
  getBanner,
  getContent,
  getGoodsList,
  getSearchBorderTxt,
  getHomePopup,
  getFincialData,
  uploadPopup
} from "@/api/home.api.js";
import { getCartCountVal } from "../../mixins/common.js";
import uniLoadMore from "@/components/uni-load-more/uni-load-more.vue";
import goodsCard from "@/components/goodsCard";
import loginPopup from "@/components/loginPopup";
import TipModal from "@/components/TipModal.vue";
import TipContentMp from "@/components/TipContentMp";
import activityModal from "@/components/activityModal";
import toTop from "@/components/toTop";
import skeleton from "./index.skeleton";
import { saTrackEvent, setRegisterPage } from "@/utils/sa.js";
import { submitSubcribeInfo, getAcceptList } from "@/utils/subscribe";
import { throtte } from "@/utils/index";
import { mpConfig } from "@/utils/mpConfig/types";
import mxPrivacy from "@/mixins/mx-privacy";
let animTimer = null;
const bannerExposureList = [];
import { SubscribeMessageConfig } from "./index.config";
export default {
  components: {
    uniLoadMore,
    goodsCard,
    loginPopup,
    toTop,
    skeleton,
    activityModal,
    TipContentMp,
    TipModal
  },
  mixins: [mxPrivacy],
  data() {
    return {
      isAnimate: mpConfig.isAnimate,
      allLoading: true,
      searchKeywords: [],
      timer: null,
      timerNum: 0,
      borderTxt: "搜索商品",
      titleNViewBackground: "",
      swiperCurrent: 0,
      carouselList: [],
      goodsList: [],
      navList: [],
      rowList: [],
      colList: [],
      layoutList: [],
      loadingType: "loading",
      progress: "finished",
      shareList: [],
      pageForm: {
        pageNo: 0,
        pageSize: 10,
        pageType: 2
      },
      tabScrollTop: 0,
      scrollTop: 0,
      old: {
        scrollTop: 0
      },
      scrollPosition: 0,
      animStatr: false,
      vccChannel: "",
      sonVccChannel: "",
      fromState: "",
      activityModalData: {},
      activityJumpUrl: ""
    };
  },
  onShareAppMessage(res) {
    const dataset = res.target.dataset.goods;
    return {
      title: dataset.shareInfo && dataset.shareInfo.shareTitle,
      path: `/pages/product/goodDetail?skuNo=${dataset.goods.goodsId}&count=1`,
      imageUrl: dataset.shareInfo && dataset.shareInfo.shareImgUrl
    };
  },

  onTabItemTap() {
    saTrackEvent("MINI_BottomTabsClick", { tab_name: "精选" });
  },

  async onLoad(option) {
    console.log("index-option====================>", option);
    // 合规
    this.initPrivacyModal();
    uni.setNavigationBarTitle({ title: this.$config("defaultTitle") });
    // 使用all可以减少等待时间
    this.init();
    // option = {
    //   // lableInfoIds: "19",
    //   vccChannel: '400000094',
    //   sonVccChannel: '221466'
    //   // from: "h5ToMiniApp",
    //   // from: "webviewToMiniApp"
    // }
    uni.$on("login", () => {
      if (this.activityJumpUrl) {
        const url = this.activityJumpUrl;
        this.activityJumpUrl = "";
        uni.redirectTo({
          url: `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(url))}`
        });
      }
    });
    process.env.NODE_ENV !== "production" &&
      uni.$on("qaEnvChange", () => {
        this.init();
      });
    if (option) {
      this.vccChannel = option.vccChannel;
      this.sonVccChannel = option.sonVccChannel;
      // this.fromState = option.from;
    }
    if (option.vccChannel) {
      uni.setStorageSync("vccChannel", option.vccChannel);
    }
    if (option.sonVccChannel) {
      uni.setStorageSync("sonVccChannel", option.sonVccChannel);
    }
  },
  onUnload() {
    uni.$off("login");
    uni.$off("qaEnvChange");
  },
  onReady() {
    this.allLoading = false;
  },
  onShow() {
    getCartCountVal();
    if (this.timer) {
      this.clearWordAnimate();
      this.keywordAnimate();
    }

    console.log(uni.getStorageSync("vccChannel"));
    console.log(uni.getStorageSync("sonVccChannel"));
    setRegisterPage({
      parent_channelid: uni.getStorageSync("vccChannel") || "",
      son_channelid: uni.getStorageSync("sonVccChannel") || ""
    });
  },
  onHide() {
    this.clearWordAnimate();
  },
  methods: {
    init() {
      Promise.all([
        this.getBannerInfo(),
        this.getContentInfo(),
        this.loadData(),
        this.getShadingText(),
        this.getHomePopup()
      ])
        .then(() => {})
        .catch(() => {});
    },
    async closeActivityModal() {
      const data = JSON.parse(JSON.stringify(this.activityModalData));
      const token = uni.getStorageSync("token") || "";
      this.activityModalData = {};
      if (data.exposureType == 3 && token) {
        const uid = data.uid;
        const exposureType = data.exposureType;
        await uploadPopup({
          uid,
          exposureType
        });
      }
    },
    async jumpToWebView(data) {
      saTrackEvent("MINI_PagePopupWindowClick", {
        popupwindow_id: data.uid,
        popupwindow_name: data.componentName,
        page_name: "首页"
      });
      data = data || {};
      const token = uni.getStorageSync("token") || "";
      const url = data.jumpUrl || "";
      this.activityJumpUrl = url;
      if (data?.needLogin && !token) {
        this.activityModalData = {};
        this.$refs["login-popup"].open();
        return;
      }
      if (data.exposureType == 2 && token) {
        const uid = data.uid;
        const exposureType = data.exposureType;
        await uploadPopup({
          uid,
          exposureType
        });
      }
      this.activityModalData = {};
      if (url.indexOf("http://") === 0 || url.indexOf("https://") === 0) {
        uni.navigateTo({
          url: `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(url))}`
        });
        return;
      }
      uni.navigateTo({
        url
      });
    },
    async getShadingText() {
      const [BorderTxt] = await getSearchBorderTxt();
      if (!BorderTxt || !BorderTxt.searchKeywords || !BorderTxt.searchKeywords.length) {
        return;
      }
      this.searchKeywords = BorderTxt.searchKeywords;
      this.keywordAnimate();
    },
    // 优化首页关键词返回之后不滚动
    keywordAnimate() {
      const searchKeywords = this.searchKeywords;
      if (searchKeywords.length) {
        this.borderTxt = searchKeywords[searchKeywords.length - 1];
        this.timer = setInterval(() => {
          if (this.timerNum > searchKeywords.length - 1) this.timerNum = 0;
          this.borderTxt = searchKeywords[this.timerNum];
          this.timerNum++;
          this.animStatr = true;
          animTimer = setTimeout(() => {
            this.animStatr = false;
            clearTimeout(animTimer);
          }, 1500);
        }, 3000);
      }
    },
    clearWordAnimate() {
      clearTimeout(animTimer);
      clearInterval(this.timer);
    },
    async getBannerInfo() {
      const [data] = await getBanner();
      if (data && data.banner && data.banner) {
        this.carouselList = data.banner.items || [];
        bannerExposureList.length = this.carouselList.length;
        bannerExposureList.fill(false);
      }
    },
    async getHomePopup() {
      const token = uni.getStorageSync("token") || "";
      const [data] = await getHomePopup();
      this.activityModalData = data || {};
      if (data.exposureType == 1 && token) {
        // 每天仅弹出一次 进行上报
        const uid = data.uid;
        const exposureType = data.exposureType;
        await uploadPopup({
          uid,
          exposureType
        });
      }
    },
    async getContentInfo() {
      const [data] = await getContent();
      const infoMap = {
        4: "navList",
        51: "rowList",
        52: "colList",
        10: "layoutList"
      };
      const cfg = (data && data.contents) || [];
      cfg.forEach(item => {
        if (infoMap[item.elementType]) this[infoMap[item.elementType]].push(item);
        switch (this[infoMap[item.elementType]][0].elementType) {
          case 4: // 4-金刚区
            this[infoMap[item.elementType]][0].items.forEach((val, inx) => {
              saTrackEvent("PD_YXMMAEC_ASMSelectionPageKingKongPositionExposure", {
                assembly_id: val.id,
                assembly_name: val.bname,
                position_number: inx
              });
            });
            break;
          case 51: // 51-运营专区-横向
            this[infoMap[item.elementType]][0].items.forEach((val, inx) => {
              saTrackEvent("PD_YXMMAEC_ASMSelectionPageOperationPromotion_Across", {
                assembly_id: val.id,
                assembly_name: val.bname,
                position_number: inx
              });
            });
            break;
          case 52: //52-运营专区-竖向
            this[infoMap[item.elementType]][0].items.forEach((val, inx) => {
              saTrackEvent("PD_YXMMAEC_ASMSelectionPageOperationPromotion_Vertical", {
                assembly_id: val.id,
                assembly_name: val.bname,
                position_number: inx
              });
            });
            break;
          case 10: //10-通栏
            this[infoMap[item.elementType]][0].items.forEach((val, inx) => {
              saTrackEvent("PD_YXMMAEC_ASMSelectionPageExtensionBannerExposure", {
                assembly_id: val.id,
                assembly_name: val.bname,
                position_number: inx
              });
            });
            break;
        }
      });
    },
    //轮播图切换修改背景色
    swiperChange(e) {
      const index = e.detail.current;
      !bannerExposureList[index] &&
        saTrackEvent("PD_YXMMAEC_ASMSelectionPageBannerExposure", {
          assembly_id: this.carouselList[index].id,
          assembly__name: this.carouselList[index].bname,
          frames_mark: index
        });
      bannerExposureList[index] = true;

      this.swiperCurrent = index;
      this.titleNViewBackground = this.carouselList[index].background;
    },
    //详情页
    async navToActivityPage(item, area, index) {
      const lowerCase = area.toLowerCase();
      saTrackEvent(`PD_YXMMAEC_UserClickSelectionPage${area}`, {
        assembly_id: item.id,
        assembly_name: item.name || "",
        url: item.jumpUrl,
        position_number: index
      });
      uni.reportAnalytics(`c_s${lowerCase}`, {
        assembly_id: item.id,
        assembly_name: item.name || "",
        url: item.jumpUrl,
        frames_mark: index,
        position_number: index
      });
      const token = uni.getStorageSync("token") || "";
      if (item.needLogin && !token) {
        this.$refs["login-popup"].open();
        return;
      }
      if (this.$config("yxm")) {
        const subKeyList = Object.keys(SubscribeMessageConfig);
        if (subKeyList.indexOf(area) > 0) {
          const { indexArray, saEvent } = SubscribeMessageConfig[area];
          const saConfig = indexArray[index];
          if (saConfig) {
            const res = await this.weiChatSubscribeMessage(saConfig.tmplIds, item);
            const saEventData = res ? saConfig.saDoneData : saConfig.saFailData;
            const saResult = typeof saEventData === "function" ? saEventData(res) : saEventData;
            saTrackEvent(saEvent, saResult);
            return;
          }
        }
      }

      setTimeout(() => {
        this.handleJumpUrl(item);
      }, 200);
    },
    weiChatSubscribeMessage(tmplIds, item) {
      console.log(item);
      return new Promise(resolve => {
        // #ifdef MP-WEIXIN
        wx.requestSubscribeMessage({
          tmplIds,
          success: res => {
            resolve(res);
            this.submitInfo(res);
            this.handleJumpUrl(item);
          },
          fail: () => {
            resolve(null);
            this.handleJumpUrl(item);
          }
        });
        // #endif
        // #ifndef MP-WEIXIN
        this.handleJumpUrl(item);
        resolve(null);
        // #endif
      });
    },
    async handleJumpUrl({ jumpUrl, financialFlag }) {
      // #ifdef MP-WEIXIN
      if (financialFlag === 2) {
        const flag = jumpUrl === "/pages/xyqbCardBag/index";
        const [res] = await getFincialData();
        uni.navigateToMiniProgram({
          appId: "wx7c92f8bed76ea778",
          path: jumpUrl,
          extraData: {
            fromAPPID: uni.getAccountInfoSync().miniProgram.appId,
            fromPage: "pages/user/user",
            params: {
              appName: "yxm",
              faceType: flag ? "xjfq" : "",
              token: res.token || "",
              bind: res.bind,
              code: res.code || "",
              phoneNo: res.phoneNo || "",
              uuid: res.uuid || "",
              userId: res.userId || "",
              tenantId: uni.getStorageSync("tenantId"),
              channel: res.vccChannel || ""
            },
            needQuery: ["phoneNo", "token"]
          },
          envVersion: "trial"
        });
        return;
      }
      // #endif
      if (/https?:\/\//gi.test(jumpUrl)) {
        console.log(jumpUrl);
        if (jumpUrl.includes("/groupBuy/")) {
          uni.navigateTo({
            url: `/pages/groupbuy/webview?url=${encodeURIComponent(JSON.stringify(jumpUrl))}`
          });
        } else {
          uni.navigateTo({
            // url: `/pages/landing/goods?frontCategoryIds=670,652,9987,5272&labelId=&hasCoupon=&title=`
            url: `/pages/webview/webview?url=${encodeURIComponent(JSON.stringify(jumpUrl))}`
          });
        }
      } else {
        uni.navigateTo({
          url: jumpUrl
        });
      }
    },
    navToSearch() {
      saTrackEvent("PD_YXMMAEC_UserClickSelectionPageTopSearchBar");
      uni.reportAnalytics("c_selectionpagetopsearchbar", {});
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/search/index?keyWords=${this.borderTxt}`
        });
      }, 500);
    },
    submitInfo(res) {
      const acceptList = getAcceptList(res);
      submitSubcribeInfo(acceptList);
    },
    async loadData() {
      let goodsIdArr = [];
      if (this.loadingType === "noMore" || this.progress === "loading") return;
      this.loadingType = "loading";
      this.progress = "loading";
      this.pageForm.pageNo++;
      const [goodsData] = await getGoodsList(this.pageForm);
      this.progress = "finished";
      if (goodsData.goodsList) {
        goodsData.goodsList.forEach(item => {
          goodsIdArr.push(item.goods.goodsId);
        });
        saTrackEvent("PD_YXMMAEC_ASMSelectionPageContentCardExposure", {
          commodity_id: goodsIdArr.toString()
        });
      }
      if (!goodsData || !goodsData.hasNext || !goodsData.goodsList) {
        this.loadingType = "noMore";
      }
      this.goodsList = this.goodsList.concat(goodsData.goodsList || []);
    },
    delGoods(index) {
      this.goodsList.splice(index, 1);
      this.$api.msg("已减少此类信息推荐");
    },
    pageScroll: throtte(function(val) {
      if (this.$refs.goodsCard) {
        this.$refs.goodsCard.goodsMaskIdx = -1;
      }
      this.scrollTop = val.detail.scrollTop;
      this.old.scrollTop = val.detail.scrollTop;
      this.scrollPosition = val.detail.scrollLeft;
    }, 1000),
    //滚动到顶部
    toTop() {
      this.tabScrollTop = this.old.scrollTop;
      this.$nextTick(function() {
        this.tabScrollTop = 0;
      });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "./index.scss";
</style>
