import { ref, defineComponent, Ref, watch } from 'vue';
import type { PropType } from 'vue';
import { SpanEditorController } from '@ibiz-template/controller';
import { useNamespace } from '@ibiz-template/vue-util';
import '@/styles/components/editor/ibiz-span/ibiz-span.scss';
import dayjs from 'dayjs';

export default defineComponent({
  props: {
    value: String,
    controller: {
      type: SpanEditorController,
      required: true,
    },
    data: {
      type: Object as PropType<IData>,
      required: true,
    },
  },
  setup(props) {
    const ns = useNamespace('span');
    const c = props.controller;

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

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

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