<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 './connectInfo-data';
import ConnectInfoDrawerComp from './connectInfo-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,
      taskName: '事项1',
      guidance: '要求指引1',
      link: '环节1',
      personInCharge: '负责人1',
      supervisor: '监交人1',
      updateTime: '2024-01-01 10:00:00',
      operator: '操作人1',
    },
    {
      id: 2,
      taskName: '事项2',
      guidance: '要求指引2',
      link: '环节2',
      personInCharge: '负责人2',
      supervisor: '监交人2',
      updateTime: '2024-01-02 11:00:00',
      operator: '操作人2',
    },
    {
      id: 3,
      taskName: '事项3',
      guidance: '要求指引3',
      link: '环节3',
      personInCharge: '负责人3',
      supervisor: '监交人3',
      updateTime: '2024-01-03 12:00:00',
      operator: '操作人3',
    },
  ],
  total: 3,
};

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.taskName) {
          filteredRows = filteredRows.filter(row => 
            row.taskName.includes(formValues.taskName)
          );
        }
        if (formValues.link) {
          filteredRows = filteredRows.filter(row => 
            row.link === formValues.link
          );
        }
        if (formValues.personInCharge) {
          filteredRows = filteredRows.filter(row => 
            row.personInCharge === formValues.personInCharge
          );
        }
        if (formValues.supervisor) {
          filteredRows = filteredRows.filter(row => 
            row.supervisor === formValues.supervisor
          );
        }
        // 模拟分页
        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-infoEntry-connectInfo-index',
};

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

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

// 新增交接事项
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 initiateHandover() {
  // 模拟发起交接操作
  console.log('发起交接');
}

// 批量删除交接事项
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>
          <ElButton
            type="success"
            @click="initiateHandover"
          >
            发起交接
          </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()" />
  </Page>
</template>

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