<script lang="ts">

import { Vue, Component, Prop, Ref, Inject } from 'vue-property-decorator'
import { mixins } from 'vue-class-component'
import { CreateElement } from 'vue'
import { FormDef, FormOptions, CustomDef, CustomOptions } from '../../type'
import FieldMixins from './FieldMixins'
import GlpFormRender from '../../GlpFormRender.vue'

@Component
export default class CustomControl extends mixins(FieldMixins) {
  @Inject() getFormRender!: () => GlpFormRender

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

  get customType (): string {
    return this.def.customType
  }

  get props () {
    const vm = this as any
    return {
      options: this.options,
      proxy: {
        get value () {
          return vm.value
        },
        set value (value: any) {
          vm.value = value
        }
      }
    }
  }

  render (h: CreateElement) {
    const props = {
      prop: this.prop,
      label: this.label,
      labelWidth: this.options?.labelWidth,
      rules: this.rules,
      disabled: this.disabled
    }
    return h('el-form-item', { props }, [this.renderCustom(h)])
  }

  private renderCustom (h: CreateElement) {
    const slot = this.getFormRender().$scopedSlots[this.customType]
    if (slot) {
      return h('div', {}, [
        slot(this.props)
      ])
    }
  }

  def!: CustomDef
}
</script>
