<template>
  <el-tabs v-model="activeTab" type="card">
    <el-tab-pane :label="$t(key('setting_value'))" 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="$t(key('enter_content'))" />
    </el-tab-pane>
    <el-tab-pane label="json" name="json">
      <tree-view :data="json" />
    </el-tab-pane>
  </el-tabs>
</template>

<script>
import { i18nMixin } from '@/composables/useI18n'

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',
  mixins: [i18nMixin('page.production_master_data.process_model.process_step')],
  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(this.$t(this.key('content_required')))
        return
      }
      try {
        this.json.process = JSON.parse(this.textarea)
        this.$emit('submit', this.json)
      } catch (e) {
        this.$message.error(this.$t(this.key('json_format_invalid')))
      }
    }
  }
}
</script>
