<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :append-to-body="true"
    :close-on-click-modal="false"
    :before-close="handleClose"
    :width="width"
  >
    <div class="setting-content">
      <el-alert
        :title="settingTip"
        type="info"
        :closable="false"
        show-icon
      />
      <div class="setting-meta">
        <el-tag v-if="type" type="warning" size="mini">{{ type }}</el-tag>
        <el-tag v-if="code" type="info" size="mini">{{ code }}</el-tag>
      </div>
      <el-input
        v-model="jsonText"
        type="textarea"
        :rows="16"
        resize="vertical"
        :placeholder="jsonPlaceholder"
      />
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">{{ $t(key('cancel')) }}</el-button>
      <el-button type="primary" @click="handleSubmit">{{ $t(key('confirm')) }}</el-button>
    </div>
  </el-dialog>
</template>

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

export default {
  name: 'ProcessStepSettingDialog',
  mixins: [i18nMixin('page.production_master_data.process_model.process_step')],
  props: {
    type: {
      type: String,
      default: ''
    },
    code: {
      type: String,
      default: ''
    },
    title: {
      type: String,
      default: ''
    },
    width: {
      type: String,
      default: '50%'
    },
    visible: {
      type: Boolean,
      default: false
    },
    pluginData: {
      default: ''
    }
  },
  data () {
    return {
      jsonText: ''
    }
  },
  computed: {
    settingTip () {
      return this.$t(this.key('setting_tip'))
    },
    jsonPlaceholder () {
      return '{\n  "key": "value"\n}'
    }
  },
  watch: {
    visible: {
      handler (val) {
        if (val) {
          this.resetJsonText()
        }
      },
      immediate: true
    },
    pluginData: {
      handler () {
        if (this.visible) {
          this.resetJsonText()
        }
      },
      deep: true
    }
  },
  methods: {
    resetJsonText () {
      const data = this.pluginData
      if (data === undefined || data === null || data === '') {
        this.jsonText = '{}'
        return
      }
      if (typeof data === 'string') {
        this.jsonText = data.trim() ? data : '{}'
        return
      }
      this.jsonText = JSON.stringify(data, null, 2)
    },
    handleClose () {
      this.$emit('close')
    },
    handleSubmit () {
      const raw = (this.jsonText || '').trim()
      if (!raw) {
        this.$emit('submit', {})
        return
      }
      try {
        const parsed = JSON.parse(raw)
        this.$emit('submit', parsed)
      } catch (error) {
        this.$message.error('JSON 格式不正确')
      }
    }
  }
}
</script>

<style scoped>
.setting-content {
  padding: 10px 0;
}
.setting-meta {
  margin: 16px 0 12px;
  display: flex;
  gap: 8px;
}
</style>
