import { FormButtonController } from '@ibiz-template/controller';
import { FormButtonModel } from '@ibiz-template/model';
import { useNamespace } from '@ibiz-template/vue-util';
import { defineComponent, ref } from 'vue';
import '@ibiz-template/theme/style/components/widgets/form/form-button.scss';

export const FormButton = defineComponent({
  name: 'FormButton',
  props: {
    modelData: {
      type: FormButtonModel,
      required: true,
    },
    controller: {
      type: FormButtonController,
      required: true,
    },
  },
  setup() {
    const ns = useNamespace('form-button');
    const isLoading = ref(false);

    return { ns, isLoading };
  },
  render() {
    if (!this.controller.visible) {
      return null;
    }
    return (
      <i-button
        onClick={async (e: MouseEvent) => {
          this.isLoading = true;
          try {
            await this.controller.onClick(e);
          } finally {
            this.isLoading = false;
          }
        }}
        loading={this.isLoading}
        class={this.ns.b()}
      >
        {this.modelData.sysImage && this.modelData.sysImage.cssClass && (
          <i class={[this.ns.e('icon'), this.modelData.sysImage.cssClass]}></i>
        )}
        {this.modelData.source.caption}
      </i-button>
    );
  },
});
export default FormButton;
