import { defineComponent, getCurrentInstance, h, watch } from 'vue';
import { useController, useNamespace } from '@ibiz-template/vue-util';
import { FormMDCtrlModel } from '@ibiz-template/model';
import '@ibiz-template/theme/style/components/widgets/form/form-mdctrl.scss';
import { FormMDCtrlController } from '@ibiz-template/controller';

export const FormMDCtrl = defineComponent({
  name: 'FormMDCtrl',
  props: {
    modelData: {
      type: FormMDCtrlModel,
      required: true,
    },
    controller: {
      type: FormMDCtrlController,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('form-mdctrl');

    // 绑定强制刷新
    const { proxy } = getCurrentInstance()!;

    useController(proxy, props.controller);

    const c = props.controller;

    watch(
      () => c.form.isLoaded,
      (n, o) => {
        if (n !== o && n === true) {
          c.loadData();
        }
      },
    );

    return { ns, c };
  },
  render() {
    const renderFormContent = () => {
      return (
        this.c.contentCtrlData.length > 0 &&
        this.c.contentCtrlData.map((data: IData, index: number) => {
          let formComponent = null;
          const { form } = this.c.model;
          if (form && this.c.providers[form.name]) {
            const tempContext = this.c.form.context.clone();
            if (this.c.model.appEntity) {
              Object.assign(tempContext, {
                [this.c.model.appEntity.codeName?.toLowerCase()]:
                  data[this.c.model.appEntity.keyName],
              });
            }
            const formProps: IData = {
              modelData: form,
              context: tempContext,
              params: this.c.form.params,
            };
            if (this.modelData.mdCtrlType === 'REPEATER') {
              formProps.simpleDataIndex = index;
            } else {
              formProps.enableAutoSave = true;
            }
            const formEmits: IData = {
              neuronInit: this.c.onNeuronInit(data.srfkey),
            };
            formComponent = h(this.c.providers[form.name].component, {
              props: formProps,
              on: formEmits,
            });
          }
          return (
            <div class={this.ns.b('form-content')} key={data.srfkey}>
              {formComponent}
              <div class={this.ns.b('btn')}>
                <i-button
                  class={this.ns.b('remove-btn')}
                  type='text'
                  on-click={() => this.c.handleRemove(data, index)}
                >
                  删除
                </i-button>
              </div>
            </div>
          );
        })
      );
    };

    const renderMainContent = () => {
      return (
        <div class={this.ns.b('main')}>
          {[
            <div class={this.ns.b('title')}>
              <span class={this.ns.b('caption')}>
                {this.modelData.source.caption}
              </span>
              <i-button
                class={this.ns.b('add-btn')}
                type='text'
                on-click={() => this.c.handleAdd()}
              >
                添加
              </i-button>
            </div>,
            renderFormContent(),
          ]}
        </div>
      );
    };

    return <div class={this.ns.b()}>{renderMainContent()}</div>;
  },
});

export default FormMDCtrl;
