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

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

import { queryFormSchema, tableColumns, initiateFormSchema } from './connectInfo-data';
import ConnectInfoDrawerComp from './connectInfo-drawer.vue';
import ConnectInfoInitiateDrawerComp from './connectInfo-initiate-drawer.vue';

import {
  connectInfoList,
  deleteConnectInfo,
  exportConnectInfo,
  initiateConnectInfo,
} from '#/api/system/infoEntry/connectInfo/connectInfo';

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 params = {
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        };
        const response = await connectInfoList(params);
        if (response.rows) {
          return {
            items: response.rows,
            total: response.total,
          };
        }
        return {
          items: [],
          total: 0,
        };
      },
    },
  },
  rowConfig: {
    keyField: 'id',
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    zoom: true,
  },
  id: 'system-infoEntry-connectInfo-index',
};

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

const [ConnectInfoDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: ConnectInfoDrawerComp,
});

const [ConnectInfoInitiateDrawer, initiateDrawerApi] = useVbenDrawer({
  connectedComponent: ConnectInfoInitiateDrawerComp,
});

// 新增交接事项
function openDrawer() {
  drawerApi.setData({ isUpdate: false }).open();
}

// 编辑交接事项
function handleEdit(row: any) {
  drawerApi.setData({ ...row, isUpdate: true }).open();
}

// 单个删除交接事项
async function confirmEvent(row: any) {
  try {
    await deleteConnectInfo([row.id]);
    await basicTableApi.reload();
  } catch (error) {
    console.error('删除失败:', error);
  }
}

// 发起交接
function initiateHandover() {
  // 打开发起交接抽屉
  initiateDrawerApi.open();
}

// 批量删除交接事项
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 () => {
    try {
      await deleteConnectInfo(ids);
      await basicTableApi.reload();
    } catch (error) {
      console.error('批量删除失败:', error);
    }
  });
}

// 导出交接事项列表
async function handleExport() {
  try {
    await exportConnectInfo({});
  } catch (error) {
    console.error('导出失败:', error);
  }
}
</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>
          <ElButton
            type="success"
            @click="initiateHandover"
          >
            发起交接
          </ElButton>
          <!-- <ElButton
            @click="handleExport"
          >
            导出
          </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>
    <ConnectInfoDrawer @reload="basicTableApi.reload()" />
    <ConnectInfoInitiateDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>

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