<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="名称" 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="handleEditClick(formRef)"
          >编辑</el-button
        >
        <el-button @click="handleResetClick(formRef)">重置</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { reactive, ref, watch } from 'vue';
import { editRole } from '~/service/role';
import { isEmptyObject } from '~/utils/index';
const formRef = ref();

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

const dialogVisible = ref(!isEmptyObject(props.modelValue));

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

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

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

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