<template>
  <div class="home">
    <div v-if="!showMainSearch">
      <ul class="associate-list" v-show="associate.show" @click="associate.show = false">
        <li @click.stop="onAssociateClick(similar)" v-for="similar in similarKeywords.result">
          <i class="icon-sousuo iconfont"></i>
          <span>{{Getsimilar(similar)}}</span>
          <!--<span v-if="ChooseTop === 'component'">{{similar.code}}</span>-->
          <!--<span v-else-if="ChooseTop === 'product'">{{similar}}</span>-->
          <!--<span v-else-if="ChooseTop === 'store'">{{similar}}</span>-->
          <!--<span v-else-if="ChooseTop === 'brand'">{{similar.nameEn}}</span>-->
        </li>
        <li @click.stop="onSearch(keyword)">查找“{{baseUtils.filterStringEllipsis(keyword, 30)}}”</li>
      </ul>
      <div class="header">
        <div class="search-content" @touchmove="preventTouchMove($event)">
          <div class="main-search-header-controll clearfix">
            <div style="display: flex;align-items: center;justify-content: space-between;width:100%;">
              <div :class="ChooseTop === 'component' ? 'active' : ''" @click="setChangelistHander('component')"><a>型号</a></div>
              <div :class="ChooseTop === 'kind' ? 'active' : ''" @click="setChangelistHander('kind')"><a>物料名称</a></div>
              <div :class="ChooseTop === 'store' ? 'active' : ''" @click="setChangelistHander('store')"><a>卖家</a></div>
              <div :class="ChooseTop === 'brand' ? 'active' : ''" @click="setChangelistHander('brand')"><a>品牌</a></div>
            </div>
          </div>
          <input type="text" v-model="keyword" id="search-box" @keyup.13="onSearch()" :placeholder="placeholder">
          <span @click="onSearch()" style="top: 0">
          <i class="iconfont icon-sousuo"></i>
        </span>
          <img src="/images/mobile/@2x/applyPurchase/home/phone.png" alt="" @click="showStoreInfo = true">
        </div>
        <div v-swiper:mySwiper="swiperOption">
          <div class="swiper-wrapper">
            <!--<div class="swiper-slide">
              <img class="home-bg" src="/images/mobile/@2x/applyPurchase/home/app-banner_03.jpg" alt="">
            </div>-->
            <div class="swiper-slide">
              <img class="home-bg" src="/images/mobile/@2x/applyPurchase/home/app-banner_01.jpg" alt="">
            </div>
            <div class="swiper-slide">
              <img class="home-bg" src="/images/mobile/@2x/applyPurchase/home/app-banner_02.jpg" alt="">
            </div>
          </div>
          <div class="swiper-pagination swiper-pagination-bullets"></div>
        </div>
      </div>
      <ul class="link-list">
        <li>
          <nuxt-link to="/mobile/supplier">
            <img src="/images/mobile/@2x/home/supplier.png" alt="">
            <span>供应商</span>
          </nuxt-link>
        </li>
        <li>
          <a @click="goOpportunity">
            <img src="/images/mobile/@2x/home/seek.png" alt="">
            <span>公司商机</span>
          </a>
        </li>
        <li>
          <nuxt-link to="/mobile/shop">
            <img src="/images/mobile/@2x/home/store.png" alt="">
            <span>店铺列表</span>
            <!-- <i></i>-->
          </nuxt-link>
        </li>
        <li>
          <nuxt-link to="/mobile/brand/brandCenter/A">
            <img src="/images/mobile/@2x/home/brand.png" alt="">
            <span>品牌墙</span>
          </nuxt-link>
        </li>
        <li>
          <a @click="goOpenStoreApply">
            <img src="/images/mobile/@2x/home/store-into.png" alt="">
            <span>商家入驻</span>
          </a>
        </li>
      </ul>

      <div class="display_card">
        <statistics-mobile/>
      </div>

      <div class="seek-title">
        <img src="/images/mobile/@2x/applyPurchase/home/seek-title.png" alt="">
        <span>最新求购信息</span>
        <nuxt-link to="/mobile/applyPurchase/list">查看更多 <img src="/images/mobile/@2x/applyPurchase/home/arrow-right.png" alt=""></nuxt-link>
      </div>
      <seek-list :purchaseManList="purchaseManListData" :isDataChange="isDataChange"></seek-list>
    </div>
    <div class="mobile-modal" v-if="showStoreInfo" @touchmove="preventTouchMove($event)">
      <div class="mobile-modal-box">
        <div class="mobile-modal-header">联系方式<i @click="showStoreInfo = false" class="icon-guanbi iconfont"></i></div>
        <div class="mobile-modal-content">
          <div>商家地址：深圳市南山区英唐大厦1楼</div>
          <!-- <div class="content-line link-url">在线咨询</div>-->
          <div>致电：<a href="tel:4008301818" target="_blank" class="content-line">4008301818</a></div>
          <div>邮件：<a href="mailto:yrsc@usoftchina.com" target="_blank" class="content-line">yrsc@usoftchina.com</a></div>
        </div>
      </div>
    </div>
    <main-search v-if="showMainSearch" @cancelSearchAction="onCancelSearch"></main-search>
    <remind-box :title="remindText" :timeoutCount="timeoutCount"></remind-box>
    <login-box @onLoginBoxClose="showLoginBox = false" v-if="showLoginBox" :url="url"></login-box>
    <pull-up :searchMore="fetching" :allPage="allPage" :page="page" @pullUpAction="getMoreSearch" :isValid="isValid"></pull-up>
  </div>
