<!--  -->
<template>
  <div class="select-con">

    <a-select v-model="selectVal"  show-search  placeholder="请选择" style="width: 300px" :filter-option="false"
        :not-found-content="loading ? undefined : null"
        @search="handlefetchEvent"
        @change="handleChange"
        @dropdownVisibleChange="handleDropdownVisibleChange"
    >
        <div slot="dropdownRender" slot-scope="menu">
        <v-nodes :vnodes="menu" />
        <a-divider style="margin: 4px 0;" />
        <div @mousedown="e => e.preventDefault()"  style="padding: 4px 8px;">
            <a-pagination :current="current"  :total="total" size="small" @change="onChange" :pageSize="pageSize"  />
        </div>
        </div>
        <a-spin v-if="loading" slot="notFoundContent" size="small" />
        <a-select-option v-for="item in data" :key="item.key" :value="item.value">
            {{ item.label }}
        </a-select-option>
    </a-select>
  </div>
</template>

<script>

function paginateArray(array, pageNumber, pageSize) {
    // 计算开始索引
    const start = (pageNumber - 1) * pageSize;
    // 计算结束索引
    const end = start + pageSize;
    // 返回分页后的数组
    return array.slice(start, end);
}

function debounce(func, delay) {
  let inDebounce;
  return function() {
    const context = this;
    const args = arguments;
    clearTimeout(inDebounce);
    inDebounce = setTimeout(() => func.apply(context, args), delay);
  };
}

export default {
  // import引入的组件需要注入到对象中才能使用
  name: 'select',
  components: {
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  props: {
    // handA: {
    //   type: String,
    //   required: true,
    //   default: '100'
    // }
  },
  data() {
    // 这里存放数据
    // this.lastFetchId = 0;
    // this.fetchUser = this.fetchUser // debounce(this.fetchUser, 800);
    return { 
        data: [],
        dataList:[],
        current:1,
        pageSize:10,
        total:0,
        selectVal:[],
        loading: false,
        
    };
  },
  // 监听属性 类似于data概念
  computed: {},
  // 监控data中的数据变化
  watch: {},
  // 生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  // 生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {
    // this.data = paginateArray(getSelevtValue,this.current,this.pageSize)
  },
  // 方法集合
  methods: {
    onChange(current){
        console.log('pagination onChange====>',current);
        
        this.current = current;
        this.data = paginateArray(this.dataList,current,this.pageSize)
    },
    handlefetchEvent(val){
        console.log('handlefetchEvent====>',val);
        const self = this
        const dispathHandler = (val_)=>{
            console.log('#############',val_);
            self.loading = true;
            self.current = 1
            self.getData4DB(val_).then(data=>{
                self.total = data.length
                self.dataList = data
                self.data = data // paginateArray(data,this.current,this.pageSize);
                self.loading = false;
            })
        }
        debounce((dispathHandler)(val), 500)
    },

    getData4DB(key_){
        return new Promise((resolve, reject)=>{
            fetch(`https://randomuser.me/api/?results=500&key=${key_}`)
            .then(response => response.json()).then(body => {
                const data =body.results.map((user,index) => ({
                    key: index,
                    label: `${user.name.first} ${user.name.last}`,
                    value: `${user.name.first} ${user.name.last}`,
                }));
                resolve(data)
            })
        })
    },

    handleDropdownVisibleChange(open){
        console.log('handleDropdownVisibleChange===>',open,this.data);
        if(open == true && this.data.length ==0){
            this.data = this.dataList
        }
    },
    handleChange(value) {
      Object.assign(this, {
        value,
        data: [],
        fetching: false,
      });
    },
  },
  }
</script>
<style lang='less'>
.select-con{
    width: 100vw;
    height: 100vh;
    display: flex;
    justify-content: center;
    align-items:flex-start;
}
</style>