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

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

import { useRouter } from 'vue-router';

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

import { ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  addbaseApi,
  checkFormExport,
  deletebaseApi,
  editbaseApi,
  querybaseApilist,
} from '#/api/system/tasksettings/checktheform';
import { commonDownloadExcel } from '#/utils/file/download';

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 gridOptions: VxeGridProps = {
  checkboxConfig: {
    highlight: true,
    reserve: true,
    trigger: 'default',
  },
  columns: tableColumns,
  size: 'medium',
  height: 'auto',
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues = {}) => {
        const res = await querybaseApilist({
          ...formValues,
          pageNum: page.currentPage,
          pageSize: page.pageSize,
        });
        return {
          items: res?.rows,
          total: res?.total,
        };
      },
    },
  },
  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) {
  try {
    await deletebaseApi(row.id);
    await basicTableApi.reload();
  } catch (error) {
    console.error('删除检查表单失败:', error);
  }
}

// 批量删除检查表单
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 deletebaseApi(ids);
    await basicTableApi.reload();
  });
}
const handleConfirm = async (data: any) => {
  drawerApi.drawerLoading(true);
  try {
    // 根据是否包含 id 来决定调用新增接口还是编辑接口
    if (data.id) {
      // 编辑操作
      await editbaseApi(data);
    } else {
      // 新增操作
      await addbaseApi(data);
    }
    await basicTableApi.reload();
    drawerApi.close();
    // 刷新表格数据
  } catch (error) {
    console.error('保存检查表单失败:', error);
  } finally {
    drawerApi.drawerLoading(false);
  }
};

// 导出检查表单
async function exportHandle() {
  await commonDownloadExcel(
    checkFormExport,
    '检查表单数据',
    basicTableApi.formApi.form.values,
    {
      fieldMappingTime: formOptions.fieldMappingTime,
    },
  );
}
// 设置检查项（跳转到formDesign页面）
async function setCheckItems(row: any) {
  try {
    // 调用详情接口获取检查项数据
    // await detailsbaseApi(row.id);
    router.push({
      path: '/system/taskDesign/formDesign',
      query: { id: row.id },
    });
  } 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>
        </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 @confirm="handleConfirm" />
  </Page>
</template>

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