<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { SystemDeptApi } from '#/api/system/dept';

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteDept, getDeptList, updateDeptEnable } from '#/api/system/dept';

import { useColumns } from './data';
import Form from './modules/form.vue';

// const userStore = useUserStore();
const [FormModal] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

// /**
//  * 编辑部门
//  * @param row
//  */
// function onEdit(row: SystemDeptApi.SystemDept) {
//   formModalApi.setData(row).open();
// }

// /**
//  * 添加下级部门
//  * @param row
//  */
// function onAppend(row: SystemDeptApi.SystemDept) {
//   formModalApi.setData({ pid: row.id }).open();
// }

// /**
//  * 创建新部门
//  */
// function onCreate() {
//   formModalApi.setData(null).open();
// }

// /**
//  * 删除部门
//  * @param row
//  */
function onDelete(row: SystemDeptApi.SystemDept) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.name]),
    duration: 0,
    key: 'action_process_msg',
  });
  deleteDept(row.id)
    .then(() => {
      message.success({
        content: $t('ui.actionMessage.deleteSuccess', [row.name]),
        key: 'action_process_msg',
      });
      refreshGrid();
    })
    .catch(() => {
      hideLoading();
    });
}
/**
 * 将Antd的Modal.confirm封装为promise，方便在异步函数中调用。
 * @param content 提示内容
 * @param title 提示标题
 */
function confirm(content: string, title: string) {
  return new Promise((reslove, reject) => {
    Modal.confirm({
      content,
      onCancel() {
        reject(new Error('已取消'));
      },
      onOk() {
        reslove(true);
      },
      title,
    });
  });
}
/**
 * 表格操作按钮的回调函数
 */
function onActionClick({
  code,
  row,
}: OnActionClickParams<SystemDeptApi.SystemDept>) {
  console.warn('1111111111');
  switch (code) {
    // case 'append': {
    //   onAppend(row);
    //   break;
    // }
    case 'delete': {
      onDelete(row);
      break;
    }
    // case 'edit': {
    //   onEdit(row);
    //   break;
    // }
  }
}
/**
 * 状态开关即将改变
 * @param newStatus 期望改变的状态值
 * @param row 行数据
 * @returns 返回false则中止改变，返回其他值（undefined、true）则允许改变
 */
async function onStatusChange(
  newStatus: boolean,
  row: SystemDeptApi.SystemDept,
) {
  // const enabled: Recordable<boolean> = {
  //   启用: true,
  //   禁用: false,
  // };
  try {
    await confirm(
      `你要将${row.name}的状态切换为 【${newStatus ? '启用' : '禁用'}】 吗？`,
      `切换状态`,
    );
    await updateDeptEnable(row.id, newStatus);
    return true;
  } catch {
    return false;
  }
}
const [Grid, gridApi] = useVbenVxeGrid({
  gridOptions: {
    columns: useColumns(onActionClick, onStatusChange),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: false,
    },
    proxyConfig: {
      ajax: {
        query: async () => {
          const { list } = await getDeptList();
          return list;
        },
      },
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      zoom: true,
    },
    treeConfig: {
      parentField: 'pid',
      rowField: 'id',
      transform: false,
    },
  } as VxeTableGridOptions,
});

/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}
</script>
<template>
  <Page auto-content-height>
    <FormModal @success="refreshGrid" />
    <Grid table-title="部门列表">
      <template #toolbar-tools>
        <!-- <Button
          type="primary"
          @click="onCreate"
          v-if="userStore.buttonPermissions.includes('addDept')"
        >
          <Plus class="size-5" />
          {{ $t('ui.actionTitle.create', [$t('system.dept.name')]) }}
        </Button> -->
      </template>
    </Grid>
  </Page>
</template>
