<template>
  <div class="fx-column">
    <div v-if="hiddenFormatter" class="fx-row fx-end-cen mb10">
      <span class="mr10 f12">内容为字符串时可尝试强制转换器</span>
      <el-radio-group v-model="formatterKey" size="mini">
        <el-radio-button v-for="f in formatters" :key="f.label" :name="f.label" :label="f.label"></el-radio-button>
      </el-radio-group>
    </div>
    <vue-json-editor v-model="formatJson"></vue-json-editor>
  </div>
</template>

<script>
/* NOTE: 包装v-json-editor, 带转化功能，可尝试转化Object, Array */
import VueJsonEditor from 'vue-json-editor'

const sharedGet = (val, vm) => {
  if (!val) return val
  try {
    return JSON.parse(val)
  } catch (e) {
    console.log('sharedGet error', e)
    vm.msgError(e)
    return val
  }
}
const sharedSet = (val, vm) => {
  if (!val) return val
  try {
    return JSON.stringify(val)
  } catch (e) {
    console.log('sharedSet error', e)
    vm.msgError(e)
    return val
  }
}

export default {
  name: "json-editor",
  components: {VueJsonEditor},
  model: {
    prop: 'json',
    event: 'change'
  },
  props: ['json', 'hiddenFormatter'],
  data() {
    return {
      formatters: [{
        label: 'Normal',
        onGet: (val) => val,
        onSet: (val) => val
      }, {
        label: 'Formatter',
        onGet: sharedGet,
        onSet: sharedSet
      }],
      formatterKey: 'Normal'
    }
  },
  computed: {
    formatter() {
      return this.formatters.find(f => f.label === this.formatterKey)
    },
    formatJson: {
      get: function () {
        return this.formatter.onGet(this.json, this)
      },
      set: function (val) {
        this.$emit('change', this.formatter.onSet(val, this))
      }
    }
  },
  methods: {
    handleChange(e) {
      console.log('trigger change', e)
    }
  }
}
</script>

<style scoped>

</style>
