<script lang="ts" setup>
import type { OnActionClickParams, VxeTableGridOptions } from '#/adapter';

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

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

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

import FormEdit from './components/edit.vue';
import { useColumns, useSearchSchema } from './data.config';

const handleDelete = async (id: number) => {
  await RoleApi.deleteDetail(id);
  message.success('数据删除成功');
  reload();
};
const handleActionClick = async ({
  code,
  row,
}: OnActionClickParams<RoleApi.RecordItem>) => {
  switch (code) {
    case 'delete': {
      await handleDelete(row.id);
      break;
    }
    case 'edit': {
      handleEdit(row, true);
      break;
    }
    case 'grantMenu': {
      await handleGrantMenu(row.id);
      break;
    }
    case 'grantUser': {
      await handleGrantUser(row.id);
      break;
    }
    case 'setStatus': {
      await handleUpdateStatus(row);
      break;
    }
  }
};

const [Grid, { reload }] = useVbenVxeGrid(
  useTableGridOptions({
    formOptions: {
      schema: useSearchSchema(),
    },
    gridOptions: {
      columns: useColumns(handleActionClick),
      proxyConfig: {
        ajax: {
          query: async ({ page }, formValues) => {
            return await RoleApi.getPage({
              pageIndex: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
            });
          },
        },
      },
    } as VxeTableGridOptions,
  }),
);

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

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

const [SelectCardModal, selectCardApi] = useVbenModal({
  connectedComponent: SelectCard,
});

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 },
    })
    .open();
};

const handleGrantMenu = async (id: number) => {
  menuGrantApi
    .setData({
      baseData: { id, type: 'role' },
    })
    .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',
      },
    })
    .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>
    </Grid>
  </Page>
</template>
