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

import { useClipboard } from '@vueuse/core';
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 FormEdit from './components/edit.vue';
import { gridOptions, searchFormOptions } from './data.config';

const { hasAccessByCodes } = useAccess();

const { copy } = useClipboard({ legacy: true });

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

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

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

const handelResetPassword = (id: number) => {
  Modal.confirm({
    iconType: 'info',
    title: '重置密码提示',
    content: `确定要重置选择的记录吗?`,
    cancelText: `关闭`,
    onOk: async () => {
      const data = await UserApi.resetPassword([id]);
      Modal.success({
        title: '重置成功',
        content: `新密码为:${data}`,
        okText: `复制密码`,
        onOk: () => {
          copy(data);
          message.success('密码复制成功！');
        },
      });
    },
  });
};

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

const handleUpdateStatus = async (record: any) => {
  await UserApi.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 handelGrantRole = async (id: number) => {
  const selectedIds = await UserApi.getRoleIds(id);
  selectCardApi.setData({
    baseData: {
      key: id,
      selectedIds,
      fieldNames: [
        { label: '编号', value: 'code', maxLength: 12 },
        { label: '名称', value: 'name', maxLength: 8 },
      ],
      config: {
        type: 'role',
      },
      api: {
        url: RoleApi.getPage,
      },
      searchName: 'name',
    },
  });

  selectCardApi.open();
};

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

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

<template>
  <Page auto-content-height>
    <FormEditModal :close-on-click-modal="false" @success="handelSuccess" />
    <SelectCardModal
      :close-on-click-modal="false"
      title="角色"
      @success="handelRoleSuccess"
    />
    <Grid>
      <template #toolbar-tools>
        <Button
          class="mr-2"
          type="primary"
          v-access:code="'user:add'"
          @click="() => handleEdit({}, false)"
        >
          新增用户
        </Button>
      </template>
      <template #action="{ row }">
        <TableAction
          :actions="[
            {
              label: '编辑',
              type: 'text',
              danger: true,
              disabled: !hasAccessByCodes(['user:edit']),
              onClick: handleEdit.bind(null, row, true),
            },
            {
              label: '重置密码',
              type: 'text',
              disabled: !hasAccessByCodes(['user:resetPwd']),
              onClick: handelResetPassword.bind(null, row.id),
            },
          ]"
          :drop-down-actions="[
            {
              label: row.status === 1 ? '禁用' : '启用',
              type: 'link',
              disabled: !hasAccessByCodes(['user:setStatus']),
              onClick: handleUpdateStatus.bind(null, row),
            },
            {
              label: '角色管理',
              type: 'link',
              disabled: !hasAccessByCodes(['user:grantRole']),
              onClick: handelGrantRole.bind(null, row.id),
            },
            {
              label: '删除',
              type: 'link',
              disabled: !hasAccessByCodes(['user:delete']),
              onClick: handleDelete.bind(null, row.id),
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
