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

import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { SysDeptApi } from '#/api/auth/dept';

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteOne, exportDetail, findList } from '#/api/auth/dept';
import { commonDownloadExcel } from '#/utils/file/download';

import { querySchema, useColumns } from './data';
import Form from './form.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',
};

const [FormDrawer, formDrawerApi] = useVbenDrawer({
  connectedComponent: Form,
});

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions: {
    columns: useColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: false,
    },
    proxyConfig: {
      ajax: {
        query: async (_, formValues = {}) => {
          const data = await findList({ ...formValues });
          return { data };
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      // 高亮当前行
      isCurrent: true,
    },
    treeConfig: {
      parentField: 'parentId',
      rowField: 'id',
      transform: false,
    },
  } as VxeTableGridOptions,
});

function onActionClick({ code, row }: OnActionClickParams<SysDeptApi.Dept>) {
  switch (code) {
    case 'append': {
      onAppend(row);
      break;
    }
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
    default: {
      break;
    }
  }
}

function onRefresh() {
  gridApi.query();
}
function onEdit(row: SysDeptApi.Dept) {
  formDrawerApi.setData(row).open();
}
function onAppend(row: SysDeptApi.Dept) {
  formDrawerApi.setData({ parentId: row.id }).open();
}
function onCreate() {
  formDrawerApi.setData({}).open();
}

function onDelete(row: SysDeptApi.Dept) {
  const hideLoading = message.loading({
    content: `正在删除${row.name}...`,
    duration: 0,
    key: 'action_process_msg',
  });
  deleteOne(row.id || 0)
    .then(() => {
      message.success({
        content: `${row.name}删除成功`,
        key: 'action_process_msg',
      });
      onRefresh();
    })
    .catch(() => {
      hideLoading();
    });
}
function handleDownloadExcel() {
  commonDownloadExcel(exportDetail, '组织架构', gridApi.formApi.form.values);
}
</script>
<template>
  <Page auto-content-height>
    <FormDrawer @success="onRefresh" />
    <Grid table-title="组织架构">
      <template #toolbar-tools>
        <Space>
          <Button
            v-access:code="['auth:dept:export']"
            @click="handleDownloadExcel"
          >
            导出
          </Button>
          <Button
            v-access:code="['auth:dept:add']"
            type="primary"
            @click="onCreate"
          >
            <Plus class="size-5" />
            新增
          </Button>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
