<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 { ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteEmergencyMaterial,
  emergencyMaterialList,
} from '#/api/oilstation/emergency/emergency';

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 gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    trigger: 'default',
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        try {
          // 构建查询参数
          const params = {
            ...formValues,
            pageNum: page.currentPage,
            pageSize: page.pageSize,
          };

          // 调用API获取数据
          const response = await emergencyMaterialList(params);
          console.log('查询应急防护列表响应:', response);
          const data = response || {};
          return {
            items: data.rows || [],
            total: data.total || 0,
          };
        } catch (error) {
          console.error('查询应急防护列表失败:', error);
          ElMessage.error('查询应急防护列表失败');
          return { items: [], total: 0 };
        }
      },
    },
  },
  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) {
  try {
    await deleteEmergencyMaterial([row.id.toString()]);
    ElMessage.success('删除成功');
    await basicTableApi.reload();
  } catch (error) {
    console.error('删除应急防护失败:', error);
    ElMessage.error('删除应急防护失败');
  }
}

// 批量删除应急防护
function deleteHandle() {
  const checkRecords = basicTableApi.grid.getCheckboxRecords();
  const ids = checkRecords.map((item: any) => item.id.toString());
  if (ids.length <= 0) {
    return;
  }

  ElMessageBox.confirm(`确认删除选中的${ids.length}条数据吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await deleteEmergencyMaterial(ids);
      ElMessage.success('删除成功');
      await basicTableApi.reload();
    } catch (error) {
      console.error('批量删除应急防护失败:', error);
      ElMessage.error('批量删除应急防护失败');
    }
  });
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="应急防护档案列表">
      <template #toolbar-tools>
        <ElSpace>
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            v-access:code="['oilstation:emergency:remove']"
            @click="deleteHandle"
          >
            批量删除
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
            v-access:code="['oilstation:emergency:add']"
          >
            新增应急防护
          </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            v-access:code="['oilstation:emergency:edit']"
            @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>
