import { FormItemController } from '@ibiz-template/controller';
import { FormItemModel } from '@ibiz-template/model';
import { defineComponent, computed, reactive } from 'vue';
import { useNamespace } from '@ibiz-template/vue-util';
import '@/styles/components/widgets/form/form-item.scss';

export const FormItem = defineComponent({
  name: 'FormItem',
  props: {
    modelData: {
      type: FormItemModel,
      required: true,
    },
    controller: {
      type: FormItemController,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('form-item');
    const c = reactive(props.controller);
    const value = computed(() => props.controller.value);
    const onValueChange = (val: unknown, name?: string) => {
      props.controller.setDataValue(val, name);
    };
    return { ns, c, value, onValueChange };
  },
  render(h) {
    if (!this.c.visible) {
      return null;
    }
    return (
      <form-item-container
        class={[this.ns.b(), this.ns.m(this.modelData.modelClass)]}
        required={this.c.required}
        error={this.c.error}
        label={this.modelData.source.caption}
        label-pos={this.c.model.labelPos}
        label-width={this.c.model.labelWidth}
      >
        {this.controller.editorProvider ? (
          h(this.controller.editorProvider.formEditor, {
            props: {
              value: this.value,
              data: this.controller.data,
              controller: this.controller.editor,
              disable: this.controller.disabled,
            },
            on: {
              change: this.onValueChange,
            },
          })
        ) : (
          <not-supported-editor modelData={this.modelData.editor} />
        )}
      </form-item-container>
    );
  },
});
export default FormItem;
