<script lang="ts" setup>
import type { VbenFormProps } from '@vben/common-ui';

import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SysRoleApi } from '#/api/auth/role';

import { computed } from 'vue';
import { useRouter } from 'vue-router';

import { useAccess } from '@vben/access';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';
import { Plus } from '@vben/icons';
import { getVxePopupContainer } from '@vben/utils';

import { Button, message, Popconfirm, Space } from 'ant-design-vue';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteRole, getRoleList } from '#/api/auth/role';
import { GhostButton } from '#/components/global/button';

import { querySchema, useColumns } from './data';
import deptDataScopeModal from './deptDataScopeModal.vue';
import Form from './form.vue';

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: querySchema,
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4',
};

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
  // destroyOnClose: true,
});

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions: {
    columns: useColumns(),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues = {}) => {
          return await getRoleList({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      // 高亮当前行
      isCurrent: true,
    },
  } as VxeTableGridOptions,
});

// function onActionClick({ code, row }: OnActionClickParams<SysRoleApi.Role>) {
//   switch (code) {
//     case 'dataScope': {
//       onDataScope(row);
//       break;
//     }
//     case 'delete': {
//       onDelete(row);
//       break;
//     }
//     case 'edit': {
//       onEdit(row);
//       break;
//     }
//     default: {
//       break;
//     }
//   }
// }

/**
 * 状态开关即将改变
 * @param newStatus 期望改变的状态值
 * @param row 行数据
 * @returns 返回false则中止改变，返回其他值（undefined、true）则允许改变
 */
// async function onStatusChange(
//   newStatus: number,
//   row: SystemRoleApi.SystemRole,
// ) {
//   const status: Recordable<string> = {
//     0: '禁用',
//     1: '启用',
//   };
//   try {
//     await confirm(
//       `你要将${row.name}的状态切换为 【${status[newStatus.toString()]}】 吗？`,
//       `切换状态`,
//     );
//     await updateRole(row.id, { status: newStatus });
//     return true;
//   } catch {
//     return false;
//   }
// }
const { hasAccessByRoles } = useAccess();

const isSuperAdmin = computed(() => hasAccessByRoles(['superadmin']));

const [DeptDataScopeModal, authModalApi] = useVbenModal({
  connectedComponent: deptDataScopeModal,
});

function onDataScope(row: SysRoleApi.Role) {
  authModalApi.setData(row).open();
}

function onRefresh() {
  gridApi.query();
}
function onEdit(row: SysRoleApi.Role) {
  formDrawerApi.setData({ id: row.id }).open();
}
function onCreate() {
  formDrawerApi.setData({}).open();
}

function onDelete(row: SysRoleApi.Role) {
  const hideLoading = message.loading({
    content: `正在删除${row.name}...`,
    duration: 0,
    key: 'action_process_msg',
  });
  deleteRole(row.id || 0)
    .then(() => {
      message.success({
        content: `${row.name}删除成功`,
        key: 'action_process_msg',
      });
      onRefresh();
    })
    .catch(() => {
      hideLoading();
    });
}

const router = useRouter();
function onAssignRole(record: SysRoleApi.Role) {
  router.push(`/auth/role-auth/user/${record.id}`);
}
</script>
<template>
  <Page auto-content-height>
    <FormDrawer @success="onRefresh" />
    <DeptDataScopeModal @reload="onRefresh" />
    <Grid table-title="角色列表">
      <template #toolbar-tools>
        <Button type="primary" @click="onCreate">
          <Plus class="size-5" />
          新增
        </Button>
      </template>
      <template #action="{ row }">
        <!-- 租户管理员不可修改admin角色 防止误操作 -->
        <!-- 超级管理员可通过租户切换来操作租户管理员角色 -->
        <!--  -->
        <!-- <template
          v-if="!row.superAdmin && (row.roleKey !== 'admin' || isSuperAdmin)"
        > -->
        <Space>
          <GhostButton
            v-access:code="['auth:role:edit']"
            @click.stop="onEdit(row)"
          >
            编辑
          </GhostButton>
          <GhostButton
            v-access:code="['auth:role:edit']"
            @click.stop="onDataScope(row)"
          >
            权限
          </GhostButton>
          <GhostButton
            v-access:code="['auth:role:edit']"
            @click.stop="onAssignRole(row)"
          >
            分配
          </GhostButton>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            :title="`确认删除【${row.name}】？`"
            @confirm="onDelete(row)"
          >
            <GhostButton
              danger
              v-access:code="['auth:role:remove']"
              @click.stop=""
            >
              删除
            </GhostButton>
          </Popconfirm>
        </Space>
        <!-- </template> -->
      </template>
    </Grid>
  </Page>
</template>
