<template>
  <el-row style="line-height: 28px;">
    <el-col v-if="label" :style="'width: ' + labelWidth + ';'" class="select-label">
      {{ label }}:
    </el-col>
    <el-col :style="!label ? '100%' : 'width: calc(100% - ' + labelWidth + '); height: 28px;'">
      <el-select v-model="key" :clearable="clearable" :filterable="true" :multiple="multiple"
                 style="width: 100%; display: block;" :placeholder="'请选择' + (label ? label : '')" @change="change">
        <el-option v-for="option in options" :key="option.key" :value="option.key" :label="option.label"></el-option>
      </el-select>
    </el-col>
  </el-row>
</template>
<script>

  import {WebpageQueryService} from "../../../assets/webpage";

  export default {
    name: 'ZyFilterSelect',
    components: {},
    props: {
      sources: {type: Array, default: () => []},
      source: {type: String, required: false},
      label: {type: String},
      init: {type: Boolean, default: false},
      clearable: {type: Boolean, default: true},
      multiple: {type: Boolean, default: false},
      params: {}
    },
    model: {
      prop: 'selected',
      event: 'change'
    },
    data() {
      return {
        key: '',
        options: [],
      }
    },
    created() {
    },
    mounted() {
      this.loadData();
    },
    watch: {
      '$attrs.selected': {
        handler: function (nv) {
          this.$nextTick(() => this.key = nv);
        }
      },
      source: {
        handler: function () {
          this.key = this.$attrs.selected;
          this.loadData();
        }
      },
      params: {
        handler: function () {
          this.key = this.$attrs.selected;
          this.loadData();
        }
      },
      sources: {
        handler: function (nv) {
          this.key = this.$attrs.selected;
          this.initData(nv);
        }
      }
    },
    computed: {
      labelWidth: {
        get() {
          return (this.label.length * 15 + 20) + 'px';
        },
        set() {
        }
      }
    },
    methods: {
      change(value, init) {
        this.$emit('change', value, init);
      },
      loadData() {
        let _this = this;
        if (_this.sources && _this.sources.length !== 0) {
          return _this.initData(_this.sources)
        }
        WebpageQueryService.webpage_query_filter_options(_.merge({_code: this.source}, this.params), (res) => {
          _this.initData(res.content)
        })
      },
      initData(data) {
        let _this = this;
        _this.options = data;
        if (_this.init && !_this.key) {
          let selectedOption = _.find(data, d => d.selected);
          _this.key = selectedOption ? selectedOption.key : (data.length > 0 ? data[0].key : '');
          this.change(_this.key, true);
        }
      }
    },
  }
</script>
<style scoped>
  .select-label {
    font-size: 14px;
    text-align: right;
    padding-right: 12px;
  }
</style>
