import { ref, defineComponent, Ref, watch } from 'vue';
import { getSpanProps, useNamespace } from '@ibiz-template/vue-util';
import dayjs from 'dayjs';
import '@ibiz-template/theme/style/components/editor/ibiz-span/ibiz-span.scss';

export const IBizSpan = defineComponent({
  name: 'IBizSpan',
  props: getSpanProps(),
  setup(props) {
    const ns = useNamespace('span');
    const c = props.controller;

    const text: Ref<string> = ref('');

    watch(
      () => props.value,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          if (!newVal) {
            text.value = '';
            return;
          }
          if (c.valueFormat) {
            text.value = dayjs(newVal).format(c.valueFormat);
          } else {
            text.value = newVal || '';
          }
          if (c.unitName) {
            text.value += c.unitName;
          }
        }
      },
      {
        immediate: true,
      },
    );

    return {
      ns,
      text,
    };
  },
  render() {
    return <span class={this.ns.b()}>{this.text}</span>;
  },
});
