<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 { queryFormSchema, tableColumns } from './connect-data';
import ConnectDrawerComp from './connect-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,
      status: '已完成',
      district: '华东片区',
      stationName: '油站1',
      startDate: '2025-01-01',
      endDate: '2025-01-02',
      transferor: '张三',
      receiver: '李四',
      supervisor: '王五',
    },
    {
      id: 2,
      status: '待接收',
      district: '华南片区',
      stationName: '油站2',
      startDate: '2025-02-01',
      endDate: null,
      transferor: '赵六',
      receiver: null,
      supervisor: '钱七',
    },
    {
      id: 3,
      status: '接收中',
      district: '华北片区',
      stationName: '油站3',
      startDate: '2025-03-01',
      endDate: null,
      transferor: '孙八',
      receiver: '周九',
      supervisor: '吴十',
    },
    {
      id: 4,
      status: '已完成',
      district: '华西片区',
      stationName: '油站4',
      startDate: '2025-04-01',
      endDate: '2025-04-03',
      transferor: '郑一',
      receiver: '王二',
      supervisor: '冯三',
    },
    {
      id: 5,
      status: '待接收',
      district: '华东片区',
      stationName: '油站5',
      startDate: '2025-05-01',
      endDate: null,
      transferor: '陈四',
      receiver: null,
      supervisor: '楚五',
    },
  ],
  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.district) {
          filteredRows = filteredRows.filter(row => row.district === formValues.district);
        }
        if (formValues.stationName) {
          filteredRows = filteredRows.filter(row => row.stationName === formValues.stationName);
        }
        if (formValues.status) {
          filteredRows = filteredRows.filter(row => row.status === formValues.status);
        }
        if (formValues.receiver) {
          filteredRows = filteredRows.filter(row => row.receiver && row.receiver.includes(formValues.receiver));
        }
        if (formValues.transferor) {
          filteredRows = filteredRows.filter(row => row.transferor.includes(formValues.transferor));
        }
        if (formValues.supervisor) {
          filteredRows = filteredRows.filter(row => row.supervisor && row.supervisor.includes(formValues.supervisor));
        }
        if (formValues.startDate) {
          filteredRows = filteredRows.filter(row => 
            !row.startDate || new Date(row.startDate) >= new Date(formValues.startDate)
          );
        }
        if (formValues.endDate) {
          filteredRows = filteredRows.filter(row => 
            row.endDate && new Date(row.endDate) <= new Date(formValues.endDate)
          );
        }
        // 模拟分页
        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-connect-index',
};

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

const [ConnectDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: ConnectDrawerComp,
});

// 新增交接记录
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>
    <ConnectDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>

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