<template>
  <div class="dsk-json-editor">
    <json-editor-vue class="dsk-json-editor-ins" v-model="modelValue" ref="dskJsonEditor" :mode.sync="mode" :readOnly="readOnly"
      @input="jsonChange"></json-editor-vue>
  </div>
</template>
<script>
import JsonEditorVue from 'json-editor-vue';
import { jsonEscape, jsonTraversal } from "@/utils";
export default {
  name: "dskJsonEditor",
  components: {
    JsonEditorVue
  },
  props: {
    jsonValue: {
      required: true,
      type: [Object, String],
      default: ""
    },
    defaultMode: {
      required: true,
      type: [String],
      default: "text"
    },
    jsonReadOnly: {
      required: true,
      type: [Boolean],
      default: false
    }
  },
  watch: {
    jsonValue: {
      handler(newValue) {
        this.modelValue = newValue;
      },
      deep: true
    }
  },
  data() {
    return {
      modelValue: this.jsonValue,
      mode: this.defaultMode,
      readOnly: this.jsonReadOnly
    };
  },
  //可访问data属性
  created() {

  },
  //计算集
  computed: {

  },
  //方法集
  methods: {
    validateJson() {
      return new Promise((resolve, reject) => {
        try {
          let isPass = false;
          // 验证通过
          if (!this.$refs["dskJsonEditor"].jsonEditor.validate()) {
            isPass = true;
            let jsonText = this.modelValue;
            // 初始默认对象
            if (Object.prototype.toString.call(jsonText) == "[object Object]") {
              // 对象转为json字符串
              jsonText = JSON.stringify(jsonText);
            }
            // 转换字符串 去除空格 换行符
            jsonText = jsonEscape(jsonText);
            // 特殊字符识别编码
            jsonText = JSON.stringify(jsonTraversal(JSON.parse(jsonText)));
            console.log(jsonText);
            return resolve({ isPass, value: jsonText });
          }
          resolve({ isPass });
        } catch (error) {
          console.log(error);
          reject(error);
        }
      });
    },
    jsonChange(e) {
      try {
        this.$emit("jsonChange", e);
      } catch (error) {
        console.log(error);
      }
    }
  },
}
</script>
<style lang="scss" scoped>
.dsk-json-editor {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  ::v-deep .dsk-json-editor-ins {
    width: 100%;
    height: 100%;
    .jsoneditor-vue {
      width: 100%;
      height: 100%;
    }
    .jsoneditor-poweredBy {
      display: none;
    }
  }
}
</style>
