<template>
  <el-select style="width:100%" v-model="selected" :placeholder="$t('form.placeholderSelect')" clearable  :disabled="readonly" :multiple="multiple" @change="handleChange" filterable>
    <el-option v-for="item in list"  :key="item.id" :label="item.name" :value="item.id" />
  </el-select>
</template>

<script>
import { studyUser } from "@/api/system/user";
export default {
  name: "SelectStudyUser",
  components: {},
  props: {
    value: {
      type: [Number, String , Array],
      default: '',
    },
    readonly: {
      type: Boolean,
      default: false
    },
    multiple: {
      type: Boolean,
      default: false
    },
    placeholder:{
      type:String,
      default:''
    },

    query: {
      type: Object,
      default:()=>{
        return {
          studyId:'',
          studySubject:'',
          permit:''
        }
      }
    },
  },
  watch: {
    value: {
      immediate: true,
      handler(v) {
        if(!this.multiple){
          this.selected = v ? (v+'') : ''
        }else{
          if(v){
            //默认传的,分割的字符串，有传数组再改造
            let arr = v.split(',')
            let s = []
            _.forEach(arr,a=>{
              s.push(a)
            })
            this.selected = s
          }else{
            this.selected = []
          }
        }
      }
    },
    // query:{
    //   handler(v) {
    //     this.getList()
    //   }
    // }
  },
  data() {
    return {
      selected: '',
      list: []
    };
  },
  mounted() {
    this.getList()
  },
  methods: {
    getList() {
      this.list = []
      studyUser(this.query).then(response => {
        this.list = response.data || []
      })
    },
    handleChange(val) {
      //默认传的,分割的字符串，有传数组再改造
      this.$emit('input', this.multiple ? (val && val.length>0 ? val.join(','): ''):(val || ''))
      if(this.multiple){
        debugger
        let arr = []
        if(val && val.length>0){
          for(let i=0;i<val.length;i++){
            for(let j=0;j<this.list.length;j++){
              if(val[i]===this.list[j].id){
                arr.push(this.list[j])
                break
              }
            }
          }
        }
        this.$emit('change',arr)
      }else{
        let obj = {}
        if(val){
          for(let j=0;j<this.list.length;j++){
            if(val===this.list[j].id){
              obj = this.list[j]
              break
            }
          }
        }
        this.$emit('change', obj)
      }
    },
  }
};
</script>
