<template>
  <div>
    <div class="tab-filter" >
      <div class="inline-block item" @click="sortBy('normal1')" :class="{'active': activeTag === 'normal1'}">默认排序</div>
      <div class="inline-block item" @click="sortBy('normal2')" :class="activeTag==='normal2'?'active':''">现货优选<i class="fa fa-long-arrow-down" v-show="reserve_asc"></i><i class="fa fa-long-arrow-up" v-show="!reserve_asc"></i></div>
      <div class="inline-block item" @click="sortBy('price')" :class="activeTag==='price'?'active':''">价格<i class="fa fa-long-arrow-down" v-show="price_asc"></i><i class="fa fa-long-arrow-up" v-show="!price_asc"></i></div>
      <div class="inline-block price-filter">
        <input type="number" min="0" step="0.01" v-model="min_price" class="form-control" placeholder="￥" onfocus="this.placeholder=''" onblur="this.placeholder='￥'" />
        <span>&nbsp;-&nbsp;</span>
        <input type="number" :min="min_price === ''?0:min_price" step="0.01" v-model="max_price" class="form-control" placeholder="￥" onfocus="this.placeholder=''" onblur="this.placeholder='￥'" />
        <a class="fp-btn inline-block" @click="filter_price">确定</a>
      </div>
      <div class="fr">
        <span>共{{good_list.total}}条商品信息</span>
        <span class="page-info"><span class="active">{{nowPage}}</span>/{{total_page}}</span>
        <a href="javascript:void(0)" class="icon-xiangzuo iconfont" @click="changePage('pre')"></a>
        <a href="javascript:void(0)" class="icon-xiangyou iconfont" @click="changePage('next')"></a>
      </div>
    </div>
    <ul class="good-list" v-if="good_list.pcbgoods && good_list.pcbgoods.length">
      <li v-for="item in good_list.pcbgoods" class="inline-block">
        <nuxt-link :to="`/pcb/product/${item.productid}/${item.batchCode}`">
          <div class="img">
            <img :src="getLogo(item)">
          </div>
          <p class="price">{{item.prices ? item.currencyName === 'RMB' ? '¥' + '&nbsp;&nbsp;' + item.prices[0].rMBPrice : '$' +  '&nbsp;&nbsp;' + item.prices[0].uSDPrice : '-'}}</p>
          <p>{{item.code}}</p>
          <p>销量<span class="sell-count">{{item.saleQty || 0}}</span>件</p>
        </nuxt-link>
      </li>
    </ul>
    <div class="com-empty" v-if="!good_list.pcbgoods || !good_list.pcbgoods.length">
      <img class="com-empty-img" src="/images/brandList/empty-cart.png">
      <span class="com-empty-text">暂无搜索结果</span>
    </div>
    <page :total="total_count" :page-size="pageSize"
          :current="nowPage" @childEvent="listenPage"></page>
  </div>
</template>

