<template>
  <div class="layout-no-cols">
    <el-toolbar>
      <el-button @click="goBack" type="primary" size="medium" round class="shadow-primary"><i class="fa fa-chevron-left"></i> 返回上页</el-button>
      <span class="button-separator"></span>
      <el-button type="button" :priv=" isEdit() ? 'com.zving.cms.Link.Edit.'+ ID : 'LinkManage.Add'" class="el-button el-button--default save" :loading="confirmLoading" @click="confirm"><span><i class="fa fa-save"></i>保存</span></el-button>
    </el-toolbar>
      <!-- 链接分组表单 -->
    <div class="">
      <div class="detail-panel">
        <el-form :model="tmpLinksGroupData" ref="createLinksGroupForm" label-width="120px" v-loading="dataLoading">
          <el-form-item label="链接分类名称：" prop="name" :verify="['NotNull']">
            <el-input style="width:320px;" v-model="tmpLinksGroupData.name" @blur.prevent="setAlias"></el-input>
          </el-form-item>
          <el-form-item label="链接分类别名：" prop="code" :verify="['NotNull']">
            <el-input style="width:320px;" v-model="tmpLinksGroupData.code" :disabled="!!tmpLinksGroupData.ID"></el-input>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>

import util from '@src/common/util.js'
export default {
  props: {
    ID: {
      required: true
    }
  },

  data() {
    return {
      confirmLoading: false,
      dataLoading: false,
      tmpLinksGroupData: {
        name: '',
        code: ''
      }
    }
  },

  created() {
    if (this.isEdit()) {
      this.initData()
    }
  },

  methods: {
    async initData() {
      this.confirmLoading = false
      this.dataLoading = true
      try {
        let res = await axios.get(`/ui/links/${this.ID}`)
        this.tmpLinksGroupData = res.data.data
      } catch (e) {
      }
      this.dataLoading = false
    },
    // 新建/编辑分组确认按钮事件
    async confirm() {
      try {
        await util.validateForm(this.$refs['createLinksGroupForm'])
      } catch (e) {
        util.showErrorMessageBox(e)
        return
      }
      this.confirmLoading = true
      let linksGroupData = this.tmpLinksGroupData
      let res = this.isEdit() ? await axios.put(`/ui/links/${this.ID}`, linksGroupData) : await axios.post('/ui/links', linksGroupData)
      util.showResponseMessage(res.data)
      this.confirmLoading = false
      if (res.data.status === 1) {
        this.goBack()
      }
    },

    setAlias() {
      if (this.tmpLinksGroupData.code === '' && this.tmpLinksGroupData.name !== '') {
        this.tmpLinksGroupData.code = window.util.getSpell(this.tmpLinksGroupData.name, true)
      }
    },

    isEdit() {
      return this.ID && this.ID !== 'new'
    },

    goBack() {
      this.$router.back()
    }
  }
}

</script>
<style scoped>
  .form-item {
    width: 80%;
  }
</style>
