<template>
  <el-select 
    v-model="value"
    :placeholder="attrs.placeholder?attrs.placeholder:'请选择'"
    :disabled="attrs.disabled"
    :size="attrs.size"
    :clearable="attrs.clearable"
    @clear="onChange"
    @change="onChange"
  >
      <el-option
        v-for="item in options"
        :key="item[itemValue]"
        :label="item[itemLabel]"
        :value="item[itemValue]">
      </el-option>
  </el-select>
</template>

<script lang="ts">
/*
  配置说明
  config:{
    attrs:{
      itemLabel:''  //选项的标签
      itemValue:''  //选项的值
      disabled：true/false  //是否禁用
      size：medium/small/mini //尺寸
      clearable：true/false  //是否清空
      placeholder：''  //占位符

    },
    request:{}
  }
*/
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
@Component
export default class BySelect extends Vue {
  config:any={};
  value:any='';
  options:Array<any>=[]
   
  @Prop()
  propConfig: any

  @Prop()
  propValue:any

  get attrs(){
    return this.config?.attr ? this.config.attr : {};
  }

  get requestConfig(){
    return this.config?.request ? this.config.request : null;
  }

  get itemLabel(){
    let n = 'label';
    if(this.attrs.label){
      n = this.attrs.label
    }
    return n;
  }

  get itemValue(){
    let n = 'value';
    if(this.attrs.value){
      n = this.attrs.value
    }
    return n;
  }

  created(){
    if(this.propConfig){
      this.setConfig(this.propConfig)
    }
    if(this.propValue){
      this.setValue(this.propConfig)
    }
  }

  mounted(){
    this.$nextTick(()=>{
      if(this.requestConfig){
        this.request();
      }else if(this.attrs.data){
        this.setOptions(this.attrs.data)
      }
    })
  }

  setConfig(c:any){
    if(c){
      this.config = c;
    }
  }
  getConfig(){
    return (this as any).$lodash.cloneDeep(this.config)
  }

  setValue(data:any){
    if(data){
      this.value = (this as any).$lodash.cloneDeep(data);
    }else{
      this.value = {};
    }
  }

  getValue(){
    return (this as any).$lodash.cloneDeep(this.value);
  }

  setOptions(data:Array<any>){
    this.options = data;
  }

  onChange(){
    this.$emit('onChange',this.value);
  }

  // 清空数据
  clearValue(){
    this.value = ''
  }

  request(){
    if(!this.requestConfig || !this.requestConfig.url){
      return
    }
    (this as any).$request(this.requestConfig).then((res:any) => {
      if(res.data){
        this.setOptions(res.data);
      }
    })
  }
}
</script>

<style lang="scss" scoped>

</style>