<template>
  <div class="layout-no-flex">
    <el-toolbar>
      <el-button type="primary" @click="$router.back()" size="medium" round class="shadow-primary">
        <i class="fa fa-chevron-left"></i> 返回上页
      </el-button>
      <span class="button-separator"></span>
      <el-button :loading="confirmLoading" @click="confirmClickHandler" priv="Platform.Metadata.Save" >
        <i class="fa fa-save"></i>保存
      </el-button>
    </el-toolbar>
    <div class="detail-panel detail-form">
      <el-form :model="tmpColumnGroup" ref="form" label-width="200px" class="metadata-column-group-add-form" label-suffix="：">
        <el-form-item label="名称" prop="name" :verify="['NotNull']">
          <el-input v-model="tmpColumnGroup.name" @change="setAlias"></el-input>
        </el-form-item>
        <el-form-item label="代码" prop="code" :verify="['NotNull','Regex=^[a-zA-Z0-9_\.\-\/]+$|只能填写字母、数字、.、下划线、中划线']">
          <el-input v-model="tmpColumnGroup.code"></el-input>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>
<script>
import util from '@src/common/util.js'
export default {
  props: {
    modelID: {
      type: [Number, String],
      default: 0
    },
    code: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      confirmLoading: false,
      tmpColumnGroup: { name: '', code: '' } // form临时数据存储
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    setAlias() {
      if (this.tmpColumnGroup.code.trim()) {
        return
      }
      this.tmpColumnGroup.code = window.util.getSpell(
        this.tmpColumnGroup.name,
        true
      )
    },
    async confirmClickHandler() {
      this.confirmLoading = true
      try {
        await util.validateForm(this.$refs['form'])
        let res = ''
        if (this.code === 'new') {
          res = await axios.post(`/ui/metamodels/${this.modelID}/groups`, this.tmpColumnGroup)
        } else {
          res = await axios.put(`/ui/metamodels/${this.modelID}/groups/${this.code}`, this.tmpColumnGroup)
        }
        this.confirmLoading = false
        util.showResponseMessage(res.data)
        if (res.data.status === 1 && this.code === 'new') {
          let path = this.$route.path.replace('new', this.code)
          this.$router.replace(path)
        }
        if (res.data.status === 1) {
          this.$router.back()
        }
      } catch (e) {
        this.confirmLoading = false
        util.showErrorMessageBox(e)
      }
    },
    async loadData() {
      if (this.code && this.code !== 'new') {
        let res = await axios.get(`/ui/metamodels/${this.modelID}/groups/${this.code}`)
        this.tmpColumnGroup = res.data.data
      } else {
        this.tmpColumnGroup = { name: '', code: '' }
      }
    }
  }
}
</script>
<style>
.detail-form .is-required {
  display: block;
}
.metadata-column-group-add-form .el-form-item .el-input {
  width: 260px;
  margin-right: 5px;
}
</style>
