<!--
 * @Description: 搜索组件
 * @Author: 王晓颖
 * @Date: 2022-05-18
 -->
<template>
  <div>
    <!--搜索条件-->
    <div class="map-search-div">
      <el-input v-model.trim="keywords" :placeholder="placeholder" clearable>
        <el-button slot="append" class="filter-item" type="primary" icon="el-icon-search" @click="search">
          搜索
        </el-button>
      </el-input>
    </div>
    <!--搜索结果弹出框-->
    <el-popover
      v-show="list.length>0"
      v-model="resultShow"
      placement="bottom-end"
      width="290"
      trigger="click"
    >
      <el-card slot="reference" shadow="always" class="selectAnswer">
        共找到 {{ list.length }} 个符合条件的{{ name }}
      </el-card>
      <div v-show="list.length>0">
        <search-item v-for="(data,index) in currentPageList" :key="'search-item-'+index" :data="data" :index="index" @click="clickItem" />
      </div>
      <div class="clear" />
      <el-pagination
        :total="list.length"
        :current-page="pageNum"
        :page-size="pageSize"
        :hide-on-single-page="true"
        small
        layout="prev, pager, next"
        @current-change="changePage"
      />
    </el-popover>
  </div>
</template>

<script>
export default {
  name: 'SearchComp',
  props: {
    name: {
      type: String,
      default: '井'
    }, // 结果展示类型
    placeholder: {
      type: String,
      default: '关键字'
    },
    list: {
      type: Array,
      default: () => []
    } // 结果列表
  },
  data() {
    return {
      resultShow: false, // 是否显示查询结果
      keywords: '', // 查询条件
      currentPageList: [], // 当前页数据
      pageSize: 5, // 页面容量
      pageNum: 1 // 页码
    }
  },
  watch: {
    list(val) { // 监控list的数量，为0时不显示
      if (val && val.length > 0) {
        this.resultShow = true
        this.changePage(1)
      } else {
        this.resultShow = false
        this.currentPageList = []
      }
    }
  },
  methods: {
    // 点击搜索按钮
    search() {
      this.$emit('search', this.keywords)
    },
    // 切换页码
    changePage(val) {
      const offset = val
      const start = (offset - 1) * this.pageSize
      const end = start + this.pageSize
      this.currentPageList = this.list.slice(start, end)
      this.$emit('change-page', this.currentPageList)
    },
    // 点击结果项
    clickItem(item) {
      this.$emit('click-item', item)
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.map-search-div{
  position: absolute;
  z-index: 100;
  left: 30px;
  top: 5px;
}
</style>
