<template>
  <div class="home-page" v-loading="isShowLoading" ondragstart="return false" >
    <template v-if="isShowSwiper">
      <Swiper
        direction="vertical"
        class="home-swiper"
        :resistanceRatio="0"
        :modules="swiperModules"
        @slideChange="onOuterSlideChange"
        @swiper="onOuterSwiper"
        v-if="widgetList[0]?.length"
      >
        <template v-for="(widgetItem, index) in widgetList" :key="index">
          <swiper-slide v-if="widgetItem.length">
            <Swiper
              observer: true
              class="second-swiper"
              :nested="true"
              direction="vertical"
              slidesPerView="auto"
              :resistanceRatio="0"
              :modules="swiperModules"
              :freeMode="{
                enabled: true
              }"
              @swiper="onInnerSwiper"
              @sliderMove="onInnerSliderMove"
              @touchStart="onInnerSliderStart"
              @transitionEnd="onTransitionEnd"
            >
              <swiper-slide class="swiper-container" :style="{
                  'padding-top': cptDistDistanceFromTop + 'px'
                }" >
                <!--
                Because the 'swiper' will not detect changes in the internal height of the component,
                So it may cause some components to fail to load
                The solution is to load an image display: none, and dynamically control the display and hiding of this image.
                Let the 'swiper' dynamically monitor the internal height to prevent the effect of the component not being able to load
              -->
                <img
                  v-if="isUpdateSwiperHeight"
                  style="display: none"
                  :src="`${IMAGE_URL}assets/image/icons/rightArrowGrey.png`"
                  alt=""
                />
                <component
                  :style="{
                    ...(componentIndex + 1 === widgetItem.length && {paddingBottom:tabbarHeight + 'px'})
                  }"
                  v-for="(componentItem, componentIndex) in widgetItem"
                  :key="componentItem.uuid"
                  :is="filterComponent(componentItem.categoryType)"
                  :properties="componentItem"
                  @updateSlideHeight="onUpdateSlideHeight"
                ></component>
              </swiper-slide>
            </Swiper>
          </swiper-slide>
        </template>
      </Swiper>
    </template>
    <template v-else>
      <div class="not-PIPL-gateway">
        <div class="not-PIPL-gateway-logo">
          <img :src="badgeLogoUrl" alt="" />
        </div>
        <div class="not-PIPL-gateway-search">
          <div class="gateway-search-box" @click="router.push('/search')">
            <img :src="searchIconUrl" alt="" />
            <span>搜索</span>
          </div>
        </div>
        <recommend-list
          :title="$t('modules.detailPage.BEST_SELLING_ITEM_RECOMMENDATION')"
        />
      </div>
    </template>
    <float-login-prompt :isShow="isShowFloatLoginPrompt" showPageType="gateway" @handleLogin="handleLogin"/>
    <popup-widget :widgetList="popupWidgetList"></popup-widget>
    <gateway-floating-window
      :floatingData="floatingData"
      :isShowBackTop="isShowBackTop"
      @resettingScrollTop="handleResettingScrollTop"
    />
  </div>
</template>
<script setup>
import { useWindowSize } from '@vueuse/core';
import { useRouter } from 'vue-router';
import { useStore } from 'vuex';
import { isAppEnv } from '@/utils/device';
import { Bridge } from '@/utils/bridge';
import { nextTick, onMounted, ref, shallowRef, onUnmounted, computed } from 'vue';
import 'swiper/css/scrollbar';
import constants, { marketplace } from '@/constants';
import {
  getGatewayModulesInfo,
  getWidgetPopup,
  getFloatingWindow
} from '@/models/api/landingPageApi';
import { useLess } from '@/models/hooks';
import { Scrollbar, FreeMode } from 'swiper';
import { Swiper, SwiperSlide } from 'swiper/vue';
import gatewayComponent from './gatewayComponent';
import {
  isLoginAuthenticated,
  isShowPIPLConfirmAlertView,
  handleStartLogin
} from '@/utils/common';
import recommendList from '@/components/RecommendedAsins.vue';
import FloatLoginPrompt from '@/components/FloatLoginPrompt.vue';
import GatewayFloatingWindow from '@/components/GatewayFloatingWindow.vue';
import { LANDING_PAGE_PARAMS_PAGE_TYPE } from '@/utils/landingPageCommon.js';
import { LAYOUT_TYPE } from '@/components/landingPageComponents/common.js';
import PopupWidget from '@/components/landingPageComponents/popupWidget/PopupWidget.vue';
import { SET_AGENT_DATA } from '@/store/mutations.types';