<script>
  import Page from '~components/common/page/pageComponent.vue'
  import Buy from '~components/common/buyOrCar/buyComponent.vue'
  export default {
    data () {
      return {
        nowPage: 1,
        pageSize: 20,
        sorting: {},
        price_asc: true,
        reserve_asc: true,
        min_price: '',
        max_price: '',
        filter: {},
        activeTag: 'normal1'
      }
    },
    components: {
      Page,
      Buy
    },
    filters: {
      currency: function (input) {
        if (typeof input === 'number') {
          if (input <= 0.000001) {
            input = 0.000001
          } else {
            if (input.toString().indexOf('.') === -1) {
              input = input + '.00'
            } else {
              let inputStr = input.toString()
              let arr = inputStr.split('.')
              let floatNum = arr[1]
              if (floatNum.length > 6) {
                input = inputStr.substring(0, arr[0].length + 7)
                if (Number(floatNum.charAt(6)) > 4) {
                  input = (Number(input) * 1000000 + 1) / 1000000
                }
              } else if (floatNum.length === 1) {
                input = input + '0'
              }
            }
          }
        }
        return input
      }
    },
    watch: {
      $route: function (val, oldVal) {
        this.filter = {}
        this.activeTag = 'normal1'
      }
    },
    computed: {
      good_lists () {
        return this.$store.state.pcb.search.list
      },
      good_list () {
        return this.good_lists.data
      },
      total_count () {
        return Math.min(this.good_list.total, 100 * this.pageSize)
      },
      total_page () {
        let currentCount = Math.floor(this.good_list.total / this.pageSize) + (this.good_list.total % this.pageSize > 0 ? 1 : 0)
        return currentCount > 100 ? 100 : currentCount
      },
      buy_info () {
        return this.$store.state.user.buy.buyInfo.data
      },
      car_info () {
        return this.$store.state.user.car.addCarInfo.data
      },
      tab () {
        return this.$store.state.chat.tab.tab.data
      },
      user () {
        return this.$store.state.option.user
      }
    },
    methods: {
      goWebChat: function () {
        if (!this.user.logged) {
          this.$http.get('/login/page').then(response => {
            if (response.data) {
              this.$router.push('/auth/login')
            }
          })
        } else {
          // 获得窗口的垂直位置
          let iTop = (window.screen.availHeight - 30 - 780) / 2
          // 获得窗口的水平位置
          let iLeft = (window.screen.availWidth - 10 - 1030) / 2
          if (this.tab.close) {
            this.tab.close()
          }
          let newTab = window.open('', '即时对话框', 'height=750, width=1000, top=' + iTop + ', left=' + iLeft + ', toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no')
          newTab.close()
          newTab = window.open('', '即时对话框', 'height=750, width=1000, top=' + iTop + ', left=' + iLeft + ', toolbar=no, menubar=no, scrollbars=no, resizable=no, location=no, status=no')
          this.$store.dispatch('chat/setChatTab', {tab: newTab})
          this.$http.get('/basic/enterprise/' + this.storeInfo.enUU + '/info')
            .then(response => {
              let obj = {}
              obj.userPhone = this.user.data.userTel
              obj.userType = 'ENTERPRISE'
              this.user.data.enterprises.forEach(function (item, index) {
                if (item.current) {
                  obj.enUU = item.uu
                  obj.enterprise = {enUU: item.uu, name: item.enName}
                }
              })
              obj.otherEnUU = response.data.uu
              obj.otherUserType = 'STORE'
              obj.otherEnterprise = {enUU: response.data.uu, name: response.data.enName}
              obj.type = 'CHAT'
              if (!(/^1\d{10}$/).test(response.data.enTel)) {
                this.$http.get('/basic/enterprise/' + response.data.uu + '/admin').then(response => {
                  obj.toPhone = response.data.userTel
                  this.openWebChat(newTab, obj)
                }, err => {
                  console.log(err)
                  this.$message.error('暂无卖家管理员手机号！')
                })
              } else {
                obj.toPhone = response.data.enTel
                this.openWebChat(newTab, obj)
              }
            }, err => {
              console.log(err)
            })
        }
      },
      openWebChat: function (newTab, obj) {
        this.$http.post('https://im.ubtob.com/api/chat/infos?condition=chat_info', obj)
          .then(response => {
            if (response.data.success) {
              newTab.location.href = 'https://im.ubtob.com/chat/visit?gid=' + response.data.content
            }
          })
      },
      listenPage: function (changedPage) {
        this.nowPage = changedPage
        this.$emit('pageEvent', this.nowPage)
      },
      changePage: function (type) {
        if (type === 'next' && this.nowPage < this.total_page) {
          this.listenPage(++this.nowPage)
        } else if (type === 'pre' && this.nowPage > 1) {
          this.listenPage(--this.nowPage)
        }
      },
      sortBy: function (param) {
        if (param === 'normal1') {
          this.sorting = {}
          this.activeTag = 'normal1'
        } else if (param === 'normal2') {
          if (this.reserve_asc) {
            this.sorting = {'RESERVE': 'ASC'}
          } else {
            this.sorting = {'RESERVE': 'DESC'}
          }
          this.activeTag = 'normal2'
          this.reserve_asc = !this.reserve_asc
        } else if (param === 'type') {
          this.sorting = {'RESERVE': 'DESC'}
          this.activeTag = 'type'
        } else if (param === 'price') {
          if (this.price_asc) {
            this.sorting = {'PRICE': 'ASC'}
          } else {
            this.sorting = {'PRICE': 'DESC'}
          }
          this.activeTag = 'price'
          this.price_asc = !this.price_asc
        }
        this.$emit('sortEvent', this.sorting)
        this.nowPage = 1
      },
      filter_price: function () {
        if (this.min_price === '' && this.max_price !== '') {
          this.filter.goods_maxpricermb = this.max_price
        } else if (this.min_price !== '' && this.max_price === '') {
          this.filter.goods_minpricermb = this.min_price
        } else if (this.min_price !== '' && this.max_price !== '') {
          if (this.min_price <= this.max_price) {
            this.filter.goods_minpricermb = this.min_price
            this.filter.goods_maxpricermb = this.max_price
          }
        } else {
          delete this.filter.goods_minpricermb
          delete this.filter.goods_maxpricermb
        }
        this.$emit('filterPriceEvent', this.filter)
      },
      clear_price: function () {
        this.min_price = ''
        this.max_price = ''
        this.$emit('filterPriceEvent', this.filter)
      },
      goUnstandardDetail: function (comp) {
        if (!comp.uuid) {
          this.$router.push('/store/productDetail/' + comp.batchCode)
        }
      },
      getLogo: function (item) {
        if (item.batchCode) {
          if (item.img) {
            return item.img
          } else {
            return '/images/component/default.png'
          }
        } else {
          if (item.brand && item.brand.logoUrl) {
            return item.brand.logoUrl
          } else {
            return '/images/component/default.png'
          }
        }
      }
    }
  }
