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

import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { SysTenantApi } from '#/api/system/sysTenant';

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

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

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  apiDelete,
  apiExport,
  apiPage,
  tenantSyncDict,
  tenantSyncPackage,
} from '#/api/system/sysTenant';
import { GhostButton } from '#/components/global/button';
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(),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: true,
    },
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues = {}) => {
          return await apiPage({
            pageNo: page.currentPage,
            pageSize: page.pageSize,
            ...formValues,
          });
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      // 高亮当前行
      isCurrent: true,
    },
  } as VxeTableGridOptions,
});

// function onActionClick({
//   code,
//   row,
// }: OnActionClickParams<SysTenantApi.Tenant>) {
//   switch (code) {
//     case 'delete': {
//       onDelete(row);
//       break;
//     }
//     case 'edit': {
//       onEdit(row);
//       break;
//     }
//     case 'syncPackage': {
//       handleSyncPackage(row);
//       break;
//     }
//     default: {
//       break;
//     }
//   }
// }

function onRefresh() {
  gridApi.query();
}
function onEdit(row: SysTenantApi.Tenant) {
  formDrawerApi.setData(row).open();
}
function onCreate() {
  formDrawerApi.setData({}).open();
}

function onDelete(row: SysTenantApi.Tenant) {
  const hideLoading = message.loading({
    content: `正在删除${row.companyName}...`,
    duration: 0,
    key: 'action_process_msg',
  });
  apiDelete(row.id || 0)
    .then(() => {
      message.success({
        content: `${row.companyName}删除成功`,
        key: 'action_process_msg',
      });
      onRefresh();
    })
    .catch(() => {
      hideLoading();
    });
}
function handleDownloadExcel() {
  commonDownloadExcel(apiExport, '租户列表', gridApi.formApi.form.values);
}

async function handleSyncPackage(row: SysTenantApi.Tenant) {
  const { id, packageId } = row;
  await tenantSyncPackage(id!, packageId!);
  onRefresh();
}

function handleSyncTenantDict() {
  Modal.confirm({
    title: '提示',
    iconType: 'warning',
    content: '确认同步租户字典？',
    onOk: async () => {
      await tenantSyncDict();
      onRefresh();
    },
  });
}

function handleSyncTenantConfig() {
  Modal.confirm({
    title: '提示',
    iconType: 'warning',
    content: '确认同步租户参数配置？',
    onOk: async () => {
      await syncTenantConfig();
      await tableApi.query();
    },
  });
}
</script>
<template>
  <Page auto-content-height>
    <FormDrawer @success="onRefresh" />
    <Grid table-title="租户列表">
      <template #toolbar-tools>
        <Space>
          <Button
            v-access:code="['system:tenant:edit']"
            @click="handleSyncTenantDict"
          >
            同步租户字典
          </Button>
          <Button
            v-access:code="['system:tenant:edit']"
            @click="handleSyncTenantConfig"
          >
            同步租户参数配置
          </Button>
          <Button
            v-access:code="['system:tenant:export']"
            @click="handleDownloadExcel"
          >
            导出
          </Button>
          <Button
            type="primary"
            v-access:code="['system:tenant:add']"
            @click="onCreate"
          >
            <Plus class="size-5" />
            新增
          </Button>
        </Space>
      </template>
      <template #action="{ row }">
        <Space v-if="row.id !== 1">
          <GhostButton
            v-access:code="['system:tenant:edit']"
            @click="onEdit(row)"
          >
            编辑
          </GhostButton>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            :title="`确认同步[${row.companyName}]的套餐吗?`"
            placement="left"
            @confirm="handleSyncPackage(row)"
          >
            <GhostButton
              class="btn-success"
              v-access:code="['system:tenant:edit']"
            >
              同步
            </GhostButton>
          </Popconfirm>
          <Popconfirm
            :get-popup-container="getVxePopupContainer"
            placement="left"
            title="确认删除？"
            @confirm="onDelete(row)"
          >
            <GhostButton
              danger
              v-access:code="['system:tenant:remove']"
              @click.stop=""
            >
              删除
            </GhostButton>
          </Popconfirm>
        </Space>
      </template>
    </Grid>
  </Page>
</template>
