<template>
  <el-tabs v-model="activeTab" type="card">
    <el-tab-pane :label="$t(key('setting_value'))" name="process">
      <div class="non-standard-setting">
        <div class="setting-search-card">
          <el-card class="box-card" style="height:550px">
            <div slot="header">
              <span>{{ $t(key('search')) }}</span>
            </div>
            <el-form label-position="top" :model="searchForm" size="mini">
              <el-form-item :label="$t(key('name'))">
                <el-input v-model.trim="searchForm.name" :placeholder="$t(key('enter_name'))" clearable />
              </el-form-item>
              <el-form-item :label="$t(key('param'))">
                <el-input v-model.trim="searchForm.code" :placeholder="$t(key('enter_param'))" clearable />
              </el-form-item>
            </el-form>
          </el-card>
        </div>
        <div class="setting-table">
          <el-table :data="filteredRows" border height="550" style="width:100%">
            <el-table-column prop="name" :label="$t(key('name'))" width="220" show-overflow-tooltip />
            <el-table-column prop="code" :label="$t(key('param'))" width="180" show-overflow-tooltip />
            <el-table-column prop="value" :label="$t(key('default_value'))" min-width="140" show-overflow-tooltip />
            <el-table-column :label="$t(key('unit'))" width="140" show-overflow-tooltip>
              <template slot-scope="{ row }">{{ unitMap[row.unit] || row.unit }}</template>
            </el-table-column>
            <el-table-column prop="remark" :label="$t(key('remark'))" min-width="160" show-overflow-tooltip />
            <el-table-column :label="$t(key('operation'))" width="100" fixed="right" align="center">
              <template slot-scope="{ row }">
                <el-button type="text" icon="el-icon-edit" @click="openEdit(row)" />
                <el-button type="text" icon="el-icon-delete" style="color:#F56C6C" @click="removeRow(row)" />
              </template>
            </el-table-column>
          </el-table>
          <div class="setting-actions">
            <el-button type="primary" size="small" @click="openAdd">{{ $t(key('add_row')) }}</el-button>
          </div>
        </div>
      </div>
      <el-dialog
        :title="editIndex >= 0 ? $t(key('edit')) : $t(key('add'))"
        :visible.sync="dialogVisible"
        append-to-body
        width="800px"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="100px" size="mini">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item :label="$t(key('param'))" prop="code">
                <el-input v-model="form.code" :placeholder="$t(key('enter_param'))" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t(key('name'))" prop="name">
                <el-input v-model="form.name" :placeholder="$t(key('enter_name'))" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t(key('default_value'))" prop="value">
                <el-input v-model="form.value" :placeholder="$t(key('enter_default_value'))" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t(key('unit'))" prop="unit">
                <el-select v-model="form.unit" :placeholder="$t(key('select_unit'))" filterable clearable style="width:100%">
                  <el-option
                    v-for="item in unitOptions"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code"
                  />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t(key('remark'))">
                <el-input v-model="form.remark" :placeholder="$t(key('enter_remark'))" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogVisible = false">{{ $t(key('cancel')) }}</el-button>
          <el-button type="primary" @click="submitRow">{{ $t(key('confirm')) }}</el-button>
        </div>
      </el-dialog>
    </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'
import { getUnitAll } from '@/api/production-master-data/material-unit'

function isJson (value) {
  if (typeof value !== 'string') return false
  try {
    JSON.parse(value)
    return true
  } catch (e) {
    return false
  }
}

function parseSetting (value, fallback = { process: [] }) {
  if (value === undefined || value === null || value === '') return JSON.parse(JSON.stringify(fallback))
  if (typeof value === 'object') return JSON.parse(JSON.stringify(value))
  if (isJson(value)) return JSON.parse(value)
  return JSON.parse(JSON.stringify(fallback))
}

export default {
  name: 'ProcessStepNonStandardSettingPlugin',
  mixins: [i18nMixin('page.production_master_data.process_model.process_step')],
  props: { settingJson: { default: '' } },
  data () {
    return {
      activeTab: 'process',
      json: { process: [] },
      rows: [],
      searchForm: { name: '', code: '' },
      dialogVisible: false,
      editIndex: -1,
      form: { code: '', name: '', value: '', unit: '', remark: '' },
      rules: {
        code: [{ required: true, message: this.$t(this.key('enter_param')), trigger: 'blur' }],
        name: [{ required: true, message: this.$t(this.key('enter_name')), trigger: 'blur' }],
        value: [{ required: true, message: this.$t(this.key('enter_default_value')), trigger: 'blur' }],
        unit: [{ required: true, message: this.$t(this.key('select_unit')), trigger: 'change' }]
      },
      unitOptions: [],
      unitMap: {}
    }
  },
  computed: {
    filteredRows () {
      const name = (this.searchForm.name || '').trim()
      const code = (this.searchForm.code || '').trim()
      return this.rows.filter(row => {
        const matchName = !name || String(row.name || '').includes(name)
        const matchCode = !code || String(row.code || '').includes(code)
        return matchName && matchCode
      })
    }
  },
  watch: {
    settingJson: {
      handler (val) {
        const parsed = parseSetting(val, { process: [] })
        const process = Array.isArray(parsed.process) ? parsed.process : []
        this.json = { ...parsed, process }
        this.rows = process.map(item => ({ ...item }))
      },
      immediate: true
    },
    rows: {
      handler (val) {
        this.json = { ...this.json, process: val.map(item => ({ ...item })) }
      },
      deep: true
    }
  },
  created () {
    getUnitAll().then(res => {
      const list = (res && res.data && (res.data.data || res.data.list || res.data)) || []
      this.unitOptions = Array.isArray(list) ? list : []
      this.unitMap = this.unitOptions.reduce((map, item) => {
        map[item.code] = item.name
        return map
      }, {})
    }).catch(() => {
      this.unitOptions = []
      this.unitMap = {}
    })
  },
  methods: {
    openAdd () {
      this.editIndex = -1
      this.form = { code: '', name: '', value: '', unit: '', remark: '' }
      this.dialogVisible = true
      this.$nextTick(() => this.$refs.form && this.$refs.form.clearValidate())
    },
    openEdit (row) {
      this.editIndex = this.rows.indexOf(row)
      this.form = { ...row }
      this.dialogVisible = true
      this.$nextTick(() => this.$refs.form && this.$refs.form.clearValidate())
    },
    removeRow (row) {
      const index = this.rows.indexOf(row)
      if (index !== -1) this.rows.splice(index, 1)
    },
    submitRow () {
      this.$refs.form.validate(valid => {
        if (!valid) return
        const duplicate = this.rows.some((item, index) => {
          return index !== this.editIndex && (item.name === this.form.name || item.code === this.form.code)
        })
        if (duplicate) {
          this.$message.error(this.$t(this.key('name_or_param_exists')))
          return
        }
        if (this.editIndex >= 0) {
          this.$set(this.rows, this.editIndex, { ...this.form })
        } else {
          this.rows.push({ ...this.form })
        }
        this.dialogVisible = false
      })
    },
    handleFormSubmit () {
      this.$emit('submit', this.json)
    }
  }
}
</script>

<style scoped>
.non-standard-setting {
  display: flex;
  flex-direction: row;
  justify-content: center;
}
.setting-search-card {
  width: 20%;
  margin-right: 20px;
}
.setting-table {
  width: 80%;
}
.setting-actions {
  margin-top: 10px;
  text-align: right;
}
</style>
