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

// @ts-ignore
import type { VxeGridProps } from '#/adapter/vxe-table';
// @ts-ignore
import type { Role } from '#/api/system/role/model';

import { useRouter } from 'vue-router';

// @ts-ignore
import { useAccess } from '@vben/access';
// @ts-ignore
import { Page, useVbenDrawer } from '@vben/common-ui';
// @ts-ignore
import { $t } from '@vben/locales';

import { ElMessageBox } from 'element-plus';

// @ts-ignore
import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteRole,
  exportRole,
  getRoleList,
  modifyRoleStatus,
  // @ts-ignore
} from '#/api/system/role/role';
// @ts-ignore
import { commonDownloadExcel } from '#/utils/file/download';

import { columns, querySchema } from './config-data';
// @ts-ignore
import PermDrawer from './perm-drawer.vue';
// @ts-ignore
import RoleDrawer from './role-drawer.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',
  // 日期选择格式化
  fieldMappingTime: [
    [
      'createTime',
      ['params[beginTime]', 'params[endTime]'],
      ['YYYY-MM-DD 00:00:00', 'YYYY-MM-DD 23:59:59'],
    ],
  ],
};

// 列表中显示配置
const gridOptions: VxeGridProps = {
  checkboxConfig: {
    // 高亮
    highlight: true,
    // 翻页时保留选中状态
    reserve: true,
    // 点击行选中
    trigger: 'default',
    checkMethod: ({ row }) => row?.roleId !== 1,
  },
  columns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await getRoleList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  rowConfig: {
    keyField: 'roleId',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-role-index',
};
const [BasicTable, BasicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
const [VbenRoleDrawer, roleDrawerApi] = useVbenDrawer({
  connectedComponent: RoleDrawer,
});
// 新增打开测试
function openDrawer() {
  roleDrawerApi.setData({}).open();
}
// 编辑修改角色
function handleEdit(role: Role) {
  roleDrawerApi.setData({ roleId: role.roleId, isUpdate: true }).open();
}
// 单个删除角色
async function confirmEvent(role: Role) {
  await deleteRole([role.roleId]);
  await BasicTableApi.reload();
}
// 多个删除角色
function deleteRoles() {
  // 获取全部选中的数据
  const checkRecords = BasicTableApi.grid.getCheckboxRecords();
  // 数据转换只要roleId
  const ids = checkRecords.map((item: Role) => item.roleId);
  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 删除角色
    await deleteRole(ids!);
    // 重置查询
    await BasicTableApi.reload();
  });
}
// 修改角色状态
function roleStatusChange(role: Role) {
  ElMessageBox.confirm(
    `确定要${role.status === '0' ? '启用' : '停用'}${role.roleName}?`,
    '系统提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    },
  )
    .then(async () => {
      await modifyRoleStatus(role);
    })
    .catch(() => {
      role.status = role.status === '0' ? '1' : '0';
    });
}
async function exportRoles() {
  await commonDownloadExcel(
    exportRole,
    '角色数据',
    BasicTableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
const [VbenPermDrawer, permDrawerApi] = useVbenDrawer({
  connectedComponent: PermDrawer,
});
// 数据权限配置侧拉
function openDataScopeDrawer(role: Role) {
  permDrawerApi.setData(role).open();
}
const router = useRouter();
function jumpRoute(role: Role) {
  router.push(`/system/role-assign/${role.roleId}`);
}
const { hasAccessByCodes } = useAccess();
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="角色列表">
      <template #roleKey="{ row }">
        <ElTag>
          {{ row.roleKey }}
        </ElTag>
      </template>
      <template #status="{ row }">
        <ElSwitch
          v-model="row.status"
          inline-prompt
          active-text="正常"
          inactive-text="停用"
          active-value="0"
          inactive-value="1"
          style="--el-switch-off-color: #ff4949"
          @change="roleStatusChange(row)"
          :disabled="!hasAccessByCodes(['system:role:edit'])"
        />
      </template>
      <template #toolbar-tools>
        <ElSpace>
          <ElButton @click="exportRoles" v-access:code="['system:role:export']">
            导出
          </ElButton>
          <ElButton
            type="danger"
            :disabled="
              !(BasicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteRoles"
            v-access:code="['system:role:remove']"
          >
            删除
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
            v-access:code="['system:role:add']"
          >
            {{ $t('pages.common.add') }}
          </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace v-if="row.roleId !== 1">
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['system:role:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['system:role:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
          <ElDropdown>
            <ElButton
              type="primary"
              size="small"
              link
              v-access:code="['system:role:edit']"
            >
              更多
            </ElButton>
            <template #dropdown>
              <ElDropdownMenu>
                <ElDropdownItem @click="openDataScopeDrawer(row)">
                  数据权限
                </ElDropdownItem>
                <ElDropdownItem @click="jumpRoute(row)">
                  分配用户
                </ElDropdownItem>
              </ElDropdownMenu>
            </template>
          </ElDropdown>
        </ElSpace>
      </template>
    </BasicTable>
    <VbenRoleDrawer @reload="BasicTableApi.reload()" />
    <VbenPermDrawer @reload="BasicTableApi.reload()" />
  </Page>
</template>
<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
