<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加角色"
    width="30%"
    @closed="closeDialog"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-position="top"
      style="max-width: 460px"
    >
      <el-form-item :label-width="labelWidth" label="名称" prop="role_name">
        <el-input v-model="formData.role_name" type="text"></el-input>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button type="primary" @click="handleAddClick(formRef)"
          >添加</el-button
        >
        <el-button @click="handleResetClick(formRef)">重置</el-button>
        <el-button @click="closeDialog()">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, toRef, watch } from 'vue';
import { addRole } from '~/service/role';
const formRef = ref();
const labelWidth = 90;

const props = defineProps({
  modelValue: Boolean,
  done: Function
});
const emits = defineEmits(['update:modelValue']);

const dialogVisible = ref(props.modelValue);

const rules = reactive({
  role_name: [
    {
      required: true,
      message: '请输入名称'
    }
  ]
});
const formData = reactive({
  user_name: ''
});

watch(props, v => {
  dialogVisible.value = v.modelValue;
});

const closeDialog = () => {
  handleResetClick(formRef.value);
  dialogVisible.value = false;
  emits('update:modelValue', false);
};

const handleAddClick = async formEl => {
  console.log(formEl);
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) {
      return;
    }
    const { code } = await addRole(formData);
    if (code == 0) {
      closeDialog();
      props.done();
    }
  });
};
const handleResetClick = async formEl => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>
