<template>
<el-form-item :prop="prop" :label="label" :label-width="options.labelWidth" :rules="rules">
<el-select v-model="value" style="width: 100%; min-height: 33px;" v-bind="props" :loading="loading" @change="onChange">
  <el-option v-for="row in items" :key="row.__value" :value="row.__value" :label="row.__label"></el-option>
</el-select>
</el-form-item>
</template>

<script lang="ts">

import { Vue, Component, Prop, Ref, Watch } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import { SelectOptions, SelectDef } from '../../type'
import OptionFieldMixins from './OptionFieldMixins'
import { ArrayDataOptions } from '../../type/common'

@Component
export default class SelectControl extends mixins(OptionFieldMixins) {
  loading = false

  get options () {
    return Object.assign(new SelectOptions(), this.def?.options)
  }

  get multiple (): boolean {
    return !!this.options?.multiple
  }

  get props () {
    const remoteMethod = this.options?.remoteMethod
    const cb = (data: any[] = []) => {
      this.loading = false
      this.items = data
    }
    const rm = (q: string) => {
      this.loading = true
      try {
        if (remoteMethod) remoteMethod(q, cb)
      } catch (e) {
        this.loading = false
        throw e
      }
    }
    return {
      multiple: this.multiple,
      disabled: this.disabled,
      filterable: this.options?.filterable,
      remote: this.options?.remote,
      remoteMethod: remoteMethod ? rm : undefined,
      placeholder: this.options?.placeholder || `请选择${this.def?.label}`,
      clearable: this.options?.clearable
    }
  }

  onChange (val: any) {
    const fn = this.options?.onChange
    if (fn) fn({ value: this.value, form: this.actualForm, rowForm: this.rowForm, items: this.items })
  }

  @Watch('value') valueChange (newVal: any) {
    const fn = this.options?.onValueChange
    if (fn) fn({ value: newVal, form: this.actualForm, rowForm: this.rowForm, items: this.items })
  }

  def!: SelectDef
}
</script>
