<!--
自定义下拉应用列表
@Author: linqian
@Date: 2021/08/30 10:30
-->
<template>
  <el-select
    ref="selectApp"
    class="dg-select"
    v-model="appValue"
    v-bind="$attrs"
    v-on="$listeners"
    @filter-change="handleFilter"
    @clearSelect="handleClearSelect"
    :placeholder="placeholder"
    :filterable="true"
    :loadData="appList"
    :loading="loading"
    clearable
    @scroll-bottom="handleScrollBottom"
    @change="handleChange"
  >
    <el-option v-for="item in appList" :key="item.id" :label="item[labelName]" :value="item[valueName]"></el-option>
  </el-select>
</template>

<script>
import ElSelect from '../select-org-tree/select.vue';
import { getDropdownApp } from '@/api/common';
export default {
  props: {
    apiUrl: {
      type: String
    },
    valueName: {
      type: String,
      default: 'id'
    },
    labelName: {
      type: String,
      default: 'name'
    },
    // 搜索应用列表字段名
    searchAppName: {
      type: String,
      default: 'applyName'
    },
    // 搜索表格的字段名
    tableSearchName: {
      type: String,
      default: 'appName'
    },
    placeholder: {
      type: String,
      default: "请选择应用系统名称"
    }
  },
  components: {
    ElSelect
  },
  data() {
    return {
      appValue: '',
      appList: [],
      loading: true,
      page: 0,
      size: 50,
      condition: {}
    };
  },
  computed: {},
  watch: {
    appValue(val) {
      if (val) {
        this.$refs.selectApp.blur();
        this.$refs.selectApp.oldValue = this.appList.find((item) => item[this.valueName] == val)[this.labelName];
      }
    }
  },
  methods: {
    handleScrollBottom() {
      if (!this.isLast) {
        this.page++;
        this.getAppList();
      }
    },
    handleFilter(val) {
      const value = val.trim();
      this.page = 0;
      if (val) {
        this.condition[this.searchAppName] = {
          value,
          op: 'like'
        };
      } else {
        this.condition = {};
      }
      this.getAppList();
    },
    handleClearSelect() {
      this.appValue = '';
      this.$emit('submitAppValue', '', this.tableSearchName);
      this.$emit('submitCurrentApp', {});
    },
    getAppList() {
      this.loading = true;
      const params = {
        page: this.page,
        size: this.size,
        searchCondition: this.condition
      };
      getDropdownApp(this.apiUrl, params).then((res) => {
        let { content, totalElements } = res.data;
        if (this.page == 0) {
          this.appList = [];
        }
        this.appList = [...this.appList, ...content];
        this.isLast = this.appList.length == totalElements;
        this.loading = false;
      });
    },
    handleChange(val) {
      this.$emit('submitAppValue', val, this.tableSearchName);
      const currentApp = this.appList.filter((item) => item[this.valueName] == val)[0];
      this.$emit('submitCurrentApp', currentApp);
    }
  },
  created() {
    this.getAppList();
  },
  mounted() {}
};
</script>

<style lang='scss'>
</style>