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

import type { VxeGridProps } from '#/adapter/vxe-table';
import type { Filter } from '#/api/oilstation/filter/model';

import { useRouter } from 'vue-router';

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

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteFilter,
  filterExport,
  getFilterList,
} from '#/api/oilstation/filter/filter';
import { commonDownloadExcel } from '#/utils/file/download';

import { queryFormSchema, tableColumns } from './filter-data';
import FilterDrawerComp from './filter-drawer.vue';
import FilterImport from './filter-import.vue';

const router = useRouter();

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

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    trigger: 'default',
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const resp = await getFilterList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows || [], total: resp.total || 0 };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'oilstation-filter-index',
};

const [BasicTable, basicTableApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
});

const [FilterDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: FilterDrawerComp,
});

// 导入过滤器模态框
const [ImportModal, ImportModalApi] = useVbenModal({
  connectedComponent: FilterImport,
});

function handleAdd() {
  drawerApi.setData({ isUpdate: false }).open();
}
// 编辑过滤器--查看
function handleEdit(row: Filter) {
  // drawerApi.setData({ ...row, isUpdate: true }).open();
  router.push({
    name: 'FilterDetail',
    params: { id: row.id },
  });
}

// 打开导入模态框
function handleImport() {
  ImportModalApi.open();
}

// 单个删除过滤器
async function handleDelete(row: Filter) {
  try {
    await ElMessageBox.confirm(
      `确认删除过滤器${row.filterNumber}吗?`,
      '系统提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    );
    await deleteFilter(row.id);
    await basicTableApi.reload();
  } catch {
    // 用户取消删除操作
  }
}

// 批量删除过滤器
async function handleBatchDelete() {
  const checkRecords = basicTableApi.grid.getCheckboxRecords();
  if (checkRecords.length <= 0) {
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确认删除选中的${checkRecords.length}条数据吗?`,
      '系统提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    );
    const ids = checkRecords.map((item: Filter) => item.id);
    await deleteFilter(ids);
    await basicTableApi.reload();
  } catch {
    // 用户取消删除操作
  }
}

// 导出过滤器列表
async function exportHandle() {
  await commonDownloadExcel(
    filterExport,
    '场站过滤器列表',
    basicTableApi.formApi.form.values,
  );
}

// const handleView = (row: Filter) => {
//   // drawerApi.setData({ ...row, isUpdate: false }).open();
// };
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="过滤器档案列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            type="primary"
            v-access:code="['oilstation:filter:add']"
            @click="handleAdd"
          >
            新增过滤器
          </ElButton>
          <ElButton
            type="primary"
            v-access:code="['oilstation:filter:export']"
            @click="exportHandle"
          >
            导出
          </ElButton>
          <ElButton
            type="primary"
            v-access:code="['oilstation:filter:import']"
            @click="handleImport"
          >
            导入
          </ElButton>
          <ElButton
            type="danger"
            v-access:code="['oilstation:filter:remove']"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="handleBatchDelete"
          >
            批量删除
          </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['oilstation:filter:edit']"
          >
            查看
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="handleDelete(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                v-access:code="['oilstation:filter:remove']"
                plain
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <FilterDrawer @reload="basicTableApi.reload()" />
    <ImportModal @reload="basicTableApi.reload()" />
  </Page>
</template>

<style scoped lang="scss">
:deep(.el-tooltip__trigger:focus) {
  outline: none;
}
</style>
