import { ElLoading } from 'element-plus'

import './switch.scss'

export default defineComponent({
  name: 'XBJSwitch',
  props: {
    modelValue: {
      type: [Number, String, Boolean],
      require: true,
    },
    activeValue: {
      type: [Number, String, Boolean],
    },
    inactiveValue: {
      type: [Number, String, Boolean],
    },
    activeText: {
      type: String,
      default: '启用',
    },
    inactiveText: {
      type: String,
      default: '停用',
    },
    beforeChange: {
      type: Function,
      default: () => true,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    loading: {
      type: Boolean,
      default: false,
    },
  },
  emits: ['update:modelValue'],
  setup(props, ctx) {
    const active = computed(() => {
      if (
        props.activeValue === undefined &&
        props.inactiveValue === undefined
      ) {
        return props.modelValue
      }
      if (props.activeValue === props.modelValue) {
        return true
      }
      if (props.inactiveValue === props.modelValue) {
        return false
      }
    })
    const click = async () => {
      if (props.disabled) return false
      try {
        if (await props.beforeChange()) {
          const v1 =
            props.inactiveValue === undefined
              ? props.modelValue
              : props.inactiveValue
          const v2 =
            props.activeValue === undefined
              ? props.modelValue
              : props.activeValue
          const value = active.value ? v1 : v2
          ctx.emit('update:modelValue', value)
        }
      } catch {}
    }
    const switch_com = ref<any>(null)
    let loadingInstance: any = null

    watch(
      () => props.loading,
      (loading) => {
        loading
          ? (loadingInstance = ElLoading.service({
              target: switch_com.value,
            }))
          : loadingInstance.close?.()
      },
    )

    return () => (
      <div
        class={[
          'switch-box',
          props.disabled || props.loading ? 'disabled' : '',
        ]}
        onClick={click}
      >
        <div
          class={['switch', active.value ? 'active' : 'deact']}
          ref={switch_com}
        >
          {active.value ? props.activeText : props.inactiveText}
        </div>
        <span class="switch-box-left">{props.inactiveText}</span>
        <span class="switch-box-right">{props.activeText}</span>
      </div>
    )
  },
})
