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

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

import { onMounted, ref } from 'vue';
import { useRouter } from 'vue-router';

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

import { ElMessageBox } from 'element-plus';

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

import { queryFormSchema, tableColumns } from './checkForm-data';
import CheckFormDrawerComp from './checkForm-drawer.vue';

const router = useRouter();

const formOptions: VbenFormProps = {
  commonConfig: {
    labelWidth: 120,
    componentProps: {
      allowClear: true,
    },
  },
  schema: queryFormSchema(),
  wrapperClass: 'grid-cols-1 md:grid-cols-2 lg:grid-cols-4',
};

// 模拟数据
const mockData = {
  rows: [
    {
      id: 1,
      formName: '安全检查表单',
      createBy: '管理员',
      createTime: '2024-01-01 10:00:00',
    },
    {
      id: 2,
      formName: '设备检查表单',
      createBy: '管理员',
      createTime: '2024-01-02 11:00:00',
    },
    {
      id: 3,
      formName: '环境检查表单',
      createBy: '管理员',
      createTime: '2024-01-03 12:00:00',
    },
    {
      id: 4,
      formName: '消防检查表单',
      createBy: '管理员',
      createTime: '2024-01-04 13:00:00',
    },
    {
      id: 5,
      formName: '卫生检查表单',
      createBy: '管理员',
      createTime: '2024-01-05 14:00:00',
    },
  ],
  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.formName) {
          filteredRows = filteredRows.filter(row => 
            row.formName.includes(formValues.formName)
          );
        }
        // 模拟分页
        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-checkForm-index',
};

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

const [CheckFormDrawer, drawerApi] = useVbenDrawer({
  connectedComponent: CheckFormDrawerComp,
});

// 新增检查表单
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();
  });
}

// 导出检查表单
function exportHandle() {
  // 模拟导出操作
  console.log('导出检查表单');
}

// 设置检查项（跳转到formDesign页面）
function setCheckItems(row: any) {
  // 跳转到设置检查项页面
  router.push({
    path: '/system/taskDesign/formDesign',
    query: { formId: row.id, formName: row.formName },
  });
}
</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>
          <ElButton
            size="small"
            type="success"
            plain
            @click="exportHandle"
          >
            导出
          </ElButton>
          <ElButton
            size="small"
            type="warning"
            plain
            @click="setCheckItems(row)"
          >
            设置检查项
          </ElButton>
          <ElPopconfirm title="确认删除" @confirm="confirmEvent(row)">
            <template #reference>
              <ElButton
                size="small"
                type="danger"
                plain
              >
                删除
              </ElButton>
            </template>
          </ElPopconfirm>
        </ElSpace>
      </template>
    </BasicTable>
    <CheckFormDrawer @reload="basicTableApi.reload()" />
  </Page>
</template>

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