</template>
<script>
  import SeekList from './applyPurchase/SeekList.vue'
  import MainSearch from '~/components/mobile/search/MainSearch.vue'
  import { RemindBox, LoginBox, PullUp, StatisticsMobile } from '~components/mobile/common'
  export default {
    data () {
      return {
        showStoreInfo: false,
        showMainSearch: false,
        swiperOption: {
          autoplay: 3000,
          initialSlide: 0,
          pagination: '.swiper-pagination',
          // 解决点击分页器后图片就不能轮播的问题
          autoplayDisableOnInteraction: false,
          paginationClickable: true,
          mousewheelControl: false,
          effect: 'fade',
          lazyLoading: true,
          loop: true,
          prevButton: '.swiper-button-prev',
          nextButton: '.swiper-button-next'
        },
        remindText: '',
        timeoutCount: 0,
        showLoginBox: false,
        isSearchSearchingMore: false,
        page: 1,
        size: 5,
        purchaseManListData: [],
        isChange: false,
        isDataChange: false,
        url: '',
        isValid: true,
        ChooseTop: 'component',
        keyword: '',
        associate: {
          show: false
        }
      }
    },
    components: {
      SeekList,
      MainSearch,
      RemindBox,
      LoginBox,
      PullUp,
      StatisticsMobile
    },
    watch: {
      '$store.state.applyPurchase.purchaseManList.purchaseHomeList.data': {
        handler: function (val) {
          if (val.length === 0) {
            // console.log(111)
            this.$store.dispatch('applyPurchase/loadMobileHomeList', {
              pageNumber: 1,
              pageSize: 5,
              enUU: this.$store.state.option.user.data.enterprise ? this.$store.state.option.user.data.enterprise.uu : null
            })
          } else if (this.isChange) {
            this.purchaseManListData = []
            this.page = 1
            this.isChange = false
            this.isDataChange = false
          } else {
            // console.log(val.content)
            this.purchaseManListData = this.purchaseManListData.concat(val.content)
            this.isSearchSearchingMore = false
            this.isDataChange = true
          }
        },
        immediate: true
      },
      'keyword': function (val, oldVal) {
        let keywords = this.similarKeywords.data
        if (!keywords || !keywords.length) {
          this.onChange()
        }
      }
//      $route: {
//        handler: function (val) {
//          window.removeEventListener('scroll', this.scroll)
//        }
//      }
    },
    computed: {
      similarKeywords () {
        return this.$store.state.search.keywords.data
      },
      placeholder() {
        if (this.ChooseTop === 'component') {
          return '请输入您要搜索的型号'
        } else if (this.ChooseTop === 'kind') {
          return '请输入您要搜索的物料名称'
        } else if (this.ChooseTop === 'store') {
          return '请输入您要搜索的卖家名称'
        } else if (this.ChooseTop === 'brand') {
          return '请输入您要搜索的品牌'
        }
      },
      purchaseManList () {
        return this.$store.state.applyPurchase.purchaseManList.purchaseHomeList.data
      },
      allPage () {
        return Math.floor(this.purchaseManList.totalElements / this.purchaseManList.size) + Math.floor(this.purchaseManList.totalElements % this.purchaseManList.size > 0 ? 1 : 0)
      },
      fetching () {
        return this.$store.state.applyPurchase.purchaseManList.purchaseHomeList.fetching
      }
    },
    methods: {
      onSearch (item) {
        if (item) {
          this.keyword = item
        }
        if (this.keyword) {
          this.$router.push(`/mobile/search/newkeycode?choosetype=${this.ChooseTop}&keyword=${encodeURIComponent(this.keyword)}`)
        }
      },
      onChange () {
        if (!this.keyword) {
          this.associate.show = false
          this.$store.dispatch('resetSearchKeywords')
        } else {
          this.searchKeywords()
        }
        if (this.click_flag) {
          this.associate.show = false
        }
      },
      setChangelistHander(str) {
        this.ChooseTop = str
        if (!this.keyword) return
        this.$store.dispatch('searchKeywords', {keyword: this.keyword, type: this.ChooseTop})
        this.associate.show = true
      },
      searchKeywords () {
        this.$store.dispatch('searchKeywords', {keyword: this.keyword, type: this.ChooseTop})
        this.associate.show = true
      },
      onAssociateClick (word) {
        if (this.ChooseTop === 'component') {
          this.keyword = word.code
        } else if (this.ChooseTop === 'kind') {
          this.keyword = word.nameCn
        } else if (this.ChooseTop === 'store') {
          this.keyword = word.name
        } else if (this.ChooseTop === 'brand') {
          this.keyword = word.nameEn
        }
        this.onSearch()
      },
      Getsimilar(word) {
        if (this.ChooseTop === 'component') {
          return word.code
        } else if (this.ChooseTop === 'kind') {
          return word.nameCn
        } else if (this.ChooseTop === 'store') {
          return word.name
        } else if (this.ChooseTop === 'brand') {
          return word.nameEn
        }
      },
//      scroll: function () {
//         let scrolled = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop
//         if (Math.ceil(scrolled + window.screen.availHeight) >= document.body.scrollHeight && !this.isSearchSearchingMore && this.page < this.allPage) {
//           this.getMoreSearch()
//         }
//      },
      onHomeSearchClick () {
        this.isValid = false
        this.showMainSearch = true
        this.$store.dispatch('searchData/getSearchHistory')
      },
      onCancelSearch: function () {
        this.isValid = true
        this.showMainSearch = false
      },
      goOpportunity () {
        if (this.user.logged) {
          if (this.user.data.enterprise.uu) {
            this.$router.push('/mobile/center/vendor/seek?seekType=wait')
          } else if (this.user.data.enterprise.isVendor !== 313) {
            this.onRemind('抱歉，您暂未开通卖家中心，可前往PC端开通')
          }
        } else {
          this.url = '/mobile/center/vendor/seek?seekType=wait'
          this.showLoginBox = true
        }
      },
      onRemind: function (str) {
        this.remindText = str
        this.timeoutCount ++
      },
      reloadData: function () {
        this.$store.dispatch('applyPurchase/loadMobileHomeList', {pageNumber: this.page, pageSize: this.size, sorting: {'releaseDate': 'DESC'}, enUU: this.$store.state.option.user.data.enterprise ? this.$store.state.option.user.data.enterprise.uu : null, isLogin: this.user.logged ? '1' : '0'})
      },
      getMoreSearch: function () {
        this.page++
        this.isSearchSearchingMore = true
        this.reloadData()
      },
      // 商家入驻
      goOpenStoreApply: function () {
        if (this.user.logged) {
          if (this.user.data.enterprise.uu) {
            if (this.user.data.enterprise.isVendor === 313) {
              this.$http.get('/basic/vendor/transactionInfo').then(response => {
                if (response.data.isOpenStore) {
                  window.location.href = '/mobile/user/storeinfo'
                } else {
                  this.onRemind('您的申请已提交，请耐心等待工作人员审核（2-3个工作日）')
                }
              }, err => {
                this.$message.error('获取开店信息失败')
                console.log(err)
              })
            } else {
              this.$router.push('/mobile/store')
            }
          } else {
            this.$router.push('/mobile/store/register')
          }
        } else {
          this.login()
        }
      }
    },
    mounted() {
      this.$nextTick(() => {
        let ua = this.$store.state.option.userAgent.toLowerCase()
        let info = localStorage.getItem('USOFTMALLWECHATINFO')
        // 如果本地有缓存 则证明存在openid
        info = info && JSON.parse(info)
        if (ua.match(/micromessenger/i) && ua.match(/micromessenger/i)[0] === 'micromessenger' && !this.$route.query.code && !info) {
            window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxb3274b676737a319&redirect_uri=https://mall.usoftchina.com&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
          } else if (ua.match(/micromessenger/i) && ua.match(/micromessenger/i)[0] === 'micromessenger') {
            if (!info) {
              this.$store.dispatch('GerWechatInfo', {code: this.$route.query.code})
            }
        }
      })
    }
  }
