<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    :width="width"
    append-to-body
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <wait-plugin
      v-if="type === 'WaitPlugin'"
      ref="plugin"
      :setting-json="pluginData"
      @submit="handleChildSubmit"
    />
    <json-plugin
      v-else
      ref="plugin"
      :setting-json="pluginData"
      :plugin-type="type"
      :workingsubclass-code="code"
      @submit="handleChildSubmit"
    />

    <div slot="footer">
      <el-button size="small" @click="handleClose">{{ $t(key('cancel')) }}</el-button>
      <el-button type="primary" size="small" @click="handleFormSubmit">{{ $t(key('confirm')) }}</el-button>
    </div>
  </el-dialog>
</template>

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

function parseSettingJson (value) {
  if (value === undefined || value === null || value === '') return { process: {} }
  if (typeof value === 'object') return value
  try {
    return JSON.parse(value)
  } catch (e) {
    return { process: {} }
  }
}

const WaitPlugin = {
  name: 'ProcessRoutingWaitPlugin',
  mixins: [i18nMixin('page.production_master_data.process_model.process_routing.card')],
  props: {
    settingJson: { default: '' }
  },
  data () {
    return {
      form: { time: undefined, time_range: undefined, alert: '0' },
      rules: {
        time: [{ pattern: /^[0-9]\d*$/, message: this.key('integer_ge_0'), trigger: 'change' }],
        time_range: [{ pattern: /^[0-9]\d*$/, message: this.key('integer_ge_0'), trigger: 'change' }]
      }
    }
  },
  watch: {
    settingJson: {
      handler (val) {
        const json = parseSettingJson(val)
        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
    }
  },
  methods: {
    handleFormSubmit () {
      this.$refs.form.validate(valid => {
        if (!valid) {
          this.$message.error(this.$t(this.key('validation_fail')))
          return
        }
        this.$emit('submit', { process: { ...this.form } })
      })
    }
  },
  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>
  `
}

const JsonPlugin = {
  name: 'ProcessRoutingJsonPlugin',
  mixins: [i18nMixin('page.production_master_data.process_model.process_routing.card')],
  props: {
    settingJson: { default: '' },
    pluginType: { type: String, default: '' },
    workingsubclassCode: { type: String, default: '' }
  },
  data () {
    return {
      activeTab: 'process',
      jsonText: '{}',
      parsedJson: { process: {} }
    }
  },
  watch: {
    settingJson: {
      handler (val) {
        this.parsedJson = parseSettingJson(val)
        this.jsonText = JSON.stringify(this.parsedJson.process || {}, null, 2)
      },
      immediate: true
    }
  },
  methods: {
    handleFormSubmit () {
      if (!this.jsonText) {
        this.$message.error(this.$t(this.key('input_empty')))
        return
      }
      try {
        this.$emit('submit', { ...this.parsedJson, process: JSON.parse(this.jsonText) })
      } catch (e) {
        this.$message.error(this.$t(this.key('json_format_error')))
      }
    }
  },
  template: `
    <el-tabs v-model="activeTab" type="card">
      <el-tab-pane :label="$t(key('setting'))" name="process">
        <el-alert
          v-if="pluginType"
          :title="pluginType + (workingsubclassCode ? ' / ' + workingsubclassCode : '')"
          type="info"
          :closable="false"
          show-icon
          style="margin-bottom:12px"
        />
        <el-input
          v-model="jsonText"
          type="textarea"
          :rows="15"
          :placeholder="$t(key('enter_setting_json'))"
        />
      </el-tab-pane>
      <el-tab-pane label="JSON" name="json">
        <pre class="json-preview">{{ JSON.stringify(parsedJson, null, 2) }}</pre>
      </el-tab-pane>
    </el-tabs>
  `
}

export default {
  name: 'ProcessRoutingTechnologyFlowModel',
  components: { WaitPlugin, JsonPlugin },
  mixins: [i18nMixin('page.production_master_data.process_model.process_routing.card')],
  props: {
    type: { type: String, default: '' },
    code: { type: String, default: '' },
    title: { type: String, default: '' },
    width: { type: String, default: '35%' },
    visible: { type: Boolean, default: false },
    pluginData: { default: '' }
  },
  methods: {
    handleClose () {
      this.$emit('close')
    },
    handleFormSubmit () {
      this.$refs.plugin && this.$refs.plugin.handleFormSubmit()
    },
    handleChildSubmit (data) {
      this.$emit('submit', data)
    }
  }
}
</script>

<style scoped>
.json-preview {
  max-height: 360px;
  overflow: auto;
  padding: 12px;
  background: #f5f7fa;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}
</style>
