<template>
  <el-form v-loading="loading" element-loading-text="初始化数据中..." :model="roleForm" :inline="true" label-suffix=":"
    label-width="80px">
    <el-form-item label="角色名">
      <el-input v-model="roleForm.name"></el-input>
    </el-form-item>
    <el-form-item label="是否启用">
      <el-switch v-model="roleForm.roleState" :active-value="1" :inactive-value="0"></el-switch>
    </el-form-item>
    <el-form-item style="width: 100%;" label="权限">
      <el-tree :data="roles" :props="treeProps" show-checkbox default-expand-all node-key="id"
        :default-checked-keys="roleForm.values?.split(',')" @check="handleCheckChange" />
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch } from "vue";
import { systemMenueType } from "@/types/systemMenue";
import api from "@/lib/request";
import { roleType } from "@/types/role";

const props = defineProps<{
  data?: roleType;
  executeType?: string;
}>();
const emits = defineEmits(["updateData"]);
let roles = ref<systemMenueType[]>([]);
let loading = ref(true);
let treeProps = { label: "name", children: "children" };
let auths = ref<string[]>([]);

let roleForm = ref<roleType>({ 
  name: "",
  roleState: 1,
  values: ''
});

onMounted(async () => {
  let respone = await api().get('/system-menue/list');
  roles.value = respone.data.list;

  loading.value = false;

  if (props.executeType === "edit") {
    roleForm.value = { ...props.data };
    auths.value = roleForm.value.values?.split(',') as string[];
  }

  watch(
    () => roleForm,
    (newVal) => {
      emits("updateData", newVal.value);
    },
    { deep: true }
  );

})

function handleCheckChange(val: string[], checkVal: any) {
  auths.value = checkVal.checkedKeys.filter(item => String(item));
  roleForm.value.values = auths.value.join(',');
}

</script>
<style lang="scss" scoped>
.el-input__wrapper {
  width: 200px;
}

.el-select {
  width: 192px;
}
</style>
@/types/systemMenue