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

import { reactive } from 'vue';

import { BcPage } from '@vben/baicai-ui';
import { confirm, useVbenModal } from '@vben/common-ui';

import { useClipboard } from '@vueuse/core';
import { Button, message } from 'ant-design-vue';

import { useTableGridOptions, useVbenVxeGrid } from '#/adapter';
import { DepartmentApi, RoleApi, UserApi } from '#/api';
import { BcTree } from '#/components/bc-tree';
import { SelectCard } from '#/components/select-card';
import {
  SystemUserDelete,
  SystemUserGrant,
  SystemUserResetPassword,
  SystemUserStatus,
} from '#/service/apis/System/UserController';

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

const { copy } = useClipboard({ legacy: true });
const searchInfo = reactive<Record<string, any>>({});

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

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

const handelResetPassword = async (id: number) => {
  const data = await SystemUserResetPassword([id]);
  confirm({
    title: '重置成功',
    content: `新密码为:${data}`,
    confirmText: '复制密码',
    beforeClose: ({ isConfirm }: { isConfirm: boolean }) => {
      if (isConfirm) {
        copy(data);
        message.success('密码复制成功！');
      }
      return true;
    },
  });
};

const handleDelete = async (id: string) => {
  await SystemUserDelete({ id });
  message.success('数据删除成功');
  reload();
};

const handleUpdateStatus = async (record: any) => {
  await SystemUserStatus({
    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 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',
      },
    })
    .open();
};

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

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

const handleActionClick = async ({
  code,
  row,
}: OnActionClickParams<UserApi.RecordItem>) => {
  switch (code) {
    case 'delete': {
      await handleDelete(row.id);
      break;
    }
    case 'edit': {
      handleEdit(row, true);
      break;
    }
    case 'grantRole': {
      handelGrantRole(row.id);
      break;
    }
    case 'resetPwd': {
      handelResetPassword(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 UserApi.getPage({
              pageIndex: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
              ...searchInfo,
            });
          },
        },
      },
    } as VxeTableGridOptions,
  }),
);

const handleDepartmentChange = (keys: any[]) => {
  searchInfo.departmentId = keys[0];
  reload();
};
</script>

<template>
  <BcPage auto-content-height :default-layout="[20, 80, 0]">
    <template #left>
      <BcTree
        title="组织架构"
        :api="{ url: DepartmentApi.getTree, type: 'api' }"
        :field-names="{ label: 'name', value: 'id' }"
        @change="handleDepartmentChange"
      />
    </template>
    <FormEditModal @success="handelSuccess" />
    <SelectCardModal title="角色" @success="handelRoleSuccess" />
    <Grid>
      <template #table-title>
        <span class="border-l-primary border-l-8 border-solid pl-2">
          用户列表
        </span>
      </template>
      <template #toolbar-tools>
        <Button
          class="mr-2"
          type="primary"
          v-access:code="'user:add'"
          @click="() => handleEdit({}, false)"
        >
          新增用户
        </Button>
      </template>
    </Grid>
  </BcPage>
</template>
