<template>
  <schema-table
    ref="table"
    :schema="schema"
  >
    <confirm-dialog
      ref="editDialog"
      :title="dialogTitle"
      @confirm="onSave"
    >
      <div class="c-grid-form u-align-self--center">
        <span class="c-grid-form__label required">名称：</span>
        <el-input
          v-model.trim="currObj.name"
          placeholder="最多50个字符"
          maxlength="50"
          clearable
        />
        <span class="c-grid-form__label">备注：</span>
        <el-input
          v-model.trim="currObj.remark"
          type="textarea"
          maxlength="100"
          :rows="3"
          show-word-limit
        />
      </div>
    </confirm-dialog>
  </schema-table>
</template>

<script>
import {
  getProductTypes,
  addProductType,
  updateProductType,
  deleteProductType
} from '@/api/device'

export default {
  name: 'ProductType',
  props: {
    group: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      isAdd: false,
      currObj: {},
      schema: {
        condition: { name: '', tenant: this.group.path },
        list: getProductTypes,
        buttons: [
          { type: 'add', on: this.onAdd }
        ],
        cols: [
          { prop: 'name', label: '类型名称' },
          { prop: 'remark', label: '备注' },
          { type: 'invoke', render: [
            { label: '编辑', on: this.onEdit },
            { label: '删除', on: this.onDel }
          ] }
        ]
      }
    }
  },
  computed: {
    tenant () {
      return this.group.path
    },
    dialogTitle () {
      return this.isAdd ? `新增产品类型` : `编辑产品类型`
    }
  },
  methods: {
    onAdd () {
      this.isAdd = true
      this.currObj = {
        name: '',
        remark: '',
        tenant: this.tenant
      }
      this.$refs.editDialog.show()
    },
    onEdit (productType) {
      this.isAdd = false
      const { id, name, remark } = productType
      this.currObj = { id, name, remark }
      this.$currObj = productType
      this.$refs.editDialog.show()
    },
    onSave (done) {
      if (!this.currObj.name) {
        this.$message({
          type: 'warning',
          message: '产品分类名称不能为空'
        })
        return
      }
      this.save(done).then(() => {
        this.$refs.table.pageTo(this.isAdd ? 1 : 0)
      })
    },
    save (done) {
      if (!this.isAdd && Object.keys(this.currObj).every(key => this.currObj[key] === this.$currObj[key])) {
        done()
        return Promise.reject()
      }
      return (this.isAdd ? addProductType : updateProductType)(this.currObj).then(done)
    },
    onDel (product) {
      return deleteProductType(product).then(() => {
        this.$refs.table.decrease(1)
      })
    }
  }
}
</script>
