<script setup lang="ts">
import { ref } from "vue";
import { useUserStoreHook } from "@/store/modules/user";
import { ElTree, FormInstance, FormRules } from "element-plus";
import { AddRoleCommand, UpdateRoleCommand } from "@/api/system/role";
import { MenuDTO } from "@/api/system/menu";

interface Props {
  formInline: AddRoleCommand & Partial<UpdateRoleCommand>;
  menuOptions: MenuDTO[];
}

const props = withDefaults(defineProps<Props>(), {
  formInline: () => ({
    roleId: 0,
    dataScope: "5",
    menuIds: [],
    remark: "",
    roleKey: "",
    roleName: "",
    roleSort: 1,
    status: ""
  }),
  menuOptions: () => []
});
const formData = ref(props.formInline);

const statusList = useUserStoreHook().dictionaryMap["common.status"];

const rules: FormRules = {
  roleName: [
    {
      required: true,
      message: "角色名称不能为空"
    }
  ],
  roleKey: [
    {
      required: true,
      message: "权限标识不能为空"
    }
  ],
  roleSort: [
    {
      required: true,
      message: "角色序号不能为空"
    }
  ]
};
const formRef = ref<FormInstance>();

const treeRef = ref<InstanceType<typeof ElTree>>();
function handleCheckChange() {
  formData.value.menuIds = treeRef.value.getCheckedKeys(false) as number[];
}

function getFormRuleRef() {
  return formRef.value;
}

defineExpose({ getFormRuleRef });
</script>

<template>
  <el-form :model="formData" label-width="120px" :rules="rules" ref="formRef">
    <el-form-item prop="roleName" label="角色名称" required inline-message>
      <el-input v-model="formData.roleName" />
    </el-form-item>
    <el-form-item prop="roleKey" label="权限字符" required>
      <el-input v-model="formData.roleKey" />
    </el-form-item>
    <el-form-item prop="roleSort" label="角色顺序" required>
      <el-input-number :min="1" v-model="formData.roleSort" />
    </el-form-item>
    <el-form-item prop="status" label="角色状态">
      <el-radio-group v-model="formData.status">
        <el-radio
          v-for="item in Object.keys(statusList)"
          :key="item"
          :label="statusList[item].value"
          >{{ statusList[item].label }}</el-radio
        >
      </el-radio-group>
    </el-form-item>
    <el-form-item label="菜单权限" prop="menuIds">
      <el-tree
        ref="treeRef"
        :props="{ label: 'menuName', children: 'children' }"
        :data="props.menuOptions"
        node-key="id"
        check-strictly
        show-checkbox
        default-expand-all
        check-on-click-node
        :expand-on-click-node="false"
        :default-checked-keys="formData.menuIds"
        @check-change="handleCheckChange"
        style="width: 100%"
      />
    </el-form-item>
    <el-form-item prop="remark" label="备注" style="margin-bottom: 0">
      <el-input type="textarea" v-model="formData.remark" />
    </el-form-item>
  </el-form>
</template>
