import { getSwitchProps, useNamespace } from '@ibiz-template/vue-util';
import { defineComponent, ref, watch } from 'vue';

export const IBizSwitch = defineComponent({
  name: 'IBIzSwitch',
  props: getSwitchProps(),
  setup(props, { emit }) {
    const ns = useNamespace('switch');
    const currentVal = ref(false);

    watch(
      () => props.value,
      (newVal, oldVal) => {
        if (newVal !== oldVal) {
          if (!newVal) {
            currentVal.value = false;
          } else {
            // eslint-disable-next-line eqeqeq
            currentVal.value = props.value == 1;
          }
        }
      },
      { immediate: true },
    );

    const onChange = (value: boolean) => {
      const emitValue = value === true ? 1 : 0;
      emit('change', emitValue);
    };
    return {
      ns,
      currentVal,
      onChange,
    };
  },
  render() {
    return (
      <div class={this.ns.b()}>
        <i-switch
          disabled={this.disabled}
          v-model={this.currentVal}
          onOn-change={this.onChange}
        ></i-switch>
      </div>
    );
  },
});
