<template>
  <json-editor-vue
    :currentMode="currentMode"
    v-model="dataValue"
    language="zh-CN"
    :options="{ mainMenuBar: false }"
    @update:modelValue="dataValueChange"
    @click="dataValueClick"
    @blur="dataValueBlur"
    @focus="dataValueFocus"
    :style="{ height: (props.record?.itemHeight || 200) + 'px' }"
  ></json-editor-vue>
</template>

<script setup name="FormJson">
import { ref, onMounted, watch, computed } from 'vue';
import JsonEditorVue from 'json-editor-vue3';

const props = defineProps({
  value: {
    type: String,
    default: ''
  },
  //是否禁用
  disabled: {
    type: Boolean,
    default: false
  },
  record: {
    type: Object,
    default: {}
  },
  placeholder: {
    type: String,
    default: '请输入'
  },
  // 是否只读
  readonly: {
    type: Boolean,
    default: false
  }
});

const emits = defineEmits(['update:value', 'change', 'onBlur', 'onClick', 'onChange', 'onFocus']);

// 选中的值
const dataValue = ref({});

// 当前模式
const currentMode = computed(() => {
  if (props.readonly || props.disabled) {
    return 'view';
  }
  return 'code';
});

onMounted(() => {
  setDataValue();
});

watch(
  () => props.value,
  val => {
    setDataValue();
  },
  { deep: true }
);

// 设置值
const setDataValue = () => {
  if (props.value) {
    dataValue.value = JSON.parse(props.value);
  } else {
    dataValue.value = {};
  }
};

// 更改值
const dataValueChange = () => {
  emits('update:value', JSON.stringify(dataValue.value));
  emits('change', JSON.stringify(dataValue.value));
  emits('onChange', props.record);
};
// 点击
const dataValueClick = () => {
  emits('onClick', props.record);
};
// 失去焦点
const dataValueBlur = () => {
  emits('onBlur', props.record);
};
// 获取焦点
const dataValueFocus = () => {
  emits('onFocus', props.record);
};
</script>

<style></style>
