import { ref, defineComponent, Ref, watch, computed } 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';
import { CodeListItem } from '@ibiz-template/service';

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

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

    const codeList = c.model.codeList;
    // 值分隔符
    let valueSeparator = ',';
    if (codeList && codeList.valueSeparator) {
      valueSeparator = codeList.valueSeparator;
    }

    watch(
      () => props.value,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          if (newVal == null) {
            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,
      },
    );

    // 代码表数据
    const items = ref<readonly CodeListItem[]>([]);
    if (codeList) {
      watch(
        () => props.data,
        newVal => {
          c.loadCodeList(newVal).then(_codeList => {
            items.value = _codeList;
          });
        },
        {
          immediate: true,
          deep: true,
        },
      );
    }

    /** 代码表转换后文本 */
    const codeListText = computed(() => {
      if (!codeList || !props.value || items.value.length === 0) {
        return undefined;
      }
      if (codeList.codeItemValueNumber) {
        return items.value.find(item => item.value === props.value);
      }
      const values = (props.value as string).split(valueSeparator);
      const selects = items.value.filter(item =>
        values.includes(item.value as string & Number),
      );
      return selects.map(item => item.text).join(valueSeparator);
    });

    return {
      ns,
      text,
      codeListText,
    };
  },
  render() {
    let text = '';
    if (this.codeListText != null) {
      text = this.codeListText as string;
    } else if (this.text != null) {
      text = this.text;
    }
    return (
      <span
        class={[
          this.ns.b(),
          this.disabled ? this.ns.m('disabled') : '',
          this.readonly ? this.ns.m('readonly') : '',
        ]}
      >
        {text}
      </span>
    );
  },
});
