<template>
  <el-select
    placeholder="请选择"
    filterable
    :value="model"
    remote=true
    :remote-method="search"
    @change="change"
  >
    <el-option
      v-for="item in options"
      :label="item[title]"
      :value="item[code]"
    >
    </el-option>
    <el-button v-if="buttonShow"  @click="loadMore" :loading="loading" type="text" style="width: 100%">加载更多</el-button>
  </el-select>
</template>

<script>
  import request from '@/router/axios';
    export default {
        name: "lazy-select",
        props: {
          dicUrl: {
            type: "String",
            default: ''
          },
          size: {
            type: "Number",
            default: 20
          },
          query: {
            type: 'Object',
            default: {}
          },
          title: {
            type: 'String',
            default: 'title'
          },
          code: {
            type: 'String',
            default: 'code'
          },
          model:{
            type: 'String',
            default: ''
          }
        },

        data() {
          return {
            buttonShow: true,
            loading: false,
            options: [],
            formData: {
              pageIndex: 1,
              pageSize: 20,
            }
          };
        },
        async mounted() {
          this.formData.pageSize = this.size;
          await this.getList(this.formData);
        },
        methods: {
          search(data){
            this.options = [];
            this.query[this.title] = data;
            this.getList(this.formData);
          },
          change(value){
            let _this = this;
            let data = this.options.filter(x => x[_this.code] === value);
            this.model = data[0][this.title]
            this.$emit('change',data[0]);
          },
          async loadMore() {
            this.formData.pageIndex++;
            this.loading = true;
            await this.getList(this.formData);
            this.loading = false;
          },
          async getList(formData) {
            let res = await request({
              url: this.dicUrl,
              method: 'get',
              params: {
                ...this.query,
                current:formData.pageIndex,
                size: formData.pageSize,
              }
            });
            this.buttonShow = res.data.data.records.length<20? false:true;

            this.options = [...this.options, ...res.data.data.records];
          }
        }
    }
</script>

<style scoped>

</style>
