<template>
  <view class="page-container">
    <view class="status-bar"></view>
    <view class="page-head">
      <view class="page-head-btn" @click="goBack">
        <uni-icons type="back" size="26" color="#fff"></uni-icons>
      </view>
      <u-search v-model="wd" placeholder="请输入要搜索的内容" :actionStyle="{width: '50px', fontSize: '16px',color:'#FC5667'}" @search="search" @custom="search"></u-search>
    </view>
    <view class="search-container">
      <search-history ref="history" v-show="history" @item-click="search" />
      <search-empty v-show="empty" />
      <search-list ref="list" v-if="list" :wd="wd" @empty="showEmpty" />
    </view>
  </view>
</template>

<script>
import searchHistory from './history.vue'
import searchEmpty from './empty.vue'
import searchList from './list.vue'

export default {
  components: {
    searchHistory,
    searchEmpty,
    searchList
  },
  data() {
    return {
      wd: '',
      list: false,
      history: true,
      empty: false,
      loading: false
    }
  },
  methods: {
    async search(value) {
      if (value === '') return
      this.wd = value
      this.history = false
      this.empty = false
      this.list = true
      this.$nextTick(() => {
        this.$refs.list.search()
      })
      let history = uni.getStorageSync('search_history')
      if (history) {
        history = JSON.parse(history)
        const i = history.indexOf(value)
        if (i >= 0) {
          history.splice(i, 1)
        } else if (history.length >= 10) {
          history.pop()
        }
        history.unshift(value)
      } else {
        history = [value]
      }
      uni.setStorage({
        key: 'search_history',
        data: JSON.stringify(history)
      })
    },
    reset() {
      this.list = false
      this.empty = false
      this.history = true
      this.$nextTick(() => {
        this.$refs.history.getHistory()
      })
    },
    showEmpty() {
      this.list = false
      this.empty = true
    },
    goBack() {
      if (this.history) {
        this.back()
      } else {
        this.reset()
      }
    }
  }
}
</script>

<style lang="scss">
.page-container {
  height: 100%;
  background-color: $uni-bg-color;
  .page-head {
    height: 50px;
  }
  .search-container {
    height: calc(100% - var(--safe-top) - 50px);
  }
}
</style>