import { PropType, defineComponent, getCurrentInstance, ref, watch } from 'vue';
import { useHtmlViewController, useNamespace } from '@ibiz-template/vue-util';
import { IModal } from '@ibiz-template/runtime';
import { StringUtil } from '@ibiz-template/core';
import _404View from '../../../views/404-view/404-view';
import './html-view.scss';

export const HtmlView = defineComponent({
  name: 'IBizHtmlView',
  props: {
    context: Object as PropType<IContext>,
    params: { type: Object as PropType<IParams>, default: () => ({}) },
    modelPath: { type: String, required: true },
    modal: { type: Object as PropType<IModal> },
    state: { type: Object as PropType<IData> },
  },
  setup(props) {
    const ns = useNamespace('view');

    const { proxy } = getCurrentInstance()!;

    const c = useHtmlViewController(proxy, props.modelPath);

    const url = ref('');

    watch(
      () => c,
      () => {
        if (c.model && c.model.htmlUrl) {
          url.value = StringUtil.fill(c.model.htmlUrl, c.context, c.params);
        } else {
          url.value = '';
        }
      },
      {
        immediate: true,
        deep: true,
      },
    );

    c.beginViewLoading();
    const onLoad = () => {
      c.endViewLoading();
    };

    return { c, ns, url, onLoad };
  },
  render() {
    if (this.url) {
      return (
        <view-base class={this.ns.b()} controller={this.c}>
          <div class={[this.ns.b('dehtmlview')]}>
            <iframe
              src={this.url}
              onLoad={() => this.onLoad()}
              onError={() => this.onLoad()}
            ></iframe>
          </div>
        </view-base>
      );
    }
    return (
      <div class={this.ns.b()}>
        <_404View></_404View>
      </div>
    );
  },
});
