<template>
  <el-tabs v-model="activeTab" type="card">
    <el-tab-pane label="设定值" name="process">
      <el-alert
        v-if="type || code"
        :title="[type, code].filter(Boolean).join(' / ')"
        type="info"
        :closable="false"
        show-icon
        style="margin-bottom:12px"
      />
      <el-input v-model="textarea" type="textarea" :rows="15" placeholder="请输入内容" />
    </el-tab-pane>
    <el-tab-pane label="json" name="json">
      <tree-view :data="json" />
    </el-tab-pane>
  </el-tabs>
</template>

<script>
function parseSetting (value) {
  if (value === undefined || value === null || value === '') return { process: {} }
  if (typeof value === 'object') return JSON.parse(JSON.stringify(value))
  try {
    return JSON.parse(value)
  } catch (e) {
    return { process: {} }
  }
}

export default {
  name: 'ProcessStepJsonSettingPlugin',
  props: {
    settingJson: { default: '' },
    type: { type: String, default: '' },
    code: { type: String, default: '' }
  },
  data () {
    return {
      activeTab: 'process',
      json: { process: {} },
      textarea: '{}'
    }
  },
  watch: {
    settingJson: {
      handler (val) {
        this.json = parseSetting(val)
        this.textarea = JSON.stringify(this.json.process || {}, null, 2)
      },
      immediate: true
    }
  },
  methods: {
    handleFormSubmit () {
      if (!this.textarea) {
        this.$message.info('输入内容不能为空')
        return
      }
      try {
        this.json.process = JSON.parse(this.textarea)
        this.$emit('submit', this.json)
      } catch (e) {
        this.$message.error('JSON 格式不正确')
      }
    }
  }
}
</script>
