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

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Department } from '#/api/system/dept/model';
import type { DictOption } from '#/store/dict';

import { nextTick, onMounted, ref } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';
import { DictEnum } from '@vben/constants';
import { $t } from '@vben/locales';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteDept, deptList } from '#/api/system/dept/dept';
import { DictTag } from '#/components/dict';
import { getDictOptions } from '#/utils/dict';
import { queryFormSchema, tableColumns } from '#/views/system/dept/config-data';

import DeptDrawer from './dept-drawer.vue';

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 80,
    componentProps: {
      allowClear: true,
    },
  },
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-4',
};

const gridOptions: VxeGridProps = {
  // 配置属性结构
  treeConfig: {
    transform: true,
    rowField: 'deptId',
    parentField: 'parentId',
  },
  // 配置字体大小
  size: 'medium',
  // 配置表格右上角全屏、刷新
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  // 关闭分页
  pagerConfig: {
    enabled: false,
  },
  // 获取表格数据
  proxyConfig: {
    ajax: {
      query: async (_, formValues = {}) => {
        const resp = await deptList({
          ...formValues,
        });
        console.log(resp);
        return { items: resp };
      },
      querySuccess: () => {
        nextTick(() => {
          basicTableApi.grid?.setAllTreeExpand(true);
        });
      },
    },
  },
  // 配置显示列
  columns: tableColumns,
};

const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});
const [DeptVbenDrawer, deptVbenDrawerApi] = useVbenDrawer({
  connectedComponent: DeptDrawer,
});
// 编辑部门
function handleEdit(dept: Department) {
  deptVbenDrawerApi.setData({ ...dept, isUpdate: true }).open();
}
// 新增部门
function handleAdd(dept: Department) {
  console.log(dept);
  deptVbenDrawerApi.setData({ ...dept, isUpdate: false }).open();
}
// 删除部门
async function confirmEvent(dept: Department) {
  await deleteDept(dept.deptId);
  await basicTableApi.reload();
}
// 展开
const expandAll = () => {
  basicTableApi.grid?.setAllTreeExpand(true);
};
// 折叠
const collapseAll = () => {
  basicTableApi.grid?.setAllTreeExpand(false);
};
// 添加部门
const addDept = () => {
  deptVbenDrawerApi.setData({ isUpdate: false }).open();
};
// 获取状态字典值
const dictDataRef = ref<DictOption[]>([]);
onMounted(async () => {
  dictDataRef.value = getDictOptions(DictEnum.SYS_NORMAL_DISABLE);
});
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="部门列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton @click="collapseAll">
            {{ $t('pages.common.collapse') }}
          </ElButton>
          <ElButton @click="expandAll">
            {{ $t('pages.common.expand') }}
          </ElButton>
          <ElButton
            type="primary"
            @click="addDept"
            v-access:code="['system:dept:add']"
          >
            {{ $t('pages.common.add') }}
          </ElButton>
        </ElSpace>
      </template>
      <template #status="{ row }">
        <DictTag :dicts="dictDataRef" :value="row.status" />
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['system:dept:edit']"
          >
            编辑
          </ElButton>
          <ElButton
            size="small"
            type="success"
            plain
            @click="handleAdd(row)"
            v-access:code="['system:dept:add']"
          >
            新增
          </ElButton>
          <ElPopconfirm
            :title="$t('common.confirm-delete')"
            @confirm="confirmEvent(row)"
            v-if="row.parentId"
          >
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['system:dept:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <DeptVbenDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>