</script>

<style scoped lang="scss">
  .tab-filter {
    height: 34px;
    background: #f4f4f4;
    padding: 5px 31px 0 14px;
    margin-bottom: 20px;
    line-height: normal;
    .item {
      width: 74px;
      height: 24px;
      text-align: center;
      color: #999;
      line-height: 22px;
      background: #fff;
      border: 1px solid #d9d9d9;
      border-right: none;
      cursor: pointer;
      font-size: 12px;
      &:last-child {
        border-right: 1px solid #d9d9d9;
      }
      &.active {
        border: 1px solid #5078cb;
        background: #5078cb;
        color: #fff;
      }
    }
    .price-filter {
      margin-left: 30px;
      .form-control {
        width: 74px;
        height: 24px;
        border: 1px solid #d9d9d9;
        border-radius: 0;
        padding: 0 6px;
        font-size: 12px;
      }
      .fp-btn {
        width: 43px;
        height: 24px;
        line-height: 24px;
        background: #5078cb;
        color: #fff;
        text-align: center;
        border-radius: 2px;
        margin-left: 6px;
      }
    }
    .fr {
      height: 24px;
      line-height: 24px;
      color: #999;
      .page-info {
        margin-left: 20px;
        margin-right: 4px;
        .active {
          color: #3f85f6;
        }
      }
      .iconfont {
        display: inline-block;
        width: 38px;
        height: 24px;
        line-height: 24px;
        text-align: center;
        border: 1px solid #d9d9d9;
        color: #666;
        background: #fff;
      }
    }
  }
  .good-list {
    .inline-block {
      width: 220px;
      height: 300px;
      margin-right: 15px;
      border: 1px solid #d9d9d9;
      padding: 0 20px;
      margin-bottom: 15px;
      &:nth-child(5n) {
        margin-right: 0;
      }
      p {
        color: #666;
      }
      $img-size: 179px;
      .img {
        width: $img-size;
        height: $img-size;
        line-height: $img-size;
        text-align: center;
        margin: 0 auto;
        img {
          max-width: $img-size;
          max-height: $img-size;
        }
      }
      .price {
        font-size: 18px;
        color: #e4393c;
      }
      .sell-count {
        color: #767cf9;
      }
    }
  }
  .com-empty{
    text-align: center;
    height:130px;
    border: 1px solid #eee;
    line-height: 130px;
    margin-bottom: 20px;
    .com-empty-text {
      color: #aaa;
      margin-left: 10px;
    }
  }
</style>
