import { ref, watch, defineComponent } from 'vue';
import { useNamespace } from '@ibiz-template/vue-util';
import { isNil } from 'ramda';
import './code-list.scss';

export const CodeList = defineComponent({
  props: {
    codeListItems: {
      type: Array<IData>,
    },
    codeList: {
      type: Object,
      required: true,
    },
    value: {
      type: [String, Number],
    },
  },
  setup(props) {
    const ns = useNamespace('code-list');
    const items = ref<IData[]>([]);

    watch(
      () => props.value,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          if (isNil(newVal) || newVal === '') {
            // 空值置空
            items.value = [];
          } else {
            // 非空值解析代码表
            let values: string[] | number[];
            if (typeof newVal === 'string') {
              values = newVal.split(',');
            } else {
              values = [newVal];
            }
            items.value = values.map(val => {
              const findItem = props.codeListItems?.find(
                item => item.value === val,
              );
              return {
                text: findItem?.text || val,
                color: findItem?.color,
              };
            });
          }
        }
      },
      { immediate: true },
    );

    return { items, ns };
  },
  render() {
    if (this.items.length === 0) {
      return this.codeList.emptyText;
    }
    return (
      <span class={this.ns.b()}>
        {this.items.map((item, index) => {
          return [
            index !== 0 ? this.codeList?.textSeparator : null,
            <span
              class={this.ns.e('item')}
              style={this.ns.cssVarBlock({
                'item-color': `${item.color}`,
              })}
            >
              {item.text}
            </span>,
          ];
        })}
      </span>
    );
  },
});
