<template>
  <div class="home">
    <meta name="keywords" content="电商,购物,商城" />
    <!-- 头部 -->
    <div class="head">
      <div class="content">
        <nuxt-link to="/" class="logo">
          <img class="logo-img" v-if="webConfigData.pcLogoImgText" :src="webConfigData.pcLogoImgText"/>
          <!--          <div class="name">-->
          <!--            <span class="cn">蓝海创新科技</span>-->
          <!--            <span class="en">Blue Ocean Mall</span>-->
          <!--          </div>-->
        </nuxt-link>
        <div :class="['menu',this.$store.state.locale == 'en'?'menu-en':'']">
          <nuxt-link to="/" class="item item-on">{{ $t('commonHead.home') }}</nuxt-link>
          <nuxt-link class="item" to="/list?st=0">{{ $t('commonHead.productList') }}</nuxt-link>
          <nuxt-link class="item" to="/list?st=1">{{ $t('commonHead.newProducts') }}</nuxt-link>
          <nuxt-link class="item" to="/special-discount">{{ $t('commonHead.limitedTimeOffer') }}</nuxt-link>
          <nuxt-link class="item" to="/group-buy">{{ $t('commonHead.groupDiscount') }}</nuxt-link>
          <nuxt-link class="item" to="/flash-sale">{{ $t('commonHead.spikeSpecial') }}</nuxt-link>
          <!-- <nuxt-link class="item" to="/coupons">领券中心</nuxt-link> -->
          <a class="item" href="javascript:void(0)" @click="toCoupons">{{ $t('commonHead.voucherCenter') }}</a>
        </div>
        <div class="search">
          <input
            type="text"
            class="search-input"
            :placeholder="$t('searchByStOrpN')"
          />
          <input type="submit" class="search-btn" value="搜索" />
        </div>
      </div>
    </div>
    <!-- /头部 -->
    <!-- 下滑时候的头部 -->
    <transition name="fade">
      <div v-if="showHeadScroll" class="head-scroll">
        <div class="content">
          <nuxt-link to="/" class="logo">
            <img class="logo-img" v-if="webConfigData.pcLogoImgText" :src="webConfigData.pcLogoImgText"/>
            <!--            <div class="name">-->
            <!--              <span class="cn">蓝海创新科技</span>-->
            <!--              <span class="en">Blue Ocean Mall</span>-->
            <!--            </div>-->
          </nuxt-link>
          <div :class="['menu',this.$store.state.locale == 'en'?'menu-en':'']">
            <nuxt-link class="item item-on" to="/">{{ $t('commonHead.home') }}</nuxt-link>
            <nuxt-link to="/list?st=0" class="item">{{ $t('commonHead.productList') }}</nuxt-link>
            <nuxt-link to="/list?st=1" class="item">{{ $t('commonHead.newProducts') }}</nuxt-link>
            <nuxt-link to="/special-discount" class="item">{{ $t('commonHead.limitedTimeOffer') }}</nuxt-link>
            <nuxt-link to="/group-buy" class="item">{{ $t('commonHead.groupDiscount') }}</nuxt-link>
            <nuxt-link to="/flash-sale" class="item">{{ $t('commonHead.spikeSpecial') }}</nuxt-link>
            <!-- <nuxt-link to="/coupons" class="item">领券中心</nuxt-link> -->
            <a href="javascript:void(0)" class="item" @click="toCoupons">{{ $t('commonHead.voucherCenter') }}</a>
          </div>
          <div class="right">
            <div class="search">
              <input
                type="text"
                v-model="topsearchTerms"
                @keyup.enter="topSearchProd"
                class="search-input"
                :placeholder="$t('searchByStOrpN')"
              />
              <input
                type="submit"
                @click="topSearchProd"
                class="search-btn"
                value="搜索"
              />
            </div>
            <div class="scroll-cart" @click="toCart">
              <span class="number" v-if="totalCartCount">{{ totalCartCount > 99 ? '99+' : totalCartCount }}</span>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <!-- 下滑时候的头部 -->

    <!-- 分类筛选 -->
    <CategroySidebar />
    <!-- /分类筛选 -->

    <!-- banner -->
    <div class="banner" v-if="banners.length">
      <el-carousel height="450px" style="overflow-y: hidden;">
        <el-carousel-item
          v-for="banner in banners"
          :key="banner.imgUrl"
          :style="{cursor:(banner.type !== 0 ? 'default' : 'pointer')}"
          class="banner-item"
        >
          <img
            :src="banner.imgUrl"
            style="width:100%;height:100%;"
            @click="imgToProd(banner)"
          />
        </el-carousel-item>
      </el-carousel>
    </div>
    <!-- /banner -->

    <!-- 搜索 -->
    <div :class="['home-search',banners.length?'':'up']" :style="hotSearchList.length?'':'justify-content: flex-end;'">
      <div class="hot-word" v-if="hotSearchList.length"
      >
        <div class="tit" :style=" this.$store.state.locale == 'en'? 'width:95px;':'width:75px;' ">{{$t('index.popularSearches')}}：</div>
        <div :class="['con',this.$store.state.locale == 'en'?'con-en':'']">
          <span
            :title="hot.title"
            class="item"
            v-for="(hot, index) in hotSearchList"
            :key="index"
            @click="onHistSearch(hot.content)"
            >{{ hot.title }}</span
          >
        </div>
      </div>
      <div class="search-msg" onselectstart="return false">
        <div class="search-input-box">
          <input
            type="text"
            class="search-input"
            :style=" this.$store.state.locale == 'en'? 'width:58%;':'width:63%;' "
            v-model="searchTerms"
            @keyup.enter="toSearchProdPage"
            :placeholder="$t('searchByStOrpN')"
          />
          <div class="select-search" @click="selectChoose">
            <div class="select-box">
              <span >{{ searchItem }}</span>
              <img src="~/assets/images/switch.png" class="switch-icon" alt="">
            </div>
          </div>
          <ul class="select-list" v-if="showSelectItem">
            <li class="select-item" @click="selectSearchItem(0)">{{$t('index.prod')}}</li>
            <li class="select-item" @click="selectSearchItem(1)">{{$t('index.shop')}}</li>
          </ul>
        </div>
        <input
          type="submit"
          class="search-btn"
          :value="$t('index.search')"
          @click="toSearchProdPage"
          :style="$t('language')=='en'?'':'letter-spacing: 2px;'"
        />
      </div>
      <div class="cart-btn" @click="toCart">
        {{$t('index.shoppingCart')}}
        <span class="number" v-if="totalCartCount">{{ totalCartCount > 99 ? '99+' : totalCartCount }}</span>
      </div>
    </div>
    <!-- /搜索 -->

    <div class="content">
      <!-- 快捷入口 -->
      <div class="shortcut" v-if="false">
        <div class="item item01">
          <div class="text">
            <div class="cn">{{$t('index.newProduct')}}</div>
          </div>
          <div class="img">
            <img src="~/assets/img/short-01.png" alt />
          </div>
        </div>
        <div class="item item02">
          <div class="text">
            <div class="cn">{{$t('index.limitedTimeOffer')}}</div>
          </div>
          <div class="img">
            <img src="~/assets/img/short-02.png" alt />
          </div>
        </div>
        <div class="item item03">
          <div class="text">
            <div class="cn">{{$t('index.groupDiscount')}}</div>
          </div>
          <div class="img">
            <img src="~/assets/img/short-03.png" alt />
          </div>
        </div>
        <div class="item item04">
          <div class="text">
            <div class="cn">{{$t('index.specialSale')}}</div>
          </div>
          <div class="img">
            <img src="~/assets/img/short-04.png" alt />
          </div>
        </div>
        <div class="item item05">
          <div class="text">
            <div class="cn">{{$t('index.couponsCenter')}}</div>
          </div>
          <div class="img">
            <img src="~/assets/img/short-05.png" alt />
          </div>
        </div>
      </div>

      <!-- 广告 -->
      <nuxt-link to="/flash-sale" class="adv" v-if="snapUpList.length">
        <img src="~/assets/img/adv1.jpg" alt />
      </nuxt-link>

      <!-- 秒杀专区 -->
      <div class="goods-list flash-sale" v-if="snapUpList.length">
        <div class="list-tit">
          <div class="text">
            <span class="tit">{{$t('index.secondKillZone')}}</span>
            <span class="description">{{$t('index.selectedProductsLimited')}}</span>
          </div>
          <nuxt-link to="/flash-sale" class="view-more">
            {{$t('index.seeMore')}}
            <span class="arrow">></span>
          </nuxt-link>
        </div>
        <ProdItem :pale-list="snapUpList" :list-type="2" />
      </div>

      <!-- 广告 -->
      <nuxt-link to="/group-buy" class="adv" v-if="composeGroup.length">
        <img src="~/assets/img/adv2.jpg" alt />
      </nuxt-link>

      <!-- 优惠团购 -->
      <div class="goods-list group-list" v-if="composeGroup.length">
        <div class="list-tit">
          <div class="text">
            <span class="tit">{{$t('index.groupDiscount')}}</span>
            <span class="description">{{$t('index.recommendGoodThings')}}</span>
          </div>
          <nuxt-link to="/group-buy" class="view-more">
            {{$t('index.seeMore')}}
            <span class="arrow">></span>
          </nuxt-link>
        </div>
        <ProdItem :pale-list="composeGroup" :list-type="1" />
      </div>

      <!-- 广告 -->
      <nuxt-link to="/list" class="adv" v-if="hotSalesList.records[0].products.length">
        <img src="~/assets/img/adv3.jpg" alt />
      </nuxt-link>

      <!-- 商城热销 -->
      <div class="goods-list group-list" v-if="hotSalesList.records[0].products.length">
        <div class="list-tit">
          <div class="text">
            <span class="tit">{{$t('index.hotSale')}}</span>
            <span class="description">{{$t('index.wordGoodiesInfiniteRepurchase')}}</span>
          </div>
          <nuxt-link to="/list?st=0" class="view-more">
            {{$t('index.seeMore')}}
            <span class="arrow">></span>
          </nuxt-link>
        </div>
        <ProdItem :pale-list="hotSalesList.records[0].products" :list-type="0"/>
      </div>

      <!-- 广告 -->
      <nuxt-link v-if="hotShopList.length" to="/shopList?type=1" class="adv">
        <img src="~/assets/img/adv4.jpg" alt />
      </nuxt-link>

      <!-- 优选好店 -->
      <div v-if="hotShopList.length" class="goods-list shop-list">
        <div class="list-tit">
          <div class="text">
            <span class="tit">{{$t('index.preferredStores')}}</span>
            <span class="description">{{$t('index.recommendGoodThingsTogetherWithTheGroup')}}</span>
          </div>
          <nuxt-link to="/shopList?type=1" class="view-more">
            {{$t('index.seeMore')}}
            <span class="arrow">></span>
          </nuxt-link>
        </div>
        <ShopItem :shop-list="hotShopList" />
      </div>
      <!-- /优选好店 -->
    </div>
    <!-- 登录弹窗组件 -->
    <LoginPopup v-if="showLogin" v-on:hideLoginPop="hideLoginPop" />
    <!-- /登录弹窗组件 -->
  </div>
