<template>
  <el-dialog
    title="新建标签"
    width="30%"
    :visible.sync="modal"
    :close-on-click-modal="false"
    @close="$emit('cancel')"
  >
    <el-form ref="ruleForm" :model="form" :rules="rules">
      <el-form-item label="标签类型" prop="type" label-width="80px">
        <el-radio-group v-model="form.type">
          <el-radio
            v-for="item in options"
            :key="item.value"
            :label="item.value"
          >{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="标签名称" prop="name" label-width="80px">
        <el-input v-model="form.name" autocomplete="off" :maxlength="nameMaxLength" />
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="handleSubmit('ruleForm')">提交</el-button>
      <el-button @click="modal = false">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { saveItem } from '@/model/tag'
import EMITKEY from '@/const/emitNameKey'
import MODULETYPE from '@/const/moduleType'

const constData = ({
  nameMaxLength: '230'
})

export default {
  name: 'TagAddItem',

  props: {
    tagType: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      modal: true,
      options: MODULETYPE.TAG_ADD_TYPE,
      ...constData,
      form: {
        type: '',
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入标签名称', trigger: 'blur' },
          { max: 10, message: `不超过${this.nameMaxLength}个汉字`, trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择标签类型', trigger: 'change' }
        ]
      }
    }
  },

  watch: {
    tagType: {
      handler(val) {
        this.form.type = val
      },
      immediate: true
    }
  },

  methods: {
    handleSubmit(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.saveData()
        }
      })
    },
    async saveData() {
      const { success, msg } = await saveItem({
        data: {
          name: this.form.name,
          moduleType: this.form.type,
          // 默认数值
          isShow: true,
          sort: 0
        }
      })
      if (success) {
        this.$message.success('新增成功~')
        this.bus.$emit(EMITKEY.TAGRELOAD)
        this.modal = false
      } else {
        this.$message.error(msg)
      }
    }
  }
}
</script>

<style scoped>
.btn-right {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
</style>
