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

import type { VxeGridProps } from '#/adapter/vxe-table';

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

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';

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

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

// 模拟数据
const mockData = {
  rows: [
    {
      id: 1,
      stationName: '油站1',
      filterNo: 'FL-20250001',
      filterModel: 'F-Model-001',
      dispenserModel: 'D-Model-001',
      relatedGun: '1#',
      relatedOil: '92#汽油',
      totalFilteredLiters: 12000,
      nextReplaceDate: '2025-12-31',
      operator: '管理员',
      operationTime: '2025-01-01 10:00:00',
    },
    {
      id: 2,
      stationName: '油站1',
      filterNo: 'FL-20250002',
      filterModel: 'F-Model-002',
      dispenserModel: 'D-Model-002',
      relatedGun: '2#',
      relatedOil: '95#汽油',
      totalFilteredLiters: 15000,
      nextReplaceDate: '2025-11-30',
      operator: '管理员',
      operationTime: '2025-01-02 11:00:00',
    },
    {
      id: 3,
      stationName: '油站2',
      filterNo: 'FL-20250003',
      filterModel: 'F-Model-001',
      dispenserModel: 'D-Model-001',
      relatedGun: '3#',
      relatedOil: '0#柴油',
      totalFilteredLiters: 20000,
      nextReplaceDate: '2025-10-31',
      operator: '操作员A',
      operationTime: '2025-01-03 12:00:00',
    },
    {
      id: 4,
      stationName: '油站2',
      filterNo: 'FL-20250004',
      filterModel: 'F-Model-003',
      dispenserModel: 'D-Model-003',
      relatedGun: '4#',
      relatedOil: '98#汽油',
      totalFilteredLiters: 8000,
      nextReplaceDate: '2025-09-30',
      operator: '操作员B',
      operationTime: '2025-01-04 13:00:00',
    },
    {
      id: 5,
      stationName: '油站3',
      filterNo: 'FL-20250005',
      filterModel: 'F-Model-002',
      dispenserModel: 'D-Model-002',
      relatedGun: '5#',
      relatedOil: '92#汽油',
      totalFilteredLiters: 18000,
      nextReplaceDate: '2025-12-15',
      operator: '管理员',
      operationTime: '2025-01-05 14:00:00',
    },
  ],
  total: 5,
};

const gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    trigger: 'default',
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        // 模拟API请求
        console.log('查询参数:', formValues, page);
        // 模拟过滤
        let filteredRows = [...mockData.rows];
        if (formValues.stationName) {
          filteredRows = filteredRows.filter(row => row.stationName === formValues.stationName);
        }
        if (formValues.operationTime) {
          const [startDate, endDate] = formValues.operationTime;
          filteredRows = filteredRows.filter(row => {
            const operationDate = new Date(row.operationTime);
            return operationDate >= startDate && operationDate <= endDate;
          });
        }
        if (formValues.filterModel) {
          filteredRows = filteredRows.filter(row => 
            row.filterModel.includes(formValues.filterModel)
          );
        }
        if (formValues.filterNo) {
          filteredRows = filteredRows.filter(row => 
            row.filterNo.includes(formValues.filterNo)
          );
        }
        // 模拟分页
        const start = (page.currentPage - 1) * page.pageSize;
        const end = start + page.pageSize;
        const paginatedRows = filteredRows.slice(start, end);
        return { 
          items: paginatedRows, 
          total: filteredRows.length 
        };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-checklis-filter-index',
};

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

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

// 新增过滤器
function openDrawer() {
  drawerApi.setData({ isUpdate: false }).open();
}

// 编辑过滤器
function handleEdit(row: any) {
  drawerApi.setData({ ...row, isUpdate: true }).open();
}

// 单个删除过滤器
async function confirmEvent(row: any) {
  // 模拟删除操作
  console.log('删除过滤器:', row.id);
  await basicTableApi.reload();
}

// 批量删除过滤器
function deleteHandle() {
  const checkRecords = basicTableApi.grid.getCheckboxRecords();
  const ids = checkRecords.map((item: any) => item.id);
  if (ids.length <= 0) {
    return;
  }

  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    // 模拟批量删除操作
    console.log('批量删除标签:', ids);
    await basicTableApi.reload();
  });
}

// 导入模板
function handleImport() {
  console.log('导入模板');
  // 这里可以实现导入逻辑
}

// 下载模板
function handleDownloadTemplate() {
  console.log('下载模板');
  // 这里可以实现下载模板逻辑
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="过滤器档案列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            type="primary"
            @click="handleImport"
          >
            导入
          </ElButton>
          <ElButton
            type="primary"
            @click="handleDownloadTemplate"
          >
            下载模板
          </ElButton>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteHandle"
          >
            批量删除
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
          >
            新增过滤器
          </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <FilterDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>

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