<template>
  <div class="level-set-wrap">
    <Card>
      <div class="toolbar">
        <Button type="primary" icon="md-add" @click="openAdd">新增</Button>
      </div>
      <div class="table-wrap">
        <span class="table-tip">重要配置，请勿随意更改</span>
        <Table border :loading="loading" :columns="columns" :data="list">
          <template slot="action" slot-scope="{ row }">
            <Button size="small" type="primary" @click="openEdit(row)">修改</Button>
            <Poptip confirm title="确定删除该项？" placement="bottom" transfer class-name="level-set-poptip" @on-ok="doDelete(row)">
              <Button size="small" type="error" style="margin-left:8px">删除</Button>
            </Poptip>
          </template>
        </Table>
      </div>
    </Card>

    <Modal v-model="modal.visible" :title="modalTitle" width="520">
      <Form :model="form" :label-width="120" ref="form" :rules="rules">
        <FormItem label="评分等级" prop="value">
          <Input v-model="form.value" placeholder="如 A/B/C..." />
        </FormItem>
        <FormItem label="评分描述" prop="label">
          <Input v-model="form.label" placeholder="如 A类/B类..." />
        </FormItem>
        <FormItem label="排序" prop="sort">
          <Input v-model="form.sort" placeholder="数字，升序" />
        </FormItem>
      </Form>
      <div slot="footer">
        <Button @click="modal.visible=false">取消</Button>
        <Button type="primary" :loading="modal.submitting" @click="submit">保存</Button>
      </div>
    </Modal>
  </div>

</template>

<script>
import { selectLevelSetList, saveLevelSet, deleteLevelSet } from '@/api/key-person'
export default {
  name: 'key-person-level-set-index',
  data () {
    return {
      loading: false,
      list: [],
      columns: [
        { title: '评分等级', key: 'value', align: 'center', minWidth: 140 },
        { title: '评分描述', key: 'label', align: 'center', minWidth: 180 },
        { title: '排序(重要程度升序排序)', key: 'sort', align: 'center', minWidth: 120 },
        { title: '操作', slot: 'action', align: 'center', width: 160 }
      ],
      modal: { visible: false, submitting: false, isEdit: false },
      form: { id: '', value: '', label: '', sort: '' },
      rules: {
        value: [
          { required: true, message: '请输入评分等级', trigger: 'blur' },
          { validator: (r, v, cb) => (/^\S+$/.test(String(v || ''))) ? cb() : cb(new Error('评分等级不可为空格')), trigger: 'blur' }
        ],
        label: [{ required: true, message: '请输入评分描述', trigger: 'blur' }],
        sort: [
          { required: true, message: '请输入排序', trigger: 'blur' },
          { validator: (r, v, cb) => (/^-?\d+(\.\d+)?$/.test(String(v || ''))) ? cb() : cb(new Error('排序必须为数字')), trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    modalTitle () { return this.modal.isEdit ? '修改评分等级' : '新增评分等级' }
  },
  created () {
    this.loadList()
  },
  methods: {
    loadList () {
      this.loading = true
      selectLevelSetList({}).then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          const results = (ret.data.data && ret.data.data.results) || ret.data.data || []
          this.list = Array.isArray(results) ? results : []
        } else {
          this.$Notice.error({ title: '查询失败', desc: (ret && ret.data && ret.data.errmsg) || '' })
        }
      }).finally(() => { this.loading = false })
    },
    openAdd () {
      this.modal.isEdit = false
      this.form = { id: '', value: '', label: '', sort: '' }
      this.modal.visible = true
      this.$nextTick(() => { this.$refs.form && this.$refs.form.clearValidate() })
    },
    openEdit (row) {
      this.modal.isEdit = true
      this.form = { id: row.id || '', value: String(row.value || ''), label: row.label || '', sort: String(row.sort || '') }
      this.modal.visible = true
      this.$nextTick(() => { this.$refs.form && this.$refs.form.clearValidate() })
    },
    submit () {
      this.$refs.form.validate((valid) => {
        if (!valid) return
        // 前端再做一次重复校验（同 value 不可重复）
        const curId = this.form.id
        const curVal = String(this.form.value).trim()
        const dup = (this.list || []).some(it => String(it.value) === curVal && String(it.id) !== String(curId))
        if (dup) { this.$Message.error('评分等级已存在，不可重复'); return }
        this.modal.submitting = true
        const payload = { id: this.form.id, value: curVal, label: String(this.form.label || ''), sort: String(this.form.sort || '') }
        saveLevelSet(payload).then((ret) => {
          if (ret && ret.data && ret.data.errcode === 0) {
            this.$Notice.success({ title: '保存成功' })
            this.modal.visible = false
            this.loadList()
          } else {
            this.$Notice.error({ title: '保存失败', desc: (ret && ret.data && ret.data.errmsg) || '' })
          }
        }).finally(() => { this.modal.submitting = false })
      })
    },
    doDelete (row) {
      deleteLevelSet({ id: row.id }).then((ret) => {
        if (ret && ret.data && ret.data.errcode === 0) {
          this.$Notice.success({ title: '删除成功' })
          this.loadList()
        } else {
          this.$Notice.error({ title: '删除失败', desc: (ret && ret.data && ret.data.errmsg) || '' })
        }
      })
    }
  }
}
</script>

<style scoped>
.level-set-wrap { padding: 10px; }
.toolbar { margin-bottom: 10px; }
.table-wrap { position: relative; }
.table-tip { position: absolute; right: 0; top: -26px; color: #f00; font-size: 12px; }
/* hide default yellow help icon in confirm poptip for this page only */
.level-set-wrap >>> .ivu-poptip-confirm .ivu-poptip-body > i.ivu-icon { display: none; }
</style>
<style>
/* apply when transfer appends to body */
.level-set-poptip.ivu-poptip.ivu-poptip-confirm .ivu-poptip-body > i.ivu-icon { display: none; }
</style>