</template>

<script>
import Cookie from 'js-cookie'
import LoginPopup from '~/components/login-popup'
import ProdItem from '~/components/prod-item'
import ShopItem from '~/components/shop-item'
import CategroySidebar from '~/components/categroy-sidebar'
import util from '~/plugins/util'
export default {
  layout: 'home',
  components: {
    ProdItem,
    ShopItem,
    CategroySidebar,
    LoginPopup
  },
  //在页面加载之前先加载数据
  async asyncData ({ app, query }) {
    let [requestWebConfigData, requestSnapUp, requestTeamBuy, requestHotSales,requestHotShops] = await Promise.all([
      // 网站配置信息
      app.$axios.get('/webConfig/getPcWebConfig'),
      // 秒杀商品
      app.$axios.get('/search/page', {
        params: {
          current: 1,
          size: 4,
          prodType: 2,
          isActive: 1 // 过滤掉活动商品
        }
      }),
      // 团购商品
      app.$axios.get('/search/page', {
        params: {
          current: 1,
          size: 4,
          prodType: 1,
          isActive: 1 // 过滤掉活动商品
        }
      }),
      // 热销商品
      app.$axios.get('/search/page', {
        params: {
          current: 1,
          size: 12,
          sort: 2,
          orderBy: 1,
          isActive: 1 // 过滤掉活动商品
        }
      }),
      // 好店
      app.$axios.get('/shop/hotShops'),
    ])
    return {
      snapUpList: requestSnapUp.data.records[0].products,  // 秒杀
      composeGroup: requestTeamBuy.data.records[0].products,  // 团购
      hotSalesList: requestHotSales.data,  //热销
      hotShopList: requestHotShops.data,  //好店
      webConfigData: requestWebConfigData.data //网站配置信息
    }
  },

  data () {
    return {
      showLogin: false,
      showHeadScroll: false,  //头部显隐
      banners: [],  //轮播图
      hotSearchList: [],  //热搜
      snapUpList: [],  //秒杀专场
      composeGroup: [],  //优惠团购
      hotSalesList: [],  //商城热销
      current: 1,
      size: 10,
      sort: 1,
      orderBy: 1,
      showSelectItem: false, //搜索下拉选择框显隐
      searchItem: this.$t('index.prod'),  //搜索下拉框选择店铺或商品
      searchTerms: '',  //搜索词
      topsearchTerms: '',  //上滑头部搜索词
      hotShopList: [],  //优选好店
      searchType: 0,  //搜索类型 0商品 1店铺
      totalCartCount: 0, // 购物车总数量
      webConfigData: {},  //网站配置信息
      language: this.$store.state.locale
    }
  },
  mounted () {
    // 缓存到本地
    localStorage.setItem('webConfig', JSON.stringify(this.webConfigData))
    util.changeFavicon()
    // 设置网页标题文本和图标
    document.title = this.webConfigData.pcTitleContentCn || ''
    // 监听页面滚动
    window.addEventListener('scroll', this.scrollToTop);
    //轮播图
    this.getIndexBanner()
    //热搜
    this.getHotSearch(this.searchType)
    //优选好店
    this.getHotShopsHead()
    // 获取购物车数量
    this.getCartCount()
  },
  watch:{
  },
  methods: {

     /**
     * 获取购物车商品总数
     */
    getCartCount () {
      if (Cookie.get('token')) {
          this.$axios.get('/p/shopCart/prodCount').then(({ data }) => {
          this.totalCartCount = data
          this.$store.commit('cartNumber/changeCartNumber', data)
        })
      }
    },
    /**
     * 页面滚动事件
     */
    scrollToTop () {
      let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      this.showHeadScroll = scrollTop > 90 ? true : false;
    },
     /**
     * 领券中心
     */
    toCoupons () {
      // if (Cookie.get('token')) {
      //   console.log('token1:',Cookie.get('token'))
      //   this.$router.push({ path: '/coupons' })
      // } else {
      //   console.log('token2:',Cookie.get('token'))
      //   this.showLogin = true
      // }
      this.$router.push({ path: '/coupons' })
    },
    /**
     * 隐藏登录弹窗
     */
    hideLoginPop () {
      this.showLogin = false
    },
    /**
     * 轮播图
     */
    getIndexBanner () {
      this.$axios.get('/indexImgs/0', {
        params: {
          imgType: 1
        }
      }).then(({ data }) => { this.banners = data || [] })
    },
    /**
     * 热搜词
     */
    getHotSearch () {
      let url = this.searchType ? '/shop/hotShops' : '/search/hotSearch'
      this.$axios.get(url, {
        params: {
          number: 4,
          sort: 1,
        }
      }).then(({ data }) => {
        if(this.searchType){
          this.hotSearchList = []
          for(let i=0;i<(data.length > 6 ? 6 : data.length);i++){
            let shoInfo = {
              title : data[i].shopName,
              hotSearchId : data[i].shopId,
              content: data[i].shopName
            }
            this.hotSearchList.push(shoInfo)
          }
        }else {
          this.hotSearchList = data
        }
      })

    },
    /** 搜索框选择 */
    selectChoose () {
      this.showSelectItem = !this.showSelectItem
    },
    /** 点击选择 店铺 || 商品 */
    selectSearchItem (sts) {
      if (sts === 0) {
        this.searchItem = this.$t('index.prod')
        this.showSelectItem = false
        this.searchType = 0 //商品

      } else if (sts === 1) {
        this.searchItem = this.$t('index.shop')
        this.showSelectItem = false
        this.searchType = 1 //店铺
      }

      this.getHotSearch()
    },

    /**
     * 搜索
     */
    toSearchProdPage () {
      var searchType = this.searchType
      var searchTerms = this.searchTerms.trim() //去除字符串的头尾空格
      if (searchType == 0) {
        if (!searchTerms) {
          this.$message({
            message: this.$t('commonHead.productNameCannotBeEmpty'),
            type: 'error',
            duration: 1000
          })
          return
        }
        // 跳转到商品列表页
        this.$router.push({ path: '/list?pn=' + searchTerms })
      } else if (searchType == 1) {
        if (!searchTerms) {
          this.$message({
            message: this.$t('commonHead.storeNameCannotBeEmpty'),
            type: 'error',
            duration: 1000
          })
          return
        }
        // 跳转到店铺列表页
        this.$router.push({ path: '/shopList?shopName=' + searchTerms })
      }
    },
    topSearchProd () {
      var searchTerms = this.topsearchTerms.trim() //去除字符串的头尾空格
      if (!searchTerms) {
        this.$message({
          message: this.$t('commonHead.productNameCannotBeEmpty'),
          type: 'error',
          duration: 1000
        })
        return
      }
      // 跳转到商品列表页
      this.$router.push({ path: '/list?pn=' + searchTerms })
    },
    /**
     * 点击热搜词搜索商品
     */
    onHistSearch (name) {
      this.searchTerms = name
      // this.searchType = 1
      this.toSearchProdPage();
    },

    /**
     * 商城热销
     */
    // getHotSalesProds () {
    //   this.$axios.get('/search/searchProdPage', {
    //     params: {
    //       current: this.current,
    //       size: 12,
    //       sort: 1,
    //       orderBy: 1
    //     }
    //   }).then(({ data }) => {
    //     this.hotSalesList = data.records
    //   })
    // },
    /**
     * 优选好店
     */
    getHotShopsHead () {
      this.$axios.get('/shop/hotShops').then(({ data }) => { this.hotShopList = data })
    },


    /**
     * 跳转购物车页面
     */
    toCart () {
      this.$router.push('/cart')
    },
    /**
     * 轮播图跳转到商品
     */
    imgToProd (banner) {
      if (banner.type !==0 ) {
        return
      }
      const prodId = banner.relation
      this.$axios.get('/prod/isStatus', {
        params: {
          prodId: prodId
        }
      }).then(({ data }) => {
        if (data) {
          this.$router.push({ name: 'detail-prodId', params: {prodId:prodId, bannerEnter: '1' } })
        }
      })
    }
  },
  destroyed () {
    // 页面销毁时移除监听
    window.removeEventListener('scroll', this.scrollToTop);
  }
}
</script>

<style scoped src='~/assets/css/home.css'>
</style>
