import { VueLikePage } from '../../utils/page'
import { saveSearchHistory, loadSearchHistory, removeSearchHistory } from '../../utils/storage'
import GoodsApi from '../../apis/goods'
import Router from '../../utils/routes'
VueLikePage([], {
  data: {
    showResult: false,
    selectShowStatus: false,
    resultList: [],
    searchTypes: [
      {
        text: '企业',
        value: 'company'
      },
      {
        text: '产品',
        value: 'goods'
      },
    ],
    activeIndex: 1,
    keyword: ''
  },
  methods: {
    onLoad () {
      this.setData({
        history: loadSearchHistory()
      })
    },
    clearHistory () {
      removeSearchHistory()
      this.setData({
        history: []
      })
    },
    hideSelect () {
      this.setData({
        selectShowStatus: false
      })
    },
    showSelect () {
      this.setData({
        selectShowStatus: true
      })
    },
    changeSearchType (e) {
      this.setData({
        activeIndex: e.currentTarget.dataset.index
      })
    },
    searchHistory (e) {
      e.detail.value = e.currentTarget.dataset.keyword
      this.search(e)
    },
    search (e) {
      const { activeIndex, searchTypes } = this.data
      const { value } = e.detail
      if (!value) {
        this.setData({
          showResult: false
        })
        return
      }
      saveSearchHistory(value)
      const params = {
        type: searchTypes[activeIndex].value,
        keyword: e.detail.value
      }
      GoodsApi.searchGoodsOrCompany(params).then(res => {
        const name_key = params.type === 'company' ? 'companyName' : 'name'
        const id_key = params.type === 'company' ? 'companyId' : 'goodsId'
        const img_key = params.type === 'company' ? 'introduceImage' : 'listPicUrl'
        this.setData({
          showResult: true,
          resultList: res.data.list.map(item => {
            item.name = item[name_key]
            item.id = item[id_key]
            item.img = item[img_key]
            return item
          }),
          history: loadSearchHistory(),
          keyword: params.keyword
        })
      })
    },
    toResultDetail (e) {
      const { index } = e.currentTarget.dataset
      const item = this.data.resultList[index]
      if (item.vrLink) {
        Router.push({
          url: 'scene',
          query: {
            vr_link: item.vrLink
          }
        })
      } else {
        Router.push({
          url: 'goodsDetail',
          query: {
            goods_id: item.id
          }
        })
      }
    }
  }
})