import { computed, defineComponent, ref } from 'vue';
import {
  getEditorEmits,
  getRadioProps,
  useNamespace,
} from '@ibiz-template/vue-util';
import '@ibiz-template/theme/style/components/editor/ibiz-radio/ibiz-radio.scss';

export const IBizRadio = defineComponent({
  name: 'IBizRadio',
  props: getRadioProps(),
  emits: getEditorEmits(),
  setup(props, { emit }) {
    const ns = useNamespace('radio');

    const c = props.controller;

    const editorModel = c.model;

    const onSelectValueChange = (value: string | number) => {
      emit('change', value);
    };

    // 代码表
    const items = ref<readonly IData[]>([]);

    props.controller.loadCodeList(props.data).then(codeList => {
      items.value = codeList;
    });

    const valueText = computed(() => {
      return items.value.find(item => item.value === props.value)?.text || '';
    });

    return {
      ns,
      editorModel,
      items,
      valueText,
      onSelectValueChange,
    };
  },
  render() {
    return (
      <div class={this.ns.b()}>
        {this.infoMode ? (
          this.valueText
        ) : (
          <i-radio-group
            class={this.ns.e('group')}
            value={this.value}
            on-on-change={this.onSelectValueChange}
          >
            {this.items.map((_item, index: number) => (
              <i-radio
                key={index}
                label={_item.value}
                readonly={this.editorModel.readOnly}
              >
                <span class={this.ns.e('text')}>{_item.text}</span>
              </i-radio>
            ))}
          </i-radio-group>
        )}
      </div>
    );
  },
});
