<script lang="ts" setup>
import { useAccess } from '@vben/access';
import { Page, useVbenDrawer, useVbenModal } from '@vben/common-ui';

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { RoleApi, UserApi } from '#/api';
import { SelectCard } from '#/components/select-card';
import { TableAction } from '#/components/table-action';
import MenuGrant from '#/views/system/menu/components/grant.vue';

import FormEdit from './components/edit.vue';
import { gridOptions, searchFormOptions } from './data.config';

const { hasAccessByCodes } = useAccess();

const [Grid, { reload }] = useVbenVxeGrid({
  formOptions: searchFormOptions,
  gridOptions,
});

const [FormEditModal, formEditApi] = useVbenModal({
  connectedComponent: FormEdit,
});

const [MenuGrantModal, menuGrantApi] = useVbenDrawer({
  connectedComponent: MenuGrant,
});

const [SelectCardModal, selectCardApi] = useVbenModal({
  connectedComponent: SelectCard,
});
const handleDelete = (id: number) => {
  Modal.confirm({
    iconType: 'info',
    title: '删除提示',
    content: `确定要删除选择的记录吗?`,
    cancelText: `关闭`,
    onOk: async () => {
      await RoleApi.deleteDetail(id);
      message.success('数据删除成功');
      reload();
    },
  });
};

const handleUpdateStatus = async (record: any) => {
  await RoleApi.updateStatus({
    id: record.id,
    status: record.status === 1 ? 2 : 1,
  });
  reload();
};

const handleEdit = (record: any, isUpdate: boolean) => {
  formEditApi.setData({
    isUpdate,
    baseData: { id: record.id },
  });

  formEditApi.open();
};

const handleGrantMenu = async (id: number) => {
  menuGrantApi.setData({
    baseData: { id, type: 'role' },
  });

  menuGrantApi.open();
};

const handleGrantUser = async (id: number) => {
  const selectedIds = await RoleApi.getUserIds(id);
  selectCardApi.setData({
    baseData: {
      key: id,
      selectedIds,
      fieldNames: [
        { label: '电话', value: 'phone', maxLength: 12 },
        { label: '姓名', value: 'realName', maxLength: 8 },
      ],
      config: {
        type: 'user',
      },
      api: {
        url: UserApi.getPage,
      },
      searchName: 'name',
    },
  });

  selectCardApi.open();
};

const handelSuccess = () => {
  reload();
};

const handelUserSuccess = async (data: any) => {
  await RoleApi.updateGrantUser({ id: data.key, relationIds: data.ids });
  message.success('授权成功');
};
</script>

<template>
  <Page auto-content-height>
    <FormEditModal :close-on-click-modal="false" @success="handelSuccess" />
    <MenuGrantModal :close-on-click-modal="false" />
    <SelectCardModal
      :close-on-click-modal="false"
      title="用户"
      @success="handelUserSuccess"
    />
    <Grid>
      <template #toolbar-tools>
        <Button
          class="mr-2"
          type="primary"
          v-access:code="'role:add'"
          @click="() => handleEdit({}, false)"
        >
          新增角色
        </Button>
      </template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              type: 'text',
              danger: true,
              disabled: !hasAccessByCodes(['role:edit']),
              onClick: handleEdit.bind(null, row, true),
            },
            {
              label: '授权菜单',
              type: 'text',
              disabled: !hasAccessByCodes(['role:grantMenu']),
              onClick: handleGrantMenu.bind(null, row.id),
            },
          ]"
          :drop-down-actions="[
            {
              label: '添加成员',
              type: 'link',
              disabled: !hasAccessByCodes(['role:grantUser']),
              onClick: handleGrantUser.bind(null, row.id),
            },
            {
              label: row.status === 1 ? '禁用' : '启用',
              type: 'link',
              disabled: !hasAccessByCodes(['role:setStatus']),
              onClick: handleUpdateStatus.bind(null, row),
            },
            {
              label: '删除',
              type: 'link',
              disabled: !hasAccessByCodes(['role:delete']),
              onClick: handleDelete.bind(null, row.id),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
