<template>
  <div v-if="valueType">
    <template v-if="valueType === 'switch'">
      <el-switch :disabled="disabled" v-model="newValue" active-text="是" inactive-text="否" @change="handleChange">
      </el-switch>
    </template>
    <template v-else-if="valueType === 'inputNumber'">
      <el-input-number :disabled="disabled" v-model="newValue" @change="handleChange"></el-input-number>
    </template>
    <el-input v-else-if="valueType === 'json'" type="textarea" placeholder="请输入内容" v-model="newValue" @change="handleChange"/>
    <template v-else>
      <el-input :disabled="disabled" v-model="newValue" placeholder="" @change="handleChange"></el-input>
    </template>
  </div>
</template>
<script>
export default {
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    value: {
      type: String | Number | Boolean | Object | Array,
      default: ''
    },
    type: {
      type: String,
      default: ''
    }
  },
  computed: {
    valueType() {
      // 根据value的类型判断type
      if (typeof this.value === 'boolean') {
        return 'switch';
      } else if (typeof this.value === 'number') {
        return 'inputNumber';
      } else if (['[object Object]', '[object Array]'].includes(Object.prototype.toString.apply(this.value))) {
        return 'json';
      } else {
        return 'text';
      }
    },
    validType() {
      return this.type || this.valueType;
    }
  },
  data() {
    return {
      newValue: ''
    };
  },
  created() {
    this.newValue = typeof this.value === 'object' ? JSON.stringify(this.value) : this.value;
  },
  methods: {
    handleChange() {
      console.info(this.valueType, this.validType)
      if (this.validType === 'json') {
        try {
          console.log(JSON.parse(this.newValue))
          this.$emit('input', JSON.parse(this.newValue));
        } catch (e) {
          this.$message.error('请输入正确的json格式');
        }
      } else {
        this.$emit('input', this.newValue);
      }
    }
  }
};
</script>
<style lang="scss" scoped></style>
