<template>
  <el-tabs v-model="activeTab" type="card">
    <el-tab-pane label="设定值" name="process">
      <div class="non-standard-setting">
        <div class="setting-search-card">
          <el-card class="box-card" style="height:550px">
            <div slot="header">
              <span>查询</span>
            </div>
            <el-form label-position="top" :model="searchForm" size="mini">
              <el-form-item label="名称">
                <el-input v-model.trim="searchForm.name" placeholder="请输入名称" clearable />
              </el-form-item>
              <el-form-item label="参数">
                <el-input v-model.trim="searchForm.code" placeholder="请输入参数" 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="名称" width="220" show-overflow-tooltip />
            <el-table-column prop="code" label="参数" width="180" show-overflow-tooltip />
            <el-table-column prop="value" label="默认值" min-width="140" show-overflow-tooltip />
            <el-table-column label="单位" width="140" show-overflow-tooltip>
              <template slot-scope="{ row }">{{ unitMap[row.unit] || row.unit }}</template>
            </el-table-column>
            <el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip />
            <el-table-column label="操作" 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">新增一行</el-button>
          </div>
        </div>
      </div>
      <el-dialog
        :title="editIndex >= 0 ? '编辑' : '新增'"
        :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="参数" prop="code">
                <el-input v-model="form.code" placeholder="请输入参数" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="名称" prop="name">
                <el-input v-model="form.name" placeholder="请输入名称" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="默认值" prop="value">
                <el-input v-model="form.value" placeholder="请输入默认值" clearable />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单位" prop="unit">
                <el-select v-model="form.unit" placeholder="请选择单位" 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="备注">
                <el-input v-model="form.remark" placeholder="请输入备注" clearable />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitRow">确定</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 { 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',
  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: '请输入参数', trigger: 'blur' }],
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        value: [{ required: true, message: '请输入默认值', trigger: 'blur' }],
        unit: [{ required: true, message: '请选择单位', 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('名称或参数已存在')
          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>
