<template>
  <el-drawer :title="title" v-model="drawerOpened" @close="reset">
    <el-form 
      label-position="left" 
      label-width="80px" 
      :model="formData" 
      :rules="formRules"
      ref="formInstance"
    >
      <el-form-item label="角色名称" prop="roleName">
        <el-input placeholder="角色名称" v-model="formData.roleName" />
      </el-form-item>

      <el-form-item label="角色权限">
        <PermissioTreeCard title="相机权限" :tree-data="cameraPermTreeData" ref="cameraCardInstance" />
        <PermissioTreeCard title="菜单权限" :tree-data="menuPermTreeData" ref="menuCardInstance" />
        <PermissioTreeCard title="功能权限" :tree-data="funcPermTreeData" ref="funcCardInstance" />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input type="textarea" placeholder="备注" v-model="formData.remark" />
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="reset">重置</el-button>
      <el-button type="primary" @click="submit">提交</el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
  import { reactive, ref, computed, toRaw } from 'vue';
  import PermissioTreeCard from './PermissionTreeCard.vue';
  import { RoleForm, Role, AssignedPermissions } from '@/types/role/type';
  import { FormRules, FormInstance, ElMessage } from 'element-plus';
  import useMenuPermTree from '../hooks/useMenuPermissionTree';
  import useFuncPermTree from '../hooks/useFunctionPermissionTree';
  import useCameraPermTree from '../hooks/useCameraPermissionTree';
  import { createRole, editRole, getAssignedPerms } from '@/api/system/role';
  import { PermissionTreeKey } from '@/types/permission/type';

  defineProps<{
    title: string;
  }>();

  const emits = defineEmits<{
    (e: 'submitted'): void;  // 提交之后触发的事件
  }>();

  const { cameraPermTreeData } = useCameraPermTree();
  const { menuPermTreeData } = useMenuPermTree();
  const { funcPermTreeData} = useFuncPermTree();

  const drawerOpened = ref(false);
  const cameraCardInstance = ref<InstanceType<typeof PermissioTreeCard>>();
  const menuCardInstance = ref<InstanceType<typeof PermissioTreeCard>>();
  const funcCardInstance = ref<InstanceType<typeof PermissioTreeCard>>();   

  // 表单相关
  const defaultFormData = (): RoleForm => ({
    id: null,
    roleName: '',
    remark: '',
    cameraIds: [],
    menuIds: [],
    permIds: [],
  });
  const formData = reactive<RoleForm>(defaultFormData());
  const formRules: FormRules = {
    roleName: { required: true, trigger: 'blur', message: '请填写角色名称' },
    remark: {},
  };
  const formInstance = ref<FormInstance>();
  
  const isEditing = computed(() => formData.id != null);

  /**
   * 打开 drawer。如果未传递 roleId，表示创建角色；反之，表示编辑角色
   * @param roleId 可选
   */
  const open = (role?: Role) => {
    if (role) {
      formData.id = role.id;
      formData.roleName = role.roleName;
      formData.remark = role.remark;
      getAssignedPermissions(role.id);

      // TODO: 获取已拥有的权限
    }

    drawerOpened.value = true;
  };

  /**
   * 获取当前角色已分配的权限数据，并更新相应的权限数
   */
  const getAssignedPermissions = async (roleId: number) => {
    try {
      const result = await getAssignedPerms(roleId);
      displayAssignedPermissions(result);
    } catch (e) {
      console.error(e);
    }
  }

  const displayAssignedPermissions = (result: AssignedPermissions) => {
    if (result.cameraIds?.length) {
      // 相机树很有可能会有 id 重复的情况，比如说 一个camera id 和 一个 workspace id 相同，这样会导致 tree 节点 value 不唯一，因此需要给个前缀
      const cameraIds = result.cameraIds.map(id => `camera-${id}`);
      cameraCardInstance.value?.setAssignedPermissions(cameraIds);
    }

    if (result.menuIds?.length) {
      menuCardInstance.value?.setAssignedPermissions(result.menuIds);
    }

    if (result.permIds?.length) {
      funcCardInstance.value?.setAssignedPermissions(result.permIds);
    }
  }

  /**
   * 重置表单
   */
  const reset = () => {
    formInstance.value?.resetFields();
    Object.assign(formData, defaultFormData());
    cameraCardInstance.value?.reset();
    menuCardInstance.value?.reset();
    funcCardInstance.value?.reset();
  };

  /**
   * 提交。创建和编辑统一
   */
  const submit = async () => {
    formData.cameraIds = cleanCameraPermissions(cameraCardInstance.value!.getSelectedPermissions());
    formData.menuIds = menuCardInstance.value!.getSelectedPermissions();
    formData.permIds = funcCardInstance.value!.getSelectedPermissions();

    const api = isEditing.value ? editRole : createRole;
    try {
      await formInstance.value?.validate();
      await api(toRaw(formData));
      drawerOpened.value = false;
      ElMessage.success('提交成功');
      // 让父组件更新列表
      emits('submitted');
    } catch (e) {
      console.error(e);
    }
  }

  /**
   * 获取到的相机的权限码是 camera-xxx， 例如 camera-11， 提交后端转换成数字 11
   */
  const cleanCameraPermissions = (perms: PermissionTreeKey[]) => {
    return perms.map(perm => {
      if (typeof perm === 'string' && perm.includes('-')) {
        const splits = perm.split('-');
        return +splits[1];
      }

      // 否则正常返回
      return perm;
    });
  }

  defineExpose({ open });
</script>
