<template>
  <el-select
    v-model="myValue"
    :size="size"
    clearable
    :popper-append-to-body="popperAppendToBody"
    :style="{ width: width }"
    value-key="id"
    collapse-tags
    filterable
    :multiple="multiple"
    :loading="loading"
    @change="e => $emit('input',e)"
  >
    <el-option
      v-for="(item) in list"
      :key="item.id"
      :label="item.name"
      :value="item.id"
    />
  </el-select>
</template>

<script>
let listData = []
import { index } from '@/api/user'
export default {
  props: {
    popperAppendToBody: {
      type: Boolean,
      default: true
    },
    width: String,
    multiple: Boolean,
    size: String,
    value: {
      type: [String, Number, Array],
      default: '',
      required: true
    }
  },
  data() {
    return {
      total: 0,
      loading: false,
      myValue: '',
      list: [],
      // select: {
      //   rows: 20,
      //   page: 1,
      //   keyword: ""
      // },
      select: {
        rows: 9999,
        page: 1
      }
    }
  },
  computed: {},
  watch: {
    value: {
      handler: function(newVal) {
        this.myValue = newVal
      },
      immediate: true
    }
  },
  mounted() {
    this.getList()
    // this.initLoadMore();
  },
  beforeDestroy() {
    // this.$el?.querySelector(".el-scrollbar__wrap")?.removeEventListener("scroll",this.loadListener)
  },
  methods: {
    remoteMethod(query) {
      if (query !== '') {
        this.select.keyword = query
        this.select.page = 1
        this.list = []
        this.getList()
      } else {
        this.list = []
        this.select.page = 1
        this.getList()
      }
    },
    async getList() {
      if (listData instanceof Array && listData.length > 0) {
        this.list = listData
      } else {
        this.loading = true
        try {
          const res = await index(this.select)
          listData = res.data
          this.list = res.data
          this.total = res.total

          this.loading = false
        } catch (err) {
          this.loading = false
        }
      }
    },
    // async getList () {
    //   if ((this.list.length >= this.total) && this.list.length !== 0) return;
    //
    //   this.loading = true;
    //   try {
    //     const res = await index(this.select);
    //     this.list = this.list.concat(res.data);
    //     this.total = res.total;
    //     console.log(this.list)
    //
    //     this.loading = false;
    //   } catch (err) {
    //     this.loading = false;
    //   }
    // },

    initLoadMore() {
      this.$nextTick(() => {
        this.$el.querySelector('.el-scrollbar__wrap').addEventListener('scroll', this.loadListener)
      })
    },
    loadListener(e) {
      const sign = 0
      const scrollDistance = e.scrollHeight - e.scrollTop - e.clientHeight
      if (scrollDistance <= sign) {
        this.getList()
      }
    }
  }
}
</script>

<style scoped lang="scss">
</style>
