<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：''  //占位符
      requestFormat:''
    },
    request:{}
  }
*/
import { Component, Prop, Vue, Watch } from "vue-property-decorator";
import VueViews from '@/benyun/compVue/VueViews'
@Component
export default class BySelect extends VueViews {
  value:any='';
  options:Array<any>=[]

  @Watch('propValue')
  propValueChange(v:any){
    this.setValue(v);
  }

  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.propValue)
    }
  }

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

  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;
    if(!this.value && this.attrs.defaultIndex >= 0 && this.options[this.attrs.defaultIndex]){
      this.value = this.options[this.attrs.defaultIndex][this.itemValue];
      this.onChange();
    }
  }

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

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

  //请求url
  request(){
    if(!this.requestConfig || !this.requestConfig.url){
      return
    }
    let parame = (this as any).$lodash.cloneDeep(this.requestConfig);
    parame.success = (res:any) => {
      let f = this.attrs.requestFormat?this.attrs.requestFormat:'data'
      if(res.data && res.data[f]){
        this.setOptions(res.data[f]);
      }
    }
    parame.fail = (err:any) => {}
    this.requestHandle(parame);
  }
}
</script>

<style lang="scss" scoped>

</style>