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

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

import { onMounted, ref } from 'vue';

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

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  deleteEmergencyInfo,
  emergencyInfoList,
  exportEmergencyInfo,
} from '#/api/system/infoEntry/emergencyInfo/emergencyInfo';
import { getDictOptions } from '#/utils/dict';
import { commonDownloadExcel } from '#/utils/file/download';

import { queryFormSchema, tableColumns, loadAreaList } from './emergencyInfo-data';
import EmergencyInfoDrawerComp from './emergencyInfo-drawer.vue';

// 字典标识常量
const DICT_KEYS = {
  // 应急防护类型字典标识
  EMERGENCY_PROTECTION_TYPE: 'emergency_protection_type',
};

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 emergencyInfoList({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return { items: resp.rows, total: resp.total };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-infoEntry-emergencyInfo-index',
};

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

const [EmergencyInfoDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: EmergencyInfoDrawerComp,
});

// 字典数据引用
const protectionTypes = ref<any[]>([]);

// 加载字典数据
onMounted(async () => {
  // 获取字典数据
  protectionTypes.value = getDictOptions(DICT_KEYS.EMERGENCY_PROTECTION_TYPE);
  // 加载片区列表
  await loadAreaList();
});

// 新增应急防护用品
function openDrawer() {
  drawerApi.setData({ isUpdate: false }).open();
}

// 编辑应急防护用品
function handleEdit(row: any) {
  drawerApi.setData({ ...row, isUpdate: true }).open();
}

// 单个删除应急防护用品
async function confirmEvent(row: any) {
  await deleteEmergencyInfo([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 () => {
    await deleteEmergencyInfo(ids);
    await basicTableApi.reload();
  });
}

// 导出应急防护用品数据
async function exportHandle() {
  await commonDownloadExcel(
    exportEmergencyInfo,
    '应急防护用品数据',
    basicTableApi.formApi.form.values,
  );
}
</script>

<template>
  <Page :auto-content-height="true">
    <BasicTable table-title="应急防护用品列表">
      <template #toolbar-tools>
        <ElSpace>
          <!-- <ElButton
            @click="exportHandle"
            v-access:code="['system:infoEntry:emergencyInfo:export']"
          >
            导出
          </ElButton> -->
          <ElButton
            type="danger"
            :disabled="
              !(basicTableApi?.grid?.getCheckboxRecords?.()?.length > 0)
            "
            @click="deleteHandle"
            v-access:code="['system:infoEntry:emergencyInfo:remove']"
          >
            批量删除
          </ElButton>
          <ElButton
            type="primary"
            @click="openDrawer"
            v-access:code="['system:infoEntry:emergencyInfo:add']"
          >
            新增应急防护用品
          </ElButton>
        </ElSpace>
      </template>
      <template #action="{ row }">
        <ElSpace>
          <ElButton
            size="small"
            type="primary"
            plain
            @click="handleEdit(row)"
            v-access:code="['system:infoEntry:emergencyInfo:edit']"
          >
            编辑
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
                v-access:code="['system:infoEntry:emergencyInfo:remove']"
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <EmergencyInfoDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>

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