<template>
  <my-dialog
    :visible="visible"
    :header="title"
    :width="500"
    attach="body"
    :closeOnOverlayClick="false"
    @close="emit('update:visible', false)"
  >
    <t-form ref="formRef" :data="formData" :rules="rules" labelAlign="top">
      <t-form-item label="角色名称" name="name">
        <t-input v-model="formData.name" clearable></t-input>
      </t-form-item>
    </t-form>
    <template #foot>
      <t-button theme="default" @click="emit('update:visible', false)"
        >取消</t-button
      >
      <t-button theme="primary" @click="save">保存</t-button>
    </template>
  </my-dialog>
</template>

<script setup name="AddRoleDialog">
import useClearDialog from '@/hooks/useClearDialog';
import { ref, computed } from 'vue';
import { addRole } from '@/api/user';

const props = defineProps({
  visible: Boolean,
  curRow: Object,
});
const emit = defineEmits(['update:visible']);

const title = computed(() => {
  return (isEdit.value ? '编辑' : '新增') + '角色';
});

const formRef = ref(null);
const rules = {
  name: [
    {
      required: true,
      message: '请输入角色名',
      type: 'error',
      trigger: 'change',
    },
  ],
};

const getDetail = () => {
  formData.id = props.curRow.id || null;
  formData.name = props.curRow.name;
};
const { formData, isEdit } = useClearDialog(
  {
    id: '',
    name: '',
    privilegeIds: [],
  },
  props,
  formRef,
  getDetail
);

const save = async () => {
  const valid = await formRef.value.validate();
  if (valid !== true) return;

  const res = await addRole(formData).catch(() => {});
  if (!res) return;

  MessagePlugin.success('保存成功');
  emit('update:visible', false);
  emit('success');
};
</script>
