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

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

import { ref } from 'vue';

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

import { ElMessageBox } from 'element-plus';

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

import { queryFormSchema, tableColumns } from './emergency-data';
import EmergencyDrawerComp from './emergency-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: '第一加油站',
      name: '干粉灭火器',
      type: 'fire_extinguisher',
      unit: '个',
      quantity: 5,
      remark: '定期检查压力',
      createBy: '管理员',
      createTime: '2024-01-01 10:00:00',
    },
    {
      id: 2,
      stationName: '第二加油站',
      name: '防毒面具',
      type: 'gas_mask',
      unit: '套',
      quantity: 10,
      remark: '有效期至2025-12-31',
      createBy: '管理员',
      createTime: '2024-01-02 11:00:00',
    },
    {
      id: 3,
      stationName: '第一加油站',
      name: '急救箱',
      type: 'first_aid_kit',
      unit: '个',
      quantity: 2,
      remark: '包含常用药品',
      createBy: '管理员',
      createTime: '2024-01-03 12:00:00',
    },
    {
      id: 4,
      stationName: '第三加油站',
      name: '防护服',
      type: 'protective_clothing',
      unit: '套',
      quantity: 8,
      remark: '防火防化',
      createBy: '管理员',
      createTime: '2024-01-04 13:00:00',
    },
    {
      id: 5,
      stationName: '第二加油站',
      name: '消防栓',
      type: 'fire_hydrant',
      unit: '个',
      quantity: 3,
      remark: '每月检查一次',
      createBy: '管理员',
      createTime: '2024-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.type) {
          filteredRows = filteredRows.filter(row => row.type === formValues.type);
        }
        // 模拟分页
        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-emergency-index',
};

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

const [EmergencyDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: EmergencyDrawerComp,
});

// 新增应急防护
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();
  });
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="应急防护档案列表">
      <template #toolbar-tools>
        <ElSpace>
          <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>
    <EmergencyDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>

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