<!--
 * @Author: 曹捷
 * @Date: 2021-09-02 16:24:11
 * @LastEditors: 曹捷
 * @LastEditTime: 2022-01-06 20:19:43
 * @Description: 扩展 checkbox 不支持自定义 开和关的值
-->
<template>
  <a-checkbox v-model:checked="checked">
    <slot></slot>
  </a-checkbox>

</template>

<script>
import { reactive, toRefs, watch } from 'vue'
export default {
  emits: ['change', 'update:value'],
  props: {
    value: {
      type: [Boolean, String, Number]
    },
    // switch 打开时的值
    activeValue: {
      type: [Boolean, String, Number],
      default: '1'
    },
    // switch 关闭时的值	
    inactiveValue: {
      type: [Boolean, String, Number],
      default: '0'
    },
  },
  setup (props, context) {
    let _data = reactive({
      checked: props.value == props.activeValue
    })

    let methods = {
      sysnValueToChecked () {
        if (props.value === props.activeValue) {
          _data.checked = true
        } else if (props.value === props.inactiveValue) {
          _data.checked = false
        }
      }
    }
    watch(() => _data.checked, (value, oldvalue) => {
      if (oldvalue !== value) {
        context.emit('update:value', value ? props.activeValue : props.inactiveValue)
        context.emit("change", value ? props.activeValue : props.inactiveValue)
      }
    })
    watch(() => props.value, (value, oldvalue) => {
      if (oldvalue !== value) {
        methods.sysnValueToChecked()
      }
    })
    return {
      ...toRefs(_data),
      ...methods
    }
  }
}
</script>

<style>
</style>