<template>
  <el-form ref="form" :inline="true" :model="form" :rules="rules" size="mini">
    <el-form-item :label="$t(key('rest_time'))" prop="time">
      <el-input v-model="form.time" :placeholder="$t(key('enter_rest_time'))" clearable>
        <template slot="append">{{ $t(key('minute')) }}</template>
      </el-input>
    </el-form-item>
    <el-form-item :label="$t(key('precision_range'))" prop="time_range">
      <el-input v-model="form.time_range" :placeholder="$t(key('enter_precision_range'))" clearable>
        <template slot="append">{{ $t(key('minute')) }}</template>
      </el-input>
    </el-form-item>
  </el-form>
</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: 'ProcessStepWaitSettingPlugin',
  mixins: [i18nMixin('page.production_master_data.process_model.process_step')],
  props: { settingJson: { default: '' } },
  data () {
    return {
      json: { process: {} },
      form: { time: undefined, time_range: undefined, alert: '0' },
      rules: {
        time: [{ pattern: /^[0-9]\d*$/, message: this.$t(this.key('non_negative_integer')), trigger: 'change' }],
        time_range: [{ pattern: /^[0-9]\d*$/, message: this.$t(this.key('non_negative_integer')), trigger: 'change' }]
      }
    }
  },
  watch: {
    settingJson: {
      handler (val) {
        const json = parseSetting(val)
        this.json = json
        this.form = {
          time: json.process && json.process.time !== undefined ? json.process.time : undefined,
          time_range: json.process && json.process.time_range !== undefined ? json.process.time_range : undefined,
          alert: json.process && json.process.alert !== undefined ? json.process.alert : '0'
        }
      },
      immediate: true
    },
    form: {
      handler (val) {
        this.json = { process: { ...val } }
      },
      deep: true
    }
  },
  methods: {
    handleFormSubmit () {
      this.$refs.form.validate(valid => {
        if (!valid) {
          this.$message.error(this.$t(this.key('validation_fail')))
          return
        }
        this.$emit('submit', this.json)
      })
    }
  }
}
</script>
