<template>
  <a-modal :visible="visible" :title="modalTitle" :width="500" @cancel="onCancel" @ok="onSubmit">
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-model-item ref="name" label="名称" prop="name">
        <a-input v-model="form.name" />
      </a-form-model-item>
      <a-form-model-item ref="code" label="编码" prop="code">
        <a-input v-model="form.code" />
      </a-form-model-item>
      <a-form-model-item ref="sort" label="排序" prop="sort">
        <a-input-number v-model="form.sort" />
      </a-form-model-item>
      <a-form-model-item ref="remark" label="备注" prop="remark">
        <a-textarea :rows="4" v-model="form.remark" >
        </a-textarea>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
  import {
    roleAdd,
    roleEdit
  } from '@/api/security/role'

  export default {
    props: {
      id: {
        type: String,
        default: undefined
      }
    },
    data() {
      return {
        modalTitle: '新增角色',
        visible: false,
        labelCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 5
          }
        },
        wrapperCol: {
          xs: {
            span: 24
          },
          sm: {
            span: 18
          }
        },
        form: {
          name: '',
          code: '',
          sort: 0,
          remark: ''
        },
        rules: {
          name: [{
            required: true,
            message: '请输入角色名称',
            trigger: 'blur'
          }],
          code: [{
            required: true,
            message: '请输入编码',
            trigger: 'blur'
          }]
        }
      }
    },
    methods: {
      add() {
        this.modalTitle = '新增角色'
        this.visible = true
      },
      edit(obj) {
        this.modalTitle = '修改角色'
        this.visible = true
        this.form = obj
      },
      onSubmit(e) {
        this.$refs.ruleForm.validate(valid => {
          if (valid) {
            if (this.form.id) {
              roleEdit(this.form).then(res => {
                if (res.code == 200) {
                  this.$message.success('编辑成功')
                  this.onCancel()
                } else {
                  this.$message.error('编辑失败：' + res.msg)
                }
              })
            } else {
              roleAdd(this.form).then(data => {
                if (res.code == 200) {
                  this.$message.success('新增成功')
                  this.onCancel()
                } else {
                  this.$message.error('新增失败：' + res.msg)
                }
              })
            }
          } else {
            return false
          }
        })
      },
      onCancel() {
        this.$refs.ruleForm.resetFields()
        this.visible = false
      }
    }
  }
</script>