</script>
<style lang="scss">
  @mixin overFlowHidden {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
  @mixin lineHeight($value) {
    height: $value;
    line-height: $value;
  }
  @import '~assets/scss/mobileCommon';
  .swiper-slide1 {
    background: url('/images/mobile/@2x/applyPurchase/home/app-banner_01.jpg');
    background-repeat: no-repeat;
    background-size: cover;
  }
  .home {
    padding-bottom: 1rem;
    background: #f3f3f7;
    .search-content {
      padding: 0.19rem 0 0.15rem;
      position: absolute;
      z-index: 10;
      width: 100%;
      input {
        margin-top: -0.02rem;
        outline: 0;
        border: 0;
      }
    }
    .main-search-header-controll {
      width: 5.48rem;
      margin-left: 0.21rem;
      transform: translateY(1px);
      div {
        div {
          font-size: 0.28rem;
          color: #fff;
          margin: 0;
          border-radius: 0;
          padding: 0.1rem 0.1rem;
          a {
            font-size: .26rem;
            color: #f1f1f1;
          }
          &.active {
            background: #fff;
            border-top-left-radius: 0.05rem;
            border-top-right-radius: 0.05rem;
          }
          &.active a {
            color: #2d8cf0;
          }
        }
      }
    }
    .associate-list {
      position: absolute;
      width: 100%;
      background: #fff;
      top: 1.29rem;
      border: 1px solid #dcdcdc;
      z-index: 100;
      height: 100%;
      left: 0;
      bottom: 0;
      right: 0;
      overflow-y: auto;
      li {
        height: 0.7rem;
        line-height: .9rem;
        margin: 0 .45rem;
        border-bottom: .04rem solid #f1f0f0;
        @include overFlowHidden();
        i {
          font-size: .36rem;
          margin-right: .24rem;
          color: #ddd;
        }
        span {
          color: #999;
          font-size: .28rem;
          line-height: .58rem;
          height: .58rem;
          display: inline-block;
        }
        &:active, &:hover {
          background: #eee;
        }
        &:last-child {
          text-align: center;
          font-size: .3rem;
          color: #3976f4;
          border-bottom: none;
          &:active, &:hover {
            background: #fff;
          }
        }
      }
    }
    .header {
      position: relative;
      height: 4.08rem;
      overflow: hidden;
      .swiper-container {
        width: 100%;
        z-index: 0;
        height: 4.08rem;
        overflow: hidden;
        img {
          max-width: 100%;
          /*height: 4.08rem;*/
        }
      }
      .swiper-pagination-fraction, .swiper-pagination-custom, .swiper-container-horizontal > .swiper-pagination-bullets {
        bottom: .1rem !important;
      }
      .swiper-container-horizontal > .swiper-pagination-bullets .swiper-pagination-bullet {
        width: .16rem !important;
        height: .16rem !important;
        margin: 0 .2rem;
      }
    }
    .link-list {
      background: #fff;
      height: 1.56rem;
      margin-bottom: .2rem;
      li {
        position: relative;
        display: inline-block;
        width: 20%;
        text-align: center;
        float: left;
        height: 1.56rem;
        img {
          width: .7rem;
          height: .7rem;
          margin-top: .2rem;
        }
        span {
          font-size: .26rem;
          color: #666;
          display: block;
          margin-top: .15rem;
        }
        i {
          height: 0.9rem;
          width: .01rem;
          background: #ddd;
          display: block;
          position: absolute;
          right: 0;
          top: .2rem;
        }
      }
    }
  }
</style>
