const util = require('../../utils/util.js');
const api = require('../../config/api.js');
const user = require('../../services/user.js');
import header from './data'
import {
  Router
} from '../../utils/router.js'

//获取应用实例
Router({
  data: {
    currentBanner: 0,
    banners: [],
    showSearch: false,
    activeType: -1,
    header: [],
    noRecord: '',
    hideMask: false,
    keyword: '',
    url: 'https://www.4dkankan.com/eShopMobile.html?m=',
    totalPages: 1,
    currentPage: 1,
    size: 10,
    loading: false,
    brandList: []
  },
  swiperChange(e) {
    this.setData({
      currentBanner: e.detail.current
    })
  },
  onShareAppMessage: function () {
    return {
      path: '/pages/index/index'
    }
  },
  getImgHeight() {
    const aw = 750
    const ah = 480
    this.setData({
      imgHeight: ah * wx.getSystemInfoSync().windowWidth / aw
    })

    this.navTop = this.data.imgHeight * 0.87
    this.bgTop = this.data.imgHeight * 0.6
    this.setData({
      navTop: this.bgTop
    })
    wx.createSelectorQuery().select('#index-nav').boundingClientRect( (rect) => {
      console.error(rect.top)
      this.setData({
        navPosTop: rect.top
      })
    }).exec()
    // console.log(this.navTop, this.bgTop)
  },
  onPageScroll(e) {
    if (e.scrollTop < 0) return;
    this.setData({
      bgTop: e.scrollTop > this.bgTop ? this.bgTop : e.scrollTop,
      bgIsTop: e.scrollTop > this.navTop,
      isFixed: e.scrollTop > this.data.navPosTop
    })
  },
  onPullDownRefresh() {
    this.setData({
      brandList: this.data.brandList.slice(0, 10),
      currentPage: 1
    });
    this.getBrandList(1, false, true);
    getApp().onPullDownRefresh()
  },

  onReachBottom() {
    if (!this.data.loading) {
      this.loadMore();
      console.log('reach down')
    }
  },

  clickSwiper() {
    wx.navigateTo({
      url: this.data.banners[this.data.currentBanner].redirectUrl,
    })
  },
  loadMore: function () {
    if (this.data.currentPage < this.data.totalPages) {
      console.log(this.data.currentPage + 1)
      this.getBrandList(this.data.currentPage + 1);
    } else {
      return;
    }
  },

  getBrandList(page, isSearch = false, refresh = false) {
    this.setData({
      loading: true
    })
    let tempContent = this.data.brandList ?
      this.data.brandList : [];
    let {
      activeType,
      size,
      keyword,
    } = this.data

    util.request(api.IndexList, {
        type: activeType,
        page,
        name: keyword,
        size
      })
      .then(res => {
        res.data.data = res.data.data.map(item => {
          if (item.pvTotalNum) {
            item.pvTotalNum = item.pvTotalNum >= 10000 ?
              (
                item.pvTotalNum > 990000 ? 99 + 'W+' :
                (item.pvTotalNum / 10000).toFixed(1) + 'W'
              ) :
              item.pvTotalNum
          } else {
            item.pvTotalNum = 0
          }
          return item
        })
        if (isSearch) {
          // if (res.data.data.length <= 0) {
          //   this.setData({
          //     noRecord: true
          //   });
          // }
          // else {
          wx.pageScrollTo({
            scrollTop: 0
          })
          this.setData({
            brandList: res.data.data,
            currentPage: res.data.currentPage,
            totalPages: res.data.totalPages,
            loading: false,
            noRecord: false,
            showSearch: false
          });
          // }
        } else if (refresh) {
          this.setData({
            brandList: res.data.data,
            currentPage: res.data.currentPage,
            totalPages: res.data.totalPages,
            loading: false
          });
        } else {
          this.setData({
            brandList: tempContent.concat(res.data.data),
            currentPage: res.data.currentPage,
            totalPages: res.data.totalPages,
            loading: false
          });
        }



      });
  },

  inputChange: function (e) {
    let val = e.detail.value
    this.setData({
      keyword: val,
      noRecord: false
    })

    this.search()
  },

  handleScroll(ev) {
    this.setData({
      isFixed: ev.detail.isFixed
    })
  },
  search: function () {
    let {
      keyword
    } = this.data

    this.getBrandList(1, true)
    // if (this.brandList.length <= 0) {
    //   this.setData({
    //     noRecord: true
    //   })
    // }
    // else {
    //   this.setData({
    //     activeType: -1,
    //     noRecord: false,
    //     showSearch: false
    //   })
    // }
  },

  inputFocus: function () {

  },
  gotoCateg() {
    wx.navigateTo({
      url: '/pages/ncategory/category?id=search',
    })
  },

  tapHeaderBar(e) {
    // let { id } = e.currentTarget.dataset
    // wx.navigateTo({
    //   url: '/pages/ncategory/category?id=' + id,
    // })
    let {
      id
    } = e.currentTarget.dataset
    this.setData({
      activeType: id,
      showSearch: false,
      keyword: '',
      brandList: [],
      currentPage: 1
    })

    this.getBrandList(1)
  },

  tabShow() {
    this.setData({
      showSearch: true
    })
  },


  tabHide() {
    this.setData({
      showSearch: false,
      noRecord: false,
      keyword: ''
    })
  },




  onLoad: async function (options) {
    getApp().checkNetStatu();
    // this.checkNetStatu()
    this.setData({
      imgServer: util.imgServer
    })
    this.getBrandList(1)
    this.getBanner()
    this.getType()
    this.getImgHeight()

    // wx.setBackgroundColor({
    //   backgroundColor: '#ff7701'
    // })
  },

  async getBanner() {
    let {
      data
    } = await util.request(api.HomeBanner)
    this.setData({
      banners: data
    })
  },

  async getType() {
    let {
      data
    } = await util.request(api.IndexTypeList)
    let items = [{
      name: '推荐',
      id: -1
    }]
    data.forEach(item => {
      Object.keys(item).forEach(key => {
        items.push({
          name: key,
          id: item[key]
        })
      })
    })
    this.setData({
      header: items
    })
  },

  onReady: function () {
    // 页面渲染完成
  },

  onShow: function (options) {
    if (global.type) {
      this.tapHeaderBar({
        currentTarget: {
          dataset: this.data.header[0]
        }
      })
      global.type = null
    }
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }

    getApp().updateCardCount()
    // 页面显示
  },
  onHide: function () {
    // 页面隐藏
  },
  onUnload: function () {
    // 页面关闭
  },
  gotoWV: function (event) {
    let {
      id
    } = event.currentTarget.dataset

    wx.navigateTo({
      url: `/pages/webview/index?id=${id}`,
      // url: `/pages/share/share?id=${id}`,
    })
  }
})