import { FormItemController } from '@ibiz-template/controller';
import { FormItemModel } from '@ibiz-template/model';
import { defineComponent } from 'vue';
import { useNamespace } from '@ibiz-template/vue-util';
import '@ibiz-template/theme/style/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 = props.controller;
    const onValueChange = (val: unknown, name?: string) => {
      props.controller.setDataValue(val, name);
    };

    return { ns, c, onValueChange };
  },
  render(h) {
    if (!this.c.visible) {
      return null;
    }

    // 编辑器内容
    let editor = null;
    if (this.c.form.isLoaded) {
      if (this.controller.editorProvider) {
        editor = h(this.controller.editorProvider.formEditor, {
          props: {
            value: this.controller.value,
            data: this.controller.data,
            controller: this.controller.editor,
            disabled: this.controller.disabled,
            readonly: this.controller.editor!.readonly,
          },
          on: {
            change: this.onValueChange,
          },
        });
      } else {
        editor = <not-supported-editor modelData={this.modelData.editor} />;
      }
    }

    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}
      >
        {editor}
      </form-item-container>
    );
  },
});
export default FormItem;
