<template>
  <el-dialog
      v-model="props.visible"
      :title="props.roleId?'编辑':'新增'"
      width="500"
      :close-on-click-modal="false"
      :before-close="dialogClose"
  >
    <el-form
        class="ls-form"
        ref="formRef"
        :model="formData"
        label-width="80px"
    >
      <el-form-item
          label="角色名称"
          prop="name"
          :rules="{ required: true, message: '请输入角色名称', trigger: 'blur' }"
      >
        <el-input
            class="ls-input"
            v-model="formData.name"
            placeholder="请输入角色名称"
            clearable
        />
      </el-form-item>
      <el-form-item
          label="角色编码"
          prop="code"
          :rules="{ required: true, message: '请输入角色编码', trigger: 'blur' }"
      >
        <el-input
            class="ls-input"
            v-model="formData.code"
            placeholder="请输入角色编码"
            clearable
        />
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="formData.sort"/>
      </el-form-item>
      <el-form-item label="备注" prop="note">
          <el-input v-model="formData.note" type="textarea" placeholder="请输入备注" clearable />
        </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogClose">取消</el-button>
        <el-button :loading="subLoading" type="primary" @click="submit">
          确定
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import type {FormInstance} from "element-plus";
import {getRoleDetail,roleAdd,roleUpdate} from "@/api/system/role";
import {onMounted, reactive, shallowRef} from "vue";
import {message} from "@/utils/auth";
import {useLockFn} from "@/utils/useLockFn";

const emit = defineEmits(["success", "update:visible"]);
const formRef = shallowRef<FormInstance>();
const formData = reactive({
  id: "",
  name: "",
  code: "",
  sort: 0,
  note:''
});

const props = defineProps({
  visible: {
    type: Boolean,
    required: true,
    default: false
  },
  roleId: {
    type: Number,
    required: true,
    default: 0
  }
});

const handleSubmit = async () => {
    await formRef.value?.validate();
    props.roleId ? await roleUpdate(formData) : await roleAdd(formData);
    message("操作成功");
    emit("update:visible", false);
    emit("success");
};

const dialogClose = () => {
  emit("update:visible", false);
};

const { isLock:subLoading,lockFn: submit } = useLockFn(handleSubmit);


const setFormData = async () => {
  const data = await getRoleDetail(props.roleId);
  for (const key in formData) {
    if (data[key] != null && data[key] != undefined) {
      //@ts-ignore
      formData[key] = data[key];
    }
  }
};

onMounted(() => {
  if (props.roleId) {
    setFormData();
  }
});

</script>
