<script lang="ts" setup>
import { ref, computed, nextTick } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { message } from 'ant-design-vue';

import { getMenuTreeOption } from '#/views/system/menu/api';
import { getRoleQuickNavList, batchSaveRoleQuickNav } from '#/views/system/role-quick-nav/api';
import { getMenuIdsByRoleIds } from '../api';
import QuickNavTransfer from './quick-nav-transfer.vue';

const record = ref();
const menuTreeData = ref<any[]>([]);
const checkedMenuIds = ref<number[]>([]);
const savedQuickNavItems = ref<any[]>([]);
const loading = ref(false);
const roleMenuIds = ref<number[]>([]);

const drawerTitle = computed(() => {
  const roleName = record.value?.name || '';
  return roleName ? `快捷导航管理 - ${roleName}` : '快捷导航管理';
});

const fetchRoleMenuIds = async () => {
  if (!record.value?.id) {
    roleMenuIds.value = [];
    return;
  }

  try {
    const res = await getMenuIdsByRoleIds({
      id: record.value.id,
    });
    roleMenuIds.value = Array.isArray(res) ? res : [];
  } catch (error) {
    console.error('获取角色菜单ID失败:', error);
    message.error('获取角色菜单ID失败');
    roleMenuIds.value = [];
  }
};

const fetchMenuTree = async () => {
  try {
    const res = await getMenuTreeOption({
      filterByUser: 1,
    });
    menuTreeData.value = res;
  } catch (error) {
    console.error('获取菜单树失败:', error);
    message.error('获取菜单树失败');
  }
};

const fetchQuickNavList = async () => {
  if (!record.value?.id) return;

  loading.value = true;
  try {
    const res = await getRoleQuickNavList({
      role_id: record.value.id,
      page: 1,
      pageSize: 1000,
    });
    const items = res.items || res.data || res || [];
    const sorted = [...items].sort((a: any, b: any) => {
      if (a.sort !== b.sort) {
        return (a.sort || 0) - (b.sort || 0);
      }
      return (a.id || 0) - (b.id || 0);
    });

    savedQuickNavItems.value = sorted;
    checkedMenuIds.value = sorted
      .map((item: any) => item.menu_id)
      .filter(Boolean);

    await nextTick();
  } catch (error) {
    console.error('获取快捷导航列表失败:', error);
    message.error('获取快捷导航列表失败');
    checkedMenuIds.value = [];
    savedQuickNavItems.value = [];
  } finally {
    loading.value = false;
  }
};

const handleSave = async () => {
  if (!record.value?.id) {
    message.error('角色ID不能为空');
    return;
  }

  DrawerApi.setState({
    loading: true,
    confirmLoading: true,
  });

  try {
    await batchSaveRoleQuickNav({
      role_id: record.value.id,
      menu_id: checkedMenuIds.value,
    });
    message.success('保存成功');
    await fetchQuickNavList();
  } catch (error) {
    console.error('保存失败:', error);
    message.error('保存失败');
  } finally {
    DrawerApi.setState({
      loading: false,
      confirmLoading: false,
    });
  }
};

const [Drawer, DrawerApi] = useVbenDrawer({
  onOpenChange(isOpen) {
    record.value = isOpen ? DrawerApi.getData()?.record : {};
    if (isOpen) {
      checkedMenuIds.value = [];
      savedQuickNavItems.value = [];
      roleMenuIds.value = [];
      menuTreeData.value = [];
      DrawerApi.setState({
        loading: true,
      });
      fetchRoleMenuIds()
        .then(() => nextTick())
        .then(() => fetchMenuTree())
        .then(() => nextTick())
        .then(() => fetchQuickNavList())
        .finally(() => {
          DrawerApi.setState({
            loading: false,
          });
        });
    }
  },
  onConfirm: handleSave,
});

defineExpose({
  DrawerApi,
});
</script>

<template>
  <Drawer :title="drawerTitle" class="w-[95%]">
    <QuickNavTransfer
      v-model="checkedMenuIds"
      :loading="loading"
      :menu-tree="menuTreeData"
      :role-menu-ids="roleMenuIds"
      :saved-items="savedQuickNavItems"
    />
  </Drawer>
</template>
