<template>
  <a-modal
    :visible="isModal"
    :title="title"
    :width="width"
    @cancel="handleClose"
    @ok="formSubmit"
    :confirmLoading="subLoading"
    destroyOnClose
  >
    <a-form-model
      ref="formRef"
      :model="formParams"
      :rules="rules"
      :labelCol="{ span: 5 }"
      :wrapperCol="{ span: 18 }"
    >
      <a-form-model-item label="分组名称" prop="name">
        <a-input v-model="formParams.name" placeholder="请输入分组名称" />
      </a-form-model-item>
    </a-form-model>

    <template slot="footer">
      <a-button @click="handleReset">重置</a-button>
      <a-button type="primary" :loading="subLoading" @click="formSubmit">提交</a-button>
    </template>
  </a-modal>
</template>

<script>
import { postAction, putAction } from '@api/manage'

export default {
  name: 'FormGroupModal',
  props: {
    title: {
      type: String,
      default: '创建分组'
    },
    width: {
      type: Number,
      default: 450
    }
  },
  data() {
    return {
      isModal: false,
      subLoading: false,
      formRef: null,
      formParams: {
        id: null,
        name: ''
      },
      rules: {
        name: [
          { required: true, message: '分组名称不能为空', trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    defaultValue() {
      return {
        id: null,
        name: ''
      };
    },
    openModal({ id, name }) {
      this.formParams = Object.assign({}, this.defaultValue());
      if (id) {
        this.formParams.id = id;
        this.formParams.name = name;
      }
      this.isModal = true;
    },
    closeModal() {
      this.isModal = false;
    },
    handleReset() {
      if (this.$refs.formRef) {
        this.$refs.formRef.resetFields();
      }
      this.formParams = Object.assign({}, this.defaultValue());
    },
    handleClose() {
      this.isModal = false;
    },
    formSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.subLoading = true;
          const request = this.formParams.id
            ? putAction('/workflow/group',this.formParams)
            : postAction('/workflow/group',this.formParams);

          request.then(() => {
            this.$message.success(this.formParams.id ? '编辑成功' : '添加成功');
            this.handleReset();
            this.closeModal();
          }).catch(() => {
            this.$message.error('操作失败');
          }).finally(() => {
            this.$emit('change');
            this.subLoading = false;
          });
        } else {
          this.$message.error('请填写完整信息');
        }
      });
    }
  }
};
</script>
