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.disabled ? this.ns.m('disabled') : '',
          this.readonly ? this.ns.m('readonly') : '',
        ]}
      >
        {this.readonly ? (
          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} disabled={this.disabled}>
                <span class={this.ns.e('text')}>{_item.text}</span>
              </i-radio>
            ))}
          </i-radio-group>
        )}
      </div>
    );
  },
});
