<template>
  <switch class="cv-switch-switch" :disabled="disabled" name="checked" :checked="checked" @change="handleChange" />
</template>
<script>
import mpMixin from '../../libs/mixin/mpMixin.js';
import mixin from '../../libs/mixin/mixin.js';
export default {
  mixins: [mpMixin, mixin],
  name: 'cvSwitch',
  emits: ['input', 'update:modelValue'],
  props: {
    value: {
      type: [Number, String, Boolean],
      default: 0
    },
    modelValue: {
      type: [Number, String, Boolean],
      default: 0
    },
    disabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      localVal: 0,
      itemsValue: '',
      dataType: 'Number',
      checked: false
    };
  },
  watch: {
    value(newVal) {
      this.localVal = newVal;
      this._dealDataList();
    },
    modelValue(newVal) {
      this.localVal = newVal;
      this._dealDataList();
    }
  },
  created() {
    this.localVal = this.doValueGet();
    this._dealDataList();
  },
  methods: {
    doValueGet() {
      if (this.value === '') return this.modelValue;
      if (this.modelValue === '') return this.value;
      return this.value;
    },
    /* 整理数据 */
    _dealDataList() {
      this.dataType = typeof this.localVal;
      switch (this.dataType) {
        case 'boolean':
          this.checked = this.localVal;
          break;
        case 'number':
          if (this.localVal === 1) {
            this.checked = true;
          } else {
            this.checked = false;
          }
          break;
        case 'string':
          if (this.localVal === '1') {
            this.checked = true;
          } else {
            this.checked = false;
          }
          break;
      }
    },
    handleChange: function (e) {
      this.checked = e.detail.value;
      this.funcOnInput();
    },
    funcOnInput() {
      switch (this.dataType) {
        case 'boolean':
          this.localVal = this.checked;
          break;
        case 'number':
          if (this.checked == true) {
            this.localVal = 1;
          } else {
            this.localVal = 0;
          }
          break;
        case 'string':
          if (this.checked == true) {
            this.localVal = '1';
          } else {
            this.localVal = '0';
          }
          break;
      }
      this.$emit('input', this.localVal);
      this.$emit('update:modelValue', this.localVal);
    }
  }
};
</script>

<style>
.cv-switch-switch {
  transform: scale(0.7);
  position: absolute;
  right: 2px;
}
</style>