const {
  ENCRYPTED_MARKETPLACE_ID,
  ENCRYPTED_MARKETPLACE_ID_LOCALE_MAP,
  MARKET_PLACE_ID,
  IMAGE_URL,
  GATEWAY_MODULE,
  NEW_IMAGE_URL
} = constants;
useLess('views/gateway/Gateway.less');
const router = useRouter();
const store = useStore();
const isShowSwiper = ref(false);
const isShowLoading = ref(true);
const swiperModules = [Scrollbar, FreeMode];
// Full screen component type
const FULL_SCREEN_COMPONENTS = ['bestseller'];
// If the type of infinite scrolling component is infinite scrolling, place this component at the end
const WATERFALL_COMPONENTS = ['dealWidget', 'recommendedAsin'];
const widgetList = ref([]);
const popupWidgetList = ref([]); // Pop up advertising data
const isUpdateSwiperHeight = ref(true);
const badgeLogoUrl = `${NEW_IMAGE_URL}04_BadgeLogo/Logo_Settings3x.png`;
const searchIconUrl = `${IMAGE_URL}assets/svg/dNavSearch.svg`;
const floatingData = shallowRef({});
const innerSwiperRef = ref(null);
const activeOuterSlideIndex = ref(0);
const isShowBackTop = ref(false);
// 当前的选中的内部slide
const activeSlideRef = ref(null);
const isShowFloatLoginPrompt = ref(false);
const windowClientHeight = ref(0);
const cptDistDistanceFromTop = computed(
  () => store.state.navigator.agentData?.top ?? 0
);
const tabbarHeight = computed(() => store.state.common.tabbarHeight ?? 0);
const handleLogin = async () => {
  if (await isShowPIPLConfirmAlertView()) return;
  handleStartLogin();
};

const onInnerSliderStart = swiper => {
  activeSlideRef.value = swiper;
  swiper.setTranslate(swiper.translate); // 设定偏移量
};

const onInnerSliderMove = swiper => {
  if((swiper.translate * -1) > windowClientHeight.value) {
    if(!isShowBackTop.value) isShowBackTop.value = true;
  }else{
    if(isShowBackTop.value) isShowBackTop.value = false;
  }
};

const onOuterSlideChange = el => {
  activeOuterSlideIndex.value = el.activeIndex;
};

