<template>
  <section class="AiSearchPopup">
    <u-popup v-model="show" :length="length" closeable :mode="mode" border-radius="32">
      <slot v-if="$slots.default"/>
      <div class="searchPane" v-else>
        <div class="title">{{ title }}</div>
        <u-search v-model="search" :placeholder="placeholder" :show-action="false" @search="getList()" :focus="show"/>
        <div class="result">
          <div class="option" v-for="(op,i) in list" :key="i" @tap="handleSelect(op)">{{ op[ops.label] }}</div>
        </div>
      </div>
    </u-popup>
    <div @tap="show=true">
      <slot name="btn"/>
    </div>
  </section>
</template>

<script>
export default {
  name: "AiSearchPopup",
  props: {
    title: {default: "搜索"},
    placeholder: {default: "请搜索"},
    ops: {default: () => ({label: 'label', search: 'name'})},
    url: String,
    mode: {default: "right"},
    length: {default: "100%"}
  },
  data() {
    return {
      show: false,
      search: "",
      list: []
    }
  },
  watch: {
    show(v) {
      !v && this.$emit('close')
    }
  },
  methods: {
    getList() {
      this.url && this.$instance.post(this.url, null, {
        params: {[this.ops.search]: this.search}
      }).then(res => {
        if (res?.data) {
          this.list = res.data
        }
      })
    },
    showPopup() {
      this.show = true
    },
    handleSelect(op) {
      this.$emit('select', op)
      this.show = false
    }
  }
}
</script>

<style lang="scss" scoped>
.AiSearchPopup {
  ::v-deep .searchPane {
    padding: 0 16px;
    display: flex;
    flex-direction: column;
    height: 100%;

    .title {
      width: 100%;
      height: 100px;
      text-align: center;
      line-height: 100px;
    }

    .result {
      flex: 1;
      min-height: 0;
      overflow-y: auto;
      padding-bottom: 30px;
    }

    .option {
      display: flex;
      align-items: center;
      height: 80px;
      border-bottom: 1px solid #eee;
      font-size: 32px;
    }
  }
}
</style>
