<script setup lang="ts">
import { insertRule, updateRule } from '@/api/system/role';
const props = defineProps({
  formRoleValue: {
    type: Object,
    default: () => ({}),
  },
});
const emit = defineEmits(['reloadTable']);
const formRef = ref();
const { formRoleValue } = toRefs(props);
const roleTitle = ref('新增角色');
const formBtnLoading = ref(false);
const showRoleModal = ref(false);
const rules = {
  roleName: {
    required: true,
    message: '请输入角色名称',
    trigger: 'blur',
  },
};

// 提交表单
const confirmForm = () => {
  formRef.value.validate(async (errors: any) => {
    if (!errors) {
      formRoleValue.value.id ? updateRuleApi() : insertRuleApi();
    }
  });
};

// 修改
const updateRuleApi = async () => {
  const { roleName, description, status, id } = formRoleValue.value;
  const params = {
    id,
    roleName,
    description,
    status,
  };
  const res = await updateRule(params);
  if (res.status === 200) window['$message'].success('修改成功!');
  close();
  emit('reloadTable');
};

// 新增
const insertRuleApi = async () => {
  const { roleName, description, status } = formRoleValue.value;
  const params = {
    roleName,
    description,
    status,
  };
  const res = await insertRule(params);
  if (res.status === 200) window['$message'].success('新增成功!');
  close();
  emit('reloadTable');
};

const init = (str: string) => {
  str === 'add'
    ? (roleTitle.value = '新增角色')
    : (roleTitle.value = '编辑角色');
  showRoleModal.value = true;
};

const close = () => {
  showRoleModal.value = false;
};
defineExpose({
  init,
  close,
});
</script>

<template>
  <!-- 新增角色 -->
  <n-modal
    v-model:show="showRoleModal"
    :show-icon="false"
    preset="dialog"
    :title="roleTitle"
  >
    <n-form
      ref="formRef"
      :rules="rules"
      label-placement="left"
      label-width="auto"
      :model="formRoleValue"
      require-mark-placement="right-hanging"
    >
      <n-form-item label="角色名称" path="roleName">
        <n-input
          v-model:value="formRoleValue.roleName"
          placeholder="输入角色名称"
        />
      </n-form-item>
      <n-form-item label="状态">
        <n-radio-group v-model:value="formRoleValue.status" name="radiogroup1">
          <n-space>
            <n-radio :value="false"> 冻结 </n-radio>
            <n-radio :value="true"> 启用 </n-radio>
          </n-space>
        </n-radio-group>
      </n-form-item>
      <n-form-item label="描述">
        <n-input
          v-model:value="formRoleValue.description"
          type="textarea"
          placeholder="请输入描述"
        />
      </n-form-item>
    </n-form>
    <template #action>
      <n-space>
        <n-button type="primary" :loading="formBtnLoading" @click="confirmForm"
          >提交</n-button
        >
      </n-space>
    </template>
  </n-modal>
</template>