const onInnerSwiper = el => {
  innerSwiperRef.value = el;
};
const handleResettingScrollTop = () => {
  isShowBackTop.value = false;
  activeSlideRef.value.setTranslate(0);
};
const onUpdateSlideHeight = () => {
  isUpdateSwiperHeight.value = false;
  nextTick(() => {
    isUpdateSwiperHeight.value = true;
  });
};
const combinedShelfDataProcessing = data => {
  // If it is infinite scrolling, place this component at the back
  const componentIndex = data.findIndex(component => {
    if (
      WATERFALL_COMPONENTS.some(
        infiniteScrollingComponent =>
          infiniteScrollingComponent === component.categoryType
      ) &&
      component.displayQuantity === 0 &&
      component.showType !== LAYOUT_TYPE.TRANSVERSE
    ) {
      return true;
    }
    return false;
  });
  if (componentIndex >= 0) {
    data.push(data.splice(componentIndex, 1)[0]);
  }
  const list = [[]];
  // Distinguish full screen components
  data.forEach(categoryItem => {
    // Find full screen components
    if (
      FULL_SCREEN_COMPONENTS.some(item => item === categoryItem.categoryType)
    ) {
      list.push([categoryItem]);
      // After meeting the conditions, create a new array and add subsequent items to the new array
      list.push([]);
    } else {
      list[list.length - 1].push(categoryItem);
    }
  });
  list.forEach(item => {
    if (item.length) {
      widgetList.value.push(item);
    }
  });
};
const filterComponent = categoryType => {
  return gatewayComponent.filter(
    componentItem => componentItem.type === categoryType
  )?.[0]?.component;
};
// Combined shelf data
const combinedShelfData = async () => {
 const params = {
    marketplaceId: marketplace,
    language: ENCRYPTED_MARKETPLACE_ID_LOCALE_MAP[marketplace],
    pageType: LANDING_PAGE_PARAMS_PAGE_TYPE.HOME_PAGE
  };
  const getGatewayModulesInfoRes = await getGatewayModulesInfo(params)['catch'](
    () => {}
  );
  if (getGatewayModulesInfoRes?.data?.code === 200) {
    combinedShelfDataProcessing(getGatewayModulesInfoRes.data.widgets);
  } else {
    combinedShelfDataProcessing(constants.GATEWAY_MODULE_MOCK.WIDGETS);
  }
};
const getHeader = async () => {
  let token = '';
  if (isAppEnv()) {
    if (await isLoginAuthenticated(false)) {
      const { accessToken: tokenApp } = await Bridge.callFnVal(
        'getAccessToken',
        {}
      );
      token = tokenApp;
    }
  } else {
    // This is for development process
    token = sessionStorage.getItem('token') || '';
  }
  return { token };
};
const getWidgetPopupInfo = async () => {
  const params = {
    marketplaceId: marketplace,
    language: ENCRYPTED_MARKETPLACE_ID_LOCALE_MAP[ENCRYPTED_MARKETPLACE_ID],
    paramType: 0,
    pageType: LANDING_PAGE_PARAMS_PAGE_TYPE.GATEWAY
  };
  const { data } = await getWidgetPopup(params, await getHeader());
  if (data.code === 200) {
    popupWidgetList.value = data.data?.list || [];
    Bridge.callFn('saveDataToMemoryCache', {
      key: 'isGatewayWidgetPopupCalled',
      value: true
    });
  }
};

const getGatewayFloatingWindow = async () => {
  const params = {
    marketplaceId: marketplace,
    language: ENCRYPTED_MARKETPLACE_ID_LOCALE_MAP[ENCRYPTED_MARKETPLACE_ID],
    paramType: 0,
    pageType: LANDING_PAGE_PARAMS_PAGE_TYPE.GATEWAY
  };
  const { data } = await getFloatingWindow(params, await getHeader());
  if (data.code === 200) {
    floatingData.value = data.data;
  }
};

const getWindowSize = async () => {
  await nextTick();
  const { height } = useWindowSize();
  windowClientHeight.value = height.value;
};

onMounted(async () => {
  store.commit(`navigator/${SET_AGENT_DATA}`, { top: 0 });
  isShowFloatLoginPrompt.value = !(await isLoginAuthenticated(false));
  isShowLoading.value = true;
  isShowSwiper.value = !(await isShowPIPLConfirmAlertView(false));
  isShowLoading.value = false;
  getWindowSize();
  if (isShowSwiper.value) {
    Bridge.callFn(
      'getDataFromMemoryCache',
        {
          key: 'isGatewayWidgetPopupCalled'
        },
        res => {
          console.log("isGatewayWidgetPopupCalled", res);
          if (JSON.stringify(res.value) === '{}') {
            getWidgetPopupInfo();
          }
        }
    );
    getGatewayFloatingWindow();
    if (await isLoginAuthenticated(false)) {
      combinedShelfData();
    } else {
      // Product requirement: Unregistered gateway data set to false data
      combinedShelfDataProcessing(constants.GATEWAY_MODULE_MOCK.NOT_LOGGED_IN_DATA);
    }
  }
});

onUnmounted(() => {
  store.commit(`navigator/${SET_AGENT_DATA}`);
});
</script>
解决滑动抖动