import { RadioButtonListEditorController } from '@ibiz-template/controller';
import { computed, defineComponent, ref } from 'vue';
import type { PropType } from 'vue';
import { useNamespace } from '@ibiz-template/vue-util';
import '@/styles/components/editor/ibiz-radio-button-list/ibiz-radio-button-list.scss';

export default defineComponent({
  props: {
    value: [String, Number],
    controller: {
      type: RadioButtonListEditorController,
      required: true,
    },
    data: {
      type: Object as PropType<IData>,
      required: true,
    },
  },
  emits: {
    change: (_value: string | number) => true,
  },
  setup(props, { emit }) {
    const ns = useNamespace('radio-button-list');

    const c = props.controller;

    const editorModel = c.model;

    const selectValue = computed({
      get() {
        return props.value || '';
      },
      set(newValue: string | number) {
        emit('change', newValue);
      },
    });

    const onSelectValueChange = (value: string | number) => {
      selectValue.value = value;
    };

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

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

    return {
      ns,
      editorModel,
      selectValue,
      items,
      onSelectValueChange,
    };
  },
  render() {
    return (
      <div class={this.ns.b()}>
        <i-radio-group
          class={this.ns.b('radio-group')}
          value={this.selectValue}
          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.be('radio-group', 'text')}>
                {_item.text}
              </span>
            </i-radio>
          ))}
        </i-radio-group>
      </div>
    );
  },
});
